Deleted Added
full compact
fil.c (355795) fil.c (363769)
1/* $FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 355795 2019-12-16 02:38:47Z cy $ */
1/* $FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 363769 2020-08-02 04:25:36Z cy $ */
2
3/*
4 * Copyright (C) 2012 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Copyright 2008 Sun Microsystems.
9 *
10 * $Id$
11 *
12 */
13#if defined(KERNEL) || defined(_KERNEL)
14# undef KERNEL
15# undef _KERNEL
16# define KERNEL 1
17# define _KERNEL 1
18#endif
19#include <sys/errno.h>
20#include <sys/types.h>
21#include <sys/param.h>
22#include <sys/time.h>
23#if defined(_KERNEL) && defined(__FreeBSD_version)
24# if !defined(IPFILTER_LKM)
25# include "opt_inet6.h"
26# endif
27# include <sys/filio.h>
28#else
29# include <sys/ioctl.h>
30#endif
31#if defined(__SVR4) || defined(sun) /* SOLARIS */
32# include <sys/filio.h>
33#endif
34# include <sys/fcntl.h>
35#if defined(_KERNEL)
36# include <sys/systm.h>
37# include <sys/file.h>
38#else
39# include <stdio.h>
40# include <string.h>
41# include <stdlib.h>
42# include <stddef.h>
43# include <sys/file.h>
44# define _KERNEL
45# include <sys/uio.h>
46# undef _KERNEL
47#endif
48#if !defined(__SVR4)
49# include <sys/mbuf.h>
50#else
51# include <sys/byteorder.h>
52# if (SOLARIS2 < 5) && defined(sun)
53# include <sys/dditypes.h>
54# endif
55#endif
56# include <sys/protosw.h>
57#include <sys/socket.h>
58#include <net/if.h>
59#ifdef sun
60# include <net/af.h>
61#endif
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/tcp.h>
66# include <netinet/udp.h>
67# include <netinet/ip_icmp.h>
68#include "netinet/ip_compat.h"
69#ifdef USE_INET6
70# include <netinet/icmp6.h>
71# if !SOLARIS && defined(_KERNEL)
72# include <netinet6/in6_var.h>
73# endif
74#endif
75#include "netinet/ip_fil.h"
76#include "netinet/ip_nat.h"
77#include "netinet/ip_frag.h"
78#include "netinet/ip_state.h"
79#include "netinet/ip_proxy.h"
80#include "netinet/ip_auth.h"
81#ifdef IPFILTER_SCAN
82# include "netinet/ip_scan.h"
83#endif
84#include "netinet/ip_sync.h"
85#include "netinet/ip_lookup.h"
86#include "netinet/ip_pool.h"
87#include "netinet/ip_htable.h"
88#ifdef IPFILTER_COMPILED
89# include "netinet/ip_rules.h"
90#endif
91#if defined(IPFILTER_BPF) && defined(_KERNEL)
92# include <net/bpf.h>
93#endif
94#if defined(__FreeBSD_version)
95# include <sys/malloc.h>
96#endif
97#include "netinet/ipl.h"
98
99#if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100# include <sys/callout.h>
101extern struct callout ipf_slowtimer_ch;
102#endif
103/* END OF INCLUDES */
104
105#if !defined(lint)
106static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
2
3/*
4 * Copyright (C) 2012 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Copyright 2008 Sun Microsystems.
9 *
10 * $Id$
11 *
12 */
13#if defined(KERNEL) || defined(_KERNEL)
14# undef KERNEL
15# undef _KERNEL
16# define KERNEL 1
17# define _KERNEL 1
18#endif
19#include <sys/errno.h>
20#include <sys/types.h>
21#include <sys/param.h>
22#include <sys/time.h>
23#if defined(_KERNEL) && defined(__FreeBSD_version)
24# if !defined(IPFILTER_LKM)
25# include "opt_inet6.h"
26# endif
27# include <sys/filio.h>
28#else
29# include <sys/ioctl.h>
30#endif
31#if defined(__SVR4) || defined(sun) /* SOLARIS */
32# include <sys/filio.h>
33#endif
34# include <sys/fcntl.h>
35#if defined(_KERNEL)
36# include <sys/systm.h>
37# include <sys/file.h>
38#else
39# include <stdio.h>
40# include <string.h>
41# include <stdlib.h>
42# include <stddef.h>
43# include <sys/file.h>
44# define _KERNEL
45# include <sys/uio.h>
46# undef _KERNEL
47#endif
48#if !defined(__SVR4)
49# include <sys/mbuf.h>
50#else
51# include <sys/byteorder.h>
52# if (SOLARIS2 < 5) && defined(sun)
53# include <sys/dditypes.h>
54# endif
55#endif
56# include <sys/protosw.h>
57#include <sys/socket.h>
58#include <net/if.h>
59#ifdef sun
60# include <net/af.h>
61#endif
62#include <netinet/in.h>
63#include <netinet/in_systm.h>
64#include <netinet/ip.h>
65#include <netinet/tcp.h>
66# include <netinet/udp.h>
67# include <netinet/ip_icmp.h>
68#include "netinet/ip_compat.h"
69#ifdef USE_INET6
70# include <netinet/icmp6.h>
71# if !SOLARIS && defined(_KERNEL)
72# include <netinet6/in6_var.h>
73# endif
74#endif
75#include "netinet/ip_fil.h"
76#include "netinet/ip_nat.h"
77#include "netinet/ip_frag.h"
78#include "netinet/ip_state.h"
79#include "netinet/ip_proxy.h"
80#include "netinet/ip_auth.h"
81#ifdef IPFILTER_SCAN
82# include "netinet/ip_scan.h"
83#endif
84#include "netinet/ip_sync.h"
85#include "netinet/ip_lookup.h"
86#include "netinet/ip_pool.h"
87#include "netinet/ip_htable.h"
88#ifdef IPFILTER_COMPILED
89# include "netinet/ip_rules.h"
90#endif
91#if defined(IPFILTER_BPF) && defined(_KERNEL)
92# include <net/bpf.h>
93#endif
94#if defined(__FreeBSD_version)
95# include <sys/malloc.h>
96#endif
97#include "netinet/ipl.h"
98
99#if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100# include <sys/callout.h>
101extern struct callout ipf_slowtimer_ch;
102#endif
103/* END OF INCLUDES */
104
105#if !defined(lint)
106static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
107static const char rcsid[] = "@(#)$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 355795 2019-12-16 02:38:47Z cy $";
107static const char rcsid[] = "@(#)$FreeBSD: stable/11/sys/contrib/ipfilter/netinet/fil.c 363769 2020-08-02 04:25:36Z cy $";
108/* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
109#endif
110
111#ifndef _KERNEL
112# include "ipf.h"
113# include "ipt.h"
114extern int opts;
115extern int blockreason;
116#endif /* _KERNEL */
117
108/* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
109#endif
110
111#ifndef _KERNEL
112# include "ipf.h"
113# include "ipt.h"
114extern int opts;
115extern int blockreason;
116#endif /* _KERNEL */
117
118#define FASTROUTE_RECURSION
119
118#define LBUMP(x) softc->x++
119#define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
120
121static INLINE int ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122static u_32_t ipf_checkcipso __P((fr_info_t *, u_char *, int));
123static u_32_t ipf_checkripso __P((u_char *));
124static u_32_t ipf_decaps __P((fr_info_t *, u_32_t, int));
125#ifdef IPFILTER_LOG
126static frentry_t *ipf_dolog __P((fr_info_t *, u_32_t *));
127#endif
128static int ipf_flushlist __P((ipf_main_softc_t *, int *,
129 frentry_t **));
130static int ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
131 int));
132static ipfunc_t ipf_findfunc __P((ipfunc_t));
133static void *ipf_findlookup __P((ipf_main_softc_t *, int,
134 frentry_t *,
135 i6addr_t *, i6addr_t *));
136static frentry_t *ipf_firewall __P((fr_info_t *, u_32_t *));
137static int ipf_fr_matcharray __P((fr_info_t *, int *));
138static int ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
139 void *));
140static void ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141static int ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142static int ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
143 ipfgeniter_t *));
144static void ipf_getstat __P((ipf_main_softc_t *,
145 struct friostat *, int));
146static int ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147static void ipf_group_free __P((frgroup_t *));
148static int ipf_grpmapfini __P((struct ipf_main_softc_s *,
149 frentry_t *));
150static int ipf_grpmapinit __P((struct ipf_main_softc_s *,
151 frentry_t *));
152static frentry_t *ipf_nextrule __P((ipf_main_softc_t *, int, int,
153 frentry_t *, int));
154static int ipf_portcheck __P((frpcmp_t *, u_32_t));
155static INLINE int ipf_pr_ah __P((fr_info_t *));
156static INLINE void ipf_pr_esp __P((fr_info_t *));
157static INLINE void ipf_pr_gre __P((fr_info_t *));
158static INLINE void ipf_pr_udp __P((fr_info_t *));
159static INLINE void ipf_pr_tcp __P((fr_info_t *));
160static INLINE void ipf_pr_icmp __P((fr_info_t *));
161static INLINE void ipf_pr_ipv4hdr __P((fr_info_t *));
162static INLINE void ipf_pr_short __P((fr_info_t *, int));
163static INLINE int ipf_pr_tcpcommon __P((fr_info_t *));
164static INLINE int ipf_pr_udpcommon __P((fr_info_t *));
165static void ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
166 int, int));
167static void ipf_rule_expire_insert __P((ipf_main_softc_t *,
168 frentry_t *, int));
169static int ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
170 void *));
171static void ipf_token_flush __P((ipf_main_softc_t *));
172static void ipf_token_unlink __P((ipf_main_softc_t *,
173 ipftoken_t *));
174static ipftuneable_t *ipf_tune_findbyname __P((ipftuneable_t *,
175 const char *));
176static ipftuneable_t *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
177 void **));
178static int ipf_updateipid __P((fr_info_t *));
179static int ipf_settimeout __P((struct ipf_main_softc_s *,
180 struct ipftuneable *,
181 ipftuneval_t *));
182#if !defined(_KERNEL) || SOLARIS
183static int ppsratecheck(struct timeval *, int *, int);
184#endif
185
186
187/*
188 * bit values for identifying presence of individual IP options
189 * All of these tables should be ordered by increasing key value on the left
190 * hand side to allow for binary searching of the array and include a trailer
191 * with a 0 for the bitmask for linear searches to easily find the end with.
192 */
193static const struct optlist ipopts[] = {
194 { IPOPT_NOP, 0x000001 },
195 { IPOPT_RR, 0x000002 },
196 { IPOPT_ZSU, 0x000004 },
197 { IPOPT_MTUP, 0x000008 },
198 { IPOPT_MTUR, 0x000010 },
199 { IPOPT_ENCODE, 0x000020 },
200 { IPOPT_TS, 0x000040 },
201 { IPOPT_TR, 0x000080 },
202 { IPOPT_SECURITY, 0x000100 },
203 { IPOPT_LSRR, 0x000200 },
204 { IPOPT_E_SEC, 0x000400 },
205 { IPOPT_CIPSO, 0x000800 },
206 { IPOPT_SATID, 0x001000 },
207 { IPOPT_SSRR, 0x002000 },
208 { IPOPT_ADDEXT, 0x004000 },
209 { IPOPT_VISA, 0x008000 },
210 { IPOPT_IMITD, 0x010000 },
211 { IPOPT_EIP, 0x020000 },
212 { IPOPT_FINN, 0x040000 },
213 { 0, 0x000000 }
214};
215
216#ifdef USE_INET6
217static const struct optlist ip6exthdr[] = {
218 { IPPROTO_HOPOPTS, 0x000001 },
219 { IPPROTO_IPV6, 0x000002 },
220 { IPPROTO_ROUTING, 0x000004 },
221 { IPPROTO_FRAGMENT, 0x000008 },
222 { IPPROTO_ESP, 0x000010 },
223 { IPPROTO_AH, 0x000020 },
224 { IPPROTO_NONE, 0x000040 },
225 { IPPROTO_DSTOPTS, 0x000080 },
226 { IPPROTO_MOBILITY, 0x000100 },
227 { 0, 0 }
228};
229#endif
230
231/*
232 * bit values for identifying presence of individual IP security options
233 */
234static const struct optlist secopt[] = {
235 { IPSO_CLASS_RES4, 0x01 },
236 { IPSO_CLASS_TOPS, 0x02 },
237 { IPSO_CLASS_SECR, 0x04 },
238 { IPSO_CLASS_RES3, 0x08 },
239 { IPSO_CLASS_CONF, 0x10 },
240 { IPSO_CLASS_UNCL, 0x20 },
241 { IPSO_CLASS_RES2, 0x40 },
242 { IPSO_CLASS_RES1, 0x80 }
243};
244
245char ipfilter_version[] = IPL_VERSION;
246
247int ipf_features = 0
248#ifdef IPFILTER_LKM
249 | IPF_FEAT_LKM
250#endif
251#ifdef IPFILTER_LOG
252 | IPF_FEAT_LOG
253#endif
254 | IPF_FEAT_LOOKUP
255#ifdef IPFILTER_BPF
256 | IPF_FEAT_BPF
257#endif
258#ifdef IPFILTER_COMPILED
259 | IPF_FEAT_COMPILED
260#endif
261#ifdef IPFILTER_CKSUM
262 | IPF_FEAT_CKSUM
263#endif
264 | IPF_FEAT_SYNC
265#ifdef IPFILTER_SCAN
266 | IPF_FEAT_SCAN
267#endif
268#ifdef USE_INET6
269 | IPF_FEAT_IPV6
270#endif
271 ;
272
273
274/*
275 * Table of functions available for use with call rules.
276 */
277static ipfunc_resolve_t ipf_availfuncs[] = {
278 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280 { "", NULL, NULL, NULL }
281};
282
283static ipftuneable_t ipf_main_tuneables[] = {
284 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285 "ipf_flags", 0, 0xffffffff,
286 stsizeof(ipf_main_softc_t, ipf_flags),
287 0, NULL, NULL },
288 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
289 "active", 0, 0,
290 stsizeof(ipf_main_softc_t, ipf_active),
291 IPFT_RDONLY, NULL, NULL },
292 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293 "control_forwarding", 0, 1,
294 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
295 0, NULL, NULL },
296 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
297 "update_ipid", 0, 1,
298 stsizeof(ipf_main_softc_t, ipf_update_ipid),
299 0, NULL, NULL },
300 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
301 "chksrc", 0, 1,
302 stsizeof(ipf_main_softc_t, ipf_chksrc),
303 0, NULL, NULL },
304 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
305 "min_ttl", 0, 1,
306 stsizeof(ipf_main_softc_t, ipf_minttl),
307 0, NULL, NULL },
308 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309 "icmp_minfragmtu", 0, 1,
310 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
311 0, NULL, NULL },
312 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313 "default_pass", 0, 0xffffffff,
314 stsizeof(ipf_main_softc_t, ipf_pass),
315 0, NULL, NULL },
316 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317 "tcp_idle_timeout", 1, 0x7fffffff,
318 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319 0, NULL, ipf_settimeout },
320 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321 "tcp_close_wait", 1, 0x7fffffff,
322 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323 0, NULL, ipf_settimeout },
324 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325 "tcp_last_ack", 1, 0x7fffffff,
326 stsizeof(ipf_main_softc_t, ipf_tcplastack),
327 0, NULL, ipf_settimeout },
328 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329 "tcp_timeout", 1, 0x7fffffff,
330 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331 0, NULL, ipf_settimeout },
332 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333 "tcp_syn_sent", 1, 0x7fffffff,
334 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335 0, NULL, ipf_settimeout },
336 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337 "tcp_syn_received", 1, 0x7fffffff,
338 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339 0, NULL, ipf_settimeout },
340 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341 "tcp_closed", 1, 0x7fffffff,
342 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343 0, NULL, ipf_settimeout },
344 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345 "tcp_half_closed", 1, 0x7fffffff,
346 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347 0, NULL, ipf_settimeout },
348 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349 "tcp_time_wait", 1, 0x7fffffff,
350 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351 0, NULL, ipf_settimeout },
352 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353 "udp_timeout", 1, 0x7fffffff,
354 stsizeof(ipf_main_softc_t, ipf_udptimeout),
355 0, NULL, ipf_settimeout },
356 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357 "udp_ack_timeout", 1, 0x7fffffff,
358 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359 0, NULL, ipf_settimeout },
360 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361 "icmp_timeout", 1, 0x7fffffff,
362 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363 0, NULL, ipf_settimeout },
364 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365 "icmp_ack_timeout", 1, 0x7fffffff,
366 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367 0, NULL, ipf_settimeout },
368 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369 "ip_timeout", 1, 0x7fffffff,
370 stsizeof(ipf_main_softc_t, ipf_iptimeout),
371 0, NULL, ipf_settimeout },
372#if defined(INSTANCES) && defined(_KERNEL)
373 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374 "intercept_loopback", 0, 1,
375 stsizeof(ipf_main_softc_t, ipf_get_loopback),
376 0, NULL, ipf_set_loopback },
377#endif
378 { { 0 },
379 NULL, 0, 0,
380 0,
381 0, NULL, NULL }
382};
383
384
385/*
386 * The next section of code is a collection of small routines that set
387 * fields in the fr_info_t structure passed based on properties of the
388 * current packet. There are different routines for the same protocol
389 * for each of IPv4 and IPv6. Adding a new protocol, for which there
390 * will "special" inspection for setup, is now more easily done by adding
391 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392 * adding more code to a growing switch statement.
393 */
394#ifdef USE_INET6
395static INLINE int ipf_pr_ah6 __P((fr_info_t *));
396static INLINE void ipf_pr_esp6 __P((fr_info_t *));
397static INLINE void ipf_pr_gre6 __P((fr_info_t *));
398static INLINE void ipf_pr_udp6 __P((fr_info_t *));
399static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
400static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
401static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
402static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
403static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
404static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
405static INLINE int ipf_pr_routing6 __P((fr_info_t *));
406static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
407static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
408static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
409
410
411/* ------------------------------------------------------------------------ */
412/* Function: ipf_pr_short6 */
413/* Returns: void */
414/* Parameters: fin(I) - pointer to packet information */
415/* xmin(I) - minimum header size */
416/* */
417/* IPv6 Only */
418/* This is function enforces the 'is a packet too short to be legit' rule */
419/* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
420/* for ipf_pr_short() for more details. */
421/* ------------------------------------------------------------------------ */
422static INLINE void
423ipf_pr_short6(fin, xmin)
424 fr_info_t *fin;
425 int xmin;
426{
427
428 if (fin->fin_dlen < xmin)
429 fin->fin_flx |= FI_SHORT;
430}
431
432
433/* ------------------------------------------------------------------------ */
434/* Function: ipf_pr_ipv6hdr */
435/* Returns: void */
436/* Parameters: fin(I) - pointer to packet information */
437/* */
438/* IPv6 Only */
439/* Copy values from the IPv6 header into the fr_info_t struct and call the */
440/* per-protocol analyzer if it exists. In validating the packet, a protocol*/
441/* analyzer may pullup or free the packet itself so we need to be vigiliant */
442/* of that possibility arising. */
443/* ------------------------------------------------------------------------ */
444static INLINE void
445ipf_pr_ipv6hdr(fin)
446 fr_info_t *fin;
447{
448 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449 int p, go = 1, i, hdrcount;
450 fr_ip_t *fi = &fin->fin_fi;
451
452 fin->fin_off = 0;
453
454 fi->fi_tos = 0;
455 fi->fi_optmsk = 0;
456 fi->fi_secmsk = 0;
457 fi->fi_auth = 0;
458
459 p = ip6->ip6_nxt;
460 fin->fin_crc = p;
461 fi->fi_ttl = ip6->ip6_hlim;
462 fi->fi_src.in6 = ip6->ip6_src;
463 fin->fin_crc += fi->fi_src.i6[0];
464 fin->fin_crc += fi->fi_src.i6[1];
465 fin->fin_crc += fi->fi_src.i6[2];
466 fin->fin_crc += fi->fi_src.i6[3];
467 fi->fi_dst.in6 = ip6->ip6_dst;
468 fin->fin_crc += fi->fi_dst.i6[0];
469 fin->fin_crc += fi->fi_dst.i6[1];
470 fin->fin_crc += fi->fi_dst.i6[2];
471 fin->fin_crc += fi->fi_dst.i6[3];
472 fin->fin_id = 0;
473 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
475
476 hdrcount = 0;
477 while (go && !(fin->fin_flx & FI_SHORT)) {
478 switch (p)
479 {
480 case IPPROTO_UDP :
481 ipf_pr_udp6(fin);
482 go = 0;
483 break;
484
485 case IPPROTO_TCP :
486 ipf_pr_tcp6(fin);
487 go = 0;
488 break;
489
490 case IPPROTO_ICMPV6 :
491 ipf_pr_icmp6(fin);
492 go = 0;
493 break;
494
495 case IPPROTO_GRE :
496 ipf_pr_gre6(fin);
497 go = 0;
498 break;
499
500 case IPPROTO_HOPOPTS :
501 p = ipf_pr_hopopts6(fin);
502 break;
503
504 case IPPROTO_MOBILITY :
505 p = ipf_pr_mobility6(fin);
506 break;
507
508 case IPPROTO_DSTOPTS :
509 p = ipf_pr_dstopts6(fin);
510 break;
511
512 case IPPROTO_ROUTING :
513 p = ipf_pr_routing6(fin);
514 break;
515
516 case IPPROTO_AH :
517 p = ipf_pr_ah6(fin);
518 break;
519
520 case IPPROTO_ESP :
521 ipf_pr_esp6(fin);
522 go = 0;
523 break;
524
525 case IPPROTO_IPV6 :
526 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527 if (ip6exthdr[i].ol_val == p) {
528 fin->fin_flx |= ip6exthdr[i].ol_bit;
529 break;
530 }
531 go = 0;
532 break;
533
534 case IPPROTO_NONE :
535 go = 0;
536 break;
537
538 case IPPROTO_FRAGMENT :
539 p = ipf_pr_fragment6(fin);
540 /*
541 * Given that the only fragments we want to let through
542 * (where fin_off != 0) are those where the non-first
543 * fragments only have data, we can safely stop looking
544 * at headers if this is a non-leading fragment.
545 */
546 if (fin->fin_off != 0)
547 go = 0;
548 break;
549
550 default :
551 go = 0;
552 break;
553 }
554 hdrcount++;
555
556 /*
557 * It is important to note that at this point, for the
558 * extension headers (go != 0), the entire header may not have
559 * been pulled up when the code gets to this point. This is
560 * only done for "go != 0" because the other header handlers
561 * will all pullup their complete header. The other indicator
562 * of an incomplete packet is that this was just an extension
563 * header.
564 */
565 if ((go != 0) && (p != IPPROTO_NONE) &&
566 (ipf_pr_pullup(fin, 0) == -1)) {
567 p = IPPROTO_NONE;
568 break;
569 }
570 }
571
572 /*
573 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574 * and destroy whatever packet was here. The caller of this function
575 * expects us to return if there is a problem with ipf_pullup.
576 */
577 if (fin->fin_m == NULL) {
578 ipf_main_softc_t *softc = fin->fin_main_soft;
579
580 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
581 return;
582 }
583
584 fi->fi_p = p;
585
586 /*
587 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
589 */
590 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591 ipf_main_softc_t *softc = fin->fin_main_soft;
592
593 fin->fin_flx |= FI_BAD;
594 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
597 }
598}
599
600
601/* ------------------------------------------------------------------------ */
602/* Function: ipf_pr_ipv6exthdr */
603/* Returns: struct ip6_ext * - pointer to the start of the next header */
604/* or NULL if there is a prolblem. */
605/* Parameters: fin(I) - pointer to packet information */
606/* multiple(I) - flag indicating yes/no if multiple occurances */
607/* of this extension header are allowed. */
608/* proto(I) - protocol number for this extension header */
609/* */
610/* IPv6 Only */
611/* This function embodies a number of common checks that all IPv6 extension */
612/* headers must be subjected to. For example, making sure the packet is */
613/* big enough for it to be in, checking if it is repeated and setting a */
614/* flag to indicate its presence. */
615/* ------------------------------------------------------------------------ */
616static INLINE struct ip6_ext *
617ipf_pr_ipv6exthdr(fin, multiple, proto)
618 fr_info_t *fin;
619 int multiple, proto;
620{
621 ipf_main_softc_t *softc = fin->fin_main_soft;
622 struct ip6_ext *hdr;
623 u_short shift;
624 int i;
625
626 fin->fin_flx |= FI_V6EXTHDR;
627
628 /* 8 is default length of extension hdr */
629 if ((fin->fin_dlen - 8) < 0) {
630 fin->fin_flx |= FI_SHORT;
631 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
632 return NULL;
633 }
634
635 if (ipf_pr_pullup(fin, 8) == -1) {
636 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
637 return NULL;
638 }
639
640 hdr = fin->fin_dp;
641 switch (proto)
642 {
643 case IPPROTO_FRAGMENT :
644 shift = 8;
645 break;
646 default :
647 shift = 8 + (hdr->ip6e_len << 3);
648 break;
649 }
650
651 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
652 fin->fin_flx |= FI_BAD;
653 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
655 return NULL;
656 }
657
658 fin->fin_dp = (char *)fin->fin_dp + shift;
659 fin->fin_dlen -= shift;
660
661 /*
662 * If we have seen a fragment header, do not set any flags to indicate
663 * the presence of this extension header as it has no impact on the
664 * end result until after it has been defragmented.
665 */
666 if (fin->fin_flx & FI_FRAG)
667 return hdr;
668
669 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670 if (ip6exthdr[i].ol_val == proto) {
671 /*
672 * Most IPv6 extension headers are only allowed once.
673 */
674 if ((multiple == 0) &&
675 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676 fin->fin_flx |= FI_BAD;
677 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
678 } else
679 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
680 break;
681 }
682
683 return hdr;
684}
685
686
687/* ------------------------------------------------------------------------ */
688/* Function: ipf_pr_hopopts6 */
689/* Returns: int - value of the next header or IPPROTO_NONE if error */
690/* Parameters: fin(I) - pointer to packet information */
691/* */
692/* IPv6 Only */
693/* This is function checks pending hop by hop options extension header */
694/* ------------------------------------------------------------------------ */
695static INLINE int
696ipf_pr_hopopts6(fin)
697 fr_info_t *fin;
698{
699 struct ip6_ext *hdr;
700
701 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
702 if (hdr == NULL)
703 return IPPROTO_NONE;
704 return hdr->ip6e_nxt;
705}
706
707
708/* ------------------------------------------------------------------------ */
709/* Function: ipf_pr_mobility6 */
710/* Returns: int - value of the next header or IPPROTO_NONE if error */
711/* Parameters: fin(I) - pointer to packet information */
712/* */
713/* IPv6 Only */
714/* This is function checks the IPv6 mobility extension header */
715/* ------------------------------------------------------------------------ */
716static INLINE int
717ipf_pr_mobility6(fin)
718 fr_info_t *fin;
719{
720 struct ip6_ext *hdr;
721
722 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
723 if (hdr == NULL)
724 return IPPROTO_NONE;
725 return hdr->ip6e_nxt;
726}
727
728
729/* ------------------------------------------------------------------------ */
730/* Function: ipf_pr_routing6 */
731/* Returns: int - value of the next header or IPPROTO_NONE if error */
732/* Parameters: fin(I) - pointer to packet information */
733/* */
734/* IPv6 Only */
735/* This is function checks pending routing extension header */
736/* ------------------------------------------------------------------------ */
737static INLINE int
738ipf_pr_routing6(fin)
739 fr_info_t *fin;
740{
741 struct ip6_routing *hdr;
742
743 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
744 if (hdr == NULL)
745 return IPPROTO_NONE;
746
747 switch (hdr->ip6r_type)
748 {
749 case 0 :
750 /*
751 * Nasty extension header length?
752 */
753 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755 ipf_main_softc_t *softc = fin->fin_main_soft;
756
757 fin->fin_flx |= FI_BAD;
758 DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
760 return IPPROTO_NONE;
761 }
762 break;
763
764 default :
765 break;
766 }
767
768 return hdr->ip6r_nxt;
769}
770
771
772/* ------------------------------------------------------------------------ */
773/* Function: ipf_pr_fragment6 */
774/* Returns: int - value of the next header or IPPROTO_NONE if error */
775/* Parameters: fin(I) - pointer to packet information */
776/* */
777/* IPv6 Only */
778/* Examine the IPv6 fragment header and extract fragment offset information.*/
779/* */
780/* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781/* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
782/* packets with a fragment header can fit into. They are as follows: */
783/* */
784/* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
785/* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
786/* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
787/* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
788/* 5. [IPV6][0-n EH][FH][data] */
789/* */
790/* IPV6 = IPv6 header, FH = Fragment Header, */
791/* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
792/* */
793/* Packets that match 1, 2, 3 will be dropped as the only reasonable */
794/* scenario in which they happen is in extreme circumstances that are most */
795/* likely to be an indication of an attack rather than normal traffic. */
796/* A type 3 packet may be sent by an attacked after a type 4 packet. There */
797/* are two rules that can be used to guard against type 3 packets: L4 */
798/* headers must always be in a packet that has the offset field set to 0 */
799/* and no packet is allowed to overlay that where offset = 0. */
800/* ------------------------------------------------------------------------ */
801static INLINE int
802ipf_pr_fragment6(fin)
803 fr_info_t *fin;
804{
805 ipf_main_softc_t *softc = fin->fin_main_soft;
806 struct ip6_frag *frag;
807
808 fin->fin_flx |= FI_FRAG;
809
810 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
811 if (frag == NULL) {
812 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
813 return IPPROTO_NONE;
814 }
815
816 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
817 /*
818 * Any fragment that isn't the last fragment must have its
819 * length as a multiple of 8.
820 */
821 if ((fin->fin_plen & 7) != 0) {
822 fin->fin_flx |= FI_BAD;
823 DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
824 }
825 }
826
827 fin->fin_fraghdr = frag;
828 fin->fin_id = frag->ip6f_ident;
829 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830 if (fin->fin_off != 0)
831 fin->fin_flx |= FI_FRAGBODY;
832
833 /*
834 * Jumbograms aren't handled, so the max. length is 64k
835 */
836 if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837 fin->fin_flx |= FI_BAD;
838 DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
839 }
840
841 /*
842 * We don't know where the transport layer header (or whatever is next
843 * is), as it could be behind destination options (amongst others) so
844 * return the fragment header as the type of packet this is. Note that
845 * this effectively disables the fragment cache for > 1 protocol at a
846 * time.
847 */
848 return frag->ip6f_nxt;
849}
850
851
852/* ------------------------------------------------------------------------ */
853/* Function: ipf_pr_dstopts6 */
854/* Returns: int - value of the next header or IPPROTO_NONE if error */
855/* Parameters: fin(I) - pointer to packet information */
856/* */
857/* IPv6 Only */
858/* This is function checks pending destination options extension header */
859/* ------------------------------------------------------------------------ */
860static INLINE int
861ipf_pr_dstopts6(fin)
862 fr_info_t *fin;
863{
864 ipf_main_softc_t *softc = fin->fin_main_soft;
865 struct ip6_ext *hdr;
866
867 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
868 if (hdr == NULL) {
869 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
870 return IPPROTO_NONE;
871 }
872 return hdr->ip6e_nxt;
873}
874
875
876/* ------------------------------------------------------------------------ */
877/* Function: ipf_pr_icmp6 */
878/* Returns: void */
879/* Parameters: fin(I) - pointer to packet information */
880/* */
881/* IPv6 Only */
882/* This routine is mainly concerned with determining the minimum valid size */
883/* for an ICMPv6 packet. */
884/* ------------------------------------------------------------------------ */
885static INLINE void
886ipf_pr_icmp6(fin)
887 fr_info_t *fin;
888{
889 int minicmpsz = sizeof(struct icmp6_hdr);
890 struct icmp6_hdr *icmp6;
891
892 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893 ipf_main_softc_t *softc = fin->fin_main_soft;
894
895 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
896 return;
897 }
898
899 if (fin->fin_dlen > 1) {
900 ip6_t *ip6;
901
902 icmp6 = fin->fin_dp;
903
904 fin->fin_data[0] = *(u_short *)icmp6;
905
906 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907 fin->fin_flx |= FI_ICMPQUERY;
908
909 switch (icmp6->icmp6_type)
910 {
911 case ICMP6_ECHO_REPLY :
912 case ICMP6_ECHO_REQUEST :
913 if (fin->fin_dlen >= 6)
914 fin->fin_data[1] = icmp6->icmp6_id;
915 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
916 break;
917
918 case ICMP6_DST_UNREACH :
919 case ICMP6_PACKET_TOO_BIG :
920 case ICMP6_TIME_EXCEEDED :
921 case ICMP6_PARAM_PROB :
922 fin->fin_flx |= FI_ICMPERR;
923 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
925 break;
926
927 if (M_LEN(fin->fin_m) < fin->fin_plen) {
928 if (ipf_coalesce(fin) != 1)
929 return;
930 }
931
932 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
933 return;
934
935 /*
936 * If the destination of this packet doesn't match the
937 * source of the original packet then this packet is
938 * not correct.
939 */
940 icmp6 = fin->fin_dp;
941 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942 if (IP6_NEQ(&fin->fin_fi.fi_dst,
943 (i6addr_t *)&ip6->ip6_src)) {
944 fin->fin_flx |= FI_BAD;
945 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
946 }
947 break;
948 default :
949 break;
950 }
951 }
952
953 ipf_pr_short6(fin, minicmpsz);
954 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955 u_char p = fin->fin_p;
956
957 fin->fin_p = IPPROTO_ICMPV6;
958 ipf_checkv6sum(fin);
959 fin->fin_p = p;
960 }
961}
962
963
964/* ------------------------------------------------------------------------ */
965/* Function: ipf_pr_udp6 */
966/* Returns: void */
967/* Parameters: fin(I) - pointer to packet information */
968/* */
969/* IPv6 Only */
970/* Analyse the packet for IPv6/UDP properties. */
971/* Is not expected to be called for fragmented packets. */
972/* ------------------------------------------------------------------------ */
973static INLINE void
974ipf_pr_udp6(fin)
975 fr_info_t *fin;
976{
977
978 if (ipf_pr_udpcommon(fin) == 0) {
979 u_char p = fin->fin_p;
980
981 fin->fin_p = IPPROTO_UDP;
982 ipf_checkv6sum(fin);
983 fin->fin_p = p;
984 }
985}
986
987
988/* ------------------------------------------------------------------------ */
989/* Function: ipf_pr_tcp6 */
990/* Returns: void */
991/* Parameters: fin(I) - pointer to packet information */
992/* */
993/* IPv6 Only */
994/* Analyse the packet for IPv6/TCP properties. */
995/* Is not expected to be called for fragmented packets. */
996/* ------------------------------------------------------------------------ */
997static INLINE void
998ipf_pr_tcp6(fin)
999 fr_info_t *fin;
1000{
1001
1002 if (ipf_pr_tcpcommon(fin) == 0) {
1003 u_char p = fin->fin_p;
1004
1005 fin->fin_p = IPPROTO_TCP;
1006 ipf_checkv6sum(fin);
1007 fin->fin_p = p;
1008 }
1009}
1010
1011
1012/* ------------------------------------------------------------------------ */
1013/* Function: ipf_pr_esp6 */
1014/* Returns: void */
1015/* Parameters: fin(I) - pointer to packet information */
1016/* */
1017/* IPv6 Only */
1018/* Analyse the packet for ESP properties. */
1019/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1020/* even though the newer ESP packets must also have a sequence number that */
1021/* is 32bits as well, it is not possible(?) to determine the version from a */
1022/* simple packet header. */
1023/* ------------------------------------------------------------------------ */
1024static INLINE void
1025ipf_pr_esp6(fin)
1026 fr_info_t *fin;
1027{
1028
1029 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030 ipf_main_softc_t *softc = fin->fin_main_soft;
1031
1032 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033 return;
1034 }
1035}
1036
1037
1038/* ------------------------------------------------------------------------ */
1039/* Function: ipf_pr_ah6 */
1040/* Returns: int - value of the next header or IPPROTO_NONE if error */
1041/* Parameters: fin(I) - pointer to packet information */
1042/* */
1043/* IPv6 Only */
1044/* Analyse the packet for AH properties. */
1045/* The minimum length is taken to be the combination of all fields in the */
1046/* header being present and no authentication data (null algorithm used.) */
1047/* ------------------------------------------------------------------------ */
1048static INLINE int
1049ipf_pr_ah6(fin)
1050 fr_info_t *fin;
1051{
1052 authhdr_t *ah;
1053
1054 fin->fin_flx |= FI_AH;
1055
1056 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1057 if (ah == NULL) {
1058 ipf_main_softc_t *softc = fin->fin_main_soft;
1059
1060 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061 return IPPROTO_NONE;
1062 }
1063
1064 ipf_pr_short6(fin, sizeof(*ah));
1065
1066 /*
1067 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068 * enough data to satisfy ah_next (the very first one.)
1069 */
1070 return ah->ah_next;
1071}
1072
1073
1074/* ------------------------------------------------------------------------ */
1075/* Function: ipf_pr_gre6 */
1076/* Returns: void */
1077/* Parameters: fin(I) - pointer to packet information */
1078/* */
1079/* Analyse the packet for GRE properties. */
1080/* ------------------------------------------------------------------------ */
1081static INLINE void
1082ipf_pr_gre6(fin)
1083 fr_info_t *fin;
1084{
1085 grehdr_t *gre;
1086
1087 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088 ipf_main_softc_t *softc = fin->fin_main_soft;
1089
1090 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1091 return;
1092 }
1093
1094 gre = fin->fin_dp;
1095 if (GRE_REV(gre->gr_flags) == 1)
1096 fin->fin_data[0] = gre->gr_call;
1097}
1098#endif /* USE_INET6 */
1099
1100
1101/* ------------------------------------------------------------------------ */
1102/* Function: ipf_pr_pullup */
1103/* Returns: int - 0 == pullup succeeded, -1 == failure */
1104/* Parameters: fin(I) - pointer to packet information */
1105/* plen(I) - length (excluding L3 header) to pullup */
1106/* */
1107/* Short inline function to cut down on code duplication to perform a call */
1108/* to ipf_pullup to ensure there is the required amount of data, */
1109/* consecutively in the packet buffer. */
1110/* */
1111/* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1112/* points to the first byte after the complete layer 3 header, which will */
1113/* include all of the known extension headers for IPv6 or options for IPv4. */
1114/* */
1115/* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1116/* is necessary to add those we can already assume to be pulled up (fin_dp */
1117/* - fin_ip) to what is passed through. */
1118/* ------------------------------------------------------------------------ */
1119int
1120ipf_pr_pullup(fin, plen)
1121 fr_info_t *fin;
1122 int plen;
1123{
1124 ipf_main_softc_t *softc = fin->fin_main_soft;
1125
1126 if (fin->fin_m != NULL) {
1127 if (fin->fin_dp != NULL)
1128 plen += (char *)fin->fin_dp -
1129 ((char *)fin->fin_ip + fin->fin_hlen);
1130 plen += fin->fin_hlen;
1131 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132#if defined(_KERNEL)
1133 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134 DT(ipf_pullup_fail);
1135 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1136 return -1;
1137 }
1138 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1139#else
1140 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1141 /*
1142 * Fake ipf_pullup failing
1143 */
1144 fin->fin_reason = FRB_PULLUP;
1145 *fin->fin_mp = NULL;
1146 fin->fin_m = NULL;
1147 fin->fin_ip = NULL;
1148 return -1;
1149#endif
1150 }
1151 }
1152 return 0;
1153}
1154
1155
1156/* ------------------------------------------------------------------------ */
1157/* Function: ipf_pr_short */
1158/* Returns: void */
1159/* Parameters: fin(I) - pointer to packet information */
1160/* xmin(I) - minimum header size */
1161/* */
1162/* Check if a packet is "short" as defined by xmin. The rule we are */
1163/* applying here is that the packet must not be fragmented within the layer */
1164/* 4 header. That is, it must not be a fragment that has its offset set to */
1165/* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1166/* entire layer 4 header must be present (min). */
1167/* ------------------------------------------------------------------------ */
1168static INLINE void
1169ipf_pr_short(fin, xmin)
1170 fr_info_t *fin;
1171 int xmin;
1172{
1173
1174 if (fin->fin_off == 0) {
1175 if (fin->fin_dlen < xmin)
1176 fin->fin_flx |= FI_SHORT;
1177 } else if (fin->fin_off < xmin) {
1178 fin->fin_flx |= FI_SHORT;
1179 }
1180}
1181
1182
1183/* ------------------------------------------------------------------------ */
1184/* Function: ipf_pr_icmp */
1185/* Returns: void */
1186/* Parameters: fin(I) - pointer to packet information */
1187/* */
1188/* IPv4 Only */
1189/* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1190/* except extrememly bad packets, both type and code will be present. */
1191/* The expected minimum size of an ICMP packet is very much dependent on */
1192/* the type of it. */
1193/* */
1194/* XXX - other ICMP sanity checks? */
1195/* ------------------------------------------------------------------------ */
1196static INLINE void
1197ipf_pr_icmp(fin)
1198 fr_info_t *fin;
1199{
1200 ipf_main_softc_t *softc = fin->fin_main_soft;
1201 int minicmpsz = sizeof(struct icmp);
1202 icmphdr_t *icmp;
1203 ip_t *oip;
1204
1205 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1206
1207 if (fin->fin_off != 0) {
1208 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1209 return;
1210 }
1211
1212 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1214 return;
1215 }
1216
1217 icmp = fin->fin_dp;
1218
1219 fin->fin_data[0] = *(u_short *)icmp;
1220 fin->fin_data[1] = icmp->icmp_id;
1221
1222 switch (icmp->icmp_type)
1223 {
1224 case ICMP_ECHOREPLY :
1225 case ICMP_ECHO :
1226 /* Router discovery messaes - RFC 1256 */
1227 case ICMP_ROUTERADVERT :
1228 case ICMP_ROUTERSOLICIT :
1229 fin->fin_flx |= FI_ICMPQUERY;
1230 minicmpsz = ICMP_MINLEN;
1231 break;
1232 /*
1233 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234 * 3 * timestamp(3 * 4)
1235 */
1236 case ICMP_TSTAMP :
1237 case ICMP_TSTAMPREPLY :
1238 fin->fin_flx |= FI_ICMPQUERY;
1239 minicmpsz = 20;
1240 break;
1241 /*
1242 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1243 * mask(4)
1244 */
1245 case ICMP_IREQ :
1246 case ICMP_IREQREPLY :
1247 case ICMP_MASKREQ :
1248 case ICMP_MASKREPLY :
1249 fin->fin_flx |= FI_ICMPQUERY;
1250 minicmpsz = 12;
1251 break;
1252 /*
1253 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1254 */
1255 case ICMP_UNREACH :
1256#ifdef icmp_nextmtu
1257 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259 fin->fin_flx |= FI_BAD;
1260 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1261 }
1262 }
1263#endif
1264 /* FALLTHROUGH */
1265 case ICMP_SOURCEQUENCH :
1266 case ICMP_REDIRECT :
1267 case ICMP_TIMXCEED :
1268 case ICMP_PARAMPROB :
1269 fin->fin_flx |= FI_ICMPERR;
1270 if (ipf_coalesce(fin) != 1) {
1271 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1272 return;
1273 }
1274
1275 /*
1276 * ICMP error packets should not be generated for IP
1277 * packets that are a fragment that isn't the first
1278 * fragment.
1279 */
1280 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282 fin->fin_flx |= FI_BAD;
1283 DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1284 }
1285
1286 /*
1287 * If the destination of this packet doesn't match the
1288 * source of the original packet then this packet is
1289 * not correct.
1290 */
1291 if (oip->ip_src.s_addr != fin->fin_daddr) {
1292 fin->fin_flx |= FI_BAD;
1293 DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1294 }
1295 break;
1296 default :
1297 break;
1298 }
1299
1300 ipf_pr_short(fin, minicmpsz);
1301
1302 ipf_checkv4sum(fin);
1303}
1304
1305
1306/* ------------------------------------------------------------------------ */
1307/* Function: ipf_pr_tcpcommon */
1308/* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1309/* Parameters: fin(I) - pointer to packet information */
1310/* */
1311/* TCP header sanity checking. Look for bad combinations of TCP flags, */
1312/* and make some checks with how they interact with other fields. */
1313/* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1314/* valid and mark the packet as bad if not. */
1315/* ------------------------------------------------------------------------ */
1316static INLINE int
1317ipf_pr_tcpcommon(fin)
1318 fr_info_t *fin;
1319{
1320 ipf_main_softc_t *softc = fin->fin_main_soft;
1321 int flags, tlen;
1322 tcphdr_t *tcp;
1323
1324 fin->fin_flx |= FI_TCPUDP;
1325 if (fin->fin_off != 0) {
1326 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1327 return 0;
1328 }
1329
1330 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1332 return -1;
1333 }
1334
1335 tcp = fin->fin_dp;
1336 if (fin->fin_dlen > 3) {
1337 fin->fin_sport = ntohs(tcp->th_sport);
1338 fin->fin_dport = ntohs(tcp->th_dport);
1339 }
1340
1341 if ((fin->fin_flx & FI_SHORT) != 0) {
1342 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1343 return 1;
1344 }
1345
1346 /*
1347 * Use of the TCP data offset *must* result in a value that is at
1348 * least the same size as the TCP header.
1349 */
1350 tlen = TCP_OFF(tcp) << 2;
1351 if (tlen < sizeof(tcphdr_t)) {
1352 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353 fin->fin_flx |= FI_BAD;
1354 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1355 return 1;
1356 }
1357
1358 flags = tcp->th_flags;
1359 fin->fin_tcpf = tcp->th_flags;
1360
1361 /*
1362 * If the urgent flag is set, then the urgent pointer must
1363 * also be set and vice versa. Good TCP packets do not have
1364 * just one of these set.
1365 */
1366 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367 fin->fin_flx |= FI_BAD;
1368 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1369#if 0
1370 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1371 /*
1372 * Ignore this case (#if 0) as it shows up in "real"
1373 * traffic with bogus values in the urgent pointer field.
1374 */
1375 fin->fin_flx |= FI_BAD;
1376 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1377#endif
1378 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381 fin->fin_flx |= FI_BAD;
1382 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1383#if 1
1384 } else if (((flags & TH_SYN) != 0) &&
1385 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1386 /*
1387 * SYN with URG and PUSH set is not for normal TCP but it is
1388 * possible(?) with T/TCP...but who uses T/TCP?
1389 */
1390 fin->fin_flx |= FI_BAD;
1391 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1392#endif
1393 } else if (!(flags & TH_ACK)) {
1394 /*
1395 * If the ack bit isn't set, then either the SYN or
1396 * RST bit must be set. If the SYN bit is set, then
1397 * we expect the ACK field to be 0. If the ACK is
1398 * not set and if URG, PSH or FIN are set, consdier
1399 * that to indicate a bad TCP packet.
1400 */
1401 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1402 /*
1403 * Cisco PIX sets the ACK field to a random value.
1404 * In light of this, do not set FI_BAD until a patch
1405 * is available from Cisco to ensure that
1406 * interoperability between existing systems is
1407 * achieved.
1408 */
1409 /*fin->fin_flx |= FI_BAD*/;
1410 /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411 } else if (!(flags & (TH_RST|TH_SYN))) {
1412 fin->fin_flx |= FI_BAD;
1413 DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415 fin->fin_flx |= FI_BAD;
1416 DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1417 }
1418 }
1419 if (fin->fin_flx & FI_BAD) {
1420 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1421 return 1;
1422 }
1423
1424 /*
1425 * At this point, it's not exactly clear what is to be gained by
1426 * marking up which TCP options are and are not present. The one we
1427 * are most interested in is the TCP window scale. This is only in
1428 * a SYN packet [RFC1323] so we don't need this here...?
1429 * Now if we were to analyse the header for passive fingerprinting,
1430 * then that might add some weight to adding this...
1431 */
1432 if (tlen == sizeof(tcphdr_t)) {
1433 return 0;
1434 }
1435
1436 if (ipf_pr_pullup(fin, tlen) == -1) {
1437 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1438 return -1;
1439 }
1440
1441#if 0
1442 tcp = fin->fin_dp;
1443 ip = fin->fin_ip;
1444 s = (u_char *)(tcp + 1);
1445 off = IP_HL(ip) << 2;
1446# ifdef _KERNEL
1447 if (fin->fin_mp != NULL) {
1448 mb_t *m = *fin->fin_mp;
1449
1450 if (off + tlen > M_LEN(m))
1451 return;
1452 }
1453# endif
1454 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1455 opt = *s;
1456 if (opt == '\0')
1457 break;
1458 else if (opt == TCPOPT_NOP)
1459 ol = 1;
1460 else {
1461 if (tlen < 2)
1462 break;
1463 ol = (int)*(s + 1);
1464 if (ol < 2 || ol > tlen)
1465 break;
1466 }
1467
1468 for (i = 9, mv = 4; mv >= 0; ) {
1469 op = ipopts + i;
1470 if (opt == (u_char)op->ol_val) {
1471 optmsk |= op->ol_bit;
1472 break;
1473 }
1474 }
1475 tlen -= ol;
1476 s += ol;
1477 }
1478#endif /* 0 */
1479
1480 return 0;
1481}
1482
1483
1484
1485/* ------------------------------------------------------------------------ */
1486/* Function: ipf_pr_udpcommon */
1487/* Returns: int - 0 = header ok, 1 = bad packet */
1488/* Parameters: fin(I) - pointer to packet information */
1489/* */
1490/* Extract the UDP source and destination ports, if present. If compiled */
1491/* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1492/* ------------------------------------------------------------------------ */
1493static INLINE int
1494ipf_pr_udpcommon(fin)
1495 fr_info_t *fin;
1496{
1497 udphdr_t *udp;
1498
1499 fin->fin_flx |= FI_TCPUDP;
1500
1501 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503 ipf_main_softc_t *softc = fin->fin_main_soft;
1504
1505 fin->fin_flx |= FI_SHORT;
1506 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1507 return 1;
1508 }
1509
1510 udp = fin->fin_dp;
1511
1512 fin->fin_sport = ntohs(udp->uh_sport);
1513 fin->fin_dport = ntohs(udp->uh_dport);
1514 }
1515
1516 return 0;
1517}
1518
1519
1520/* ------------------------------------------------------------------------ */
1521/* Function: ipf_pr_tcp */
1522/* Returns: void */
1523/* Parameters: fin(I) - pointer to packet information */
1524/* */
1525/* IPv4 Only */
1526/* Analyse the packet for IPv4/TCP properties. */
1527/* ------------------------------------------------------------------------ */
1528static INLINE void
1529ipf_pr_tcp(fin)
1530 fr_info_t *fin;
1531{
1532
1533 ipf_pr_short(fin, sizeof(tcphdr_t));
1534
1535 if (ipf_pr_tcpcommon(fin) == 0)
1536 ipf_checkv4sum(fin);
1537}
1538
1539
1540/* ------------------------------------------------------------------------ */
1541/* Function: ipf_pr_udp */
1542/* Returns: void */
1543/* Parameters: fin(I) - pointer to packet information */
1544/* */
1545/* IPv4 Only */
1546/* Analyse the packet for IPv4/UDP properties. */
1547/* ------------------------------------------------------------------------ */
1548static INLINE void
1549ipf_pr_udp(fin)
1550 fr_info_t *fin;
1551{
1552
1553 ipf_pr_short(fin, sizeof(udphdr_t));
1554
1555 if (ipf_pr_udpcommon(fin) == 0)
1556 ipf_checkv4sum(fin);
1557}
1558
1559
1560/* ------------------------------------------------------------------------ */
1561/* Function: ipf_pr_esp */
1562/* Returns: void */
1563/* Parameters: fin(I) - pointer to packet information */
1564/* */
1565/* Analyse the packet for ESP properties. */
1566/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1567/* even though the newer ESP packets must also have a sequence number that */
1568/* is 32bits as well, it is not possible(?) to determine the version from a */
1569/* simple packet header. */
1570/* ------------------------------------------------------------------------ */
1571static INLINE void
1572ipf_pr_esp(fin)
1573 fr_info_t *fin;
1574{
1575
1576 if (fin->fin_off == 0) {
1577 ipf_pr_short(fin, 8);
1578 if (ipf_pr_pullup(fin, 8) == -1) {
1579 ipf_main_softc_t *softc = fin->fin_main_soft;
1580
1581 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1582 }
1583 }
1584}
1585
1586
1587/* ------------------------------------------------------------------------ */
1588/* Function: ipf_pr_ah */
1589/* Returns: int - value of the next header or IPPROTO_NONE if error */
1590/* Parameters: fin(I) - pointer to packet information */
1591/* */
1592/* Analyse the packet for AH properties. */
1593/* The minimum length is taken to be the combination of all fields in the */
1594/* header being present and no authentication data (null algorithm used.) */
1595/* ------------------------------------------------------------------------ */
1596static INLINE int
1597ipf_pr_ah(fin)
1598 fr_info_t *fin;
1599{
1600 ipf_main_softc_t *softc = fin->fin_main_soft;
1601 authhdr_t *ah;
1602 int len;
1603
1604 fin->fin_flx |= FI_AH;
1605 ipf_pr_short(fin, sizeof(*ah));
1606
1607 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609 return IPPROTO_NONE;
1610 }
1611
1612 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613 DT(fr_v4_ah_pullup_1);
1614 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615 return IPPROTO_NONE;
1616 }
1617
1618 ah = (authhdr_t *)fin->fin_dp;
1619
1620 len = (ah->ah_plen + 2) << 2;
1621 ipf_pr_short(fin, len);
1622 if (ipf_pr_pullup(fin, len) == -1) {
1623 DT(fr_v4_ah_pullup_2);
1624 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625 return IPPROTO_NONE;
1626 }
1627
1628 /*
1629 * Adjust fin_dp and fin_dlen for skipping over the authentication
1630 * header.
1631 */
1632 fin->fin_dp = (char *)fin->fin_dp + len;
1633 fin->fin_dlen -= len;
1634 return ah->ah_next;
1635}
1636
1637
1638/* ------------------------------------------------------------------------ */
1639/* Function: ipf_pr_gre */
1640/* Returns: void */
1641/* Parameters: fin(I) - pointer to packet information */
1642/* */
1643/* Analyse the packet for GRE properties. */
1644/* ------------------------------------------------------------------------ */
1645static INLINE void
1646ipf_pr_gre(fin)
1647 fr_info_t *fin;
1648{
1649 ipf_main_softc_t *softc = fin->fin_main_soft;
1650 grehdr_t *gre;
1651
1652 ipf_pr_short(fin, sizeof(grehdr_t));
1653
1654 if (fin->fin_off != 0) {
1655 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1656 return;
1657 }
1658
1659 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1661 return;
1662 }
1663
1664 gre = fin->fin_dp;
1665 if (GRE_REV(gre->gr_flags) == 1)
1666 fin->fin_data[0] = gre->gr_call;
1667}
1668
1669
1670/* ------------------------------------------------------------------------ */
1671/* Function: ipf_pr_ipv4hdr */
1672/* Returns: void */
1673/* Parameters: fin(I) - pointer to packet information */
1674/* */
1675/* IPv4 Only */
1676/* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1677/* Check all options present and flag their presence if any exist. */
1678/* ------------------------------------------------------------------------ */
1679static INLINE void
1680ipf_pr_ipv4hdr(fin)
1681 fr_info_t *fin;
1682{
1683 u_short optmsk = 0, secmsk = 0, auth = 0;
1684 int hlen, ol, mv, p, i;
1685 const struct optlist *op;
1686 u_char *s, opt;
1687 u_short off;
1688 fr_ip_t *fi;
1689 ip_t *ip;
1690
1691 fi = &fin->fin_fi;
1692 hlen = fin->fin_hlen;
1693
1694 ip = fin->fin_ip;
1695 p = ip->ip_p;
1696 fi->fi_p = p;
1697 fin->fin_crc = p;
1698 fi->fi_tos = ip->ip_tos;
120#define LBUMP(x) softc->x++
121#define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
122
123static INLINE int ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
124static u_32_t ipf_checkcipso __P((fr_info_t *, u_char *, int));
125static u_32_t ipf_checkripso __P((u_char *));
126static u_32_t ipf_decaps __P((fr_info_t *, u_32_t, int));
127#ifdef IPFILTER_LOG
128static frentry_t *ipf_dolog __P((fr_info_t *, u_32_t *));
129#endif
130static int ipf_flushlist __P((ipf_main_softc_t *, int *,
131 frentry_t **));
132static int ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
133 int));
134static ipfunc_t ipf_findfunc __P((ipfunc_t));
135static void *ipf_findlookup __P((ipf_main_softc_t *, int,
136 frentry_t *,
137 i6addr_t *, i6addr_t *));
138static frentry_t *ipf_firewall __P((fr_info_t *, u_32_t *));
139static int ipf_fr_matcharray __P((fr_info_t *, int *));
140static int ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
141 void *));
142static void ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
143static int ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
144static int ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
145 ipfgeniter_t *));
146static void ipf_getstat __P((ipf_main_softc_t *,
147 struct friostat *, int));
148static int ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
149static void ipf_group_free __P((frgroup_t *));
150static int ipf_grpmapfini __P((struct ipf_main_softc_s *,
151 frentry_t *));
152static int ipf_grpmapinit __P((struct ipf_main_softc_s *,
153 frentry_t *));
154static frentry_t *ipf_nextrule __P((ipf_main_softc_t *, int, int,
155 frentry_t *, int));
156static int ipf_portcheck __P((frpcmp_t *, u_32_t));
157static INLINE int ipf_pr_ah __P((fr_info_t *));
158static INLINE void ipf_pr_esp __P((fr_info_t *));
159static INLINE void ipf_pr_gre __P((fr_info_t *));
160static INLINE void ipf_pr_udp __P((fr_info_t *));
161static INLINE void ipf_pr_tcp __P((fr_info_t *));
162static INLINE void ipf_pr_icmp __P((fr_info_t *));
163static INLINE void ipf_pr_ipv4hdr __P((fr_info_t *));
164static INLINE void ipf_pr_short __P((fr_info_t *, int));
165static INLINE int ipf_pr_tcpcommon __P((fr_info_t *));
166static INLINE int ipf_pr_udpcommon __P((fr_info_t *));
167static void ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
168 int, int));
169static void ipf_rule_expire_insert __P((ipf_main_softc_t *,
170 frentry_t *, int));
171static int ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
172 void *));
173static void ipf_token_flush __P((ipf_main_softc_t *));
174static void ipf_token_unlink __P((ipf_main_softc_t *,
175 ipftoken_t *));
176static ipftuneable_t *ipf_tune_findbyname __P((ipftuneable_t *,
177 const char *));
178static ipftuneable_t *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
179 void **));
180static int ipf_updateipid __P((fr_info_t *));
181static int ipf_settimeout __P((struct ipf_main_softc_s *,
182 struct ipftuneable *,
183 ipftuneval_t *));
184#if !defined(_KERNEL) || SOLARIS
185static int ppsratecheck(struct timeval *, int *, int);
186#endif
187
188
189/*
190 * bit values for identifying presence of individual IP options
191 * All of these tables should be ordered by increasing key value on the left
192 * hand side to allow for binary searching of the array and include a trailer
193 * with a 0 for the bitmask for linear searches to easily find the end with.
194 */
195static const struct optlist ipopts[] = {
196 { IPOPT_NOP, 0x000001 },
197 { IPOPT_RR, 0x000002 },
198 { IPOPT_ZSU, 0x000004 },
199 { IPOPT_MTUP, 0x000008 },
200 { IPOPT_MTUR, 0x000010 },
201 { IPOPT_ENCODE, 0x000020 },
202 { IPOPT_TS, 0x000040 },
203 { IPOPT_TR, 0x000080 },
204 { IPOPT_SECURITY, 0x000100 },
205 { IPOPT_LSRR, 0x000200 },
206 { IPOPT_E_SEC, 0x000400 },
207 { IPOPT_CIPSO, 0x000800 },
208 { IPOPT_SATID, 0x001000 },
209 { IPOPT_SSRR, 0x002000 },
210 { IPOPT_ADDEXT, 0x004000 },
211 { IPOPT_VISA, 0x008000 },
212 { IPOPT_IMITD, 0x010000 },
213 { IPOPT_EIP, 0x020000 },
214 { IPOPT_FINN, 0x040000 },
215 { 0, 0x000000 }
216};
217
218#ifdef USE_INET6
219static const struct optlist ip6exthdr[] = {
220 { IPPROTO_HOPOPTS, 0x000001 },
221 { IPPROTO_IPV6, 0x000002 },
222 { IPPROTO_ROUTING, 0x000004 },
223 { IPPROTO_FRAGMENT, 0x000008 },
224 { IPPROTO_ESP, 0x000010 },
225 { IPPROTO_AH, 0x000020 },
226 { IPPROTO_NONE, 0x000040 },
227 { IPPROTO_DSTOPTS, 0x000080 },
228 { IPPROTO_MOBILITY, 0x000100 },
229 { 0, 0 }
230};
231#endif
232
233/*
234 * bit values for identifying presence of individual IP security options
235 */
236static const struct optlist secopt[] = {
237 { IPSO_CLASS_RES4, 0x01 },
238 { IPSO_CLASS_TOPS, 0x02 },
239 { IPSO_CLASS_SECR, 0x04 },
240 { IPSO_CLASS_RES3, 0x08 },
241 { IPSO_CLASS_CONF, 0x10 },
242 { IPSO_CLASS_UNCL, 0x20 },
243 { IPSO_CLASS_RES2, 0x40 },
244 { IPSO_CLASS_RES1, 0x80 }
245};
246
247char ipfilter_version[] = IPL_VERSION;
248
249int ipf_features = 0
250#ifdef IPFILTER_LKM
251 | IPF_FEAT_LKM
252#endif
253#ifdef IPFILTER_LOG
254 | IPF_FEAT_LOG
255#endif
256 | IPF_FEAT_LOOKUP
257#ifdef IPFILTER_BPF
258 | IPF_FEAT_BPF
259#endif
260#ifdef IPFILTER_COMPILED
261 | IPF_FEAT_COMPILED
262#endif
263#ifdef IPFILTER_CKSUM
264 | IPF_FEAT_CKSUM
265#endif
266 | IPF_FEAT_SYNC
267#ifdef IPFILTER_SCAN
268 | IPF_FEAT_SCAN
269#endif
270#ifdef USE_INET6
271 | IPF_FEAT_IPV6
272#endif
273 ;
274
275
276/*
277 * Table of functions available for use with call rules.
278 */
279static ipfunc_resolve_t ipf_availfuncs[] = {
280 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
281 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
282 { "", NULL, NULL, NULL }
283};
284
285static ipftuneable_t ipf_main_tuneables[] = {
286 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
287 "ipf_flags", 0, 0xffffffff,
288 stsizeof(ipf_main_softc_t, ipf_flags),
289 0, NULL, NULL },
290 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
291 "active", 0, 0,
292 stsizeof(ipf_main_softc_t, ipf_active),
293 IPFT_RDONLY, NULL, NULL },
294 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
295 "control_forwarding", 0, 1,
296 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
297 0, NULL, NULL },
298 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
299 "update_ipid", 0, 1,
300 stsizeof(ipf_main_softc_t, ipf_update_ipid),
301 0, NULL, NULL },
302 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
303 "chksrc", 0, 1,
304 stsizeof(ipf_main_softc_t, ipf_chksrc),
305 0, NULL, NULL },
306 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
307 "min_ttl", 0, 1,
308 stsizeof(ipf_main_softc_t, ipf_minttl),
309 0, NULL, NULL },
310 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
311 "icmp_minfragmtu", 0, 1,
312 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
313 0, NULL, NULL },
314 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
315 "default_pass", 0, 0xffffffff,
316 stsizeof(ipf_main_softc_t, ipf_pass),
317 0, NULL, NULL },
318 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
319 "tcp_idle_timeout", 1, 0x7fffffff,
320 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
321 0, NULL, ipf_settimeout },
322 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
323 "tcp_close_wait", 1, 0x7fffffff,
324 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
325 0, NULL, ipf_settimeout },
326 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
327 "tcp_last_ack", 1, 0x7fffffff,
328 stsizeof(ipf_main_softc_t, ipf_tcplastack),
329 0, NULL, ipf_settimeout },
330 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
331 "tcp_timeout", 1, 0x7fffffff,
332 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
333 0, NULL, ipf_settimeout },
334 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
335 "tcp_syn_sent", 1, 0x7fffffff,
336 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
337 0, NULL, ipf_settimeout },
338 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
339 "tcp_syn_received", 1, 0x7fffffff,
340 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
341 0, NULL, ipf_settimeout },
342 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
343 "tcp_closed", 1, 0x7fffffff,
344 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
345 0, NULL, ipf_settimeout },
346 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
347 "tcp_half_closed", 1, 0x7fffffff,
348 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
349 0, NULL, ipf_settimeout },
350 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
351 "tcp_time_wait", 1, 0x7fffffff,
352 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
353 0, NULL, ipf_settimeout },
354 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
355 "udp_timeout", 1, 0x7fffffff,
356 stsizeof(ipf_main_softc_t, ipf_udptimeout),
357 0, NULL, ipf_settimeout },
358 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
359 "udp_ack_timeout", 1, 0x7fffffff,
360 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
361 0, NULL, ipf_settimeout },
362 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
363 "icmp_timeout", 1, 0x7fffffff,
364 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
365 0, NULL, ipf_settimeout },
366 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
367 "icmp_ack_timeout", 1, 0x7fffffff,
368 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
369 0, NULL, ipf_settimeout },
370 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
371 "ip_timeout", 1, 0x7fffffff,
372 stsizeof(ipf_main_softc_t, ipf_iptimeout),
373 0, NULL, ipf_settimeout },
374#if defined(INSTANCES) && defined(_KERNEL)
375 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
376 "intercept_loopback", 0, 1,
377 stsizeof(ipf_main_softc_t, ipf_get_loopback),
378 0, NULL, ipf_set_loopback },
379#endif
380 { { 0 },
381 NULL, 0, 0,
382 0,
383 0, NULL, NULL }
384};
385
386
387/*
388 * The next section of code is a collection of small routines that set
389 * fields in the fr_info_t structure passed based on properties of the
390 * current packet. There are different routines for the same protocol
391 * for each of IPv4 and IPv6. Adding a new protocol, for which there
392 * will "special" inspection for setup, is now more easily done by adding
393 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
394 * adding more code to a growing switch statement.
395 */
396#ifdef USE_INET6
397static INLINE int ipf_pr_ah6 __P((fr_info_t *));
398static INLINE void ipf_pr_esp6 __P((fr_info_t *));
399static INLINE void ipf_pr_gre6 __P((fr_info_t *));
400static INLINE void ipf_pr_udp6 __P((fr_info_t *));
401static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
402static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
403static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
404static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
405static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
406static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
407static INLINE int ipf_pr_routing6 __P((fr_info_t *));
408static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
409static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
410static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
411
412
413/* ------------------------------------------------------------------------ */
414/* Function: ipf_pr_short6 */
415/* Returns: void */
416/* Parameters: fin(I) - pointer to packet information */
417/* xmin(I) - minimum header size */
418/* */
419/* IPv6 Only */
420/* This is function enforces the 'is a packet too short to be legit' rule */
421/* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
422/* for ipf_pr_short() for more details. */
423/* ------------------------------------------------------------------------ */
424static INLINE void
425ipf_pr_short6(fin, xmin)
426 fr_info_t *fin;
427 int xmin;
428{
429
430 if (fin->fin_dlen < xmin)
431 fin->fin_flx |= FI_SHORT;
432}
433
434
435/* ------------------------------------------------------------------------ */
436/* Function: ipf_pr_ipv6hdr */
437/* Returns: void */
438/* Parameters: fin(I) - pointer to packet information */
439/* */
440/* IPv6 Only */
441/* Copy values from the IPv6 header into the fr_info_t struct and call the */
442/* per-protocol analyzer if it exists. In validating the packet, a protocol*/
443/* analyzer may pullup or free the packet itself so we need to be vigiliant */
444/* of that possibility arising. */
445/* ------------------------------------------------------------------------ */
446static INLINE void
447ipf_pr_ipv6hdr(fin)
448 fr_info_t *fin;
449{
450 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
451 int p, go = 1, i, hdrcount;
452 fr_ip_t *fi = &fin->fin_fi;
453
454 fin->fin_off = 0;
455
456 fi->fi_tos = 0;
457 fi->fi_optmsk = 0;
458 fi->fi_secmsk = 0;
459 fi->fi_auth = 0;
460
461 p = ip6->ip6_nxt;
462 fin->fin_crc = p;
463 fi->fi_ttl = ip6->ip6_hlim;
464 fi->fi_src.in6 = ip6->ip6_src;
465 fin->fin_crc += fi->fi_src.i6[0];
466 fin->fin_crc += fi->fi_src.i6[1];
467 fin->fin_crc += fi->fi_src.i6[2];
468 fin->fin_crc += fi->fi_src.i6[3];
469 fi->fi_dst.in6 = ip6->ip6_dst;
470 fin->fin_crc += fi->fi_dst.i6[0];
471 fin->fin_crc += fi->fi_dst.i6[1];
472 fin->fin_crc += fi->fi_dst.i6[2];
473 fin->fin_crc += fi->fi_dst.i6[3];
474 fin->fin_id = 0;
475 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
476 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
477
478 hdrcount = 0;
479 while (go && !(fin->fin_flx & FI_SHORT)) {
480 switch (p)
481 {
482 case IPPROTO_UDP :
483 ipf_pr_udp6(fin);
484 go = 0;
485 break;
486
487 case IPPROTO_TCP :
488 ipf_pr_tcp6(fin);
489 go = 0;
490 break;
491
492 case IPPROTO_ICMPV6 :
493 ipf_pr_icmp6(fin);
494 go = 0;
495 break;
496
497 case IPPROTO_GRE :
498 ipf_pr_gre6(fin);
499 go = 0;
500 break;
501
502 case IPPROTO_HOPOPTS :
503 p = ipf_pr_hopopts6(fin);
504 break;
505
506 case IPPROTO_MOBILITY :
507 p = ipf_pr_mobility6(fin);
508 break;
509
510 case IPPROTO_DSTOPTS :
511 p = ipf_pr_dstopts6(fin);
512 break;
513
514 case IPPROTO_ROUTING :
515 p = ipf_pr_routing6(fin);
516 break;
517
518 case IPPROTO_AH :
519 p = ipf_pr_ah6(fin);
520 break;
521
522 case IPPROTO_ESP :
523 ipf_pr_esp6(fin);
524 go = 0;
525 break;
526
527 case IPPROTO_IPV6 :
528 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
529 if (ip6exthdr[i].ol_val == p) {
530 fin->fin_flx |= ip6exthdr[i].ol_bit;
531 break;
532 }
533 go = 0;
534 break;
535
536 case IPPROTO_NONE :
537 go = 0;
538 break;
539
540 case IPPROTO_FRAGMENT :
541 p = ipf_pr_fragment6(fin);
542 /*
543 * Given that the only fragments we want to let through
544 * (where fin_off != 0) are those where the non-first
545 * fragments only have data, we can safely stop looking
546 * at headers if this is a non-leading fragment.
547 */
548 if (fin->fin_off != 0)
549 go = 0;
550 break;
551
552 default :
553 go = 0;
554 break;
555 }
556 hdrcount++;
557
558 /*
559 * It is important to note that at this point, for the
560 * extension headers (go != 0), the entire header may not have
561 * been pulled up when the code gets to this point. This is
562 * only done for "go != 0" because the other header handlers
563 * will all pullup their complete header. The other indicator
564 * of an incomplete packet is that this was just an extension
565 * header.
566 */
567 if ((go != 0) && (p != IPPROTO_NONE) &&
568 (ipf_pr_pullup(fin, 0) == -1)) {
569 p = IPPROTO_NONE;
570 break;
571 }
572 }
573
574 /*
575 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
576 * and destroy whatever packet was here. The caller of this function
577 * expects us to return if there is a problem with ipf_pullup.
578 */
579 if (fin->fin_m == NULL) {
580 ipf_main_softc_t *softc = fin->fin_main_soft;
581
582 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
583 return;
584 }
585
586 fi->fi_p = p;
587
588 /*
589 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
590 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
591 */
592 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
593 ipf_main_softc_t *softc = fin->fin_main_soft;
594
595 fin->fin_flx |= FI_BAD;
596 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
597 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
598 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
599 }
600}
601
602
603/* ------------------------------------------------------------------------ */
604/* Function: ipf_pr_ipv6exthdr */
605/* Returns: struct ip6_ext * - pointer to the start of the next header */
606/* or NULL if there is a prolblem. */
607/* Parameters: fin(I) - pointer to packet information */
608/* multiple(I) - flag indicating yes/no if multiple occurances */
609/* of this extension header are allowed. */
610/* proto(I) - protocol number for this extension header */
611/* */
612/* IPv6 Only */
613/* This function embodies a number of common checks that all IPv6 extension */
614/* headers must be subjected to. For example, making sure the packet is */
615/* big enough for it to be in, checking if it is repeated and setting a */
616/* flag to indicate its presence. */
617/* ------------------------------------------------------------------------ */
618static INLINE struct ip6_ext *
619ipf_pr_ipv6exthdr(fin, multiple, proto)
620 fr_info_t *fin;
621 int multiple, proto;
622{
623 ipf_main_softc_t *softc = fin->fin_main_soft;
624 struct ip6_ext *hdr;
625 u_short shift;
626 int i;
627
628 fin->fin_flx |= FI_V6EXTHDR;
629
630 /* 8 is default length of extension hdr */
631 if ((fin->fin_dlen - 8) < 0) {
632 fin->fin_flx |= FI_SHORT;
633 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
634 return NULL;
635 }
636
637 if (ipf_pr_pullup(fin, 8) == -1) {
638 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
639 return NULL;
640 }
641
642 hdr = fin->fin_dp;
643 switch (proto)
644 {
645 case IPPROTO_FRAGMENT :
646 shift = 8;
647 break;
648 default :
649 shift = 8 + (hdr->ip6e_len << 3);
650 break;
651 }
652
653 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
654 fin->fin_flx |= FI_BAD;
655 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
656 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
657 return NULL;
658 }
659
660 fin->fin_dp = (char *)fin->fin_dp + shift;
661 fin->fin_dlen -= shift;
662
663 /*
664 * If we have seen a fragment header, do not set any flags to indicate
665 * the presence of this extension header as it has no impact on the
666 * end result until after it has been defragmented.
667 */
668 if (fin->fin_flx & FI_FRAG)
669 return hdr;
670
671 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
672 if (ip6exthdr[i].ol_val == proto) {
673 /*
674 * Most IPv6 extension headers are only allowed once.
675 */
676 if ((multiple == 0) &&
677 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
678 fin->fin_flx |= FI_BAD;
679 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
680 } else
681 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
682 break;
683 }
684
685 return hdr;
686}
687
688
689/* ------------------------------------------------------------------------ */
690/* Function: ipf_pr_hopopts6 */
691/* Returns: int - value of the next header or IPPROTO_NONE if error */
692/* Parameters: fin(I) - pointer to packet information */
693/* */
694/* IPv6 Only */
695/* This is function checks pending hop by hop options extension header */
696/* ------------------------------------------------------------------------ */
697static INLINE int
698ipf_pr_hopopts6(fin)
699 fr_info_t *fin;
700{
701 struct ip6_ext *hdr;
702
703 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
704 if (hdr == NULL)
705 return IPPROTO_NONE;
706 return hdr->ip6e_nxt;
707}
708
709
710/* ------------------------------------------------------------------------ */
711/* Function: ipf_pr_mobility6 */
712/* Returns: int - value of the next header or IPPROTO_NONE if error */
713/* Parameters: fin(I) - pointer to packet information */
714/* */
715/* IPv6 Only */
716/* This is function checks the IPv6 mobility extension header */
717/* ------------------------------------------------------------------------ */
718static INLINE int
719ipf_pr_mobility6(fin)
720 fr_info_t *fin;
721{
722 struct ip6_ext *hdr;
723
724 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
725 if (hdr == NULL)
726 return IPPROTO_NONE;
727 return hdr->ip6e_nxt;
728}
729
730
731/* ------------------------------------------------------------------------ */
732/* Function: ipf_pr_routing6 */
733/* Returns: int - value of the next header or IPPROTO_NONE if error */
734/* Parameters: fin(I) - pointer to packet information */
735/* */
736/* IPv6 Only */
737/* This is function checks pending routing extension header */
738/* ------------------------------------------------------------------------ */
739static INLINE int
740ipf_pr_routing6(fin)
741 fr_info_t *fin;
742{
743 struct ip6_routing *hdr;
744
745 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
746 if (hdr == NULL)
747 return IPPROTO_NONE;
748
749 switch (hdr->ip6r_type)
750 {
751 case 0 :
752 /*
753 * Nasty extension header length?
754 */
755 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
756 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
757 ipf_main_softc_t *softc = fin->fin_main_soft;
758
759 fin->fin_flx |= FI_BAD;
760 DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
761 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
762 return IPPROTO_NONE;
763 }
764 break;
765
766 default :
767 break;
768 }
769
770 return hdr->ip6r_nxt;
771}
772
773
774/* ------------------------------------------------------------------------ */
775/* Function: ipf_pr_fragment6 */
776/* Returns: int - value of the next header or IPPROTO_NONE if error */
777/* Parameters: fin(I) - pointer to packet information */
778/* */
779/* IPv6 Only */
780/* Examine the IPv6 fragment header and extract fragment offset information.*/
781/* */
782/* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
783/* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
784/* packets with a fragment header can fit into. They are as follows: */
785/* */
786/* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
787/* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
788/* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
789/* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
790/* 5. [IPV6][0-n EH][FH][data] */
791/* */
792/* IPV6 = IPv6 header, FH = Fragment Header, */
793/* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
794/* */
795/* Packets that match 1, 2, 3 will be dropped as the only reasonable */
796/* scenario in which they happen is in extreme circumstances that are most */
797/* likely to be an indication of an attack rather than normal traffic. */
798/* A type 3 packet may be sent by an attacked after a type 4 packet. There */
799/* are two rules that can be used to guard against type 3 packets: L4 */
800/* headers must always be in a packet that has the offset field set to 0 */
801/* and no packet is allowed to overlay that where offset = 0. */
802/* ------------------------------------------------------------------------ */
803static INLINE int
804ipf_pr_fragment6(fin)
805 fr_info_t *fin;
806{
807 ipf_main_softc_t *softc = fin->fin_main_soft;
808 struct ip6_frag *frag;
809
810 fin->fin_flx |= FI_FRAG;
811
812 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
813 if (frag == NULL) {
814 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
815 return IPPROTO_NONE;
816 }
817
818 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
819 /*
820 * Any fragment that isn't the last fragment must have its
821 * length as a multiple of 8.
822 */
823 if ((fin->fin_plen & 7) != 0) {
824 fin->fin_flx |= FI_BAD;
825 DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
826 }
827 }
828
829 fin->fin_fraghdr = frag;
830 fin->fin_id = frag->ip6f_ident;
831 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
832 if (fin->fin_off != 0)
833 fin->fin_flx |= FI_FRAGBODY;
834
835 /*
836 * Jumbograms aren't handled, so the max. length is 64k
837 */
838 if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
839 fin->fin_flx |= FI_BAD;
840 DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
841 }
842
843 /*
844 * We don't know where the transport layer header (or whatever is next
845 * is), as it could be behind destination options (amongst others) so
846 * return the fragment header as the type of packet this is. Note that
847 * this effectively disables the fragment cache for > 1 protocol at a
848 * time.
849 */
850 return frag->ip6f_nxt;
851}
852
853
854/* ------------------------------------------------------------------------ */
855/* Function: ipf_pr_dstopts6 */
856/* Returns: int - value of the next header or IPPROTO_NONE if error */
857/* Parameters: fin(I) - pointer to packet information */
858/* */
859/* IPv6 Only */
860/* This is function checks pending destination options extension header */
861/* ------------------------------------------------------------------------ */
862static INLINE int
863ipf_pr_dstopts6(fin)
864 fr_info_t *fin;
865{
866 ipf_main_softc_t *softc = fin->fin_main_soft;
867 struct ip6_ext *hdr;
868
869 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
870 if (hdr == NULL) {
871 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
872 return IPPROTO_NONE;
873 }
874 return hdr->ip6e_nxt;
875}
876
877
878/* ------------------------------------------------------------------------ */
879/* Function: ipf_pr_icmp6 */
880/* Returns: void */
881/* Parameters: fin(I) - pointer to packet information */
882/* */
883/* IPv6 Only */
884/* This routine is mainly concerned with determining the minimum valid size */
885/* for an ICMPv6 packet. */
886/* ------------------------------------------------------------------------ */
887static INLINE void
888ipf_pr_icmp6(fin)
889 fr_info_t *fin;
890{
891 int minicmpsz = sizeof(struct icmp6_hdr);
892 struct icmp6_hdr *icmp6;
893
894 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
895 ipf_main_softc_t *softc = fin->fin_main_soft;
896
897 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
898 return;
899 }
900
901 if (fin->fin_dlen > 1) {
902 ip6_t *ip6;
903
904 icmp6 = fin->fin_dp;
905
906 fin->fin_data[0] = *(u_short *)icmp6;
907
908 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
909 fin->fin_flx |= FI_ICMPQUERY;
910
911 switch (icmp6->icmp6_type)
912 {
913 case ICMP6_ECHO_REPLY :
914 case ICMP6_ECHO_REQUEST :
915 if (fin->fin_dlen >= 6)
916 fin->fin_data[1] = icmp6->icmp6_id;
917 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
918 break;
919
920 case ICMP6_DST_UNREACH :
921 case ICMP6_PACKET_TOO_BIG :
922 case ICMP6_TIME_EXCEEDED :
923 case ICMP6_PARAM_PROB :
924 fin->fin_flx |= FI_ICMPERR;
925 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
926 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
927 break;
928
929 if (M_LEN(fin->fin_m) < fin->fin_plen) {
930 if (ipf_coalesce(fin) != 1)
931 return;
932 }
933
934 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
935 return;
936
937 /*
938 * If the destination of this packet doesn't match the
939 * source of the original packet then this packet is
940 * not correct.
941 */
942 icmp6 = fin->fin_dp;
943 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
944 if (IP6_NEQ(&fin->fin_fi.fi_dst,
945 (i6addr_t *)&ip6->ip6_src)) {
946 fin->fin_flx |= FI_BAD;
947 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
948 }
949 break;
950 default :
951 break;
952 }
953 }
954
955 ipf_pr_short6(fin, minicmpsz);
956 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
957 u_char p = fin->fin_p;
958
959 fin->fin_p = IPPROTO_ICMPV6;
960 ipf_checkv6sum(fin);
961 fin->fin_p = p;
962 }
963}
964
965
966/* ------------------------------------------------------------------------ */
967/* Function: ipf_pr_udp6 */
968/* Returns: void */
969/* Parameters: fin(I) - pointer to packet information */
970/* */
971/* IPv6 Only */
972/* Analyse the packet for IPv6/UDP properties. */
973/* Is not expected to be called for fragmented packets. */
974/* ------------------------------------------------------------------------ */
975static INLINE void
976ipf_pr_udp6(fin)
977 fr_info_t *fin;
978{
979
980 if (ipf_pr_udpcommon(fin) == 0) {
981 u_char p = fin->fin_p;
982
983 fin->fin_p = IPPROTO_UDP;
984 ipf_checkv6sum(fin);
985 fin->fin_p = p;
986 }
987}
988
989
990/* ------------------------------------------------------------------------ */
991/* Function: ipf_pr_tcp6 */
992/* Returns: void */
993/* Parameters: fin(I) - pointer to packet information */
994/* */
995/* IPv6 Only */
996/* Analyse the packet for IPv6/TCP properties. */
997/* Is not expected to be called for fragmented packets. */
998/* ------------------------------------------------------------------------ */
999static INLINE void
1000ipf_pr_tcp6(fin)
1001 fr_info_t *fin;
1002{
1003
1004 if (ipf_pr_tcpcommon(fin) == 0) {
1005 u_char p = fin->fin_p;
1006
1007 fin->fin_p = IPPROTO_TCP;
1008 ipf_checkv6sum(fin);
1009 fin->fin_p = p;
1010 }
1011}
1012
1013
1014/* ------------------------------------------------------------------------ */
1015/* Function: ipf_pr_esp6 */
1016/* Returns: void */
1017/* Parameters: fin(I) - pointer to packet information */
1018/* */
1019/* IPv6 Only */
1020/* Analyse the packet for ESP properties. */
1021/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1022/* even though the newer ESP packets must also have a sequence number that */
1023/* is 32bits as well, it is not possible(?) to determine the version from a */
1024/* simple packet header. */
1025/* ------------------------------------------------------------------------ */
1026static INLINE void
1027ipf_pr_esp6(fin)
1028 fr_info_t *fin;
1029{
1030
1031 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1032 ipf_main_softc_t *softc = fin->fin_main_soft;
1033
1034 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1035 return;
1036 }
1037}
1038
1039
1040/* ------------------------------------------------------------------------ */
1041/* Function: ipf_pr_ah6 */
1042/* Returns: int - value of the next header or IPPROTO_NONE if error */
1043/* Parameters: fin(I) - pointer to packet information */
1044/* */
1045/* IPv6 Only */
1046/* Analyse the packet for AH properties. */
1047/* The minimum length is taken to be the combination of all fields in the */
1048/* header being present and no authentication data (null algorithm used.) */
1049/* ------------------------------------------------------------------------ */
1050static INLINE int
1051ipf_pr_ah6(fin)
1052 fr_info_t *fin;
1053{
1054 authhdr_t *ah;
1055
1056 fin->fin_flx |= FI_AH;
1057
1058 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1059 if (ah == NULL) {
1060 ipf_main_softc_t *softc = fin->fin_main_soft;
1061
1062 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1063 return IPPROTO_NONE;
1064 }
1065
1066 ipf_pr_short6(fin, sizeof(*ah));
1067
1068 /*
1069 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1070 * enough data to satisfy ah_next (the very first one.)
1071 */
1072 return ah->ah_next;
1073}
1074
1075
1076/* ------------------------------------------------------------------------ */
1077/* Function: ipf_pr_gre6 */
1078/* Returns: void */
1079/* Parameters: fin(I) - pointer to packet information */
1080/* */
1081/* Analyse the packet for GRE properties. */
1082/* ------------------------------------------------------------------------ */
1083static INLINE void
1084ipf_pr_gre6(fin)
1085 fr_info_t *fin;
1086{
1087 grehdr_t *gre;
1088
1089 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1090 ipf_main_softc_t *softc = fin->fin_main_soft;
1091
1092 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1093 return;
1094 }
1095
1096 gre = fin->fin_dp;
1097 if (GRE_REV(gre->gr_flags) == 1)
1098 fin->fin_data[0] = gre->gr_call;
1099}
1100#endif /* USE_INET6 */
1101
1102
1103/* ------------------------------------------------------------------------ */
1104/* Function: ipf_pr_pullup */
1105/* Returns: int - 0 == pullup succeeded, -1 == failure */
1106/* Parameters: fin(I) - pointer to packet information */
1107/* plen(I) - length (excluding L3 header) to pullup */
1108/* */
1109/* Short inline function to cut down on code duplication to perform a call */
1110/* to ipf_pullup to ensure there is the required amount of data, */
1111/* consecutively in the packet buffer. */
1112/* */
1113/* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1114/* points to the first byte after the complete layer 3 header, which will */
1115/* include all of the known extension headers for IPv6 or options for IPv4. */
1116/* */
1117/* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1118/* is necessary to add those we can already assume to be pulled up (fin_dp */
1119/* - fin_ip) to what is passed through. */
1120/* ------------------------------------------------------------------------ */
1121int
1122ipf_pr_pullup(fin, plen)
1123 fr_info_t *fin;
1124 int plen;
1125{
1126 ipf_main_softc_t *softc = fin->fin_main_soft;
1127
1128 if (fin->fin_m != NULL) {
1129 if (fin->fin_dp != NULL)
1130 plen += (char *)fin->fin_dp -
1131 ((char *)fin->fin_ip + fin->fin_hlen);
1132 plen += fin->fin_hlen;
1133 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1134#if defined(_KERNEL)
1135 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1136 DT(ipf_pullup_fail);
1137 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1138 return -1;
1139 }
1140 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1141#else
1142 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1143 /*
1144 * Fake ipf_pullup failing
1145 */
1146 fin->fin_reason = FRB_PULLUP;
1147 *fin->fin_mp = NULL;
1148 fin->fin_m = NULL;
1149 fin->fin_ip = NULL;
1150 return -1;
1151#endif
1152 }
1153 }
1154 return 0;
1155}
1156
1157
1158/* ------------------------------------------------------------------------ */
1159/* Function: ipf_pr_short */
1160/* Returns: void */
1161/* Parameters: fin(I) - pointer to packet information */
1162/* xmin(I) - minimum header size */
1163/* */
1164/* Check if a packet is "short" as defined by xmin. The rule we are */
1165/* applying here is that the packet must not be fragmented within the layer */
1166/* 4 header. That is, it must not be a fragment that has its offset set to */
1167/* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1168/* entire layer 4 header must be present (min). */
1169/* ------------------------------------------------------------------------ */
1170static INLINE void
1171ipf_pr_short(fin, xmin)
1172 fr_info_t *fin;
1173 int xmin;
1174{
1175
1176 if (fin->fin_off == 0) {
1177 if (fin->fin_dlen < xmin)
1178 fin->fin_flx |= FI_SHORT;
1179 } else if (fin->fin_off < xmin) {
1180 fin->fin_flx |= FI_SHORT;
1181 }
1182}
1183
1184
1185/* ------------------------------------------------------------------------ */
1186/* Function: ipf_pr_icmp */
1187/* Returns: void */
1188/* Parameters: fin(I) - pointer to packet information */
1189/* */
1190/* IPv4 Only */
1191/* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1192/* except extrememly bad packets, both type and code will be present. */
1193/* The expected minimum size of an ICMP packet is very much dependent on */
1194/* the type of it. */
1195/* */
1196/* XXX - other ICMP sanity checks? */
1197/* ------------------------------------------------------------------------ */
1198static INLINE void
1199ipf_pr_icmp(fin)
1200 fr_info_t *fin;
1201{
1202 ipf_main_softc_t *softc = fin->fin_main_soft;
1203 int minicmpsz = sizeof(struct icmp);
1204 icmphdr_t *icmp;
1205 ip_t *oip;
1206
1207 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1208
1209 if (fin->fin_off != 0) {
1210 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1211 return;
1212 }
1213
1214 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1215 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1216 return;
1217 }
1218
1219 icmp = fin->fin_dp;
1220
1221 fin->fin_data[0] = *(u_short *)icmp;
1222 fin->fin_data[1] = icmp->icmp_id;
1223
1224 switch (icmp->icmp_type)
1225 {
1226 case ICMP_ECHOREPLY :
1227 case ICMP_ECHO :
1228 /* Router discovery messaes - RFC 1256 */
1229 case ICMP_ROUTERADVERT :
1230 case ICMP_ROUTERSOLICIT :
1231 fin->fin_flx |= FI_ICMPQUERY;
1232 minicmpsz = ICMP_MINLEN;
1233 break;
1234 /*
1235 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1236 * 3 * timestamp(3 * 4)
1237 */
1238 case ICMP_TSTAMP :
1239 case ICMP_TSTAMPREPLY :
1240 fin->fin_flx |= FI_ICMPQUERY;
1241 minicmpsz = 20;
1242 break;
1243 /*
1244 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1245 * mask(4)
1246 */
1247 case ICMP_IREQ :
1248 case ICMP_IREQREPLY :
1249 case ICMP_MASKREQ :
1250 case ICMP_MASKREPLY :
1251 fin->fin_flx |= FI_ICMPQUERY;
1252 minicmpsz = 12;
1253 break;
1254 /*
1255 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1256 */
1257 case ICMP_UNREACH :
1258#ifdef icmp_nextmtu
1259 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1260 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1261 fin->fin_flx |= FI_BAD;
1262 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1263 }
1264 }
1265#endif
1266 /* FALLTHROUGH */
1267 case ICMP_SOURCEQUENCH :
1268 case ICMP_REDIRECT :
1269 case ICMP_TIMXCEED :
1270 case ICMP_PARAMPROB :
1271 fin->fin_flx |= FI_ICMPERR;
1272 if (ipf_coalesce(fin) != 1) {
1273 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1274 return;
1275 }
1276
1277 /*
1278 * ICMP error packets should not be generated for IP
1279 * packets that are a fragment that isn't the first
1280 * fragment.
1281 */
1282 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1283 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1284 fin->fin_flx |= FI_BAD;
1285 DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1286 }
1287
1288 /*
1289 * If the destination of this packet doesn't match the
1290 * source of the original packet then this packet is
1291 * not correct.
1292 */
1293 if (oip->ip_src.s_addr != fin->fin_daddr) {
1294 fin->fin_flx |= FI_BAD;
1295 DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1296 }
1297 break;
1298 default :
1299 break;
1300 }
1301
1302 ipf_pr_short(fin, minicmpsz);
1303
1304 ipf_checkv4sum(fin);
1305}
1306
1307
1308/* ------------------------------------------------------------------------ */
1309/* Function: ipf_pr_tcpcommon */
1310/* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1311/* Parameters: fin(I) - pointer to packet information */
1312/* */
1313/* TCP header sanity checking. Look for bad combinations of TCP flags, */
1314/* and make some checks with how they interact with other fields. */
1315/* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1316/* valid and mark the packet as bad if not. */
1317/* ------------------------------------------------------------------------ */
1318static INLINE int
1319ipf_pr_tcpcommon(fin)
1320 fr_info_t *fin;
1321{
1322 ipf_main_softc_t *softc = fin->fin_main_soft;
1323 int flags, tlen;
1324 tcphdr_t *tcp;
1325
1326 fin->fin_flx |= FI_TCPUDP;
1327 if (fin->fin_off != 0) {
1328 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1329 return 0;
1330 }
1331
1332 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1333 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1334 return -1;
1335 }
1336
1337 tcp = fin->fin_dp;
1338 if (fin->fin_dlen > 3) {
1339 fin->fin_sport = ntohs(tcp->th_sport);
1340 fin->fin_dport = ntohs(tcp->th_dport);
1341 }
1342
1343 if ((fin->fin_flx & FI_SHORT) != 0) {
1344 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1345 return 1;
1346 }
1347
1348 /*
1349 * Use of the TCP data offset *must* result in a value that is at
1350 * least the same size as the TCP header.
1351 */
1352 tlen = TCP_OFF(tcp) << 2;
1353 if (tlen < sizeof(tcphdr_t)) {
1354 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1355 fin->fin_flx |= FI_BAD;
1356 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1357 return 1;
1358 }
1359
1360 flags = tcp->th_flags;
1361 fin->fin_tcpf = tcp->th_flags;
1362
1363 /*
1364 * If the urgent flag is set, then the urgent pointer must
1365 * also be set and vice versa. Good TCP packets do not have
1366 * just one of these set.
1367 */
1368 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1369 fin->fin_flx |= FI_BAD;
1370 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1371#if 0
1372 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1373 /*
1374 * Ignore this case (#if 0) as it shows up in "real"
1375 * traffic with bogus values in the urgent pointer field.
1376 */
1377 fin->fin_flx |= FI_BAD;
1378 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1379#endif
1380 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1381 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1382 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1383 fin->fin_flx |= FI_BAD;
1384 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1385#if 1
1386 } else if (((flags & TH_SYN) != 0) &&
1387 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1388 /*
1389 * SYN with URG and PUSH set is not for normal TCP but it is
1390 * possible(?) with T/TCP...but who uses T/TCP?
1391 */
1392 fin->fin_flx |= FI_BAD;
1393 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1394#endif
1395 } else if (!(flags & TH_ACK)) {
1396 /*
1397 * If the ack bit isn't set, then either the SYN or
1398 * RST bit must be set. If the SYN bit is set, then
1399 * we expect the ACK field to be 0. If the ACK is
1400 * not set and if URG, PSH or FIN are set, consdier
1401 * that to indicate a bad TCP packet.
1402 */
1403 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1404 /*
1405 * Cisco PIX sets the ACK field to a random value.
1406 * In light of this, do not set FI_BAD until a patch
1407 * is available from Cisco to ensure that
1408 * interoperability between existing systems is
1409 * achieved.
1410 */
1411 /*fin->fin_flx |= FI_BAD*/;
1412 /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1413 } else if (!(flags & (TH_RST|TH_SYN))) {
1414 fin->fin_flx |= FI_BAD;
1415 DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1416 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1417 fin->fin_flx |= FI_BAD;
1418 DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1419 }
1420 }
1421 if (fin->fin_flx & FI_BAD) {
1422 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1423 return 1;
1424 }
1425
1426 /*
1427 * At this point, it's not exactly clear what is to be gained by
1428 * marking up which TCP options are and are not present. The one we
1429 * are most interested in is the TCP window scale. This is only in
1430 * a SYN packet [RFC1323] so we don't need this here...?
1431 * Now if we were to analyse the header for passive fingerprinting,
1432 * then that might add some weight to adding this...
1433 */
1434 if (tlen == sizeof(tcphdr_t)) {
1435 return 0;
1436 }
1437
1438 if (ipf_pr_pullup(fin, tlen) == -1) {
1439 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1440 return -1;
1441 }
1442
1443#if 0
1444 tcp = fin->fin_dp;
1445 ip = fin->fin_ip;
1446 s = (u_char *)(tcp + 1);
1447 off = IP_HL(ip) << 2;
1448# ifdef _KERNEL
1449 if (fin->fin_mp != NULL) {
1450 mb_t *m = *fin->fin_mp;
1451
1452 if (off + tlen > M_LEN(m))
1453 return;
1454 }
1455# endif
1456 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1457 opt = *s;
1458 if (opt == '\0')
1459 break;
1460 else if (opt == TCPOPT_NOP)
1461 ol = 1;
1462 else {
1463 if (tlen < 2)
1464 break;
1465 ol = (int)*(s + 1);
1466 if (ol < 2 || ol > tlen)
1467 break;
1468 }
1469
1470 for (i = 9, mv = 4; mv >= 0; ) {
1471 op = ipopts + i;
1472 if (opt == (u_char)op->ol_val) {
1473 optmsk |= op->ol_bit;
1474 break;
1475 }
1476 }
1477 tlen -= ol;
1478 s += ol;
1479 }
1480#endif /* 0 */
1481
1482 return 0;
1483}
1484
1485
1486
1487/* ------------------------------------------------------------------------ */
1488/* Function: ipf_pr_udpcommon */
1489/* Returns: int - 0 = header ok, 1 = bad packet */
1490/* Parameters: fin(I) - pointer to packet information */
1491/* */
1492/* Extract the UDP source and destination ports, if present. If compiled */
1493/* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1494/* ------------------------------------------------------------------------ */
1495static INLINE int
1496ipf_pr_udpcommon(fin)
1497 fr_info_t *fin;
1498{
1499 udphdr_t *udp;
1500
1501 fin->fin_flx |= FI_TCPUDP;
1502
1503 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1504 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1505 ipf_main_softc_t *softc = fin->fin_main_soft;
1506
1507 fin->fin_flx |= FI_SHORT;
1508 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1509 return 1;
1510 }
1511
1512 udp = fin->fin_dp;
1513
1514 fin->fin_sport = ntohs(udp->uh_sport);
1515 fin->fin_dport = ntohs(udp->uh_dport);
1516 }
1517
1518 return 0;
1519}
1520
1521
1522/* ------------------------------------------------------------------------ */
1523/* Function: ipf_pr_tcp */
1524/* Returns: void */
1525/* Parameters: fin(I) - pointer to packet information */
1526/* */
1527/* IPv4 Only */
1528/* Analyse the packet for IPv4/TCP properties. */
1529/* ------------------------------------------------------------------------ */
1530static INLINE void
1531ipf_pr_tcp(fin)
1532 fr_info_t *fin;
1533{
1534
1535 ipf_pr_short(fin, sizeof(tcphdr_t));
1536
1537 if (ipf_pr_tcpcommon(fin) == 0)
1538 ipf_checkv4sum(fin);
1539}
1540
1541
1542/* ------------------------------------------------------------------------ */
1543/* Function: ipf_pr_udp */
1544/* Returns: void */
1545/* Parameters: fin(I) - pointer to packet information */
1546/* */
1547/* IPv4 Only */
1548/* Analyse the packet for IPv4/UDP properties. */
1549/* ------------------------------------------------------------------------ */
1550static INLINE void
1551ipf_pr_udp(fin)
1552 fr_info_t *fin;
1553{
1554
1555 ipf_pr_short(fin, sizeof(udphdr_t));
1556
1557 if (ipf_pr_udpcommon(fin) == 0)
1558 ipf_checkv4sum(fin);
1559}
1560
1561
1562/* ------------------------------------------------------------------------ */
1563/* Function: ipf_pr_esp */
1564/* Returns: void */
1565/* Parameters: fin(I) - pointer to packet information */
1566/* */
1567/* Analyse the packet for ESP properties. */
1568/* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1569/* even though the newer ESP packets must also have a sequence number that */
1570/* is 32bits as well, it is not possible(?) to determine the version from a */
1571/* simple packet header. */
1572/* ------------------------------------------------------------------------ */
1573static INLINE void
1574ipf_pr_esp(fin)
1575 fr_info_t *fin;
1576{
1577
1578 if (fin->fin_off == 0) {
1579 ipf_pr_short(fin, 8);
1580 if (ipf_pr_pullup(fin, 8) == -1) {
1581 ipf_main_softc_t *softc = fin->fin_main_soft;
1582
1583 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1584 }
1585 }
1586}
1587
1588
1589/* ------------------------------------------------------------------------ */
1590/* Function: ipf_pr_ah */
1591/* Returns: int - value of the next header or IPPROTO_NONE if error */
1592/* Parameters: fin(I) - pointer to packet information */
1593/* */
1594/* Analyse the packet for AH properties. */
1595/* The minimum length is taken to be the combination of all fields in the */
1596/* header being present and no authentication data (null algorithm used.) */
1597/* ------------------------------------------------------------------------ */
1598static INLINE int
1599ipf_pr_ah(fin)
1600 fr_info_t *fin;
1601{
1602 ipf_main_softc_t *softc = fin->fin_main_soft;
1603 authhdr_t *ah;
1604 int len;
1605
1606 fin->fin_flx |= FI_AH;
1607 ipf_pr_short(fin, sizeof(*ah));
1608
1609 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1610 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1611 return IPPROTO_NONE;
1612 }
1613
1614 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1615 DT(fr_v4_ah_pullup_1);
1616 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1617 return IPPROTO_NONE;
1618 }
1619
1620 ah = (authhdr_t *)fin->fin_dp;
1621
1622 len = (ah->ah_plen + 2) << 2;
1623 ipf_pr_short(fin, len);
1624 if (ipf_pr_pullup(fin, len) == -1) {
1625 DT(fr_v4_ah_pullup_2);
1626 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1627 return IPPROTO_NONE;
1628 }
1629
1630 /*
1631 * Adjust fin_dp and fin_dlen for skipping over the authentication
1632 * header.
1633 */
1634 fin->fin_dp = (char *)fin->fin_dp + len;
1635 fin->fin_dlen -= len;
1636 return ah->ah_next;
1637}
1638
1639
1640/* ------------------------------------------------------------------------ */
1641/* Function: ipf_pr_gre */
1642/* Returns: void */
1643/* Parameters: fin(I) - pointer to packet information */
1644/* */
1645/* Analyse the packet for GRE properties. */
1646/* ------------------------------------------------------------------------ */
1647static INLINE void
1648ipf_pr_gre(fin)
1649 fr_info_t *fin;
1650{
1651 ipf_main_softc_t *softc = fin->fin_main_soft;
1652 grehdr_t *gre;
1653
1654 ipf_pr_short(fin, sizeof(grehdr_t));
1655
1656 if (fin->fin_off != 0) {
1657 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1658 return;
1659 }
1660
1661 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1662 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1663 return;
1664 }
1665
1666 gre = fin->fin_dp;
1667 if (GRE_REV(gre->gr_flags) == 1)
1668 fin->fin_data[0] = gre->gr_call;
1669}
1670
1671
1672/* ------------------------------------------------------------------------ */
1673/* Function: ipf_pr_ipv4hdr */
1674/* Returns: void */
1675/* Parameters: fin(I) - pointer to packet information */
1676/* */
1677/* IPv4 Only */
1678/* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1679/* Check all options present and flag their presence if any exist. */
1680/* ------------------------------------------------------------------------ */
1681static INLINE void
1682ipf_pr_ipv4hdr(fin)
1683 fr_info_t *fin;
1684{
1685 u_short optmsk = 0, secmsk = 0, auth = 0;
1686 int hlen, ol, mv, p, i;
1687 const struct optlist *op;
1688 u_char *s, opt;
1689 u_short off;
1690 fr_ip_t *fi;
1691 ip_t *ip;
1692
1693 fi = &fin->fin_fi;
1694 hlen = fin->fin_hlen;
1695
1696 ip = fin->fin_ip;
1697 p = ip->ip_p;
1698 fi->fi_p = p;
1699 fin->fin_crc = p;
1700 fi->fi_tos = ip->ip_tos;
1699 fin->fin_id = ip->ip_id;
1701 fin->fin_id = ntohs(ip->ip_id);
1700 off = ntohs(ip->ip_off);
1701
1702 /* Get both TTL and protocol */
1703 fi->fi_p = ip->ip_p;
1704 fi->fi_ttl = ip->ip_ttl;
1705
1706 /* Zero out bits not used in IPv6 address */
1707 fi->fi_src.i6[1] = 0;
1708 fi->fi_src.i6[2] = 0;
1709 fi->fi_src.i6[3] = 0;
1710 fi->fi_dst.i6[1] = 0;
1711 fi->fi_dst.i6[2] = 0;
1712 fi->fi_dst.i6[3] = 0;
1713
1714 fi->fi_saddr = ip->ip_src.s_addr;
1715 fin->fin_crc += fi->fi_saddr;
1716 fi->fi_daddr = ip->ip_dst.s_addr;
1717 fin->fin_crc += fi->fi_daddr;
1718 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1720
1721 /*
1722 * set packet attribute flags based on the offset and
1723 * calculate the byte offset that it represents.
1724 */
1725 off &= IP_MF|IP_OFFMASK;
1726 if (off != 0) {
1727 int morefrag = off & IP_MF;
1728
1729 fi->fi_flx |= FI_FRAG;
1730 off &= IP_OFFMASK;
1731 if (off == 1 && p == IPPROTO_TCP) {
1732 fin->fin_flx |= FI_SHORT; /* RFC 3128 */
1733 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1734 }
1735 if (off != 0) {
1736 fin->fin_flx |= FI_FRAGBODY;
1737 off <<= 3;
1738 if ((off + fin->fin_dlen > 65535) ||
1739 (fin->fin_dlen == 0) ||
1740 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1741 /*
1742 * The length of the packet, starting at its
1743 * offset cannot exceed 65535 (0xffff) as the
1744 * length of an IP packet is only 16 bits.
1745 *
1746 * Any fragment that isn't the last fragment
1747 * must have a length greater than 0 and it
1748 * must be an even multiple of 8.
1749 */
1750 fi->fi_flx |= FI_BAD;
1751 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1752 }
1753 }
1754 }
1755 fin->fin_off = off;
1756
1757 /*
1758 * Call per-protocol setup and checking
1759 */
1760 if (p == IPPROTO_AH) {
1761 /*
1762 * Treat AH differently because we expect there to be another
1763 * layer 4 header after it.
1764 */
1765 p = ipf_pr_ah(fin);
1766 }
1767
1768 switch (p)
1769 {
1770 case IPPROTO_UDP :
1771 ipf_pr_udp(fin);
1772 break;
1773 case IPPROTO_TCP :
1774 ipf_pr_tcp(fin);
1775 break;
1776 case IPPROTO_ICMP :
1777 ipf_pr_icmp(fin);
1778 break;
1779 case IPPROTO_ESP :
1780 ipf_pr_esp(fin);
1781 break;
1782 case IPPROTO_GRE :
1783 ipf_pr_gre(fin);
1784 break;
1785 }
1786
1787 ip = fin->fin_ip;
1788 if (ip == NULL)
1789 return;
1790
1791 /*
1792 * If it is a standard IP header (no options), set the flag fields
1793 * which relate to options to 0.
1794 */
1795 if (hlen == sizeof(*ip)) {
1796 fi->fi_optmsk = 0;
1797 fi->fi_secmsk = 0;
1798 fi->fi_auth = 0;
1799 return;
1800 }
1801
1802 /*
1803 * So the IP header has some IP options attached. Walk the entire
1804 * list of options present with this packet and set flags to indicate
1805 * which ones are here and which ones are not. For the somewhat out
1806 * of date and obscure security classification options, set a flag to
1807 * represent which classification is present.
1808 */
1809 fi->fi_flx |= FI_OPTIONS;
1810
1811 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1812 opt = *s;
1813 if (opt == '\0')
1814 break;
1815 else if (opt == IPOPT_NOP)
1816 ol = 1;
1817 else {
1818 if (hlen < 2)
1819 break;
1820 ol = (int)*(s + 1);
1821 if (ol < 2 || ol > hlen)
1822 break;
1823 }
1824 for (i = 9, mv = 4; mv >= 0; ) {
1825 op = ipopts + i;
1826
1827 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1828 u_32_t doi;
1829
1830 switch (opt)
1831 {
1832 case IPOPT_SECURITY :
1833 if (optmsk & op->ol_bit) {
1834 fin->fin_flx |= FI_BAD;
1835 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1836 } else {
1837 doi = ipf_checkripso(s);
1838 secmsk = doi >> 16;
1839 auth = doi & 0xffff;
1840 }
1841 break;
1842
1843 case IPOPT_CIPSO :
1844
1845 if (optmsk & op->ol_bit) {
1846 fin->fin_flx |= FI_BAD;
1847 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1848 } else {
1849 doi = ipf_checkcipso(fin,
1850 s, ol);
1851 secmsk = doi >> 16;
1852 auth = doi & 0xffff;
1853 }
1854 break;
1855 }
1856 optmsk |= op->ol_bit;
1857 }
1858
1859 if (opt < op->ol_val)
1860 i -= mv;
1861 else
1862 i += mv;
1863 mv--;
1864 }
1865 hlen -= ol;
1866 s += ol;
1867 }
1868
1869 /*
1870 *
1871 */
1872 if (auth && !(auth & 0x0100))
1873 auth &= 0xff00;
1874 fi->fi_optmsk = optmsk;
1875 fi->fi_secmsk = secmsk;
1876 fi->fi_auth = auth;
1877}
1878
1879
1880/* ------------------------------------------------------------------------ */
1881/* Function: ipf_checkripso */
1882/* Returns: void */
1883/* Parameters: s(I) - pointer to start of RIPSO option */
1884/* */
1885/* ------------------------------------------------------------------------ */
1886static u_32_t
1887ipf_checkripso(s)
1888 u_char *s;
1889{
1890 const struct optlist *sp;
1891 u_short secmsk = 0, auth = 0;
1892 u_char sec;
1893 int j, m;
1894
1895 sec = *(s + 2); /* classification */
1896 for (j = 3, m = 2; m >= 0; ) {
1897 sp = secopt + j;
1898 if (sec == sp->ol_val) {
1899 secmsk |= sp->ol_bit;
1900 auth = *(s + 3);
1901 auth *= 256;
1902 auth += *(s + 4);
1903 break;
1904 }
1905 if (sec < sp->ol_val)
1906 j -= m;
1907 else
1908 j += m;
1909 m--;
1910 }
1911
1912 return (secmsk << 16) | auth;
1913}
1914
1915
1916/* ------------------------------------------------------------------------ */
1917/* Function: ipf_checkcipso */
1918/* Returns: u_32_t - 0 = failure, else the doi from the header */
1919/* Parameters: fin(IO) - pointer to packet information */
1920/* s(I) - pointer to start of CIPSO option */
1921/* ol(I) - length of CIPSO option field */
1922/* */
1923/* This function returns the domain of integrity (DOI) field from the CIPSO */
1924/* header and returns that whilst also storing the highest sensitivity */
1925/* value found in the fr_info_t structure. */
1926/* */
1927/* No attempt is made to extract the category bitmaps as these are defined */
1928/* by the user (rather than the protocol) and can be rather numerous on the */
1929/* end nodes. */
1930/* ------------------------------------------------------------------------ */
1931static u_32_t
1932ipf_checkcipso(fin, s, ol)
1933 fr_info_t *fin;
1934 u_char *s;
1935 int ol;
1936{
1937 ipf_main_softc_t *softc = fin->fin_main_soft;
1938 fr_ip_t *fi;
1939 u_32_t doi;
1940 u_char *t, tag, tlen, sensitivity;
1941 int len;
1942
1943 if (ol < 6 || ol > 40) {
1944 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1945 fin->fin_flx |= FI_BAD;
1946 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1947 return 0;
1948 }
1949
1950 fi = &fin->fin_fi;
1951 fi->fi_sensitivity = 0;
1952 /*
1953 * The DOI field MUST be there.
1954 */
1955 bcopy(s + 2, &doi, sizeof(doi));
1956
1957 t = (u_char *)s + 6;
1958 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1959 tag = *t;
1960 tlen = *(t + 1);
1961 if (tlen > len || tlen < 4 || tlen > 34) {
1962 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1963 fin->fin_flx |= FI_BAD;
1964 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1965 return 0;
1966 }
1967
1968 sensitivity = 0;
1969 /*
1970 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1971 * draft (16 July 1992) that has expired.
1972 */
1973 if (tag == 0) {
1974 fin->fin_flx |= FI_BAD;
1975 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1976 continue;
1977 } else if (tag == 1) {
1978 if (*(t + 2) != 0) {
1979 fin->fin_flx |= FI_BAD;
1980 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1981 continue;
1982 }
1983 sensitivity = *(t + 3);
1984 /* Category bitmap for categories 0-239 */
1985
1986 } else if (tag == 4) {
1987 if (*(t + 2) != 0) {
1988 fin->fin_flx |= FI_BAD;
1989 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1990 continue;
1991 }
1992 sensitivity = *(t + 3);
1993 /* Enumerated categories, 16bits each, upto 15 */
1994
1995 } else if (tag == 5) {
1996 if (*(t + 2) != 0) {
1997 fin->fin_flx |= FI_BAD;
1998 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1999 continue;
2000 }
2001 sensitivity = *(t + 3);
2002 /* Range of categories (2*16bits), up to 7 pairs */
2003
2004 } else if (tag > 127) {
2005 /* Custom defined DOI */
2006 ;
2007 } else {
2008 fin->fin_flx |= FI_BAD;
2009 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2010 continue;
2011 }
2012
2013 if (sensitivity > fi->fi_sensitivity)
2014 fi->fi_sensitivity = sensitivity;
2015 }
2016
2017 return doi;
2018}
2019
2020
2021/* ------------------------------------------------------------------------ */
2022/* Function: ipf_makefrip */
2023/* Returns: int - 0 == packet ok, -1 == packet freed */
2024/* Parameters: hlen(I) - length of IP packet header */
2025/* ip(I) - pointer to the IP header */
2026/* fin(IO) - pointer to packet information */
2027/* */
2028/* Compact the IP header into a structure which contains just the info. */
2029/* which is useful for comparing IP headers with and store this information */
2030/* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2031/* this function will be called with either an IPv4 or IPv6 packet. */
2032/* ------------------------------------------------------------------------ */
2033int
2034ipf_makefrip(hlen, ip, fin)
2035 int hlen;
2036 ip_t *ip;
2037 fr_info_t *fin;
2038{
2039 ipf_main_softc_t *softc = fin->fin_main_soft;
2040 int v;
2041
2042 fin->fin_depth = 0;
2043 fin->fin_hlen = (u_short)hlen;
2044 fin->fin_ip = ip;
2045 fin->fin_rule = 0xffffffff;
2046 fin->fin_group[0] = -1;
2047 fin->fin_group[1] = '\0';
2048 fin->fin_dp = (char *)ip + hlen;
2049
2050 v = fin->fin_v;
2051 if (v == 4) {
2052 fin->fin_plen = ntohs(ip->ip_len);
2053 fin->fin_dlen = fin->fin_plen - hlen;
2054 ipf_pr_ipv4hdr(fin);
2055#ifdef USE_INET6
2056 } else if (v == 6) {
2057 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2058 fin->fin_dlen = fin->fin_plen;
2059 fin->fin_plen += hlen;
2060
2061 ipf_pr_ipv6hdr(fin);
2062#endif
2063 }
2064 if (fin->fin_ip == NULL) {
2065 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2066 return -1;
2067 }
2068 return 0;
2069}
2070
2071
2072/* ------------------------------------------------------------------------ */
2073/* Function: ipf_portcheck */
2074/* Returns: int - 1 == port matched, 0 == port match failed */
2075/* Parameters: frp(I) - pointer to port check `expression' */
2076/* pop(I) - port number to evaluate */
2077/* */
2078/* Perform a comparison of a port number against some other(s), using a */
2079/* structure with compare information stored in it. */
2080/* ------------------------------------------------------------------------ */
2081static INLINE int
2082ipf_portcheck(frp, pop)
2083 frpcmp_t *frp;
2084 u_32_t pop;
2085{
2086 int err = 1;
2087 u_32_t po;
2088
2089 po = frp->frp_port;
2090
2091 /*
2092 * Do opposite test to that required and continue if that succeeds.
2093 */
2094 switch (frp->frp_cmp)
2095 {
2096 case FR_EQUAL :
2097 if (pop != po) /* EQUAL */
2098 err = 0;
2099 break;
2100 case FR_NEQUAL :
2101 if (pop == po) /* NOTEQUAL */
2102 err = 0;
2103 break;
2104 case FR_LESST :
2105 if (pop >= po) /* LESSTHAN */
2106 err = 0;
2107 break;
2108 case FR_GREATERT :
2109 if (pop <= po) /* GREATERTHAN */
2110 err = 0;
2111 break;
2112 case FR_LESSTE :
2113 if (pop > po) /* LT or EQ */
2114 err = 0;
2115 break;
2116 case FR_GREATERTE :
2117 if (pop < po) /* GT or EQ */
2118 err = 0;
2119 break;
2120 case FR_OUTRANGE :
2121 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2122 err = 0;
2123 break;
2124 case FR_INRANGE :
2125 if (pop <= po || pop >= frp->frp_top) /* In range */
2126 err = 0;
2127 break;
2128 case FR_INCRANGE :
2129 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2130 err = 0;
2131 break;
2132 default :
2133 break;
2134 }
2135 return err;
2136}
2137
2138
2139/* ------------------------------------------------------------------------ */
2140/* Function: ipf_tcpudpchk */
2141/* Returns: int - 1 == protocol matched, 0 == check failed */
2142/* Parameters: fda(I) - pointer to packet information */
2143/* ft(I) - pointer to structure with comparison data */
2144/* */
2145/* Compares the current pcket (assuming it is TCP/UDP) information with a */
2146/* structure containing information that we want to match against. */
2147/* ------------------------------------------------------------------------ */
2148int
2149ipf_tcpudpchk(fi, ft)
2150 fr_ip_t *fi;
2151 frtuc_t *ft;
2152{
2153 int err = 1;
2154
2155 /*
2156 * Both ports should *always* be in the first fragment.
2157 * So far, I cannot find any cases where they can not be.
2158 *
2159 * compare destination ports
2160 */
2161 if (ft->ftu_dcmp)
2162 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2163
2164 /*
2165 * compare source ports
2166 */
2167 if (err && ft->ftu_scmp)
2168 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2169
2170 /*
2171 * If we don't have all the TCP/UDP header, then how can we
2172 * expect to do any sort of match on it ? If we were looking for
2173 * TCP flags, then NO match. If not, then match (which should
2174 * satisfy the "short" class too).
2175 */
2176 if (err && (fi->fi_p == IPPROTO_TCP)) {
2177 if (fi->fi_flx & FI_SHORT)
2178 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2179 /*
2180 * Match the flags ? If not, abort this match.
2181 */
2182 if (ft->ftu_tcpfm &&
2183 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2184 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2185 ft->ftu_tcpfm, ft->ftu_tcpf));
2186 err = 0;
2187 }
2188 }
2189 return err;
2190}
2191
2192
2193/* ------------------------------------------------------------------------ */
2194/* Function: ipf_check_ipf */
2195/* Returns: int - 0 == match, else no match */
2196/* Parameters: fin(I) - pointer to packet information */
2197/* fr(I) - pointer to filter rule */
2198/* portcmp(I) - flag indicating whether to attempt matching on */
2199/* TCP/UDP port data. */
2200/* */
2201/* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2202/* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2203/* this function. */
2204/* ------------------------------------------------------------------------ */
2205static INLINE int
2206ipf_check_ipf(fin, fr, portcmp)
2207 fr_info_t *fin;
2208 frentry_t *fr;
2209 int portcmp;
2210{
2211 u_32_t *ld, *lm, *lip;
2212 fripf_t *fri;
2213 fr_ip_t *fi;
2214 int i;
2215
2216 fi = &fin->fin_fi;
2217 fri = fr->fr_ipf;
2218 lip = (u_32_t *)fi;
2219 lm = (u_32_t *)&fri->fri_mip;
2220 ld = (u_32_t *)&fri->fri_ip;
2221
2222 /*
2223 * first 32 bits to check coversion:
2224 * IP version, TOS, TTL, protocol
2225 */
2226 i = ((*lip & *lm) != *ld);
2227 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2228 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2229 if (i)
2230 return 1;
2231
2232 /*
2233 * Next 32 bits is a constructed bitmask indicating which IP options
2234 * are present (if any) in this packet.
2235 */
2236 lip++, lm++, ld++;
2237 i = ((*lip & *lm) != *ld);
2238 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2239 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2240 if (i != 0)
2241 return 1;
2242
2243 lip++, lm++, ld++;
2244 /*
2245 * Unrolled loops (4 each, for 32 bits) for address checks.
2246 */
2247 /*
2248 * Check the source address.
2249 */
2250 if (fr->fr_satype == FRI_LOOKUP) {
2251 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2252 fi->fi_v, lip, fin->fin_plen);
2253 if (i == -1)
2254 return 1;
2255 lip += 3;
2256 lm += 3;
2257 ld += 3;
2258 } else {
2259 i = ((*lip & *lm) != *ld);
2260 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2261 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262 if (fi->fi_v == 6) {
2263 lip++, lm++, ld++;
2264 i |= ((*lip & *lm) != *ld);
2265 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2266 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2267 lip++, lm++, ld++;
2268 i |= ((*lip & *lm) != *ld);
2269 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2270 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271 lip++, lm++, ld++;
2272 i |= ((*lip & *lm) != *ld);
2273 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2274 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2275 } else {
2276 lip += 3;
2277 lm += 3;
2278 ld += 3;
2279 }
2280 }
2281 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2282 if (i != 0)
2283 return 1;
2284
2285 /*
2286 * Check the destination address.
2287 */
2288 lip++, lm++, ld++;
2289 if (fr->fr_datype == FRI_LOOKUP) {
2290 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2291 fi->fi_v, lip, fin->fin_plen);
2292 if (i == -1)
2293 return 1;
2294 lip += 3;
2295 lm += 3;
2296 ld += 3;
2297 } else {
2298 i = ((*lip & *lm) != *ld);
2299 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2300 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2301 if (fi->fi_v == 6) {
2302 lip++, lm++, ld++;
2303 i |= ((*lip & *lm) != *ld);
2304 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2305 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2306 lip++, lm++, ld++;
2307 i |= ((*lip & *lm) != *ld);
2308 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2309 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310 lip++, lm++, ld++;
2311 i |= ((*lip & *lm) != *ld);
2312 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2313 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2314 } else {
2315 lip += 3;
2316 lm += 3;
2317 ld += 3;
2318 }
2319 }
2320 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2321 if (i != 0)
2322 return 1;
2323 /*
2324 * IP addresses matched. The next 32bits contains:
2325 * mast of old IP header security & authentication bits.
2326 */
2327 lip++, lm++, ld++;
2328 i = (*ld - (*lip & *lm));
2329 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2330
2331 /*
2332 * Next we have 32 bits of packet flags.
2333 */
2334 lip++, lm++, ld++;
2335 i |= (*ld - (*lip & *lm));
2336 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2337
2338 if (i == 0) {
2339 /*
2340 * If a fragment, then only the first has what we're
2341 * looking for here...
2342 */
2343 if (portcmp) {
2344 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2345 i = 1;
2346 } else {
2347 if (fr->fr_dcmp || fr->fr_scmp ||
2348 fr->fr_tcpf || fr->fr_tcpfm)
2349 i = 1;
2350 if (fr->fr_icmpm || fr->fr_icmp) {
2351 if (((fi->fi_p != IPPROTO_ICMP) &&
2352 (fi->fi_p != IPPROTO_ICMPV6)) ||
2353 fin->fin_off || (fin->fin_dlen < 2))
2354 i = 1;
2355 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2356 fr->fr_icmp) {
2357 FR_DEBUG(("i. %#x & %#x != %#x\n",
2358 fin->fin_data[0],
2359 fr->fr_icmpm, fr->fr_icmp));
2360 i = 1;
2361 }
2362 }
2363 }
2364 }
2365 return i;
2366}
2367
2368
2369/* ------------------------------------------------------------------------ */
2370/* Function: ipf_scanlist */
2371/* Returns: int - result flags of scanning filter list */
2372/* Parameters: fin(I) - pointer to packet information */
2373/* pass(I) - default result to return for filtering */
2374/* */
2375/* Check the input/output list of rules for a match to the current packet. */
2376/* If a match is found, the value of fr_flags from the rule becomes the */
2377/* return value and fin->fin_fr points to the matched rule. */
2378/* */
2379/* This function may be called recusively upto 16 times (limit inbuilt.) */
2380/* When unwinding, it should finish up with fin_depth as 0. */
2381/* */
2382/* Could be per interface, but this gets real nasty when you don't have, */
2383/* or can't easily change, the kernel source code to . */
2384/* ------------------------------------------------------------------------ */
2385int
2386ipf_scanlist(fin, pass)
2387 fr_info_t *fin;
2388 u_32_t pass;
2389{
2390 ipf_main_softc_t *softc = fin->fin_main_soft;
2391 int rulen, portcmp, off, skip;
2392 struct frentry *fr, *fnext;
2393 u_32_t passt, passo;
2394
2395 /*
2396 * Do not allow nesting deeper than 16 levels.
2397 */
2398 if (fin->fin_depth >= 16)
2399 return pass;
2400
2401 fr = fin->fin_fr;
2402
2403 /*
2404 * If there are no rules in this list, return now.
2405 */
2406 if (fr == NULL)
2407 return pass;
2408
2409 skip = 0;
2410 portcmp = 0;
2411 fin->fin_depth++;
2412 fin->fin_fr = NULL;
2413 off = fin->fin_off;
2414
2415 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2416 portcmp = 1;
2417
2418 for (rulen = 0; fr; fr = fnext, rulen++) {
2419 fnext = fr->fr_next;
2420 if (skip != 0) {
2421 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2422 skip--;
2423 continue;
2424 }
2425
2426 /*
2427 * In all checks below, a null (zero) value in the
2428 * filter struture is taken to mean a wildcard.
2429 *
2430 * check that we are working for the right interface
2431 */
2432#ifdef _KERNEL
2433 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2434 continue;
2435#else
2436 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2437 printf("\n");
2438 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2439 FR_ISPASS(pass) ? 'p' :
2440 FR_ISACCOUNT(pass) ? 'A' :
2441 FR_ISAUTH(pass) ? 'a' :
2442 (pass & FR_NOMATCH) ? 'n' :'b'));
2443 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2444 continue;
2445 FR_VERBOSE((":i"));
2446#endif
2447
2448 switch (fr->fr_type)
2449 {
2450 case FR_T_IPF :
2451 case FR_T_IPF_BUILTIN :
2452 if (ipf_check_ipf(fin, fr, portcmp))
2453 continue;
2454 break;
2455#if defined(IPFILTER_BPF)
2456 case FR_T_BPFOPC :
2457 case FR_T_BPFOPC_BUILTIN :
2458 {
2459 u_char *mc;
2460 int wlen;
2461
2462 if (*fin->fin_mp == NULL)
2463 continue;
2464 if (fin->fin_family != fr->fr_family)
2465 continue;
2466 mc = (u_char *)fin->fin_m;
2467 wlen = fin->fin_dlen + fin->fin_hlen;
2468 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2469 continue;
2470 break;
2471 }
2472#endif
2473 case FR_T_CALLFUNC_BUILTIN :
2474 {
2475 frentry_t *f;
2476
2477 f = (*fr->fr_func)(fin, &pass);
2478 if (f != NULL)
2479 fr = f;
2480 else
2481 continue;
2482 break;
2483 }
2484
2485 case FR_T_IPFEXPR :
2486 case FR_T_IPFEXPR_BUILTIN :
2487 if (fin->fin_family != fr->fr_family)
2488 continue;
2489 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2490 continue;
2491 break;
2492
2493 default :
2494 break;
2495 }
2496
2497 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2498 if (fin->fin_nattag == NULL)
2499 continue;
2500 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2501 continue;
2502 }
2503 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2504
2505 passt = fr->fr_flags;
2506
2507 /*
2508 * If the rule is a "call now" rule, then call the function
2509 * in the rule, if it exists and use the results from that.
2510 * If the function pointer is bad, just make like we ignore
2511 * it, except for increasing the hit counter.
2512 */
2513 if ((passt & FR_CALLNOW) != 0) {
2514 frentry_t *frs;
2515
2516 ATOMIC_INC64(fr->fr_hits);
2517 if ((fr->fr_func == NULL) ||
2518 (fr->fr_func == (ipfunc_t)-1))
2519 continue;
2520
2521 frs = fin->fin_fr;
2522 fin->fin_fr = fr;
2523 fr = (*fr->fr_func)(fin, &passt);
2524 if (fr == NULL) {
2525 fin->fin_fr = frs;
2526 continue;
2527 }
2528 passt = fr->fr_flags;
2529 }
2530 fin->fin_fr = fr;
2531
2532#ifdef IPFILTER_LOG
2533 /*
2534 * Just log this packet...
2535 */
2536 if ((passt & FR_LOGMASK) == FR_LOG) {
2537 if (ipf_log_pkt(fin, passt) == -1) {
2538 if (passt & FR_LOGORBLOCK) {
2539 DT(frb_logfail);
2540 passt &= ~FR_CMDMASK;
2541 passt |= FR_BLOCK|FR_QUICK;
2542 fin->fin_reason = FRB_LOGFAIL;
2543 }
2544 }
2545 }
2546#endif /* IPFILTER_LOG */
2547
2548 MUTEX_ENTER(&fr->fr_lock);
2549 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2550 fr->fr_hits++;
2551 MUTEX_EXIT(&fr->fr_lock);
2552 fin->fin_rule = rulen;
2553
2554 passo = pass;
2555 if (FR_ISSKIP(passt)) {
2556 skip = fr->fr_arg;
2557 continue;
2558 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2559 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2560 pass = passt;
2561 }
2562
2563 if (passt & (FR_RETICMP|FR_FAKEICMP))
2564 fin->fin_icode = fr->fr_icode;
2565
2566 if (fr->fr_group != -1) {
2567 (void) strncpy(fin->fin_group,
2568 FR_NAME(fr, fr_group),
2569 strlen(FR_NAME(fr, fr_group)));
2570 } else {
2571 fin->fin_group[0] = '\0';
2572 }
2573
2574 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2575
2576 if (fr->fr_grphead != NULL) {
2577 fin->fin_fr = fr->fr_grphead->fg_start;
2578 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2579
2580 if (FR_ISDECAPS(passt))
2581 passt = ipf_decaps(fin, pass, fr->fr_icode);
2582 else
2583 passt = ipf_scanlist(fin, pass);
2584
2585 if (fin->fin_fr == NULL) {
2586 fin->fin_rule = rulen;
2587 if (fr->fr_group != -1)
2588 (void) strncpy(fin->fin_group,
2589 fr->fr_names +
2590 fr->fr_group,
2591 strlen(fr->fr_names +
2592 fr->fr_group));
2593 fin->fin_fr = fr;
2594 passt = pass;
2595 }
2596 pass = passt;
2597 }
2598
2599 if (pass & FR_QUICK) {
2600 /*
2601 * Finally, if we've asked to track state for this
2602 * packet, set it up. Add state for "quick" rules
2603 * here so that if the action fails we can consider
2604 * the rule to "not match" and keep on processing
2605 * filter rules.
2606 */
2607 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2608 !(fin->fin_flx & FI_STATE)) {
2609 int out = fin->fin_out;
2610
2611 fin->fin_fr = fr;
2612 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2613 LBUMPD(ipf_stats[out], fr_ads);
2614 } else {
2615 LBUMPD(ipf_stats[out], fr_bads);
2616 pass = passo;
2617 continue;
2618 }
2619 }
2620 break;
2621 }
2622 }
2623 fin->fin_depth--;
2624 return pass;
2625}
2626
2627
2628/* ------------------------------------------------------------------------ */
2629/* Function: ipf_acctpkt */
2630/* Returns: frentry_t* - always returns NULL */
2631/* Parameters: fin(I) - pointer to packet information */
2632/* passp(IO) - pointer to current/new filter decision (unused) */
2633/* */
2634/* Checks a packet against accounting rules, if there are any for the given */
2635/* IP protocol version. */
2636/* */
2637/* N.B.: this function returns NULL to match the prototype used by other */
2638/* functions called from the IPFilter "mainline" in ipf_check(). */
2639/* ------------------------------------------------------------------------ */
2640frentry_t *
2641ipf_acctpkt(fin, passp)
2642 fr_info_t *fin;
2643 u_32_t *passp;
2644{
2645 ipf_main_softc_t *softc = fin->fin_main_soft;
2646 char group[FR_GROUPLEN];
2647 frentry_t *fr, *frsave;
2648 u_32_t pass, rulen;
2649
2650 passp = passp;
2651 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2652
2653 if (fr != NULL) {
2654 frsave = fin->fin_fr;
2655 bcopy(fin->fin_group, group, FR_GROUPLEN);
2656 rulen = fin->fin_rule;
2657 fin->fin_fr = fr;
2658 pass = ipf_scanlist(fin, FR_NOMATCH);
2659 if (FR_ISACCOUNT(pass)) {
2660 LBUMPD(ipf_stats[0], fr_acct);
2661 }
2662 fin->fin_fr = frsave;
2663 bcopy(group, fin->fin_group, FR_GROUPLEN);
2664 fin->fin_rule = rulen;
2665 }
2666 return NULL;
2667}
2668
2669
2670/* ------------------------------------------------------------------------ */
2671/* Function: ipf_firewall */
2672/* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2673/* were found, returns NULL. */
2674/* Parameters: fin(I) - pointer to packet information */
2675/* passp(IO) - pointer to current/new filter decision (unused) */
2676/* */
2677/* Applies an appropriate set of firewall rules to the packet, to see if */
2678/* there are any matches. The first check is to see if a match can be seen */
2679/* in the cache. If not, then search an appropriate list of rules. Once a */
2680/* matching rule is found, take any appropriate actions as defined by the */
2681/* rule - except logging. */
2682/* ------------------------------------------------------------------------ */
2683static frentry_t *
2684ipf_firewall(fin, passp)
2685 fr_info_t *fin;
2686 u_32_t *passp;
2687{
2688 ipf_main_softc_t *softc = fin->fin_main_soft;
2689 frentry_t *fr;
2690 u_32_t pass;
2691 int out;
2692
2693 out = fin->fin_out;
2694 pass = *passp;
2695
2696 /*
2697 * This rule cache will only affect packets that are not being
2698 * statefully filtered.
2699 */
2700 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2701 if (fin->fin_fr != NULL)
2702 pass = ipf_scanlist(fin, softc->ipf_pass);
2703
2704 if ((pass & FR_NOMATCH)) {
2705 LBUMPD(ipf_stats[out], fr_nom);
2706 }
2707 fr = fin->fin_fr;
2708
2709 /*
2710 * Apply packets per second rate-limiting to a rule as required.
2711 */
2712 if ((fr != NULL) && (fr->fr_pps != 0) &&
2713 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2714 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2715 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2716 pass |= FR_BLOCK;
2717 LBUMPD(ipf_stats[out], fr_ppshit);
2718 fin->fin_reason = FRB_PPSRATE;
2719 }
2720
2721 /*
2722 * If we fail to add a packet to the authorization queue, then we
2723 * drop the packet later. However, if it was added then pretend
2724 * we've dropped it already.
2725 */
2726 if (FR_ISAUTH(pass)) {
2727 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2728 DT1(frb_authnew, fr_info_t *, fin);
2729 fin->fin_m = *fin->fin_mp = NULL;
2730 fin->fin_reason = FRB_AUTHNEW;
2731 fin->fin_error = 0;
2732 } else {
2733 IPFERROR(1);
2734 fin->fin_error = ENOSPC;
2735 }
2736 }
2737
2738 if ((fr != NULL) && (fr->fr_func != NULL) &&
2739 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2740 (void) (*fr->fr_func)(fin, &pass);
2741
2742 /*
2743 * If a rule is a pre-auth rule, check again in the list of rules
2744 * loaded for authenticated use. It does not particulary matter
2745 * if this search fails because a "preauth" result, from a rule,
2746 * is treated as "not a pass", hence the packet is blocked.
2747 */
2748 if (FR_ISPREAUTH(pass)) {
2749 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2750 }
2751
2752 /*
2753 * If the rule has "keep frag" and the packet is actually a fragment,
2754 * then create a fragment state entry.
2755 */
2756 if (pass & FR_KEEPFRAG) {
2757 if (fin->fin_flx & FI_FRAG) {
2758 if (ipf_frag_new(softc, fin, pass) == -1) {
2759 LBUMP(ipf_stats[out].fr_bnfr);
2760 } else {
2761 LBUMP(ipf_stats[out].fr_nfr);
2762 }
2763 } else {
2764 LBUMP(ipf_stats[out].fr_cfr);
2765 }
2766 }
2767
2768 fr = fin->fin_fr;
2769 *passp = pass;
2770
2771 return fr;
2772}
2773
2774
2775/* ------------------------------------------------------------------------ */
2776/* Function: ipf_check */
2777/* Returns: int - 0 == packet allowed through, */
2778/* User space: */
2779/* -1 == packet blocked */
2780/* 1 == packet not matched */
2781/* -2 == requires authentication */
2782/* Kernel: */
2783/* > 0 == filter error # for packet */
2784/* Parameters: ctx(I) - pointer to the instance context */
2785/* ip(I) - pointer to start of IPv4/6 packet */
2786/* hlen(I) - length of header */
2787/* ifp(I) - pointer to interface this packet is on */
2788/* out(I) - 0 == packet going in, 1 == packet going out */
2789/* mp(IO) - pointer to caller's buffer pointer that holds this */
2790/* IP packet. */
2791/* Solaris: */
2792/* qpi(I) - pointer to STREAMS queue information for this */
2793/* interface & direction. */
2794/* */
2795/* ipf_check() is the master function for all IPFilter packet processing. */
2796/* It orchestrates: Network Address Translation (NAT), checking for packet */
2797/* authorisation (or pre-authorisation), presence of related state info., */
2798/* generating log entries, IP packet accounting, routing of packets as */
2799/* directed by firewall rules and of course whether or not to allow the */
2800/* packet to be further processed by the kernel. */
2801/* */
2802/* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2803/* freed. Packets passed may be returned with the pointer pointed to by */
2804/* by "mp" changed to a new buffer. */
2805/* ------------------------------------------------------------------------ */
2806int
2807ipf_check(ctx, ip, hlen, ifp, out
2808#if defined(_KERNEL) && defined(MENTAT)
2809 , qif, mp)
2810 void *qif;
2811#else
2812 , mp)
2813#endif
2814 mb_t **mp;
2815 ip_t *ip;
2816 int hlen;
2817 struct ifnet *ifp;
2818 int out;
2819 void *ctx;
2820{
2821 /*
2822 * The above really sucks, but short of writing a diff
2823 */
2824 ipf_main_softc_t *softc = ctx;
2825 fr_info_t frinfo;
2826 fr_info_t *fin = &frinfo;
2827 u_32_t pass = softc->ipf_pass;
2828 frentry_t *fr = NULL;
2829 int v = IP_V(ip);
2830 mb_t *mc = NULL;
2831 mb_t *m;
2832 /*
2833 * The first part of ipf_check() deals with making sure that what goes
2834 * into the filtering engine makes some sense. Information about the
2835 * the packet is distilled, collected into a fr_info_t structure and
2836 * the an attempt to ensure the buffer the packet is in is big enough
2837 * to hold all the required packet headers.
2838 */
2839#ifdef _KERNEL
2840# ifdef MENTAT
2841 qpktinfo_t *qpi = qif;
2842
2843# ifdef __sparc
2844 if ((u_int)ip & 0x3)
2845 return 2;
2846# endif
2847# else
2848 SPL_INT(s);
2849# endif
2850
2851 if (softc->ipf_running <= 0) {
2852 return 0;
2853 }
2854
2855 bzero((char *)fin, sizeof(*fin));
2856
2857# ifdef MENTAT
2858 if (qpi->qpi_flags & QF_BROADCAST)
2859 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2860 if (qpi->qpi_flags & QF_MULTICAST)
2861 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2862 m = qpi->qpi_m;
2863 fin->fin_qfm = m;
2864 fin->fin_qpi = qpi;
2865# else /* MENTAT */
2866
2867 m = *mp;
2868
2869# if defined(M_MCAST)
2870 if ((m->m_flags & M_MCAST) != 0)
2871 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2872# endif
2873# if defined(M_MLOOP)
2874 if ((m->m_flags & M_MLOOP) != 0)
2875 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2876# endif
2877# if defined(M_BCAST)
2878 if ((m->m_flags & M_BCAST) != 0)
2879 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2880# endif
2881# ifdef M_CANFASTFWD
2882 /*
2883 * XXX For now, IP Filter and fast-forwarding of cached flows
2884 * XXX are mutually exclusive. Eventually, IP Filter should
2885 * XXX get a "can-fast-forward" filter rule.
2886 */
2887 m->m_flags &= ~M_CANFASTFWD;
2888# endif /* M_CANFASTFWD */
2889# if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2890 /*
2891 * disable delayed checksums.
2892 */
2893 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2894 in_delayed_cksum(m);
2895 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2896 }
2897# endif /* CSUM_DELAY_DATA */
2898# endif /* MENTAT */
2899#else
2900 bzero((char *)fin, sizeof(*fin));
2901 m = *mp;
2902# if defined(M_MCAST)
2903 if ((m->m_flags & M_MCAST) != 0)
2904 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2905# endif
2906# if defined(M_MLOOP)
2907 if ((m->m_flags & M_MLOOP) != 0)
2908 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2909# endif
2910# if defined(M_BCAST)
2911 if ((m->m_flags & M_BCAST) != 0)
2912 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2913# endif
2914#endif /* _KERNEL */
2915
2916 fin->fin_v = v;
2917 fin->fin_m = m;
2918 fin->fin_ip = ip;
2919 fin->fin_mp = mp;
2920 fin->fin_out = out;
2921 fin->fin_ifp = ifp;
2922 fin->fin_error = ENETUNREACH;
2923 fin->fin_hlen = (u_short)hlen;
2924 fin->fin_dp = (char *)ip + hlen;
2925 fin->fin_main_soft = softc;
2926
2927 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2928
2929 SPL_NET(s);
2930
2931#ifdef USE_INET6
2932 if (v == 6) {
2933 LBUMP(ipf_stats[out].fr_ipv6);
2934 /*
2935 * Jumbo grams are quite likely too big for internal buffer
2936 * structures to handle comfortably, for now, so just drop
2937 * them.
2938 */
2939 if (((ip6_t *)ip)->ip6_plen == 0) {
2940 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2941 pass = FR_BLOCK|FR_NOMATCH;
2942 fin->fin_reason = FRB_JUMBO;
2943 goto finished;
2944 }
2945 fin->fin_family = AF_INET6;
2946 } else
2947#endif
2948 {
2949 fin->fin_family = AF_INET;
2950 }
2951
2952 if (ipf_makefrip(hlen, ip, fin) == -1) {
2953 DT1(frb_makefrip, fr_info_t *, fin);
2954 pass = FR_BLOCK|FR_NOMATCH;
2955 fin->fin_reason = FRB_MAKEFRIP;
2956 goto finished;
2957 }
2958
2959 /*
2960 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2961 * becomes NULL and so we have no packet to free.
2962 */
2963 if (*fin->fin_mp == NULL)
2964 goto finished;
2965
2966 if (!out) {
2967 if (v == 4) {
2968 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2969 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2970 fin->fin_flx |= FI_BADSRC;
2971 }
2972 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2973 LBUMPD(ipf_stats[0], fr_v4_badttl);
2974 fin->fin_flx |= FI_LOWTTL;
2975 }
2976 }
2977#ifdef USE_INET6
2978 else if (v == 6) {
2979 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2980 LBUMPD(ipf_stats[0], fr_v6_badttl);
2981 fin->fin_flx |= FI_LOWTTL;
2982 }
2983 }
2984#endif
2985 }
2986
2987 if (fin->fin_flx & FI_SHORT) {
2988 LBUMPD(ipf_stats[out], fr_short);
2989 }
2990
2991 READ_ENTER(&softc->ipf_mutex);
2992
2993 if (!out) {
2994 switch (fin->fin_v)
2995 {
2996 case 4 :
2997 if (ipf_nat_checkin(fin, &pass) == -1) {
2998 goto filterdone;
2999 }
3000 break;
3001#ifdef USE_INET6
3002 case 6 :
3003 if (ipf_nat6_checkin(fin, &pass) == -1) {
3004 goto filterdone;
3005 }
3006 break;
3007#endif
3008 default :
3009 break;
3010 }
3011 }
3012 /*
3013 * Check auth now.
3014 * If a packet is found in the auth table, then skip checking
3015 * the access lists for permission but we do need to consider
3016 * the result as if it were from the ACL's. In addition, being
3017 * found in the auth table means it has been seen before, so do
3018 * not pass it through accounting (again), lest it be counted twice.
3019 */
3020 fr = ipf_auth_check(fin, &pass);
3021 if (!out && (fr == NULL))
3022 (void) ipf_acctpkt(fin, NULL);
3023
3024 if (fr == NULL) {
3025 if ((fin->fin_flx & FI_FRAG) != 0)
3026 fr = ipf_frag_known(fin, &pass);
3027
3028 if (fr == NULL)
3029 fr = ipf_state_check(fin, &pass);
3030 }
3031
3032 if ((pass & FR_NOMATCH) || (fr == NULL))
3033 fr = ipf_firewall(fin, &pass);
3034
3035 /*
3036 * If we've asked to track state for this packet, set it up.
3037 * Here rather than ipf_firewall because ipf_checkauth may decide
3038 * to return a packet for "keep state"
3039 */
3040 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3041 !(fin->fin_flx & FI_STATE)) {
3042 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3043 LBUMP(ipf_stats[out].fr_ads);
3044 } else {
3045 LBUMP(ipf_stats[out].fr_bads);
3046 if (FR_ISPASS(pass)) {
3047 DT(frb_stateadd);
3048 pass &= ~FR_CMDMASK;
3049 pass |= FR_BLOCK;
3050 fin->fin_reason = FRB_STATEADD;
3051 }
3052 }
3053 }
3054
3055 fin->fin_fr = fr;
3056 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3057 fin->fin_dif = &fr->fr_dif;
3058 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3059 }
3060
3061 /*
3062 * Only count/translate packets which will be passed on, out the
3063 * interface.
3064 */
3065 if (out && FR_ISPASS(pass)) {
3066 (void) ipf_acctpkt(fin, NULL);
3067
3068 switch (fin->fin_v)
3069 {
3070 case 4 :
3071 if (ipf_nat_checkout(fin, &pass) == -1) {
3072 ;
3073 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3074 if (ipf_updateipid(fin) == -1) {
3075 DT(frb_updateipid);
3076 LBUMP(ipf_stats[1].fr_ipud);
3077 pass &= ~FR_CMDMASK;
3078 pass |= FR_BLOCK;
3079 fin->fin_reason = FRB_UPDATEIPID;
3080 } else {
3081 LBUMP(ipf_stats[0].fr_ipud);
3082 }
3083 }
3084 break;
3085#ifdef USE_INET6
3086 case 6 :
3087 (void) ipf_nat6_checkout(fin, &pass);
3088 break;
3089#endif
3090 default :
3091 break;
3092 }
3093 }
3094
3095filterdone:
3096#ifdef IPFILTER_LOG
3097 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3098 (void) ipf_dolog(fin, &pass);
3099 }
3100#endif
3101
3102 /*
3103 * The FI_STATE flag is cleared here so that calling ipf_state_check
3104 * will work when called from inside of fr_fastroute. Although
3105 * there is a similar flag, FI_NATED, for NAT, it does have the same
3106 * impact on code execution.
3107 */
3108 fin->fin_flx &= ~FI_STATE;
3109
3110#if defined(FASTROUTE_RECURSION)
3111 /*
3112 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3113 * a packet below can sometimes cause a recursive call into IPFilter.
3114 * On those platforms where that does happen, we need to hang onto
3115 * the filter rule just in case someone decides to remove or flush it
3116 * in the meantime.
3117 */
3118 if (fr != NULL) {
3119 MUTEX_ENTER(&fr->fr_lock);
3120 fr->fr_ref++;
3121 MUTEX_EXIT(&fr->fr_lock);
3122 }
3123
3124 RWLOCK_EXIT(&softc->ipf_mutex);
3125#endif
3126
3127 if ((pass & FR_RETMASK) != 0) {
3128 /*
3129 * Should we return an ICMP packet to indicate error
3130 * status passing through the packet filter ?
3131 * WARNING: ICMP error packets AND TCP RST packets should
3132 * ONLY be sent in repsonse to incoming packets. Sending
3133 * them in response to outbound packets can result in a
3134 * panic on some operating systems.
3135 */
3136 if (!out) {
3137 if (pass & FR_RETICMP) {
3138 int dst;
3139
3140 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3141 dst = 1;
3142 else
3143 dst = 0;
3144 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3145 dst);
3146 LBUMP(ipf_stats[0].fr_ret);
3147 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3148 !(fin->fin_flx & FI_SHORT)) {
3149 if (((fin->fin_flx & FI_OOW) != 0) ||
3150 (ipf_send_reset(fin) == 0)) {
3151 LBUMP(ipf_stats[1].fr_ret);
3152 }
3153 }
3154
3155 /*
3156 * When using return-* with auth rules, the auth code
3157 * takes over disposing of this packet.
3158 */
3159 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3160 DT1(frb_authcapture, fr_info_t *, fin);
3161 fin->fin_m = *fin->fin_mp = NULL;
3162 fin->fin_reason = FRB_AUTHCAPTURE;
3163 m = NULL;
3164 }
3165 } else {
3166 if (pass & FR_RETRST) {
3167 fin->fin_error = ECONNRESET;
3168 }
3169 }
3170 }
3171
3172 /*
3173 * After the above so that ICMP unreachables and TCP RSTs get
3174 * created properly.
3175 */
3176 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3177 ipf_nat_uncreate(fin);
3178
3179 /*
3180 * If we didn't drop off the bottom of the list of rules (and thus
3181 * the 'current' rule fr is not NULL), then we may have some extra
3182 * instructions about what to do with a packet.
3183 * Once we're finished return to our caller, freeing the packet if
3184 * we are dropping it.
3185 */
3186 if (fr != NULL) {
3187 frdest_t *fdp;
3188
3189 /*
3190 * Generate a duplicated packet first because ipf_fastroute
3191 * can lead to fin_m being free'd... not good.
3192 */
3193 fdp = fin->fin_dif;
3194 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3195 (fdp->fd_ptr != (void *)-1)) {
3196 mc = M_COPY(fin->fin_m);
3197 if (mc != NULL)
3198 ipf_fastroute(mc, &mc, fin, fdp);
3199 }
3200
3201 fdp = fin->fin_tif;
3202 if (!out && (pass & FR_FASTROUTE)) {
3203 /*
3204 * For fastroute rule, no destination interface defined
3205 * so pass NULL as the frdest_t parameter
3206 */
3207 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3208 m = *mp = NULL;
3209 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3210 (fdp->fd_ptr != (struct ifnet *)-1)) {
3211 /* this is for to rules: */
3212 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3213 m = *mp = NULL;
3214 }
3215
3216#if defined(FASTROUTE_RECURSION)
3217 (void) ipf_derefrule(softc, &fr);
3218#endif
3219 }
3220#if !defined(FASTROUTE_RECURSION)
3221 RWLOCK_EXIT(&softc->ipf_mutex);
3222#endif
3223
3224finished:
3225 if (!FR_ISPASS(pass)) {
3226 LBUMP(ipf_stats[out].fr_block);
3227 if (*mp != NULL) {
3228#ifdef _KERNEL
3229 FREE_MB_T(*mp);
3230#endif
3231 m = *mp = NULL;
3232 }
3233 } else {
3234 LBUMP(ipf_stats[out].fr_pass);
3235 }
3236
3237 SPL_X(s);
3238
3239#ifdef _KERNEL
3240 if (FR_ISPASS(pass))
3241 return 0;
3242 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3243 return fin->fin_error;
3244#else /* _KERNEL */
3245 if (*mp != NULL)
3246 (*mp)->mb_ifp = fin->fin_ifp;
3247 blockreason = fin->fin_reason;
3248 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3249 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3250 if ((pass & FR_NOMATCH) != 0)
3251 return 1;
3252
3253 if ((pass & FR_RETMASK) != 0)
3254 switch (pass & FR_RETMASK)
3255 {
3256 case FR_RETRST :
3257 return 3;
3258 case FR_RETICMP :
3259 return 4;
3260 case FR_FAKEICMP :
3261 return 5;
3262 }
3263
3264 switch (pass & FR_CMDMASK)
3265 {
3266 case FR_PASS :
3267 return 0;
3268 case FR_BLOCK :
3269 return -1;
3270 case FR_AUTH :
3271 return -2;
3272 case FR_ACCOUNT :
3273 return -3;
3274 case FR_PREAUTH :
3275 return -4;
3276 }
3277 return 2;
3278#endif /* _KERNEL */
3279}
3280
3281
3282#ifdef IPFILTER_LOG
3283/* ------------------------------------------------------------------------ */
3284/* Function: ipf_dolog */
3285/* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3286/* Parameters: fin(I) - pointer to packet information */
3287/* passp(IO) - pointer to current/new filter decision (unused) */
3288/* */
3289/* Checks flags set to see how a packet should be logged, if it is to be */
3290/* logged. Adjust statistics based on its success or not. */
3291/* ------------------------------------------------------------------------ */
3292frentry_t *
3293ipf_dolog(fin, passp)
3294 fr_info_t *fin;
3295 u_32_t *passp;
3296{
3297 ipf_main_softc_t *softc = fin->fin_main_soft;
3298 u_32_t pass;
3299 int out;
3300
3301 out = fin->fin_out;
3302 pass = *passp;
3303
3304 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3305 pass |= FF_LOGNOMATCH;
3306 LBUMPD(ipf_stats[out], fr_npkl);
3307 goto logit;
3308
3309 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3310 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3311 if ((pass & FR_LOGMASK) != FR_LOGP)
3312 pass |= FF_LOGPASS;
3313 LBUMPD(ipf_stats[out], fr_ppkl);
3314 goto logit;
3315
3316 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3317 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3318 if ((pass & FR_LOGMASK) != FR_LOGB)
3319 pass |= FF_LOGBLOCK;
3320 LBUMPD(ipf_stats[out], fr_bpkl);
3321
3322logit:
3323 if (ipf_log_pkt(fin, pass) == -1) {
3324 /*
3325 * If the "or-block" option has been used then
3326 * block the packet if we failed to log it.
3327 */
3328 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3329 DT1(frb_logfail2, u_int, pass);
3330 pass &= ~FR_CMDMASK;
3331 pass |= FR_BLOCK;
3332 fin->fin_reason = FRB_LOGFAIL2;
3333 }
3334 }
3335 *passp = pass;
3336 }
3337
3338 return fin->fin_fr;
3339}
3340#endif /* IPFILTER_LOG */
3341
3342
3343/* ------------------------------------------------------------------------ */
3344/* Function: ipf_cksum */
3345/* Returns: u_short - IP header checksum */
3346/* Parameters: addr(I) - pointer to start of buffer to checksum */
3347/* len(I) - length of buffer in bytes */
3348/* */
3349/* Calculate the two's complement 16 bit checksum of the buffer passed. */
3350/* */
3351/* N.B.: addr should be 16bit aligned. */
3352/* ------------------------------------------------------------------------ */
3353u_short
3354ipf_cksum(addr, len)
3355 u_short *addr;
3356 int len;
3357{
3358 u_32_t sum = 0;
3359
3360 for (sum = 0; len > 1; len -= 2)
3361 sum += *addr++;
3362
3363 /* mop up an odd byte, if necessary */
3364 if (len == 1)
3365 sum += *(u_char *)addr;
3366
3367 /*
3368 * add back carry outs from top 16 bits to low 16 bits
3369 */
3370 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3371 sum += (sum >> 16); /* add carry */
3372 return (u_short)(~sum);
3373}
3374
3375
3376/* ------------------------------------------------------------------------ */
3377/* Function: fr_cksum */
3378/* Returns: u_short - layer 4 checksum */
3379/* Parameters: fin(I) - pointer to packet information */
3380/* ip(I) - pointer to IP header */
3381/* l4proto(I) - protocol to caclulate checksum for */
3382/* l4hdr(I) - pointer to layer 4 header */
3383/* */
3384/* Calculates the TCP checksum for the packet held in "m", using the data */
3385/* in the IP header "ip" to seed it. */
3386/* */
3387/* NB: This function assumes we've pullup'd enough for all of the IP header */
3388/* and the TCP header. We also assume that data blocks aren't allocated in */
3389/* odd sizes. */
3390/* */
3391/* Expects ip_len and ip_off to be in network byte order when called. */
3392/* ------------------------------------------------------------------------ */
3393u_short
3394fr_cksum(fin, ip, l4proto, l4hdr)
3395 fr_info_t *fin;
3396 ip_t *ip;
3397 int l4proto;
3398 void *l4hdr;
3399{
3400 u_short *sp, slen, sumsave, *csump;
3401 u_int sum, sum2;
3402 int hlen;
3403 int off;
3404#ifdef USE_INET6
3405 ip6_t *ip6;
3406#endif
3407
3408 csump = NULL;
3409 sumsave = 0;
3410 sp = NULL;
3411 slen = 0;
3412 hlen = 0;
3413 sum = 0;
3414
3415 sum = htons((u_short)l4proto);
3416 /*
3417 * Add up IP Header portion
3418 */
3419#ifdef USE_INET6
3420 if (IP_V(ip) == 4) {
3421#endif
3422 hlen = IP_HL(ip) << 2;
3423 off = hlen;
3424 sp = (u_short *)&ip->ip_src;
3425 sum += *sp++; /* ip_src */
3426 sum += *sp++;
3427 sum += *sp++; /* ip_dst */
3428 sum += *sp++;
3429 slen = fin->fin_plen - off;
3430 sum += htons(slen);
3431#ifdef USE_INET6
3432 } else if (IP_V(ip) == 6) {
3433 mb_t *m;
3434
3435 m = fin->fin_m;
3436 ip6 = (ip6_t *)ip;
3437 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3438 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3439 return(ipf_pcksum6(m, ip6, off, len));
3440 } else {
3441 return 0xffff;
3442 }
3443#endif
3444
3445 switch (l4proto)
3446 {
3447 case IPPROTO_UDP :
3448 csump = &((udphdr_t *)l4hdr)->uh_sum;
3449 break;
3450
3451 case IPPROTO_TCP :
3452 csump = &((tcphdr_t *)l4hdr)->th_sum;
3453 break;
3454 case IPPROTO_ICMP :
3455 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3456 sum = 0; /* Pseudo-checksum is not included */
3457 break;
3458#ifdef USE_INET6
3459 case IPPROTO_ICMPV6 :
3460 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3461 break;
3462#endif
3463 default :
3464 break;
3465 }
3466
3467 if (csump != NULL) {
3468 sumsave = *csump;
3469 *csump = 0;
3470 }
3471
3472 sum2 = ipf_pcksum(fin, off, sum);
3473 if (csump != NULL)
3474 *csump = sumsave;
3475 return sum2;
3476}
3477
3478
3479/* ------------------------------------------------------------------------ */
3480/* Function: ipf_findgroup */
3481/* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3482/* Parameters: softc(I) - pointer to soft context main structure */
3483/* group(I) - group name to search for */
3484/* unit(I) - device to which this group belongs */
3485/* set(I) - which set of rules (inactive/inactive) this is */
3486/* fgpp(O) - pointer to place to store pointer to the pointer */
3487/* to where to add the next (last) group or where */
3488/* to delete group from. */
3489/* */
3490/* Search amongst the defined groups for a particular group number. */
3491/* ------------------------------------------------------------------------ */
3492frgroup_t *
3493ipf_findgroup(softc, group, unit, set, fgpp)
3494 ipf_main_softc_t *softc;
3495 char *group;
3496 minor_t unit;
3497 int set;
3498 frgroup_t ***fgpp;
3499{
3500 frgroup_t *fg, **fgp;
3501
3502 /*
3503 * Which list of groups to search in is dependent on which list of
3504 * rules are being operated on.
3505 */
3506 fgp = &softc->ipf_groups[unit][set];
3507
3508 while ((fg = *fgp) != NULL) {
3509 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3510 break;
3511 else
3512 fgp = &fg->fg_next;
3513 }
3514 if (fgpp != NULL)
3515 *fgpp = fgp;
3516 return fg;
3517}
3518
3519
3520/* ------------------------------------------------------------------------ */
3521/* Function: ipf_group_add */
3522/* Returns: frgroup_t * - NULL == did not create group, */
3523/* != NULL == pointer to the group */
3524/* Parameters: softc(I) - pointer to soft context main structure */
3525/* num(I) - group number to add */
3526/* head(I) - rule pointer that is using this as the head */
3527/* flags(I) - rule flags which describe the type of rule it is */
3528/* unit(I) - device to which this group will belong to */
3529/* set(I) - which set of rules (inactive/inactive) this is */
3530/* Write Locks: ipf_mutex */
3531/* */
3532/* Add a new group head, or if it already exists, increase the reference */
3533/* count to it. */
3534/* ------------------------------------------------------------------------ */
3535frgroup_t *
3536ipf_group_add(softc, group, head, flags, unit, set)
3537 ipf_main_softc_t *softc;
3538 char *group;
3539 void *head;
3540 u_32_t flags;
3541 minor_t unit;
3542 int set;
3543{
3544 frgroup_t *fg, **fgp;
3545 u_32_t gflags;
3546
3547 if (group == NULL)
3548 return NULL;
3549
3550 if (unit == IPL_LOGIPF && *group == '\0')
3551 return NULL;
3552
3553 fgp = NULL;
3554 gflags = flags & FR_INOUT;
3555
3556 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3557 if (fg != NULL) {
3558 if (fg->fg_head == NULL && head != NULL)
3559 fg->fg_head = head;
3560 if (fg->fg_flags == 0)
3561 fg->fg_flags = gflags;
3562 else if (gflags != fg->fg_flags)
3563 return NULL;
3564 fg->fg_ref++;
3565 return fg;
3566 }
3567
3568 KMALLOC(fg, frgroup_t *);
3569 if (fg != NULL) {
3570 fg->fg_head = head;
3571 fg->fg_start = NULL;
3572 fg->fg_next = *fgp;
3573 bcopy(group, fg->fg_name, strlen(group) + 1);
3574 fg->fg_flags = gflags;
3575 fg->fg_ref = 1;
3576 fg->fg_set = &softc->ipf_groups[unit][set];
3577 *fgp = fg;
3578 }
3579 return fg;
3580}
3581
3582
3583/* ------------------------------------------------------------------------ */
3584/* Function: ipf_group_del */
3585/* Returns: int - number of rules deleted */
3586/* Parameters: softc(I) - pointer to soft context main structure */
3587/* group(I) - group name to delete */
3588/* fr(I) - filter rule from which group is referenced */
3589/* Write Locks: ipf_mutex */
3590/* */
3591/* This function is called whenever a reference to a group is to be dropped */
3592/* and thus its reference count needs to be lowered and the group free'd if */
3593/* the reference count reaches zero. Passing in fr is really for the sole */
3594/* purpose of knowing when the head rule is being deleted. */
3595/* ------------------------------------------------------------------------ */
3596void
3597ipf_group_del(softc, group, fr)
3598 ipf_main_softc_t *softc;
3599 frgroup_t *group;
3600 frentry_t *fr;
3601{
3602
3603 if (group->fg_head == fr)
3604 group->fg_head = NULL;
3605
3606 group->fg_ref--;
3607 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3608 ipf_group_free(group);
3609}
3610
3611
3612/* ------------------------------------------------------------------------ */
3613/* Function: ipf_group_free */
3614/* Returns: Nil */
3615/* Parameters: group(I) - pointer to filter rule group */
3616/* */
3617/* Remove the group from the list of groups and free it. */
3618/* ------------------------------------------------------------------------ */
3619static void
3620ipf_group_free(group)
3621 frgroup_t *group;
3622{
3623 frgroup_t **gp;
3624
3625 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3626 if (*gp == group) {
3627 *gp = group->fg_next;
3628 break;
3629 }
3630 }
3631 KFREE(group);
3632}
3633
3634
3635/* ------------------------------------------------------------------------ */
3636/* Function: ipf_group_flush */
3637/* Returns: int - number of rules flush from group */
3638/* Parameters: softc(I) - pointer to soft context main structure */
3639/* Parameters: group(I) - pointer to filter rule group */
3640/* */
3641/* Remove all of the rules that currently are listed under the given group. */
3642/* ------------------------------------------------------------------------ */
3643static int
3644ipf_group_flush(softc, group)
3645 ipf_main_softc_t *softc;
3646 frgroup_t *group;
3647{
3648 int gone = 0;
3649
3650 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3651
3652 return gone;
3653}
3654
3655
3656/* ------------------------------------------------------------------------ */
3657/* Function: ipf_getrulen */
3658/* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3659/* Parameters: softc(I) - pointer to soft context main structure */
3660/* Parameters: unit(I) - device for which to count the rule's number */
3661/* flags(I) - which set of rules to find the rule in */
3662/* group(I) - group name */
3663/* n(I) - rule number to find */
3664/* */
3665/* Find rule # n in group # g and return a pointer to it. Return NULl if */
3666/* group # g doesn't exist or there are less than n rules in the group. */
3667/* ------------------------------------------------------------------------ */
3668frentry_t *
3669ipf_getrulen(softc, unit, group, n)
3670 ipf_main_softc_t *softc;
3671 int unit;
3672 char *group;
3673 u_32_t n;
3674{
3675 frentry_t *fr;
3676 frgroup_t *fg;
3677
3678 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3679 if (fg == NULL)
3680 return NULL;
3681 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3682 ;
3683 if (n != 0)
3684 return NULL;
3685 return fr;
3686}
3687
3688
3689/* ------------------------------------------------------------------------ */
3690/* Function: ipf_flushlist */
3691/* Returns: int - >= 0 - number of flushed rules */
3692/* Parameters: softc(I) - pointer to soft context main structure */
3693/* nfreedp(O) - pointer to int where flush count is stored */
3694/* listp(I) - pointer to list to flush pointer */
3695/* Write Locks: ipf_mutex */
3696/* */
3697/* Recursively flush rules from the list, descending groups as they are */
3698/* encountered. if a rule is the head of a group and it has lost all its */
3699/* group members, then also delete the group reference. nfreedp is needed */
3700/* to store the accumulating count of rules removed, whereas the returned */
3701/* value is just the number removed from the current list. The latter is */
3702/* needed to correctly adjust reference counts on rules that define groups. */
3703/* */
3704/* NOTE: Rules not loaded from user space cannot be flushed. */
3705/* ------------------------------------------------------------------------ */
3706static int
3707ipf_flushlist(softc, nfreedp, listp)
3708 ipf_main_softc_t *softc;
3709 int *nfreedp;
3710 frentry_t **listp;
3711{
3712 int freed = 0;
3713 frentry_t *fp;
3714
3715 while ((fp = *listp) != NULL) {
3716 if ((fp->fr_type & FR_T_BUILTIN) ||
3717 !(fp->fr_flags & FR_COPIED)) {
3718 listp = &fp->fr_next;
3719 continue;
3720 }
3721 *listp = fp->fr_next;
3722 if (fp->fr_next != NULL)
3723 fp->fr_next->fr_pnext = fp->fr_pnext;
3724 fp->fr_pnext = NULL;
3725
3726 if (fp->fr_grphead != NULL) {
3727 freed += ipf_group_flush(softc, fp->fr_grphead);
3728 fp->fr_names[fp->fr_grhead] = '\0';
3729 }
3730
3731 if (fp->fr_icmpgrp != NULL) {
3732 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3733 fp->fr_names[fp->fr_icmphead] = '\0';
3734 }
3735
3736 if (fp->fr_srctrack.ht_max_nodes)
3737 ipf_rb_ht_flush(&fp->fr_srctrack);
3738
3739 fp->fr_next = NULL;
3740
3741 ASSERT(fp->fr_ref > 0);
3742 if (ipf_derefrule(softc, &fp) == 0)
3743 freed++;
3744 }
3745 *nfreedp += freed;
3746 return freed;
3747}
3748
3749
3750/* ------------------------------------------------------------------------ */
3751/* Function: ipf_flush */
3752/* Returns: int - >= 0 - number of flushed rules */
3753/* Parameters: softc(I) - pointer to soft context main structure */
3754/* unit(I) - device for which to flush rules */
3755/* flags(I) - which set of rules to flush */
3756/* */
3757/* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3758/* and IPv6) as defined by the value of flags. */
3759/* ------------------------------------------------------------------------ */
3760int
3761ipf_flush(softc, unit, flags)
3762 ipf_main_softc_t *softc;
3763 minor_t unit;
3764 int flags;
3765{
3766 int flushed = 0, set;
3767
3768 WRITE_ENTER(&softc->ipf_mutex);
3769
3770 set = softc->ipf_active;
3771 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3772 set = 1 - set;
3773
3774 if (flags & FR_OUTQUE) {
3775 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3776 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3777 }
3778 if (flags & FR_INQUE) {
3779 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3780 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3781 }
3782
3783 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3784 flags & (FR_INQUE|FR_OUTQUE));
3785
3786 RWLOCK_EXIT(&softc->ipf_mutex);
3787
3788 if (unit == IPL_LOGIPF) {
3789 int tmp;
3790
3791 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3792 if (tmp >= 0)
3793 flushed += tmp;
3794 }
3795 return flushed;
3796}
3797
3798
3799/* ------------------------------------------------------------------------ */
3800/* Function: ipf_flush_groups */
3801/* Returns: int - >= 0 - number of flushed rules */
3802/* Parameters: softc(I) - soft context pointerto work with */
3803/* grhead(I) - pointer to the start of the group list to flush */
3804/* flags(I) - which set of rules to flush */
3805/* */
3806/* Walk through all of the groups under the given group head and remove all */
3807/* of those that match the flags passed in. The for loop here is bit more */
3808/* complicated than usual because the removal of a rule with ipf_derefrule */
3809/* may end up removing not only the structure pointed to by "fg" but also */
3810/* what is fg_next and fg_next after that. So if a filter rule is actually */
3811/* removed from the group then it is necessary to start again. */
3812/* ------------------------------------------------------------------------ */
3813static int
3814ipf_flush_groups(softc, grhead, flags)
3815 ipf_main_softc_t *softc;
3816 frgroup_t **grhead;
3817 int flags;
3818{
3819 frentry_t *fr, **frp;
3820 frgroup_t *fg, **fgp;
3821 int flushed = 0;
3822 int removed = 0;
3823
3824 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3825 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3826 fg = fg->fg_next;
3827 if (fg == NULL)
3828 break;
3829 removed = 0;
3830 frp = &fg->fg_start;
3831 while ((removed == 0) && ((fr = *frp) != NULL)) {
3832 if ((fr->fr_flags & flags) == 0) {
3833 frp = &fr->fr_next;
3834 } else {
3835 if (fr->fr_next != NULL)
3836 fr->fr_next->fr_pnext = fr->fr_pnext;
3837 *frp = fr->fr_next;
3838 fr->fr_pnext = NULL;
3839 fr->fr_next = NULL;
3840 (void) ipf_derefrule(softc, &fr);
3841 flushed++;
3842 removed++;
3843 }
3844 }
3845 if (removed == 0)
3846 fgp = &fg->fg_next;
3847 }
3848 return flushed;
3849}
3850
3851
3852/* ------------------------------------------------------------------------ */
3853/* Function: memstr */
3854/* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3855/* Parameters: src(I) - pointer to byte sequence to match */
3856/* dst(I) - pointer to byte sequence to search */
3857/* slen(I) - match length */
3858/* dlen(I) - length available to search in */
3859/* */
3860/* Search dst for a sequence of bytes matching those at src and extend for */
3861/* slen bytes. */
3862/* ------------------------------------------------------------------------ */
3863char *
3864memstr(src, dst, slen, dlen)
3865 const char *src;
3866 char *dst;
3867 size_t slen, dlen;
3868{
3869 char *s = NULL;
3870
3871 while (dlen >= slen) {
3872 if (bcmp(src, dst, slen) == 0) {
3873 s = dst;
3874 break;
3875 }
3876 dst++;
3877 dlen--;
3878 }
3879 return s;
3880}
3881/* ------------------------------------------------------------------------ */
3882/* Function: ipf_fixskip */
3883/* Returns: Nil */
3884/* Parameters: listp(IO) - pointer to start of list with skip rule */
3885/* rp(I) - rule added/removed with skip in it. */
3886/* addremove(I) - adjustment (-1/+1) to make to skip count, */
3887/* depending on whether a rule was just added */
3888/* or removed. */
3889/* */
3890/* Adjust all the rules in a list which would have skip'd past the position */
3891/* where we are inserting to skip to the right place given the change. */
3892/* ------------------------------------------------------------------------ */
3893void
3894ipf_fixskip(listp, rp, addremove)
3895 frentry_t **listp, *rp;
3896 int addremove;
3897{
3898 int rules, rn;
3899 frentry_t *fp;
3900
3901 rules = 0;
3902 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3903 rules++;
3904
3905 if (fp == NULL)
3906 return;
3907
3908 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3909 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3910 fp->fr_arg += addremove;
3911}
3912
3913
3914#ifdef _KERNEL
3915/* ------------------------------------------------------------------------ */
3916/* Function: count4bits */
3917/* Returns: int - >= 0 - number of consecutive bits in input */
3918/* Parameters: ip(I) - 32bit IP address */
3919/* */
3920/* IPv4 ONLY */
3921/* count consecutive 1's in bit mask. If the mask generated by counting */
3922/* consecutive 1's is different to that passed, return -1, else return # */
3923/* of bits. */
3924/* ------------------------------------------------------------------------ */
3925int
3926count4bits(ip)
3927 u_32_t ip;
3928{
3929 u_32_t ipn;
3930 int cnt = 0, i, j;
3931
3932 ip = ipn = ntohl(ip);
3933 for (i = 32; i; i--, ipn *= 2)
3934 if (ipn & 0x80000000)
3935 cnt++;
3936 else
3937 break;
3938 ipn = 0;
3939 for (i = 32, j = cnt; i; i--, j--) {
3940 ipn *= 2;
3941 if (j > 0)
3942 ipn++;
3943 }
3944 if (ipn == ip)
3945 return cnt;
3946 return -1;
3947}
3948
3949
3950/* ------------------------------------------------------------------------ */
3951/* Function: count6bits */
3952/* Returns: int - >= 0 - number of consecutive bits in input */
3953/* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3954/* */
3955/* IPv6 ONLY */
3956/* count consecutive 1's in bit mask. */
3957/* ------------------------------------------------------------------------ */
3958# ifdef USE_INET6
3959int
3960count6bits(msk)
3961 u_32_t *msk;
3962{
3963 int i = 0, k;
3964 u_32_t j;
3965
3966 for (k = 3; k >= 0; k--)
3967 if (msk[k] == 0xffffffff)
3968 i += 32;
3969 else {
3970 for (j = msk[k]; j; j <<= 1)
3971 if (j & 0x80000000)
3972 i++;
3973 }
3974 return i;
3975}
3976# endif
3977#endif /* _KERNEL */
3978
3979
3980/* ------------------------------------------------------------------------ */
3981/* Function: ipf_synclist */
3982/* Returns: int - 0 = no failures, else indication of first failure */
3983/* Parameters: fr(I) - start of filter list to sync interface names for */
3984/* ifp(I) - interface pointer for limiting sync lookups */
3985/* Write Locks: ipf_mutex */
3986/* */
3987/* Walk through a list of filter rules and resolve any interface names into */
3988/* pointers. Where dynamic addresses are used, also update the IP address */
3989/* used in the rule. The interface pointer is used to limit the lookups to */
3990/* a specific set of matching names if it is non-NULL. */
3991/* Errors can occur when resolving the destination name of to/dup-to fields */
3992/* when the name points to a pool and that pool doest not exist. If this */
3993/* does happen then it is necessary to check if there are any lookup refs */
3994/* that need to be dropped before returning with an error. */
3995/* ------------------------------------------------------------------------ */
3996static int
3997ipf_synclist(softc, fr, ifp)
3998 ipf_main_softc_t *softc;
3999 frentry_t *fr;
4000 void *ifp;
4001{
4002 frentry_t *frt, *start = fr;
4003 frdest_t *fdp;
4004 char *name;
4005 int error;
4006 void *ifa;
4007 int v, i;
4008
4009 error = 0;
4010
4011 for (; fr; fr = fr->fr_next) {
4012 if (fr->fr_family == AF_INET)
4013 v = 4;
4014 else if (fr->fr_family == AF_INET6)
4015 v = 6;
4016 else
4017 v = 0;
4018
4019 /*
4020 * Lookup all the interface names that are part of the rule.
4021 */
4022 for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
4023 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4024 continue;
4025 if (fr->fr_ifnames[i] == -1)
4026 continue;
4027 name = FR_NAME(fr, fr_ifnames[i]);
4028 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4029 }
4030
4031 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4032 if (fr->fr_satype != FRI_NORMAL &&
4033 fr->fr_satype != FRI_LOOKUP) {
4034 ifa = ipf_resolvenic(softc, fr->fr_names +
4035 fr->fr_sifpidx, v);
4036 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4037 &fr->fr_src6, &fr->fr_smsk6);
4038 }
4039 if (fr->fr_datype != FRI_NORMAL &&
4040 fr->fr_datype != FRI_LOOKUP) {
4041 ifa = ipf_resolvenic(softc, fr->fr_names +
4042 fr->fr_sifpidx, v);
4043 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4044 &fr->fr_dst6, &fr->fr_dmsk6);
4045 }
4046 }
4047
4048 fdp = &fr->fr_tifs[0];
4049 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4050 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4051 if (error != 0)
4052 goto unwind;
4053 }
4054
4055 fdp = &fr->fr_tifs[1];
4056 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4057 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4058 if (error != 0)
4059 goto unwind;
4060 }
4061
4062 fdp = &fr->fr_dif;
4063 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4064 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4065 if (error != 0)
4066 goto unwind;
4067 }
4068
4069 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4070 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4071 fr->fr_srcptr = ipf_lookup_res_num(softc,
4072 fr->fr_srctype,
4073 IPL_LOGIPF,
4074 fr->fr_srcnum,
4075 &fr->fr_srcfunc);
4076 }
4077 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4078 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4079 fr->fr_dstptr = ipf_lookup_res_num(softc,
4080 fr->fr_dsttype,
4081 IPL_LOGIPF,
4082 fr->fr_dstnum,
4083 &fr->fr_dstfunc);
4084 }
4085 }
4086 return 0;
4087
4088unwind:
4089 for (frt = start; frt != fr; fr = fr->fr_next) {
4090 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4091 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4092 ipf_lookup_deref(softc, frt->fr_srctype,
4093 frt->fr_srcptr);
4094 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4095 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4096 ipf_lookup_deref(softc, frt->fr_dsttype,
4097 frt->fr_dstptr);
4098 }
4099 return error;
4100}
4101
4102
4103/* ------------------------------------------------------------------------ */
4104/* Function: ipf_sync */
4105/* Returns: void */
4106/* Parameters: Nil */
4107/* */
4108/* ipf_sync() is called when we suspect that the interface list or */
4109/* information about interfaces (like IP#) has changed. Go through all */
4110/* filter rules, NAT entries and the state table and check if anything */
4111/* needs to be changed/updated. */
4112/* ------------------------------------------------------------------------ */
4113int
4114ipf_sync(softc, ifp)
4115 ipf_main_softc_t *softc;
4116 void *ifp;
4117{
4118 int i;
4119
4120# if !SOLARIS
4121 ipf_nat_sync(softc, ifp);
4122 ipf_state_sync(softc, ifp);
4123 ipf_lookup_sync(softc, ifp);
4124# endif
4125
4126 WRITE_ENTER(&softc->ipf_mutex);
4127 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4128 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4129 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4130 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4131
4132 for (i = 0; i < IPL_LOGSIZE; i++) {
4133 frgroup_t *g;
4134
4135 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4136 (void) ipf_synclist(softc, g->fg_start, ifp);
4137 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4138 (void) ipf_synclist(softc, g->fg_start, ifp);
4139 }
4140 RWLOCK_EXIT(&softc->ipf_mutex);
4141
4142 return 0;
4143}
4144
4145
4146/*
4147 * In the functions below, bcopy() is called because the pointer being
4148 * copied _from_ in this instance is a pointer to a char buf (which could
4149 * end up being unaligned) and on the kernel's local stack.
4150 */
4151/* ------------------------------------------------------------------------ */
4152/* Function: copyinptr */
4153/* Returns: int - 0 = success, else failure */
4154/* Parameters: src(I) - pointer to the source address */
4155/* dst(I) - destination address */
4156/* size(I) - number of bytes to copy */
4157/* */
4158/* Copy a block of data in from user space, given a pointer to the pointer */
4159/* to start copying from (src) and a pointer to where to store it (dst). */
4160/* NB: src - pointer to user space pointer, dst - kernel space pointer */
4161/* ------------------------------------------------------------------------ */
4162int
4163copyinptr(softc, src, dst, size)
4164 ipf_main_softc_t *softc;
4165 void *src, *dst;
4166 size_t size;
4167{
4168 caddr_t ca;
4169 int error;
4170
4171# if SOLARIS
4172 error = COPYIN(src, &ca, sizeof(ca));
4173 if (error != 0)
4174 return error;
4175# else
4176 bcopy(src, (caddr_t)&ca, sizeof(ca));
4177# endif
4178 error = COPYIN(ca, dst, size);
4179 if (error != 0) {
4180 IPFERROR(3);
4181 error = EFAULT;
4182 }
4183 return error;
4184}
4185
4186
4187/* ------------------------------------------------------------------------ */
4188/* Function: copyoutptr */
4189/* Returns: int - 0 = success, else failure */
4190/* Parameters: src(I) - pointer to the source address */
4191/* dst(I) - destination address */
4192/* size(I) - number of bytes to copy */
4193/* */
4194/* Copy a block of data out to user space, given a pointer to the pointer */
4195/* to start copying from (src) and a pointer to where to store it (dst). */
4196/* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4197/* ------------------------------------------------------------------------ */
4198int
4199copyoutptr(softc, src, dst, size)
4200 ipf_main_softc_t *softc;
4201 void *src, *dst;
4202 size_t size;
4203{
4204 caddr_t ca;
4205 int error;
4206
4207 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4208 error = COPYOUT(src, ca, size);
4209 if (error != 0) {
4210 IPFERROR(4);
4211 error = EFAULT;
4212 }
4213 return error;
4214}
4215
4216
4217/* ------------------------------------------------------------------------ */
4218/* Function: ipf_lock */
4219/* Returns: int - 0 = success, else error */
4220/* Parameters: data(I) - pointer to lock value to set */
4221/* lockp(O) - pointer to location to store old lock value */
4222/* */
4223/* Get the new value for the lock integer, set it and return the old value */
4224/* in *lockp. */
4225/* ------------------------------------------------------------------------ */
4226int
4227ipf_lock(data, lockp)
4228 caddr_t data;
4229 int *lockp;
4230{
4231 int arg, err;
4232
4233 err = BCOPYIN(data, &arg, sizeof(arg));
4234 if (err != 0)
4235 return EFAULT;
4236 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4237 if (err != 0)
4238 return EFAULT;
4239 *lockp = arg;
4240 return 0;
4241}
4242
4243
4244/* ------------------------------------------------------------------------ */
4245/* Function: ipf_getstat */
4246/* Returns: Nil */
4247/* Parameters: softc(I) - pointer to soft context main structure */
4248/* fiop(I) - pointer to ipfilter stats structure */
4249/* rev(I) - version claim by program doing ioctl */
4250/* */
4251/* Stores a copy of current pointers, counters, etc, in the friostat */
4252/* structure. */
4253/* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4254/* program is looking for. This ensure that validation of the version it */
4255/* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4256/* allow older binaries to work but kernels without it will not. */
4257/* ------------------------------------------------------------------------ */
4258/*ARGSUSED*/
4259static void
4260ipf_getstat(softc, fiop, rev)
4261 ipf_main_softc_t *softc;
4262 friostat_t *fiop;
4263 int rev;
4264{
4265 int i;
4266
4267 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4268 sizeof(ipf_statistics_t) * 2);
4269 fiop->f_locks[IPL_LOGSTATE] = -1;
4270 fiop->f_locks[IPL_LOGNAT] = -1;
4271 fiop->f_locks[IPL_LOGIPF] = -1;
4272 fiop->f_locks[IPL_LOGAUTH] = -1;
4273
4274 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4275 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4276 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4277 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4278 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4279 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4280 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4281 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4282
4283 fiop->f_ticks = softc->ipf_ticks;
4284 fiop->f_active = softc->ipf_active;
4285 fiop->f_froute[0] = softc->ipf_frouteok[0];
4286 fiop->f_froute[1] = softc->ipf_frouteok[1];
4287 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4288 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4289
4290 fiop->f_running = softc->ipf_running;
4291 for (i = 0; i < IPL_LOGSIZE; i++) {
4292 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4293 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4294 }
4295#ifdef IPFILTER_LOG
4296 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4297 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4298 fiop->f_logging = 1;
4299#else
4300 fiop->f_log_ok = 0;
4301 fiop->f_log_fail = 0;
4302 fiop->f_logging = 0;
4303#endif
4304 fiop->f_defpass = softc->ipf_pass;
4305 fiop->f_features = ipf_features;
4306
4307#ifdef IPFILTER_COMPAT
4308 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4309 (rev / 1000000) % 100,
4310 (rev / 10000) % 100,
4311 (rev / 100) % 100);
4312#else
4313 rev = rev;
4314 (void) strncpy(fiop->f_version, ipfilter_version,
4315 sizeof(fiop->f_version));
4316#endif
4317}
4318
4319
4320#ifdef USE_INET6
4321int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4322 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4323 -1, /* 1: UNUSED */
4324 -1, /* 2: UNUSED */
4325 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4326 -1, /* 4: ICMP_SOURCEQUENCH */
4327 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4328 -1, /* 6: UNUSED */
4329 -1, /* 7: UNUSED */
4330 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4331 -1, /* 9: UNUSED */
4332 -1, /* 10: UNUSED */
4333 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4334 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4335 -1, /* 13: ICMP_TSTAMP */
4336 -1, /* 14: ICMP_TSTAMPREPLY */
4337 -1, /* 15: ICMP_IREQ */
4338 -1, /* 16: ICMP_IREQREPLY */
4339 -1, /* 17: ICMP_MASKREQ */
4340 -1, /* 18: ICMP_MASKREPLY */
4341};
4342
4343
4344int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4345 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4346 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4347 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4348 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4349 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4350 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4351 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4352 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4353 -1, /* 8: ICMP_UNREACH_ISOLATED */
4354 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4355 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4356 -1, /* 11: ICMP_UNREACH_TOSNET */
4357 -1, /* 12: ICMP_UNREACH_TOSHOST */
4358 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4359};
4360int icmpreplytype6[ICMP6_MAXTYPE + 1];
4361#endif
4362
4363int icmpreplytype4[ICMP_MAXTYPE + 1];
4364
4365
4366/* ------------------------------------------------------------------------ */
4367/* Function: ipf_matchicmpqueryreply */
4368/* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4369/* Parameters: v(I) - IP protocol version (4 or 6) */
4370/* ic(I) - ICMP information */
4371/* icmp(I) - ICMP packet header */
4372/* rev(I) - direction (0 = forward/1 = reverse) of packet */
4373/* */
4374/* Check if the ICMP packet defined by the header pointed to by icmp is a */
4375/* reply to one as described by what's in ic. If it is a match, return 1, */
4376/* else return 0 for no match. */
4377/* ------------------------------------------------------------------------ */
4378int
4379ipf_matchicmpqueryreply(v, ic, icmp, rev)
4380 int v;
4381 icmpinfo_t *ic;
4382 icmphdr_t *icmp;
4383 int rev;
4384{
4385 int ictype;
4386
4387 ictype = ic->ici_type;
4388
4389 if (v == 4) {
4390 /*
4391 * If we matched its type on the way in, then when going out
4392 * it will still be the same type.
4393 */
4394 if ((!rev && (icmp->icmp_type == ictype)) ||
4395 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4396 if (icmp->icmp_type != ICMP_ECHOREPLY)
4397 return 1;
4398 if (icmp->icmp_id == ic->ici_id)
4399 return 1;
4400 }
4401 }
4402#ifdef USE_INET6
4403 else if (v == 6) {
4404 if ((!rev && (icmp->icmp_type == ictype)) ||
4405 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4406 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4407 return 1;
4408 if (icmp->icmp_id == ic->ici_id)
4409 return 1;
4410 }
4411 }
4412#endif
4413 return 0;
4414}
4415
4416
4417/*
4418 * IFNAMES are located in the variable length field starting at
4419 * frentry.fr_names. As pointers within the struct cannot be passed
4420 * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4421 * is unused (invalid). If it is used (valid) it is an offset to the
4422 * character string of an interface name or a comment. The following
4423 * macros will assist those who follow to understand the code.
4424 */
4425#define IPF_IFNAME_VALID(_a) (_a != -1)
4426#define IPF_IFNAME_INVALID(_a) (_a == -1)
4427#define IPF_IFNAMES_DIFFERENT(_a) \
4428 !((IPF_IFNAME_INVALID(fr1->_a) && \
4429 IPF_IFNAME_INVALID(fr2->_a)) || \
4430 (IPF_IFNAME_VALID(fr1->_a) && \
4431 IPF_IFNAME_VALID(fr2->_a) && \
4432 !strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4433#define IPF_FRDEST_DIFFERENT(_a) \
4434 (memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr, \
4435 offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) || \
4436 IPF_IFNAMES_DIFFERENT(_a.fd_name))
4437
4438
4439/* ------------------------------------------------------------------------ */
4440/* Function: ipf_rule_compare */
4441/* Parameters: fr1(I) - first rule structure to compare */
4442/* fr2(I) - second rule structure to compare */
4443/* Returns: int - 0 == rules are the same, else mismatch */
4444/* */
4445/* Compare two rules and return 0 if they match or a number indicating */
4446/* which of the individual checks failed. */
4447/* ------------------------------------------------------------------------ */
4448static int
4449ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4450{
4451 int i;
4452
4453 if (fr1->fr_cksum != fr2->fr_cksum)
4454 return (1);
4455 if (fr1->fr_size != fr2->fr_size)
4456 return (2);
4457 if (fr1->fr_dsize != fr2->fr_dsize)
4458 return (3);
4459 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4460 != 0)
4461 return (4);
4462 /*
4463 * XXX: There is still a bug here as different rules with the
4464 * the same interfaces but in a different order will compare
4465 * differently. But since multiple interfaces in a rule doesn't
4466 * work anyway a simple straightforward compare is performed
4467 * here. Ultimately frentry_t creation will need to be
4468 * revisited in ipf_y.y. While the other issue, recognition
4469 * of only the first interface in a list of interfaces will
4470 * need to be separately addressed along with why only four.
4471 */
4472 for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4473 /*
4474 * XXX: It's either the same index or uninitialized.
4475 * We assume this because multiple interfaces
4476 * referenced by the same rule doesn't work anyway.
4477 */
4478 if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4479 return(5);
4480 }
4481
4482 if (IPF_FRDEST_DIFFERENT(fr_tif))
4483 return (6);
4484 if (IPF_FRDEST_DIFFERENT(fr_rif))
4485 return (7);
4486 if (IPF_FRDEST_DIFFERENT(fr_dif))
4487 return (8);
4488 if (!fr1->fr_data && !fr2->fr_data)
4489 return (0); /* move along, nothing to see here */
4490 if (fr1->fr_data && fr2->fr_data) {
4491 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4492 return (0); /* same */
4493 }
4494 return (9);
4495}
4496
4497
4498/* ------------------------------------------------------------------------ */
4499/* Function: frrequest */
4500/* Returns: int - 0 == success, > 0 == errno value */
4501/* Parameters: unit(I) - device for which this is for */
4502/* req(I) - ioctl command (SIOC*) */
4503/* data(I) - pointr to ioctl data */
4504/* set(I) - 1 or 0 (filter set) */
4505/* makecopy(I) - flag indicating whether data points to a rule */
4506/* in kernel space & hence doesn't need copying. */
4507/* */
4508/* This function handles all the requests which operate on the list of */
4509/* filter rules. This includes adding, deleting, insertion. It is also */
4510/* responsible for creating groups when a "head" rule is loaded. Interface */
4511/* names are resolved here and other sanity checks are made on the content */
4512/* of the rule structure being loaded. If a rule has user defined timeouts */
4513/* then make sure they are created and initialised before exiting. */
4514/* ------------------------------------------------------------------------ */
4515int
4516frrequest(softc, unit, req, data, set, makecopy)
4517 ipf_main_softc_t *softc;
4518 int unit;
4519 ioctlcmd_t req;
4520 int set, makecopy;
4521 caddr_t data;
4522{
4523 int error = 0, in, family, need_free = 0;
4524 enum { OP_ADD, /* add rule */
4525 OP_REM, /* remove rule */
4526 OP_ZERO /* zero statistics and counters */ }
4527 addrem = OP_ADD;
4528 frentry_t frd, *fp, *f, **fprev, **ftail;
4529 void *ptr, *uptr, *cptr;
4530 u_int *p, *pp;
4531 frgroup_t *fg;
4532 char *group;
4533
4534 ptr = NULL;
4535 cptr = NULL;
4536 fg = NULL;
4537 fp = &frd;
4538 if (makecopy != 0) {
4539 bzero(fp, sizeof(frd));
4540 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4541 if (error) {
4542 return error;
4543 }
4544 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4545 IPFERROR(6);
4546 return EINVAL;
4547 }
4548 KMALLOCS(f, frentry_t *, fp->fr_size);
4549 if (f == NULL) {
4550 IPFERROR(131);
4551 return ENOMEM;
4552 }
4553 bzero(f, fp->fr_size);
4554 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4555 fp->fr_size);
4556 if (error) {
4557 KFREES(f, fp->fr_size);
4558 return error;
4559 }
4560
4561 fp = f;
4562 f = NULL;
4563 fp->fr_next = NULL;
4564 fp->fr_dnext = NULL;
4565 fp->fr_pnext = NULL;
4566 fp->fr_pdnext = NULL;
4567 fp->fr_grp = NULL;
4568 fp->fr_grphead = NULL;
4569 fp->fr_icmpgrp = NULL;
4570 fp->fr_isc = (void *)-1;
4571 fp->fr_ptr = NULL;
4572 fp->fr_ref = 0;
4573 fp->fr_flags |= FR_COPIED;
4574 } else {
4575 fp = (frentry_t *)data;
4576 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4577 IPFERROR(7);
4578 return EINVAL;
4579 }
4580 fp->fr_flags &= ~FR_COPIED;
4581 }
4582
4583 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4584 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4585 IPFERROR(8);
4586 error = EINVAL;
4587 goto donenolock;
4588 }
4589
4590 family = fp->fr_family;
4591 uptr = fp->fr_data;
4592
4593 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4594 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4595 addrem = OP_ADD; /* Add rule */
4596 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4597 addrem = OP_REM; /* Remove rule */
4598 else if (req == (ioctlcmd_t)SIOCZRLST)
4599 addrem = OP_ZERO; /* Zero statistics and counters */
4600 else {
4601 IPFERROR(9);
4602 error = EINVAL;
4603 goto donenolock;
4604 }
4605
4606 /*
4607 * Only filter rules for IPv4 or IPv6 are accepted.
4608 */
4609 if (family == AF_INET) {
4610 /*EMPTY*/;
4611#ifdef USE_INET6
4612 } else if (family == AF_INET6) {
4613 /*EMPTY*/;
4614#endif
4615 } else if (family != 0) {
4616 IPFERROR(10);
4617 error = EINVAL;
4618 goto donenolock;
4619 }
4620
4621 /*
4622 * If the rule is being loaded from user space, i.e. we had to copy it
4623 * into kernel space, then do not trust the function pointer in the
4624 * rule.
4625 */
4626 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4627 if (ipf_findfunc(fp->fr_func) == NULL) {
4628 IPFERROR(11);
4629 error = ESRCH;
4630 goto donenolock;
4631 }
4632
4633 if (addrem == OP_ADD) {
4634 error = ipf_funcinit(softc, fp);
4635 if (error != 0)
4636 goto donenolock;
4637 }
4638 }
4639 if ((fp->fr_flags & FR_CALLNOW) &&
4640 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4641 IPFERROR(142);
4642 error = ESRCH;
4643 goto donenolock;
4644 }
4645 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4646 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4647 IPFERROR(143);
4648 error = ESRCH;
4649 goto donenolock;
4650 }
4651
4652 ptr = NULL;
4653 cptr = NULL;
4654
4655 if (FR_ISACCOUNT(fp->fr_flags))
4656 unit = IPL_LOGCOUNT;
4657
4658 /*
4659 * Check that each group name in the rule has a start index that
4660 * is valid.
4661 */
4662 if (fp->fr_icmphead != -1) {
4663 if ((fp->fr_icmphead < 0) ||
4664 (fp->fr_icmphead >= fp->fr_namelen)) {
4665 IPFERROR(136);
4666 error = EINVAL;
4667 goto donenolock;
4668 }
4669 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4670 fp->fr_names[fp->fr_icmphead] = '\0';
4671 }
4672
4673 if (fp->fr_grhead != -1) {
4674 if ((fp->fr_grhead < 0) ||
4675 (fp->fr_grhead >= fp->fr_namelen)) {
4676 IPFERROR(137);
4677 error = EINVAL;
4678 goto donenolock;
4679 }
4680 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4681 fp->fr_names[fp->fr_grhead] = '\0';
4682 }
4683
4684 if (fp->fr_group != -1) {
4685 if ((fp->fr_group < 0) ||
4686 (fp->fr_group >= fp->fr_namelen)) {
4687 IPFERROR(138);
4688 error = EINVAL;
4689 goto donenolock;
4690 }
4691 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4692 /*
4693 * Allow loading rules that are in groups to cause
4694 * them to be created if they don't already exit.
4695 */
4696 group = FR_NAME(fp, fr_group);
4697 if (addrem == OP_ADD) {
4698 fg = ipf_group_add(softc, group, NULL,
4699 fp->fr_flags, unit, set);
4700 fp->fr_grp = fg;
4701 } else {
4702 fg = ipf_findgroup(softc, group, unit,
4703 set, NULL);
4704 if (fg == NULL) {
4705 IPFERROR(12);
4706 error = ESRCH;
4707 goto donenolock;
4708 }
4709 }
4710
4711 if (fg->fg_flags == 0) {
4712 fg->fg_flags = fp->fr_flags & FR_INOUT;
4713 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4714 IPFERROR(13);
4715 error = ESRCH;
4716 goto donenolock;
4717 }
4718 }
4719 } else {
4720 /*
4721 * If a rule is going to be part of a group then it does
4722 * not matter whether it is an in or out rule, but if it
4723 * isn't in a group, then it does...
4724 */
4725 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4726 IPFERROR(14);
4727 error = EINVAL;
4728 goto donenolock;
4729 }
4730 }
4731 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4732
4733 /*
4734 * Work out which rule list this change is being applied to.
4735 */
4736 ftail = NULL;
4737 fprev = NULL;
4738 if (unit == IPL_LOGAUTH) {
4739 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4740 (fp->fr_tifs[1].fd_ptr != NULL) ||
4741 (fp->fr_dif.fd_ptr != NULL) ||
4742 (fp->fr_flags & FR_FASTROUTE)) {
4743 softc->ipf_interror = 145;
4744 error = EINVAL;
4745 goto donenolock;
4746 }
4747 fprev = ipf_auth_rulehead(softc);
4748 } else {
4749 if (FR_ISACCOUNT(fp->fr_flags))
4750 fprev = &softc->ipf_acct[in][set];
4751 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4752 fprev = &softc->ipf_rules[in][set];
4753 }
4754 if (fprev == NULL) {
4755 IPFERROR(15);
4756 error = ESRCH;
4757 goto donenolock;
4758 }
4759
4760 if (fg != NULL)
4761 fprev = &fg->fg_start;
4762
4763 /*
4764 * Copy in extra data for the rule.
4765 */
4766 if (fp->fr_dsize != 0) {
4767 if (makecopy != 0) {
4768 KMALLOCS(ptr, void *, fp->fr_dsize);
4769 if (ptr == NULL) {
4770 IPFERROR(16);
4771 error = ENOMEM;
4772 goto donenolock;
4773 }
4774
4775 /*
4776 * The bcopy case is for when the data is appended
4777 * to the rule by ipf_in_compat().
4778 */
4779 if (uptr >= (void *)fp &&
4780 uptr < (void *)((char *)fp + fp->fr_size)) {
4781 bcopy(uptr, ptr, fp->fr_dsize);
4782 error = 0;
4783 } else {
4784 error = COPYIN(uptr, ptr, fp->fr_dsize);
4785 if (error != 0) {
4786 IPFERROR(17);
4787 error = EFAULT;
4788 goto donenolock;
4789 }
4790 }
4791 } else {
4792 ptr = uptr;
4793 }
4794 fp->fr_data = ptr;
4795 } else {
4796 fp->fr_data = NULL;
4797 }
4798
4799 /*
4800 * Perform per-rule type sanity checks of their members.
4801 * All code after this needs to be aware that allocated memory
4802 * may need to be free'd before exiting.
4803 */
4804 switch (fp->fr_type & ~FR_T_BUILTIN)
4805 {
4806#if defined(IPFILTER_BPF)
4807 case FR_T_BPFOPC :
4808 if (fp->fr_dsize == 0) {
4809 IPFERROR(19);
4810 error = EINVAL;
4811 break;
4812 }
4813 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4814 IPFERROR(20);
4815 error = EINVAL;
4816 break;
4817 }
4818 break;
4819#endif
4820 case FR_T_IPF :
4821 /*
4822 * Preparation for error case at the bottom of this function.
4823 */
4824 if (fp->fr_datype == FRI_LOOKUP)
4825 fp->fr_dstptr = NULL;
4826 if (fp->fr_satype == FRI_LOOKUP)
4827 fp->fr_srcptr = NULL;
4828
4829 if (fp->fr_dsize != sizeof(fripf_t)) {
4830 IPFERROR(21);
4831 error = EINVAL;
4832 break;
4833 }
4834
4835 /*
4836 * Allowing a rule with both "keep state" and "with oow" is
4837 * pointless because adding a state entry to the table will
4838 * fail with the out of window (oow) flag set.
4839 */
4840 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4841 IPFERROR(22);
4842 error = EINVAL;
4843 break;
4844 }
4845
4846 switch (fp->fr_satype)
4847 {
4848 case FRI_BROADCAST :
4849 case FRI_DYNAMIC :
4850 case FRI_NETWORK :
4851 case FRI_NETMASKED :
4852 case FRI_PEERADDR :
4853 if (fp->fr_sifpidx < 0) {
4854 IPFERROR(23);
4855 error = EINVAL;
4856 }
4857 break;
4858 case FRI_LOOKUP :
4859 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4860 &fp->fr_src6,
4861 &fp->fr_smsk6);
4862 if (fp->fr_srcfunc == NULL) {
4863 IPFERROR(132);
4864 error = ESRCH;
4865 break;
4866 }
4867 break;
4868 case FRI_NORMAL :
4869 break;
4870 default :
4871 IPFERROR(133);
4872 error = EINVAL;
4873 break;
4874 }
4875 if (error != 0)
4876 break;
4877
4878 switch (fp->fr_datype)
4879 {
4880 case FRI_BROADCAST :
4881 case FRI_DYNAMIC :
4882 case FRI_NETWORK :
4883 case FRI_NETMASKED :
4884 case FRI_PEERADDR :
4885 if (fp->fr_difpidx < 0) {
4886 IPFERROR(24);
4887 error = EINVAL;
4888 }
4889 break;
4890 case FRI_LOOKUP :
4891 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4892 &fp->fr_dst6,
4893 &fp->fr_dmsk6);
4894 if (fp->fr_dstfunc == NULL) {
4895 IPFERROR(134);
4896 error = ESRCH;
4897 }
4898 break;
4899 case FRI_NORMAL :
4900 break;
4901 default :
4902 IPFERROR(135);
4903 error = EINVAL;
4904 }
4905 break;
4906
4907 case FR_T_NONE :
4908 case FR_T_CALLFUNC :
4909 case FR_T_COMPIPF :
4910 break;
4911
4912 case FR_T_IPFEXPR :
4913 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4914 IPFERROR(25);
4915 error = EINVAL;
4916 }
4917 break;
4918
4919 default :
4920 IPFERROR(26);
4921 error = EINVAL;
4922 break;
4923 }
4924 if (error != 0)
4925 goto donenolock;
4926
4927 if (fp->fr_tif.fd_name != -1) {
4928 if ((fp->fr_tif.fd_name < 0) ||
4929 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4930 IPFERROR(139);
4931 error = EINVAL;
4932 goto donenolock;
4933 }
4934 }
4935
4936 if (fp->fr_dif.fd_name != -1) {
4937 if ((fp->fr_dif.fd_name < 0) ||
4938 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4939 IPFERROR(140);
4940 error = EINVAL;
4941 goto donenolock;
4942 }
4943 }
4944
4945 if (fp->fr_rif.fd_name != -1) {
4946 if ((fp->fr_rif.fd_name < 0) ||
4947 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4948 IPFERROR(141);
4949 error = EINVAL;
4950 goto donenolock;
4951 }
4952 }
4953
4954 /*
4955 * Lookup all the interface names that are part of the rule.
4956 */
4957 error = ipf_synclist(softc, fp, NULL);
4958 if (error != 0)
4959 goto donenolock;
4960 fp->fr_statecnt = 0;
4961 if (fp->fr_srctrack.ht_max_nodes != 0)
4962 ipf_rb_ht_init(&fp->fr_srctrack);
4963
4964 /*
4965 * Look for an existing matching filter rule, but don't include the
4966 * next or interface pointer in the comparison (fr_next, fr_ifa).
4967 * This elminates rules which are indentical being loaded. Checksum
4968 * the constant part of the filter rule to make comparisons quicker
4969 * (this meaning no pointers are included).
4970 */
4971 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4972 for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4973 fp->fr_cksum += *p;
4974
4975 WRITE_ENTER(&softc->ipf_mutex);
4976
4977 /*
4978 * Now that the filter rule lists are locked, we can walk the
4979 * chain of them without fear.
4980 */
4981 ftail = fprev;
4982 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4983 if (fp->fr_collect <= f->fr_collect) {
4984 ftail = fprev;
4985 f = NULL;
4986 break;
4987 }
4988 fprev = ftail;
4989 }
4990
4991 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4992 if (ipf_rule_compare(fp, f) == 0)
4993 break;
4994 }
4995
4996 /*
4997 * If zero'ing statistics, copy current to caller and zero.
4998 */
4999 if (addrem == OP_ZERO) {
5000 if (f == NULL) {
5001 IPFERROR(27);
5002 error = ESRCH;
5003 } else {
5004 /*
5005 * Copy and reduce lock because of impending copyout.
5006 * Well we should, but if we do then the atomicity of
5007 * this call and the correctness of fr_hits and
5008 * fr_bytes cannot be guaranteed. As it is, this code
5009 * only resets them to 0 if they are successfully
5010 * copied out into user space.
5011 */
5012 bcopy((char *)f, (char *)fp, f->fr_size);
5013 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
5014
5015 /*
5016 * When we copy this rule back out, set the data
5017 * pointer to be what it was in user space.
5018 */
5019 fp->fr_data = uptr;
5020 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
5021
5022 if (error == 0) {
5023 if ((f->fr_dsize != 0) && (uptr != NULL)) {
5024 error = COPYOUT(f->fr_data, uptr,
5025 f->fr_dsize);
5026 if (error == 0) {
5027 f->fr_hits = 0;
5028 f->fr_bytes = 0;
5029 } else {
5030 IPFERROR(28);
5031 error = EFAULT;
5032 }
5033 }
5034 }
5035 }
5036
5037 if (makecopy != 0) {
5038 if (ptr != NULL) {
5039 KFREES(ptr, fp->fr_dsize);
5040 }
5041 KFREES(fp, fp->fr_size);
5042 }
5043 RWLOCK_EXIT(&softc->ipf_mutex);
5044 return error;
5045 }
5046
5047 if (f == NULL) {
5048 /*
5049 * At the end of this, ftail must point to the place where the
5050 * new rule is to be saved/inserted/added.
5051 * For SIOCAD*FR, this should be the last rule in the group of
5052 * rules that have equal fr_collect fields.
5053 * For SIOCIN*FR, ...
5054 */
5055 if (req == (ioctlcmd_t)SIOCADAFR ||
5056 req == (ioctlcmd_t)SIOCADIFR) {
5057
5058 for (ftail = fprev; (f = *ftail) != NULL; ) {
5059 if (f->fr_collect > fp->fr_collect)
5060 break;
5061 ftail = &f->fr_next;
5062 fprev = ftail;
5063 }
5064 ftail = fprev;
5065 f = NULL;
5066 ptr = NULL;
5067 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5068 req == (ioctlcmd_t)SIOCINIFR) {
5069 while ((f = *fprev) != NULL) {
5070 if (f->fr_collect >= fp->fr_collect)
5071 break;
5072 fprev = &f->fr_next;
5073 }
5074 ftail = fprev;
5075 if (fp->fr_hits != 0) {
5076 while (fp->fr_hits && (f = *ftail)) {
5077 if (f->fr_collect != fp->fr_collect)
5078 break;
5079 fprev = ftail;
5080 ftail = &f->fr_next;
5081 fp->fr_hits--;
5082 }
5083 }
5084 f = NULL;
5085 ptr = NULL;
5086 }
5087 }
5088
5089 /*
5090 * Request to remove a rule.
5091 */
5092 if (addrem == OP_REM) {
5093 if (f == NULL) {
5094 IPFERROR(29);
5095 error = ESRCH;
5096 } else {
5097 /*
5098 * Do not allow activity from user space to interfere
5099 * with rules not loaded that way.
5100 */
5101 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5102 IPFERROR(30);
5103 error = EPERM;
5104 goto done;
5105 }
5106
5107 /*
5108 * Return EBUSY if the rule is being reference by
5109 * something else (eg state information.)
5110 */
5111 if (f->fr_ref > 1) {
5112 IPFERROR(31);
5113 error = EBUSY;
5114 goto done;
5115 }
5116#ifdef IPFILTER_SCAN
5117 if (f->fr_isctag != -1 &&
5118 (f->fr_isc != (struct ipscan *)-1))
5119 ipf_scan_detachfr(f);
5120#endif
5121
5122 if (unit == IPL_LOGAUTH) {
5123 error = ipf_auth_precmd(softc, req, f, ftail);
5124 goto done;
5125 }
5126
5127 ipf_rule_delete(softc, f, unit, set);
5128
5129 need_free = makecopy;
5130 }
5131 } else {
5132 /*
5133 * Not removing, so we must be adding/inserting a rule.
5134 */
5135 if (f != NULL) {
5136 IPFERROR(32);
5137 error = EEXIST;
5138 goto done;
5139 }
5140 if (unit == IPL_LOGAUTH) {
5141 error = ipf_auth_precmd(softc, req, fp, ftail);
5142 goto done;
5143 }
5144
5145 MUTEX_NUKE(&fp->fr_lock);
5146 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5147 if (fp->fr_die != 0)
5148 ipf_rule_expire_insert(softc, fp, set);
5149
5150 fp->fr_hits = 0;
5151 if (makecopy != 0)
5152 fp->fr_ref = 1;
5153 fp->fr_pnext = ftail;
5154 fp->fr_next = *ftail;
5155 if (fp->fr_next != NULL)
5156 fp->fr_next->fr_pnext = &fp->fr_next;
5157 *ftail = fp;
5158 ipf_fixskip(ftail, fp, 1);
5159
5160 fp->fr_icmpgrp = NULL;
5161 if (fp->fr_icmphead != -1) {
5162 group = FR_NAME(fp, fr_icmphead);
5163 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5164 fp->fr_icmpgrp = fg;
5165 }
5166
5167 fp->fr_grphead = NULL;
5168 if (fp->fr_grhead != -1) {
5169 group = FR_NAME(fp, fr_grhead);
5170 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5171 unit, set);
5172 fp->fr_grphead = fg;
5173 }
5174 }
5175done:
5176 RWLOCK_EXIT(&softc->ipf_mutex);
5177donenolock:
5178 if (need_free || (error != 0)) {
5179 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5180 if ((fp->fr_satype == FRI_LOOKUP) &&
5181 (fp->fr_srcptr != NULL))
5182 ipf_lookup_deref(softc, fp->fr_srctype,
5183 fp->fr_srcptr);
5184 if ((fp->fr_datype == FRI_LOOKUP) &&
5185 (fp->fr_dstptr != NULL))
5186 ipf_lookup_deref(softc, fp->fr_dsttype,
5187 fp->fr_dstptr);
5188 }
5189 if (fp->fr_grp != NULL) {
5190 WRITE_ENTER(&softc->ipf_mutex);
5191 ipf_group_del(softc, fp->fr_grp, fp);
5192 RWLOCK_EXIT(&softc->ipf_mutex);
5193 }
5194 if ((ptr != NULL) && (makecopy != 0)) {
5195 KFREES(ptr, fp->fr_dsize);
5196 }
5197 KFREES(fp, fp->fr_size);
5198 }
5199 return (error);
5200}
5201
5202
5203/* ------------------------------------------------------------------------ */
5204/* Function: ipf_rule_delete */
5205/* Returns: Nil */
5206/* Parameters: softc(I) - pointer to soft context main structure */
5207/* f(I) - pointer to the rule being deleted */
5208/* ftail(I) - pointer to the pointer to f */
5209/* unit(I) - device for which this is for */
5210/* set(I) - 1 or 0 (filter set) */
5211/* */
5212/* This function attempts to do what it can to delete a filter rule: remove */
5213/* it from any linked lists and remove any groups it is responsible for. */
5214/* But in the end, removing a rule can only drop the reference count - we */
5215/* must use that as the guide for whether or not it can be freed. */
5216/* ------------------------------------------------------------------------ */
5217static void
5218ipf_rule_delete(softc, f, unit, set)
5219 ipf_main_softc_t *softc;
5220 frentry_t *f;
5221 int unit, set;
5222{
5223
5224 /*
5225 * If fr_pdnext is set, then the rule is on the expire list, so
5226 * remove it from there.
5227 */
5228 if (f->fr_pdnext != NULL) {
5229 *f->fr_pdnext = f->fr_dnext;
5230 if (f->fr_dnext != NULL)
5231 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5232 f->fr_pdnext = NULL;
5233 f->fr_dnext = NULL;
5234 }
5235
5236 ipf_fixskip(f->fr_pnext, f, -1);
5237 if (f->fr_pnext != NULL)
5238 *f->fr_pnext = f->fr_next;
5239 if (f->fr_next != NULL)
5240 f->fr_next->fr_pnext = f->fr_pnext;
5241 f->fr_pnext = NULL;
5242 f->fr_next = NULL;
5243
5244 (void) ipf_derefrule(softc, &f);
5245}
5246
5247/* ------------------------------------------------------------------------ */
5248/* Function: ipf_rule_expire_insert */
5249/* Returns: Nil */
5250/* Parameters: softc(I) - pointer to soft context main structure */
5251/* f(I) - pointer to rule to be added to expire list */
5252/* set(I) - 1 or 0 (filter set) */
5253/* */
5254/* If the new rule has a given expiration time, insert it into the list of */
5255/* expiring rules with the ones to be removed first added to the front of */
5256/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5257/* expiration interval checks. */
5258/* ------------------------------------------------------------------------ */
5259static void
5260ipf_rule_expire_insert(softc, f, set)
5261 ipf_main_softc_t *softc;
5262 frentry_t *f;
5263 int set;
5264{
5265 frentry_t *fr;
5266
5267 /*
5268 */
5269
5270 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5271 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5272 fr = fr->fr_dnext) {
5273 if (f->fr_die < fr->fr_die)
5274 break;
5275 if (fr->fr_dnext == NULL) {
5276 /*
5277 * We've got to the last rule and everything
5278 * wanted to be expired before this new node,
5279 * so we have to tack it on the end...
5280 */
5281 fr->fr_dnext = f;
5282 f->fr_pdnext = &fr->fr_dnext;
5283 fr = NULL;
5284 break;
5285 }
5286 }
5287
5288 if (softc->ipf_rule_explist[set] == NULL) {
5289 softc->ipf_rule_explist[set] = f;
5290 f->fr_pdnext = &softc->ipf_rule_explist[set];
5291 } else if (fr != NULL) {
5292 f->fr_dnext = fr;
5293 f->fr_pdnext = fr->fr_pdnext;
5294 fr->fr_pdnext = &f->fr_dnext;
5295 }
5296}
5297
5298
5299/* ------------------------------------------------------------------------ */
5300/* Function: ipf_findlookup */
5301/* Returns: NULL = failure, else success */
5302/* Parameters: softc(I) - pointer to soft context main structure */
5303/* unit(I) - ipf device we want to find match for */
5304/* fp(I) - rule for which lookup is for */
5305/* addrp(I) - pointer to lookup information in address struct */
5306/* maskp(O) - pointer to lookup information for storage */
5307/* */
5308/* When using pools and hash tables to store addresses for matching in */
5309/* rules, it is necessary to resolve both the object referred to by the */
5310/* name or address (and return that pointer) and also provide the means by */
5311/* which to determine if an address belongs to that object to make the */
5312/* packet matching quicker. */
5313/* ------------------------------------------------------------------------ */
5314static void *
5315ipf_findlookup(softc, unit, fr, addrp, maskp)
5316 ipf_main_softc_t *softc;
5317 int unit;
5318 frentry_t *fr;
5319 i6addr_t *addrp, *maskp;
5320{
5321 void *ptr = NULL;
5322
5323 switch (addrp->iplookupsubtype)
5324 {
5325 case 0 :
5326 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5327 addrp->iplookupnum,
5328 &maskp->iplookupfunc);
5329 break;
5330 case 1 :
5331 if (addrp->iplookupname < 0)
5332 break;
5333 if (addrp->iplookupname >= fr->fr_namelen)
5334 break;
5335 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5336 fr->fr_names + addrp->iplookupname,
5337 &maskp->iplookupfunc);
5338 break;
5339 default :
5340 break;
5341 }
5342
5343 return ptr;
5344}
5345
5346
5347/* ------------------------------------------------------------------------ */
5348/* Function: ipf_funcinit */
5349/* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5350/* Parameters: softc(I) - pointer to soft context main structure */
5351/* fr(I) - pointer to filter rule */
5352/* */
5353/* If a rule is a call rule, then check if the function it points to needs */
5354/* an init function to be called now the rule has been loaded. */
5355/* ------------------------------------------------------------------------ */
5356static int
5357ipf_funcinit(softc, fr)
5358 ipf_main_softc_t *softc;
5359 frentry_t *fr;
5360{
5361 ipfunc_resolve_t *ft;
5362 int err;
5363
5364 IPFERROR(34);
5365 err = ESRCH;
5366
5367 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5368 if (ft->ipfu_addr == fr->fr_func) {
5369 err = 0;
5370 if (ft->ipfu_init != NULL)
5371 err = (*ft->ipfu_init)(softc, fr);
5372 break;
5373 }
5374 return err;
5375}
5376
5377
5378/* ------------------------------------------------------------------------ */
5379/* Function: ipf_funcfini */
5380/* Returns: Nil */
5381/* Parameters: softc(I) - pointer to soft context main structure */
5382/* fr(I) - pointer to filter rule */
5383/* */
5384/* For a given filter rule, call the matching "fini" function if the rule */
5385/* is using a known function that would have resulted in the "init" being */
5386/* called for ealier. */
5387/* ------------------------------------------------------------------------ */
5388static void
5389ipf_funcfini(softc, fr)
5390 ipf_main_softc_t *softc;
5391 frentry_t *fr;
5392{
5393 ipfunc_resolve_t *ft;
5394
5395 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5396 if (ft->ipfu_addr == fr->fr_func) {
5397 if (ft->ipfu_fini != NULL)
5398 (void) (*ft->ipfu_fini)(softc, fr);
5399 break;
5400 }
5401}
5402
5403
5404/* ------------------------------------------------------------------------ */
5405/* Function: ipf_findfunc */
5406/* Returns: ipfunc_t - pointer to function if found, else NULL */
5407/* Parameters: funcptr(I) - function pointer to lookup */
5408/* */
5409/* Look for a function in the table of known functions. */
5410/* ------------------------------------------------------------------------ */
5411static ipfunc_t
5412ipf_findfunc(funcptr)
5413 ipfunc_t funcptr;
5414{
5415 ipfunc_resolve_t *ft;
5416
5417 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5418 if (ft->ipfu_addr == funcptr)
5419 return funcptr;
5420 return NULL;
5421}
5422
5423
5424/* ------------------------------------------------------------------------ */
5425/* Function: ipf_resolvefunc */
5426/* Returns: int - 0 == success, else error */
5427/* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5428/* */
5429/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5430/* This will either be the function name (if the pointer is set) or the */
5431/* function pointer if the name is set. When found, fill in the other one */
5432/* so that the entire, complete, structure can be copied back to user space.*/
5433/* ------------------------------------------------------------------------ */
5434int
5435ipf_resolvefunc(softc, data)
5436 ipf_main_softc_t *softc;
5437 void *data;
5438{
5439 ipfunc_resolve_t res, *ft;
5440 int error;
5441
5442 error = BCOPYIN(data, &res, sizeof(res));
5443 if (error != 0) {
5444 IPFERROR(123);
5445 return EFAULT;
5446 }
5447
5448 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5449 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5450 if (strncmp(res.ipfu_name, ft->ipfu_name,
5451 sizeof(res.ipfu_name)) == 0) {
5452 res.ipfu_addr = ft->ipfu_addr;
5453 res.ipfu_init = ft->ipfu_init;
5454 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5455 IPFERROR(35);
5456 return EFAULT;
5457 }
5458 return 0;
5459 }
5460 }
5461 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5462 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5463 if (ft->ipfu_addr == res.ipfu_addr) {
5464 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5465 sizeof(res.ipfu_name));
5466 res.ipfu_init = ft->ipfu_init;
5467 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5468 IPFERROR(36);
5469 return EFAULT;
5470 }
5471 return 0;
5472 }
5473 }
5474 IPFERROR(37);
5475 return ESRCH;
5476}
5477
5478
5479#if !defined(_KERNEL) || SOLARIS
5480/*
5481 * From: NetBSD
5482 * ppsratecheck(): packets (or events) per second limitation.
5483 */
5484int
5485ppsratecheck(lasttime, curpps, maxpps)
5486 struct timeval *lasttime;
5487 int *curpps;
5488 int maxpps; /* maximum pps allowed */
5489{
5490 struct timeval tv, delta;
5491 int rv;
5492
5493 GETKTIME(&tv);
5494
5495 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5496 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5497 if (delta.tv_usec < 0) {
5498 delta.tv_sec--;
5499 delta.tv_usec += 1000000;
5500 }
5501
5502 /*
5503 * check for 0,0 is so that the message will be seen at least once.
5504 * if more than one second have passed since the last update of
5505 * lasttime, reset the counter.
5506 *
5507 * we do increment *curpps even in *curpps < maxpps case, as some may
5508 * try to use *curpps for stat purposes as well.
5509 */
5510 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5511 delta.tv_sec >= 1) {
5512 *lasttime = tv;
5513 *curpps = 0;
5514 rv = 1;
5515 } else if (maxpps < 0)
5516 rv = 1;
5517 else if (*curpps < maxpps)
5518 rv = 1;
5519 else
5520 rv = 0;
5521 *curpps = *curpps + 1;
5522
5523 return (rv);
5524}
5525#endif
5526
5527
5528/* ------------------------------------------------------------------------ */
5529/* Function: ipf_derefrule */
5530/* Returns: int - 0 == rule freed up, else rule not freed */
5531/* Parameters: fr(I) - pointer to filter rule */
5532/* */
5533/* Decrement the reference counter to a rule by one. If it reaches zero, */
5534/* free it and any associated storage space being used by it. */
5535/* ------------------------------------------------------------------------ */
5536int
5537ipf_derefrule(softc, frp)
5538 ipf_main_softc_t *softc;
5539 frentry_t **frp;
5540{
5541 frentry_t *fr;
5542 frdest_t *fdp;
5543
5544 fr = *frp;
5545 *frp = NULL;
5546
5547 MUTEX_ENTER(&fr->fr_lock);
5548 fr->fr_ref--;
5549 if (fr->fr_ref == 0) {
5550 MUTEX_EXIT(&fr->fr_lock);
5551 MUTEX_DESTROY(&fr->fr_lock);
5552
5553 ipf_funcfini(softc, fr);
5554
5555 fdp = &fr->fr_tif;
5556 if (fdp->fd_type == FRD_DSTLIST)
5557 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5558
5559 fdp = &fr->fr_rif;
5560 if (fdp->fd_type == FRD_DSTLIST)
5561 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5562
5563 fdp = &fr->fr_dif;
5564 if (fdp->fd_type == FRD_DSTLIST)
5565 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5566
5567 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5568 fr->fr_satype == FRI_LOOKUP)
5569 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5570 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5571 fr->fr_datype == FRI_LOOKUP)
5572 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5573
5574 if (fr->fr_grp != NULL)
5575 ipf_group_del(softc, fr->fr_grp, fr);
5576
5577 if (fr->fr_grphead != NULL)
5578 ipf_group_del(softc, fr->fr_grphead, fr);
5579
5580 if (fr->fr_icmpgrp != NULL)
5581 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5582
5583 if ((fr->fr_flags & FR_COPIED) != 0) {
5584 if (fr->fr_dsize) {
5585 KFREES(fr->fr_data, fr->fr_dsize);
5586 }
5587 KFREES(fr, fr->fr_size);
5588 return 0;
5589 }
5590 return 1;
5591 } else {
5592 MUTEX_EXIT(&fr->fr_lock);
5593 }
5594 return -1;
5595}
5596
5597
5598/* ------------------------------------------------------------------------ */
5599/* Function: ipf_grpmapinit */
5600/* Returns: int - 0 == success, else ESRCH because table entry not found*/
5601/* Parameters: fr(I) - pointer to rule to find hash table for */
5602/* */
5603/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5604/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5605/* ------------------------------------------------------------------------ */
5606static int
5607ipf_grpmapinit(softc, fr)
5608 ipf_main_softc_t *softc;
5609 frentry_t *fr;
5610{
5611 char name[FR_GROUPLEN];
5612 iphtable_t *iph;
5613
5614#if defined(SNPRINTF) && defined(_KERNEL)
5615 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5616#else
5617 (void) sprintf(name, "%d", fr->fr_arg);
5618#endif
5619 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5620 if (iph == NULL) {
5621 IPFERROR(38);
5622 return ESRCH;
5623 }
5624 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5625 IPFERROR(39);
5626 return ESRCH;
5627 }
5628 iph->iph_ref++;
5629 fr->fr_ptr = iph;
5630 return 0;
5631}
5632
5633
5634/* ------------------------------------------------------------------------ */
5635/* Function: ipf_grpmapfini */
5636/* Returns: int - 0 == success, else ESRCH because table entry not found*/
5637/* Parameters: softc(I) - pointer to soft context main structure */
5638/* fr(I) - pointer to rule to release hash table for */
5639/* */
5640/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5641/* be called to undo what ipf_grpmapinit caused to be done. */
5642/* ------------------------------------------------------------------------ */
5643static int
5644ipf_grpmapfini(softc, fr)
5645 ipf_main_softc_t *softc;
5646 frentry_t *fr;
5647{
5648 iphtable_t *iph;
5649 iph = fr->fr_ptr;
5650 if (iph != NULL)
5651 ipf_lookup_deref(softc, IPLT_HASH, iph);
5652 return 0;
5653}
5654
5655
5656/* ------------------------------------------------------------------------ */
5657/* Function: ipf_srcgrpmap */
5658/* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5659/* Parameters: fin(I) - pointer to packet information */
5660/* passp(IO) - pointer to current/new filter decision (unused) */
5661/* */
5662/* Look for a rule group head in a hash table, using the source address as */
5663/* the key, and descend into that group and continue matching rules against */
5664/* the packet. */
5665/* ------------------------------------------------------------------------ */
5666frentry_t *
5667ipf_srcgrpmap(fin, passp)
5668 fr_info_t *fin;
5669 u_32_t *passp;
5670{
5671 frgroup_t *fg;
5672 void *rval;
5673
5674 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5675 &fin->fin_src);
5676 if (rval == NULL)
5677 return NULL;
5678
5679 fg = rval;
5680 fin->fin_fr = fg->fg_start;
5681 (void) ipf_scanlist(fin, *passp);
5682 return fin->fin_fr;
5683}
5684
5685
5686/* ------------------------------------------------------------------------ */
5687/* Function: ipf_dstgrpmap */
5688/* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5689/* Parameters: fin(I) - pointer to packet information */
5690/* passp(IO) - pointer to current/new filter decision (unused) */
5691/* */
5692/* Look for a rule group head in a hash table, using the destination */
5693/* address as the key, and descend into that group and continue matching */
5694/* rules against the packet. */
5695/* ------------------------------------------------------------------------ */
5696frentry_t *
5697ipf_dstgrpmap(fin, passp)
5698 fr_info_t *fin;
5699 u_32_t *passp;
5700{
5701 frgroup_t *fg;
5702 void *rval;
5703
5704 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5705 &fin->fin_dst);
5706 if (rval == NULL)
5707 return NULL;
5708
5709 fg = rval;
5710 fin->fin_fr = fg->fg_start;
5711 (void) ipf_scanlist(fin, *passp);
5712 return fin->fin_fr;
5713}
5714
5715/*
5716 * Queue functions
5717 * ===============
5718 * These functions manage objects on queues for efficient timeouts. There
5719 * are a number of system defined queues as well as user defined timeouts.
5720 * It is expected that a lock is held in the domain in which the queue
5721 * belongs (i.e. either state or NAT) when calling any of these functions
5722 * that prevents ipf_freetimeoutqueue() from being called at the same time
5723 * as any other.
5724 */
5725
5726
5727/* ------------------------------------------------------------------------ */
5728/* Function: ipf_addtimeoutqueue */
5729/* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5730/* timeout queue with given interval. */
5731/* Parameters: parent(I) - pointer to pointer to parent node of this list */
5732/* of interface queues. */
5733/* seconds(I) - timeout value in seconds for this queue. */
5734/* */
5735/* This routine first looks for a timeout queue that matches the interval */
5736/* being requested. If it finds one, increments the reference counter and */
5737/* returns a pointer to it. If none are found, it allocates a new one and */
5738/* inserts it at the top of the list. */
5739/* */
5740/* Locking. */
5741/* It is assumed that the caller of this function has an appropriate lock */
5742/* held (exclusively) in the domain that encompases 'parent'. */
5743/* ------------------------------------------------------------------------ */
5744ipftq_t *
5745ipf_addtimeoutqueue(softc, parent, seconds)
5746 ipf_main_softc_t *softc;
5747 ipftq_t **parent;
5748 u_int seconds;
5749{
5750 ipftq_t *ifq;
5751 u_int period;
5752
5753 period = seconds * IPF_HZ_DIVIDE;
5754
5755 MUTEX_ENTER(&softc->ipf_timeoutlock);
5756 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5757 if (ifq->ifq_ttl == period) {
5758 /*
5759 * Reset the delete flag, if set, so the structure
5760 * gets reused rather than freed and reallocated.
5761 */
5762 MUTEX_ENTER(&ifq->ifq_lock);
5763 ifq->ifq_flags &= ~IFQF_DELETE;
5764 ifq->ifq_ref++;
5765 MUTEX_EXIT(&ifq->ifq_lock);
5766 MUTEX_EXIT(&softc->ipf_timeoutlock);
5767
5768 return ifq;
5769 }
5770 }
5771
5772 KMALLOC(ifq, ipftq_t *);
5773 if (ifq != NULL) {
5774 MUTEX_NUKE(&ifq->ifq_lock);
5775 IPFTQ_INIT(ifq, period, "ipftq mutex");
5776 ifq->ifq_next = *parent;
5777 ifq->ifq_pnext = parent;
5778 ifq->ifq_flags = IFQF_USER;
5779 ifq->ifq_ref++;
5780 *parent = ifq;
5781 softc->ipf_userifqs++;
5782 }
5783 MUTEX_EXIT(&softc->ipf_timeoutlock);
5784 return ifq;
5785}
5786
5787
5788/* ------------------------------------------------------------------------ */
5789/* Function: ipf_deletetimeoutqueue */
5790/* Returns: int - new reference count value of the timeout queue */
5791/* Parameters: ifq(I) - timeout queue which is losing a reference. */
5792/* Locks: ifq->ifq_lock */
5793/* */
5794/* This routine must be called when we're discarding a pointer to a timeout */
5795/* queue object, taking care of the reference counter. */
5796/* */
5797/* Now that this just sets a DELETE flag, it requires the expire code to */
5798/* check the list of user defined timeout queues and call the free function */
5799/* below (currently commented out) to stop memory leaking. It is done this */
5800/* way because the locking may not be sufficient to safely do a free when */
5801/* this function is called. */
5802/* ------------------------------------------------------------------------ */
5803int
5804ipf_deletetimeoutqueue(ifq)
5805 ipftq_t *ifq;
5806{
5807
5808 ifq->ifq_ref--;
5809 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5810 ifq->ifq_flags |= IFQF_DELETE;
5811 }
5812
5813 return ifq->ifq_ref;
5814}
5815
5816
5817/* ------------------------------------------------------------------------ */
5818/* Function: ipf_freetimeoutqueue */
5819/* Parameters: ifq(I) - timeout queue which is losing a reference. */
5820/* Returns: Nil */
5821/* */
5822/* Locking: */
5823/* It is assumed that the caller of this function has an appropriate lock */
5824/* held (exclusively) in the domain that encompases the callers "domain". */
5825/* The ifq_lock for this structure should not be held. */
5826/* */
5827/* Remove a user defined timeout queue from the list of queues it is in and */
5828/* tidy up after this is done. */
5829/* ------------------------------------------------------------------------ */
5830void
5831ipf_freetimeoutqueue(softc, ifq)
5832 ipf_main_softc_t *softc;
5833 ipftq_t *ifq;
5834{
5835
5836 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5837 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5838 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5839 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5840 ifq->ifq_ref);
5841 return;
5842 }
5843
5844 /*
5845 * Remove from its position in the list.
5846 */
5847 *ifq->ifq_pnext = ifq->ifq_next;
5848 if (ifq->ifq_next != NULL)
5849 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5850 ifq->ifq_next = NULL;
5851 ifq->ifq_pnext = NULL;
5852
5853 MUTEX_DESTROY(&ifq->ifq_lock);
5854 ATOMIC_DEC(softc->ipf_userifqs);
5855 KFREE(ifq);
5856}
5857
5858
5859/* ------------------------------------------------------------------------ */
5860/* Function: ipf_deletequeueentry */
5861/* Returns: Nil */
5862/* Parameters: tqe(I) - timeout queue entry to delete */
5863/* */
5864/* Remove a tail queue entry from its queue and make it an orphan. */
5865/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5866/* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5867/* the correct lock(s) may not be held that would make it safe to do so. */
5868/* ------------------------------------------------------------------------ */
5869void
5870ipf_deletequeueentry(tqe)
5871 ipftqent_t *tqe;
5872{
5873 ipftq_t *ifq;
5874
5875 ifq = tqe->tqe_ifq;
5876
5877 MUTEX_ENTER(&ifq->ifq_lock);
5878
5879 if (tqe->tqe_pnext != NULL) {
5880 *tqe->tqe_pnext = tqe->tqe_next;
5881 if (tqe->tqe_next != NULL)
5882 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5883 else /* we must be the tail anyway */
5884 ifq->ifq_tail = tqe->tqe_pnext;
5885
5886 tqe->tqe_pnext = NULL;
5887 tqe->tqe_ifq = NULL;
5888 }
5889
5890 (void) ipf_deletetimeoutqueue(ifq);
5891 ASSERT(ifq->ifq_ref > 0);
5892
5893 MUTEX_EXIT(&ifq->ifq_lock);
5894}
5895
5896
5897/* ------------------------------------------------------------------------ */
5898/* Function: ipf_queuefront */
5899/* Returns: Nil */
5900/* Parameters: tqe(I) - pointer to timeout queue entry */
5901/* */
5902/* Move a queue entry to the front of the queue, if it isn't already there. */
5903/* ------------------------------------------------------------------------ */
5904void
5905ipf_queuefront(tqe)
5906 ipftqent_t *tqe;
5907{
5908 ipftq_t *ifq;
5909
5910 ifq = tqe->tqe_ifq;
5911 if (ifq == NULL)
5912 return;
5913
5914 MUTEX_ENTER(&ifq->ifq_lock);
5915 if (ifq->ifq_head != tqe) {
5916 *tqe->tqe_pnext = tqe->tqe_next;
5917 if (tqe->tqe_next)
5918 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5919 else
5920 ifq->ifq_tail = tqe->tqe_pnext;
5921
5922 tqe->tqe_next = ifq->ifq_head;
5923 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5924 ifq->ifq_head = tqe;
5925 tqe->tqe_pnext = &ifq->ifq_head;
5926 }
5927 MUTEX_EXIT(&ifq->ifq_lock);
5928}
5929
5930
5931/* ------------------------------------------------------------------------ */
5932/* Function: ipf_queueback */
5933/* Returns: Nil */
5934/* Parameters: ticks(I) - ipf tick time to use with this call */
5935/* tqe(I) - pointer to timeout queue entry */
5936/* */
5937/* Move a queue entry to the back of the queue, if it isn't already there. */
5938/* We use use ticks to calculate the expiration and mark for when we last */
5939/* touched the structure. */
5940/* ------------------------------------------------------------------------ */
5941void
5942ipf_queueback(ticks, tqe)
5943 u_long ticks;
5944 ipftqent_t *tqe;
5945{
5946 ipftq_t *ifq;
5947
5948 ifq = tqe->tqe_ifq;
5949 if (ifq == NULL)
5950 return;
5951 tqe->tqe_die = ticks + ifq->ifq_ttl;
5952 tqe->tqe_touched = ticks;
5953
5954 MUTEX_ENTER(&ifq->ifq_lock);
5955 if (tqe->tqe_next != NULL) { /* at the end already ? */
5956 /*
5957 * Remove from list
5958 */
5959 *tqe->tqe_pnext = tqe->tqe_next;
5960 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5961
5962 /*
5963 * Make it the last entry.
5964 */
5965 tqe->tqe_next = NULL;
5966 tqe->tqe_pnext = ifq->ifq_tail;
5967 *ifq->ifq_tail = tqe;
5968 ifq->ifq_tail = &tqe->tqe_next;
5969 }
5970 MUTEX_EXIT(&ifq->ifq_lock);
5971}
5972
5973
5974/* ------------------------------------------------------------------------ */
5975/* Function: ipf_queueappend */
5976/* Returns: Nil */
5977/* Parameters: ticks(I) - ipf tick time to use with this call */
5978/* tqe(I) - pointer to timeout queue entry */
5979/* ifq(I) - pointer to timeout queue */
5980/* parent(I) - owing object pointer */
5981/* */
5982/* Add a new item to this queue and put it on the very end. */
5983/* We use use ticks to calculate the expiration and mark for when we last */
5984/* touched the structure. */
5985/* ------------------------------------------------------------------------ */
5986void
5987ipf_queueappend(ticks, tqe, ifq, parent)
5988 u_long ticks;
5989 ipftqent_t *tqe;
5990 ipftq_t *ifq;
5991 void *parent;
5992{
5993
5994 MUTEX_ENTER(&ifq->ifq_lock);
5995 tqe->tqe_parent = parent;
5996 tqe->tqe_pnext = ifq->ifq_tail;
5997 *ifq->ifq_tail = tqe;
5998 ifq->ifq_tail = &tqe->tqe_next;
5999 tqe->tqe_next = NULL;
6000 tqe->tqe_ifq = ifq;
6001 tqe->tqe_die = ticks + ifq->ifq_ttl;
6002 tqe->tqe_touched = ticks;
6003 ifq->ifq_ref++;
6004 MUTEX_EXIT(&ifq->ifq_lock);
6005}
6006
6007
6008/* ------------------------------------------------------------------------ */
6009/* Function: ipf_movequeue */
6010/* Returns: Nil */
6011/* Parameters: tq(I) - pointer to timeout queue information */
6012/* oifp(I) - old timeout queue entry was on */
6013/* nifp(I) - new timeout queue to put entry on */
6014/* */
6015/* Move a queue entry from one timeout queue to another timeout queue. */
6016/* If it notices that the current entry is already last and does not need */
6017/* to move queue, the return. */
6018/* ------------------------------------------------------------------------ */
6019void
6020ipf_movequeue(ticks, tqe, oifq, nifq)
6021 u_long ticks;
6022 ipftqent_t *tqe;
6023 ipftq_t *oifq, *nifq;
6024{
6025
6026 /*
6027 * If the queue hasn't changed and we last touched this entry at the
6028 * same ipf time, then we're not going to achieve anything by either
6029 * changing the ttl or moving it on the queue.
6030 */
6031 if (oifq == nifq && tqe->tqe_touched == ticks)
6032 return;
6033
6034 /*
6035 * For any of this to be outside the lock, there is a risk that two
6036 * packets entering simultaneously, with one changing to a different
6037 * queue and one not, could end up with things in a bizarre state.
6038 */
6039 MUTEX_ENTER(&oifq->ifq_lock);
6040
6041 tqe->tqe_touched = ticks;
6042 tqe->tqe_die = ticks + nifq->ifq_ttl;
6043 /*
6044 * Is the operation here going to be a no-op ?
6045 */
6046 if (oifq == nifq) {
6047 if ((tqe->tqe_next == NULL) ||
6048 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6049 MUTEX_EXIT(&oifq->ifq_lock);
6050 return;
6051 }
6052 }
6053
6054 /*
6055 * Remove from the old queue
6056 */
6057 *tqe->tqe_pnext = tqe->tqe_next;
6058 if (tqe->tqe_next)
6059 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6060 else
6061 oifq->ifq_tail = tqe->tqe_pnext;
6062 tqe->tqe_next = NULL;
6063
6064 /*
6065 * If we're moving from one queue to another, release the
6066 * lock on the old queue and get a lock on the new queue.
6067 * For user defined queues, if we're moving off it, call
6068 * delete in case it can now be freed.
6069 */
6070 if (oifq != nifq) {
6071 tqe->tqe_ifq = NULL;
6072
6073 (void) ipf_deletetimeoutqueue(oifq);
6074
6075 MUTEX_EXIT(&oifq->ifq_lock);
6076
6077 MUTEX_ENTER(&nifq->ifq_lock);
6078
6079 tqe->tqe_ifq = nifq;
6080 nifq->ifq_ref++;
6081 }
6082
6083 /*
6084 * Add to the bottom of the new queue
6085 */
6086 tqe->tqe_pnext = nifq->ifq_tail;
6087 *nifq->ifq_tail = tqe;
6088 nifq->ifq_tail = &tqe->tqe_next;
6089 MUTEX_EXIT(&nifq->ifq_lock);
6090}
6091
6092
6093/* ------------------------------------------------------------------------ */
6094/* Function: ipf_updateipid */
6095/* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6096/* Parameters: fin(I) - pointer to packet information */
6097/* */
6098/* When we are doing NAT, change the IP of every packet to represent a */
6099/* single sequence of packets coming from the host, hiding any host */
6100/* specific sequencing that might otherwise be revealed. If the packet is */
6101/* a fragment, then store the 'new' IPid in the fragment cache and look up */
6102/* the fragment cache for non-leading fragments. If a non-leading fragment */
6103/* has no match in the cache, return an error. */
6104/* ------------------------------------------------------------------------ */
6105static int
6106ipf_updateipid(fin)
6107 fr_info_t *fin;
6108{
6109 u_short id, ido, sums;
6110 u_32_t sumd, sum;
6111 ip_t *ip;
6112
6113 ip = fin->fin_ip;
6114 ido = ntohs(ip->ip_id);
6115 if (fin->fin_off != 0) {
6116 sum = ipf_frag_ipidknown(fin);
6117 if (sum == 0xffffffff)
6118 return -1;
6119 sum &= 0xffff;
6120 id = (u_short)sum;
6121 ip->ip_id = htons(id);
6122 } else {
6123 ip_fillid(ip);
6124 id = ntohs(ip->ip_id);
6125 if ((fin->fin_flx & FI_FRAG) != 0)
6126 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6127 }
6128
6129 if (id == ido)
6130 return 0;
6131 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6132 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6133 sum += sumd;
6134 sum = (sum >> 16) + (sum & 0xffff);
6135 sum = (sum >> 16) + (sum & 0xffff);
6136 sums = ~(u_short)sum;
6137 ip->ip_sum = htons(sums);
6138 return 0;
6139}
6140
6141
6142#ifdef NEED_FRGETIFNAME
6143/* ------------------------------------------------------------------------ */
6144/* Function: ipf_getifname */
6145/* Returns: char * - pointer to interface name */
6146/* Parameters: ifp(I) - pointer to network interface */
6147/* buffer(O) - pointer to where to store interface name */
6148/* */
6149/* Constructs an interface name in the buffer passed. The buffer passed is */
6150/* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6151/* as a NULL pointer then return a pointer to a static array. */
6152/* ------------------------------------------------------------------------ */
6153char *
6154ipf_getifname(ifp, buffer)
6155 struct ifnet *ifp;
6156 char *buffer;
6157{
6158 static char namebuf[LIFNAMSIZ];
6159# if defined(MENTAT) || defined(__FreeBSD__)
6160 int unit, space;
6161 char temp[20];
6162 char *s;
6163# endif
6164
6165 if (buffer == NULL)
6166 buffer = namebuf;
6167 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6168 buffer[LIFNAMSIZ - 1] = '\0';
6169# if defined(MENTAT) || defined(__FreeBSD__)
6170 for (s = buffer; *s; s++)
6171 ;
6172 unit = ifp->if_unit;
6173 space = LIFNAMSIZ - (s - buffer);
6174 if ((space > 0) && (unit >= 0)) {
6175# if defined(SNPRINTF) && defined(_KERNEL)
6176 SNPRINTF(temp, sizeof(temp), "%d", unit);
6177# else
6178 (void) sprintf(temp, "%d", unit);
6179# endif
6180 (void) strncpy(s, temp, space);
6181 }
6182# endif
6183 return buffer;
6184}
6185#endif
6186
6187
6188/* ------------------------------------------------------------------------ */
6189/* Function: ipf_ioctlswitch */
6190/* Returns: int - -1 continue processing, else ioctl return value */
6191/* Parameters: unit(I) - device unit opened */
6192/* data(I) - pointer to ioctl data */
6193/* cmd(I) - ioctl command */
6194/* mode(I) - mode value */
6195/* uid(I) - uid making the ioctl call */
6196/* ctx(I) - pointer to context data */
6197/* */
6198/* Based on the value of unit, call the appropriate ioctl handler or return */
6199/* EIO if ipfilter is not running. Also checks if write perms are req'd */
6200/* for the device in order to execute the ioctl. A special case is made */
6201/* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6202/* The context data pointer is passed through as this is used as the key */
6203/* for locating a matching token for continued access for walking lists, */
6204/* etc. */
6205/* ------------------------------------------------------------------------ */
6206int
6207ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6208 ipf_main_softc_t *softc;
6209 int unit, mode, uid;
6210 ioctlcmd_t cmd;
6211 void *data, *ctx;
6212{
6213 int error = 0;
6214
6215 switch (cmd)
6216 {
6217 case SIOCIPFINTERROR :
6218 error = BCOPYOUT(&softc->ipf_interror, data,
6219 sizeof(softc->ipf_interror));
6220 if (error != 0) {
6221 IPFERROR(40);
6222 error = EFAULT;
6223 }
6224 return error;
6225 default :
6226 break;
6227 }
6228
6229 switch (unit)
6230 {
6231 case IPL_LOGIPF :
6232 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6233 break;
6234 case IPL_LOGNAT :
6235 if (softc->ipf_running > 0) {
6236 error = ipf_nat_ioctl(softc, data, cmd, mode,
6237 uid, ctx);
6238 } else {
6239 IPFERROR(42);
6240 error = EIO;
6241 }
6242 break;
6243 case IPL_LOGSTATE :
6244 if (softc->ipf_running > 0) {
6245 error = ipf_state_ioctl(softc, data, cmd, mode,
6246 uid, ctx);
6247 } else {
6248 IPFERROR(43);
6249 error = EIO;
6250 }
6251 break;
6252 case IPL_LOGAUTH :
6253 if (softc->ipf_running > 0) {
6254 error = ipf_auth_ioctl(softc, data, cmd, mode,
6255 uid, ctx);
6256 } else {
6257 IPFERROR(44);
6258 error = EIO;
6259 }
6260 break;
6261 case IPL_LOGSYNC :
6262 if (softc->ipf_running > 0) {
6263 error = ipf_sync_ioctl(softc, data, cmd, mode,
6264 uid, ctx);
6265 } else {
6266 error = EIO;
6267 IPFERROR(45);
6268 }
6269 break;
6270 case IPL_LOGSCAN :
6271#ifdef IPFILTER_SCAN
6272 if (softc->ipf_running > 0)
6273 error = ipf_scan_ioctl(softc, data, cmd, mode,
6274 uid, ctx);
6275 else
6276#endif
6277 {
6278 error = EIO;
6279 IPFERROR(46);
6280 }
6281 break;
6282 case IPL_LOGLOOKUP :
6283 if (softc->ipf_running > 0) {
6284 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6285 uid, ctx);
6286 } else {
6287 error = EIO;
6288 IPFERROR(47);
6289 }
6290 break;
6291 default :
6292 IPFERROR(48);
6293 error = EIO;
6294 break;
6295 }
6296
6297 return error;
6298}
6299
6300
6301/*
6302 * This array defines the expected size of objects coming into the kernel
6303 * for the various recognised object types. The first column is flags (see
6304 * below), 2nd column is current size, 3rd column is the version number of
6305 * when the current size became current.
6306 * Flags:
6307 * 1 = minimum size, not absolute size
6308 */
6309static const int ipf_objbytes[IPFOBJ_COUNT][3] = {
6310 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6311 { 1, sizeof(struct friostat), 5010000 },
6312 { 0, sizeof(struct fr_info), 5010000 },
6313 { 0, sizeof(struct ipf_authstat), 4010100 },
6314 { 0, sizeof(struct ipfrstat), 5010000 },
6315 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6316 { 0, sizeof(struct natstat), 5010000 },
6317 { 0, sizeof(struct ipstate_save), 5010000 },
6318 { 1, sizeof(struct nat_save), 5010000 },
6319 { 0, sizeof(struct natlookup), 5010000 },
6320 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6321 { 0, sizeof(struct ips_stat), 5010000 },
6322 { 0, sizeof(struct frauth), 5010000 },
6323 { 0, sizeof(struct ipftune), 4010100 },
6324 { 0, sizeof(struct nat), 5010000 },
6325 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6326 { 0, sizeof(struct ipfgeniter), 4011400 },
6327 { 0, sizeof(struct ipftable), 4011400 },
6328 { 0, sizeof(struct ipflookupiter), 4011400 },
6329 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6330 { 1, 0, 0 }, /* IPFEXPR */
6331 { 0, 0, 0 }, /* PROXYCTL */
6332 { 0, sizeof (struct fripf), 5010000 }
6333};
6334
6335
6336/* ------------------------------------------------------------------------ */
6337/* Function: ipf_inobj */
6338/* Returns: int - 0 = success, else failure */
6339/* Parameters: softc(I) - soft context pointerto work with */
6340/* data(I) - pointer to ioctl data */
6341/* objp(O) - where to store ipfobj structure */
6342/* ptr(I) - pointer to data to copy out */
6343/* type(I) - type of structure being moved */
6344/* */
6345/* Copy in the contents of what the ipfobj_t points to. In future, we */
6346/* add things to check for version numbers, sizes, etc, to make it backward */
6347/* compatible at the ABI for user land. */
6348/* If objp is not NULL then we assume that the caller wants to see what is */
6349/* in the ipfobj_t structure being copied in. As an example, this can tell */
6350/* the caller what version of ipfilter the ioctl program was written to. */
6351/* ------------------------------------------------------------------------ */
6352int
6353ipf_inobj(softc, data, objp, ptr, type)
6354 ipf_main_softc_t *softc;
6355 void *data;
6356 ipfobj_t *objp;
6357 void *ptr;
6358 int type;
6359{
6360 ipfobj_t obj;
6361 int error;
6362 int size;
6363
6364 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6365 IPFERROR(49);
6366 return EINVAL;
6367 }
6368
6369 if (objp == NULL)
6370 objp = &obj;
6371 error = BCOPYIN(data, objp, sizeof(*objp));
6372 if (error != 0) {
6373 IPFERROR(124);
6374 return EFAULT;
6375 }
6376
6377 if (objp->ipfo_type != type) {
6378 IPFERROR(50);
6379 return EINVAL;
6380 }
6381
6382 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6383 if ((ipf_objbytes[type][0] & 1) != 0) {
6384 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6385 IPFERROR(51);
6386 return EINVAL;
6387 }
6388 size = ipf_objbytes[type][1];
6389 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6390 size = objp->ipfo_size;
6391 } else {
6392 IPFERROR(52);
6393 return EINVAL;
6394 }
6395 error = COPYIN(objp->ipfo_ptr, ptr, size);
6396 if (error != 0) {
6397 IPFERROR(55);
6398 error = EFAULT;
6399 }
6400 } else {
6401#ifdef IPFILTER_COMPAT
6402 error = ipf_in_compat(softc, objp, ptr, 0);
6403#else
6404 IPFERROR(54);
6405 error = EINVAL;
6406#endif
6407 }
6408 return error;
6409}
6410
6411
6412/* ------------------------------------------------------------------------ */
6413/* Function: ipf_inobjsz */
6414/* Returns: int - 0 = success, else failure */
6415/* Parameters: softc(I) - soft context pointerto work with */
6416/* data(I) - pointer to ioctl data */
6417/* ptr(I) - pointer to store real data in */
6418/* type(I) - type of structure being moved */
6419/* sz(I) - size of data to copy */
6420/* */
6421/* As per ipf_inobj, except the size of the object to copy in is passed in */
6422/* but it must not be smaller than the size defined for the type and the */
6423/* type must allow for varied sized objects. The extra requirement here is */
6424/* that sz must match the size of the object being passed in - this is not */
6425/* not possible nor required in ipf_inobj(). */
6426/* ------------------------------------------------------------------------ */
6427int
6428ipf_inobjsz(softc, data, ptr, type, sz)
6429 ipf_main_softc_t *softc;
6430 void *data;
6431 void *ptr;
6432 int type, sz;
6433{
6434 ipfobj_t obj;
6435 int error;
6436
6437 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6438 IPFERROR(56);
6439 return EINVAL;
6440 }
6441
6442 error = BCOPYIN(data, &obj, sizeof(obj));
6443 if (error != 0) {
6444 IPFERROR(125);
6445 return EFAULT;
6446 }
6447
6448 if (obj.ipfo_type != type) {
6449 IPFERROR(58);
6450 return EINVAL;
6451 }
6452
6453 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6454 if (((ipf_objbytes[type][0] & 1) == 0) ||
6455 (sz < ipf_objbytes[type][1])) {
6456 IPFERROR(57);
6457 return EINVAL;
6458 }
6459 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6460 if (error != 0) {
6461 IPFERROR(61);
6462 error = EFAULT;
6463 }
6464 } else {
6465#ifdef IPFILTER_COMPAT
6466 error = ipf_in_compat(softc, &obj, ptr, sz);
6467#else
6468 IPFERROR(60);
6469 error = EINVAL;
6470#endif
6471 }
6472 return error;
6473}
6474
6475
6476/* ------------------------------------------------------------------------ */
6477/* Function: ipf_outobjsz */
6478/* Returns: int - 0 = success, else failure */
6479/* Parameters: data(I) - pointer to ioctl data */
6480/* ptr(I) - pointer to store real data in */
6481/* type(I) - type of structure being moved */
6482/* sz(I) - size of data to copy */
6483/* */
6484/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6485/* but it must not be smaller than the size defined for the type and the */
6486/* type must allow for varied sized objects. The extra requirement here is */
6487/* that sz must match the size of the object being passed in - this is not */
6488/* not possible nor required in ipf_outobj(). */
6489/* ------------------------------------------------------------------------ */
6490int
6491ipf_outobjsz(softc, data, ptr, type, sz)
6492 ipf_main_softc_t *softc;
6493 void *data;
6494 void *ptr;
6495 int type, sz;
6496{
6497 ipfobj_t obj;
6498 int error;
6499
6500 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6501 IPFERROR(62);
6502 return EINVAL;
6503 }
6504
6505 error = BCOPYIN(data, &obj, sizeof(obj));
6506 if (error != 0) {
6507 IPFERROR(127);
6508 return EFAULT;
6509 }
6510
6511 if (obj.ipfo_type != type) {
6512 IPFERROR(63);
6513 return EINVAL;
6514 }
6515
6516 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6517 if (((ipf_objbytes[type][0] & 1) == 0) ||
6518 (sz < ipf_objbytes[type][1])) {
6519 IPFERROR(146);
6520 return EINVAL;
6521 }
6522 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6523 if (error != 0) {
6524 IPFERROR(66);
6525 error = EFAULT;
6526 }
6527 } else {
6528#ifdef IPFILTER_COMPAT
6529 error = ipf_out_compat(softc, &obj, ptr);
6530#else
6531 IPFERROR(65);
6532 error = EINVAL;
6533#endif
6534 }
6535 return error;
6536}
6537
6538
6539/* ------------------------------------------------------------------------ */
6540/* Function: ipf_outobj */
6541/* Returns: int - 0 = success, else failure */
6542/* Parameters: data(I) - pointer to ioctl data */
6543/* ptr(I) - pointer to store real data in */
6544/* type(I) - type of structure being moved */
6545/* */
6546/* Copy out the contents of what ptr is to where ipfobj points to. In */
6547/* future, we add things to check for version numbers, sizes, etc, to make */
6548/* it backward compatible at the ABI for user land. */
6549/* ------------------------------------------------------------------------ */
6550int
6551ipf_outobj(softc, data, ptr, type)
6552 ipf_main_softc_t *softc;
6553 void *data;
6554 void *ptr;
6555 int type;
6556{
6557 ipfobj_t obj;
6558 int error;
6559
6560 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6561 IPFERROR(67);
6562 return EINVAL;
6563 }
6564
6565 error = BCOPYIN(data, &obj, sizeof(obj));
6566 if (error != 0) {
6567 IPFERROR(126);
6568 return EFAULT;
6569 }
6570
6571 if (obj.ipfo_type != type) {
6572 IPFERROR(68);
6573 return EINVAL;
6574 }
6575
6576 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6577 if ((ipf_objbytes[type][0] & 1) != 0) {
6578 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6579 IPFERROR(69);
6580 return EINVAL;
6581 }
6582 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6583 IPFERROR(70);
6584 return EINVAL;
6585 }
6586
6587 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6588 if (error != 0) {
6589 IPFERROR(73);
6590 error = EFAULT;
6591 }
6592 } else {
6593#ifdef IPFILTER_COMPAT
6594 error = ipf_out_compat(softc, &obj, ptr);
6595#else
6596 IPFERROR(72);
6597 error = EINVAL;
6598#endif
6599 }
6600 return error;
6601}
6602
6603
6604/* ------------------------------------------------------------------------ */
6605/* Function: ipf_outobjk */
6606/* Returns: int - 0 = success, else failure */
6607/* Parameters: obj(I) - pointer to data description structure */
6608/* ptr(I) - pointer to kernel data to copy out */
6609/* */
6610/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6611/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6612/* already populated with information and now we just need to use it. */
6613/* There is no need for this function to have a "type" parameter as there */
6614/* is no point in validating information that comes from the kernel with */
6615/* itself. */
6616/* ------------------------------------------------------------------------ */
6617int
6618ipf_outobjk(softc, obj, ptr)
6619 ipf_main_softc_t *softc;
6620 ipfobj_t *obj;
6621 void *ptr;
6622{
6623 int type = obj->ipfo_type;
6624 int error;
6625
6626 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6627 IPFERROR(147);
6628 return EINVAL;
6629 }
6630
6631 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6632 if ((ipf_objbytes[type][0] & 1) != 0) {
6633 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6634 IPFERROR(148);
6635 return EINVAL;
6636 }
6637
6638 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6639 IPFERROR(149);
6640 return EINVAL;
6641 }
6642
6643 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6644 if (error != 0) {
6645 IPFERROR(150);
6646 error = EFAULT;
6647 }
6648 } else {
6649#ifdef IPFILTER_COMPAT
6650 error = ipf_out_compat(softc, obj, ptr);
6651#else
6652 IPFERROR(151);
6653 error = EINVAL;
6654#endif
6655 }
6656 return error;
6657}
6658
6659
6660/* ------------------------------------------------------------------------ */
6661/* Function: ipf_checkl4sum */
6662/* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6663/* Parameters: fin(I) - pointer to packet information */
6664/* */
6665/* If possible, calculate the layer 4 checksum for the packet. If this is */
6666/* not possible, return without indicating a failure or success but in a */
6667/* way that is ditinguishable. This function should only be called by the */
6668/* ipf_checkv6sum() for each platform. */
6669/* ------------------------------------------------------------------------ */
6670INLINE int
6671ipf_checkl4sum(fin)
6672 fr_info_t *fin;
6673{
6674 u_short sum, hdrsum, *csump;
6675 udphdr_t *udp;
6676 int dosum;
6677
6678 /*
6679 * If the TCP packet isn't a fragment, isn't too short and otherwise
6680 * isn't already considered "bad", then validate the checksum. If
6681 * this check fails then considered the packet to be "bad".
6682 */
6683 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6684 return 1;
6685
6686 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6687 if (fin->fin_out == 1) {
6688 fin->fin_cksum = FI_CK_SUMOK;
6689 return 0;
6690 }
6691
6692 csump = NULL;
6693 hdrsum = 0;
6694 dosum = 0;
6695 sum = 0;
6696
6697 switch (fin->fin_p)
6698 {
6699 case IPPROTO_TCP :
6700 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6701 dosum = 1;
6702 break;
6703
6704 case IPPROTO_UDP :
6705 udp = fin->fin_dp;
6706 if (udp->uh_sum != 0) {
6707 csump = &udp->uh_sum;
6708 dosum = 1;
6709 }
6710 break;
6711
6712#ifdef USE_INET6
6713 case IPPROTO_ICMPV6 :
6714 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6715 dosum = 1;
6716 break;
6717#endif
6718
6719 case IPPROTO_ICMP :
6720 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6721 dosum = 1;
6722 break;
6723
6724 default :
6725 return 1;
6726 /*NOTREACHED*/
6727 }
6728
6729 if (csump != NULL) {
6730 hdrsum = *csump;
6731 if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6732 hdrsum = 0x0000;
6733 }
6734
6735 if (dosum) {
6736 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6737 }
6738#if !defined(_KERNEL)
6739 if (sum == hdrsum) {
6740 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6741 } else {
6742 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6743 }
6744#endif
6745 DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6746#ifdef USE_INET6
6747 if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6748#else
6749 if (hdrsum == sum) {
6750#endif
6751 fin->fin_cksum = FI_CK_SUMOK;
6752 return 0;
6753 }
6754 fin->fin_cksum = FI_CK_BAD;
6755 return -1;
6756}
6757
6758
6759/* ------------------------------------------------------------------------ */
6760/* Function: ipf_ifpfillv4addr */
6761/* Returns: int - 0 = address update, -1 = address not updated */
6762/* Parameters: atype(I) - type of network address update to perform */
6763/* sin(I) - pointer to source of address information */
6764/* mask(I) - pointer to source of netmask information */
6765/* inp(I) - pointer to destination address store */
6766/* inpmask(I) - pointer to destination netmask store */
6767/* */
6768/* Given a type of network address update (atype) to perform, copy */
6769/* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6770/* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6771/* which case the operation fails. For all values of atype other than */
6772/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6773/* value. */
6774/* ------------------------------------------------------------------------ */
6775int
6776ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6777 int atype;
6778 struct sockaddr_in *sin, *mask;
6779 struct in_addr *inp, *inpmask;
6780{
6781 if (inpmask != NULL && atype != FRI_NETMASKED)
6782 inpmask->s_addr = 0xffffffff;
6783
6784 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6785 if (atype == FRI_NETMASKED) {
6786 if (inpmask == NULL)
6787 return -1;
6788 inpmask->s_addr = mask->sin_addr.s_addr;
6789 }
6790 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6791 } else {
6792 inp->s_addr = sin->sin_addr.s_addr;
6793 }
6794 return 0;
6795}
6796
6797
6798#ifdef USE_INET6
6799/* ------------------------------------------------------------------------ */
6800/* Function: ipf_ifpfillv6addr */
6801/* Returns: int - 0 = address update, -1 = address not updated */
6802/* Parameters: atype(I) - type of network address update to perform */
6803/* sin(I) - pointer to source of address information */
6804/* mask(I) - pointer to source of netmask information */
6805/* inp(I) - pointer to destination address store */
6806/* inpmask(I) - pointer to destination netmask store */
6807/* */
6808/* Given a type of network address update (atype) to perform, copy */
6809/* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6810/* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6811/* which case the operation fails. For all values of atype other than */
6812/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6813/* value. */
6814/* ------------------------------------------------------------------------ */
6815int
6816ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6817 int atype;
6818 struct sockaddr_in6 *sin, *mask;
6819 i6addr_t *inp, *inpmask;
6820{
6821 i6addr_t *src, *and;
6822
6823 src = (i6addr_t *)&sin->sin6_addr;
6824 and = (i6addr_t *)&mask->sin6_addr;
6825
6826 if (inpmask != NULL && atype != FRI_NETMASKED) {
6827 inpmask->i6[0] = 0xffffffff;
6828 inpmask->i6[1] = 0xffffffff;
6829 inpmask->i6[2] = 0xffffffff;
6830 inpmask->i6[3] = 0xffffffff;
6831 }
6832
6833 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6834 if (atype == FRI_NETMASKED) {
6835 if (inpmask == NULL)
6836 return -1;
6837 inpmask->i6[0] = and->i6[0];
6838 inpmask->i6[1] = and->i6[1];
6839 inpmask->i6[2] = and->i6[2];
6840 inpmask->i6[3] = and->i6[3];
6841 }
6842
6843 inp->i6[0] = src->i6[0] & and->i6[0];
6844 inp->i6[1] = src->i6[1] & and->i6[1];
6845 inp->i6[2] = src->i6[2] & and->i6[2];
6846 inp->i6[3] = src->i6[3] & and->i6[3];
6847 } else {
6848 inp->i6[0] = src->i6[0];
6849 inp->i6[1] = src->i6[1];
6850 inp->i6[2] = src->i6[2];
6851 inp->i6[3] = src->i6[3];
6852 }
6853 return 0;
6854}
6855#endif
6856
6857
6858/* ------------------------------------------------------------------------ */
6859/* Function: ipf_matchtag */
6860/* Returns: 0 == mismatch, 1 == match. */
6861/* Parameters: tag1(I) - pointer to first tag to compare */
6862/* tag2(I) - pointer to second tag to compare */
6863/* */
6864/* Returns true (non-zero) or false(0) if the two tag structures can be */
6865/* considered to be a match or not match, respectively. The tag is 16 */
6866/* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6867/* compare the ints instead, for speed. tag1 is the master of the */
6868/* comparison. This function should only be called with both tag1 and tag2 */
6869/* as non-NULL pointers. */
6870/* ------------------------------------------------------------------------ */
6871int
6872ipf_matchtag(tag1, tag2)
6873 ipftag_t *tag1, *tag2;
6874{
6875 if (tag1 == tag2)
6876 return 1;
6877
6878 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6879 return 1;
6880
6881 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6882 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6883 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6884 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6885 return 1;
6886 return 0;
6887}
6888
6889
6890/* ------------------------------------------------------------------------ */
6891/* Function: ipf_coalesce */
6892/* Returns: 1 == success, -1 == failure, 0 == no change */
6893/* Parameters: fin(I) - pointer to packet information */
6894/* */
6895/* Attempt to get all of the packet data into a single, contiguous buffer. */
6896/* If this call returns a failure then the buffers have also been freed. */
6897/* ------------------------------------------------------------------------ */
6898int
6899ipf_coalesce(fin)
6900 fr_info_t *fin;
6901{
6902
6903 if ((fin->fin_flx & FI_COALESCE) != 0)
6904 return 1;
6905
6906 /*
6907 * If the mbuf pointers indicate that there is no mbuf to work with,
6908 * return but do not indicate success or failure.
6909 */
6910 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6911 return 0;
6912
6913#if defined(_KERNEL)
6914 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6915 ipf_main_softc_t *softc = fin->fin_main_soft;
6916
6917 DT1(frb_coalesce, fr_info_t *, fin);
6918 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6919# ifdef MENTAT
6920 FREE_MB_T(*fin->fin_mp);
6921# endif
6922 fin->fin_reason = FRB_COALESCE;
6923 *fin->fin_mp = NULL;
6924 fin->fin_m = NULL;
6925 return -1;
6926 }
6927#else
6928 fin = fin; /* LINT */
6929#endif
6930 return 1;
6931}
6932
6933
6934/*
6935 * The following table lists all of the tunable variables that can be
6936 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6937 * in the table below is as follows:
6938 *
6939 * pointer to value, name of value, minimum, maximum, size of the value's
6940 * container, value attribute flags
6941 *
6942 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6943 * means the value can only be written to when IPFilter is loaded but disabled.
6944 * The obvious implication is if neither of these are set then the value can be
6945 * changed at any time without harm.
6946 */
6947
6948
6949/* ------------------------------------------------------------------------ */
6950/* Function: ipf_tune_findbycookie */
6951/* Returns: NULL = search failed, else pointer to tune struct */
6952/* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6953/* next(O) - pointer to place to store the cookie for the */
6954/* "next" tuneable, if it is desired. */
6955/* */
6956/* This function is used to walk through all of the existing tunables with */
6957/* successive calls. It searches the known tunables for the one which has */
6958/* a matching value for "cookie" - ie its address. When returning a match, */
6959/* the next one to be found may be returned inside next. */
6960/* ------------------------------------------------------------------------ */
6961static ipftuneable_t *
6962ipf_tune_findbycookie(ptop, cookie, next)
6963 ipftuneable_t **ptop;
6964 void *cookie, **next;
6965{
6966 ipftuneable_t *ta, **tap;
6967
6968 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6969 if (ta == cookie) {
6970 if (next != NULL) {
6971 /*
6972 * If the next entry in the array has a name
6973 * present, then return a pointer to it for
6974 * where to go next, else return a pointer to
6975 * the dynaminc list as a key to search there
6976 * next. This facilitates a weak linking of
6977 * the two "lists" together.
6978 */
6979 if ((ta + 1)->ipft_name != NULL)
6980 *next = ta + 1;
6981 else
6982 *next = ptop;
6983 }
6984 return ta;
6985 }
6986
6987 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6988 if (tap == cookie) {
6989 if (next != NULL)
6990 *next = &ta->ipft_next;
6991 return ta;
6992 }
6993
6994 if (next != NULL)
6995 *next = NULL;
6996 return NULL;
6997}
6998
6999
7000/* ------------------------------------------------------------------------ */
7001/* Function: ipf_tune_findbyname */
7002/* Returns: NULL = search failed, else pointer to tune struct */
7003/* Parameters: name(I) - name of the tuneable entry to find. */
7004/* */
7005/* Search the static array of tuneables and the list of dynamic tuneables */
7006/* for an entry with a matching name. If we can find one, return a pointer */
7007/* to the matching structure. */
7008/* ------------------------------------------------------------------------ */
7009static ipftuneable_t *
7010ipf_tune_findbyname(top, name)
7011 ipftuneable_t *top;
7012 const char *name;
7013{
7014 ipftuneable_t *ta;
7015
7016 for (ta = top; ta != NULL; ta = ta->ipft_next)
7017 if (!strcmp(ta->ipft_name, name)) {
7018 return ta;
7019 }
7020
7021 return NULL;
7022}
7023
7024
7025/* ------------------------------------------------------------------------ */
7026/* Function: ipf_tune_add_array */
7027/* Returns: int - 0 == success, else failure */
7028/* Parameters: newtune - pointer to new tune array to add to tuneables */
7029/* */
7030/* Appends tune structures from the array passed in (newtune) to the end of */
7031/* the current list of "dynamic" tuneable parameters. */
7032/* If any entry to be added is already present (by name) then the operation */
7033/* is aborted - entries that have been added are removed before returning. */
7034/* An entry with no name (NULL) is used as the indication that the end of */
7035/* the array has been reached. */
7036/* ------------------------------------------------------------------------ */
7037int
7038ipf_tune_add_array(softc, newtune)
7039 ipf_main_softc_t *softc;
7040 ipftuneable_t *newtune;
7041{
7042 ipftuneable_t *nt, *dt;
7043 int error = 0;
7044
7045 for (nt = newtune; nt->ipft_name != NULL; nt++) {
7046 error = ipf_tune_add(softc, nt);
7047 if (error != 0) {
7048 for (dt = newtune; dt != nt; dt++) {
7049 (void) ipf_tune_del(softc, dt);
7050 }
7051 }
7052 }
7053
7054 return error;
7055}
7056
7057
7058/* ------------------------------------------------------------------------ */
7059/* Function: ipf_tune_array_link */
7060/* Returns: 0 == success, -1 == failure */
7061/* Parameters: softc(I) - soft context pointerto work with */
7062/* array(I) - pointer to an array of tuneables */
7063/* */
7064/* Given an array of tunables (array), append them to the current list of */
7065/* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7066/* the array for being appended to the list, initialise all of the next */
7067/* pointers so we don't need to walk parts of it with ++ and others with */
7068/* next. The array is expected to have an entry with a NULL name as the */
7069/* terminator. Trying to add an array with no non-NULL names will return as */
7070/* a failure. */
7071/* ------------------------------------------------------------------------ */
7072int
7073ipf_tune_array_link(softc, array)
7074 ipf_main_softc_t *softc;
7075 ipftuneable_t *array;
7076{
7077 ipftuneable_t *t, **p;
7078
7079 t = array;
7080 if (t->ipft_name == NULL)
7081 return -1;
7082
7083 for (; t[1].ipft_name != NULL; t++)
7084 t[0].ipft_next = &t[1];
7085 t->ipft_next = NULL;
7086
7087 /*
7088 * Since a pointer to the last entry isn't kept, we need to find it
7089 * each time we want to add new variables to the list.
7090 */
7091 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7092 if (t->ipft_name == NULL)
7093 break;
7094 *p = array;
7095
7096 return 0;
7097}
7098
7099
7100/* ------------------------------------------------------------------------ */
7101/* Function: ipf_tune_array_unlink */
7102/* Returns: 0 == success, -1 == failure */
7103/* Parameters: softc(I) - soft context pointerto work with */
7104/* array(I) - pointer to an array of tuneables */
7105/* */
7106/* ------------------------------------------------------------------------ */
7107int
7108ipf_tune_array_unlink(softc, array)
7109 ipf_main_softc_t *softc;
7110 ipftuneable_t *array;
7111{
7112 ipftuneable_t *t, **p;
7113
7114 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7115 if (t == array)
7116 break;
7117 if (t == NULL)
7118 return -1;
7119
7120 for (; t[1].ipft_name != NULL; t++)
7121 ;
7122
7123 *p = t->ipft_next;
7124
7125 return 0;
7126}
7127
7128
7129/* ------------------------------------------------------------------------ */
7130/* Function: ipf_tune_array_copy */
7131/* Returns: NULL = failure, else pointer to new array */
7132/* Parameters: base(I) - pointer to structure base */
7133/* size(I) - size of the array at template */
7134/* template(I) - original array to copy */
7135/* */
7136/* Allocate memory for a new set of tuneable values and copy everything */
7137/* from template into the new region of memory. The new region is full of */
7138/* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7139/* */
7140/* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7141/* In the array template, ipftp_offset is the offset (in bytes) of the */
7142/* location of the tuneable value inside the structure pointed to by base. */
7143/* As ipftp_offset is a union over the pointers to the tuneable values, if */
7144/* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7145/* ipftp_void that points to the stored value. */
7146/* ------------------------------------------------------------------------ */
7147ipftuneable_t *
7148ipf_tune_array_copy(base, size, template)
7149 void *base;
7150 size_t size;
7151 ipftuneable_t *template;
7152{
7153 ipftuneable_t *copy;
7154 int i;
7155
7156
7157 KMALLOCS(copy, ipftuneable_t *, size);
7158 if (copy == NULL) {
7159 return NULL;
7160 }
7161 bcopy(template, copy, size);
7162
7163 for (i = 0; copy[i].ipft_name; i++) {
7164 copy[i].ipft_una.ipftp_offset += (u_long)base;
7165 copy[i].ipft_next = copy + i + 1;
7166 }
7167
7168 return copy;
7169}
7170
7171
7172/* ------------------------------------------------------------------------ */
7173/* Function: ipf_tune_add */
7174/* Returns: int - 0 == success, else failure */
7175/* Parameters: newtune - pointer to new tune entry to add to tuneables */
7176/* */
7177/* Appends tune structures from the array passed in (newtune) to the end of */
7178/* the current list of "dynamic" tuneable parameters. Once added, the */
7179/* owner of the object is not expected to ever change "ipft_next". */
7180/* ------------------------------------------------------------------------ */
7181int
7182ipf_tune_add(softc, newtune)
7183 ipf_main_softc_t *softc;
7184 ipftuneable_t *newtune;
7185{
7186 ipftuneable_t *ta, **tap;
7187
7188 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7189 if (ta != NULL) {
7190 IPFERROR(74);
7191 return EEXIST;
7192 }
7193
7194 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7195 ;
7196
7197 newtune->ipft_next = NULL;
7198 *tap = newtune;
7199 return 0;
7200}
7201
7202
7203/* ------------------------------------------------------------------------ */
7204/* Function: ipf_tune_del */
7205/* Returns: int - 0 == success, else failure */
7206/* Parameters: oldtune - pointer to tune entry to remove from the list of */
7207/* current dynamic tuneables */
7208/* */
7209/* Search for the tune structure, by pointer, in the list of those that are */
7210/* dynamically added at run time. If found, adjust the list so that this */
7211/* structure is no longer part of it. */
7212/* ------------------------------------------------------------------------ */
7213int
7214ipf_tune_del(softc, oldtune)
7215 ipf_main_softc_t *softc;
7216 ipftuneable_t *oldtune;
7217{
7218 ipftuneable_t *ta, **tap;
7219 int error = 0;
7220
7221 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7222 tap = &ta->ipft_next) {
7223 if (ta == oldtune) {
7224 *tap = oldtune->ipft_next;
7225 oldtune->ipft_next = NULL;
7226 break;
7227 }
7228 }
7229
7230 if (ta == NULL) {
7231 error = ESRCH;
7232 IPFERROR(75);
7233 }
7234 return error;
7235}
7236
7237
7238/* ------------------------------------------------------------------------ */
7239/* Function: ipf_tune_del_array */
7240/* Returns: int - 0 == success, else failure */
7241/* Parameters: oldtune - pointer to tuneables array */
7242/* */
7243/* Remove each tuneable entry in the array from the list of "dynamic" */
7244/* tunables. If one entry should fail to be found, an error will be */
7245/* returned and no further ones removed. */
7246/* An entry with a NULL name is used as the indicator of the last entry in */
7247/* the array. */
7248/* ------------------------------------------------------------------------ */
7249int
7250ipf_tune_del_array(softc, oldtune)
7251 ipf_main_softc_t *softc;
7252 ipftuneable_t *oldtune;
7253{
7254 ipftuneable_t *ot;
7255 int error = 0;
7256
7257 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7258 error = ipf_tune_del(softc, ot);
7259 if (error != 0)
7260 break;
7261 }
7262
7263 return error;
7264
7265}
7266
7267
7268/* ------------------------------------------------------------------------ */
7269/* Function: ipf_tune */
7270/* Returns: int - 0 == success, else failure */
7271/* Parameters: cmd(I) - ioctl command number */
7272/* data(I) - pointer to ioctl data structure */
7273/* */
7274/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7275/* three ioctls provide the means to access and control global variables */
7276/* within IPFilter, allowing (for example) timeouts and table sizes to be */
7277/* changed without rebooting, reloading or recompiling. The initialisation */
7278/* and 'destruction' routines of the various components of ipfilter are all */
7279/* each responsible for handling their own values being too big. */
7280/* ------------------------------------------------------------------------ */
7281int
7282ipf_ipftune(softc, cmd, data)
7283 ipf_main_softc_t *softc;
7284 ioctlcmd_t cmd;
7285 void *data;
7286{
7287 ipftuneable_t *ta;
7288 ipftune_t tu;
7289 void *cookie;
7290 int error;
7291
7292 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7293 if (error != 0)
7294 return error;
7295
7296 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7297 cookie = tu.ipft_cookie;
7298 ta = NULL;
7299
7300 switch (cmd)
7301 {
7302 case SIOCIPFGETNEXT :
7303 /*
7304 * If cookie is non-NULL, assume it to be a pointer to the last
7305 * entry we looked at, so find it (if possible) and return a
7306 * pointer to the next one after it. The last entry in the
7307 * the table is a NULL entry, so when we get to it, set cookie
7308 * to NULL and return that, indicating end of list, erstwhile
7309 * if we come in with cookie set to NULL, we are starting anew
7310 * at the front of the list.
7311 */
7312 if (cookie != NULL) {
7313 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7314 cookie, &tu.ipft_cookie);
7315 } else {
7316 ta = softc->ipf_tuners;
7317 tu.ipft_cookie = ta + 1;
7318 }
7319 if (ta != NULL) {
7320 /*
7321 * Entry found, but does the data pointed to by that
7322 * row fit in what we can return?
7323 */
7324 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7325 IPFERROR(76);
7326 return EINVAL;
7327 }
7328
7329 tu.ipft_vlong = 0;
7330 if (ta->ipft_sz == sizeof(u_long))
7331 tu.ipft_vlong = *ta->ipft_plong;
7332 else if (ta->ipft_sz == sizeof(u_int))
7333 tu.ipft_vint = *ta->ipft_pint;
7334 else if (ta->ipft_sz == sizeof(u_short))
7335 tu.ipft_vshort = *ta->ipft_pshort;
7336 else if (ta->ipft_sz == sizeof(u_char))
7337 tu.ipft_vchar = *ta->ipft_pchar;
7338
7339 tu.ipft_sz = ta->ipft_sz;
7340 tu.ipft_min = ta->ipft_min;
7341 tu.ipft_max = ta->ipft_max;
7342 tu.ipft_flags = ta->ipft_flags;
7343 bcopy(ta->ipft_name, tu.ipft_name,
7344 MIN(sizeof(tu.ipft_name),
7345 strlen(ta->ipft_name) + 1));
7346 }
7347 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7348 break;
7349
7350 case SIOCIPFGET :
7351 case SIOCIPFSET :
7352 /*
7353 * Search by name or by cookie value for a particular entry
7354 * in the tuning paramter table.
7355 */
7356 IPFERROR(77);
7357 error = ESRCH;
7358 if (cookie != NULL) {
7359 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7360 cookie, NULL);
7361 if (ta != NULL)
7362 error = 0;
7363 } else if (tu.ipft_name[0] != '\0') {
7364 ta = ipf_tune_findbyname(softc->ipf_tuners,
7365 tu.ipft_name);
7366 if (ta != NULL)
7367 error = 0;
7368 }
7369 if (error != 0)
7370 break;
7371
7372 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7373 /*
7374 * Fetch the tuning parameters for a particular value
7375 */
7376 tu.ipft_vlong = 0;
7377 if (ta->ipft_sz == sizeof(u_long))
7378 tu.ipft_vlong = *ta->ipft_plong;
7379 else if (ta->ipft_sz == sizeof(u_int))
7380 tu.ipft_vint = *ta->ipft_pint;
7381 else if (ta->ipft_sz == sizeof(u_short))
7382 tu.ipft_vshort = *ta->ipft_pshort;
7383 else if (ta->ipft_sz == sizeof(u_char))
7384 tu.ipft_vchar = *ta->ipft_pchar;
7385 tu.ipft_cookie = ta;
7386 tu.ipft_sz = ta->ipft_sz;
7387 tu.ipft_min = ta->ipft_min;
7388 tu.ipft_max = ta->ipft_max;
7389 tu.ipft_flags = ta->ipft_flags;
7390 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7391
7392 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7393 /*
7394 * Set an internal parameter. The hard part here is
7395 * getting the new value safely and correctly out of
7396 * the kernel (given we only know its size, not type.)
7397 */
7398 u_long in;
7399
7400 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7401 (softc->ipf_running > 0)) {
7402 IPFERROR(78);
7403 error = EBUSY;
7404 break;
7405 }
7406
7407 in = tu.ipft_vlong;
7408 if (in < ta->ipft_min || in > ta->ipft_max) {
7409 IPFERROR(79);
7410 error = EINVAL;
7411 break;
7412 }
7413
7414 if (ta->ipft_func != NULL) {
7415 SPL_INT(s);
7416
7417 SPL_NET(s);
7418 error = (*ta->ipft_func)(softc, ta,
7419 &tu.ipft_un);
7420 SPL_X(s);
7421
7422 } else if (ta->ipft_sz == sizeof(u_long)) {
7423 tu.ipft_vlong = *ta->ipft_plong;
7424 *ta->ipft_plong = in;
7425
7426 } else if (ta->ipft_sz == sizeof(u_int)) {
7427 tu.ipft_vint = *ta->ipft_pint;
7428 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7429
7430 } else if (ta->ipft_sz == sizeof(u_short)) {
7431 tu.ipft_vshort = *ta->ipft_pshort;
7432 *ta->ipft_pshort = (u_short)(in & 0xffff);
7433
7434 } else if (ta->ipft_sz == sizeof(u_char)) {
7435 tu.ipft_vchar = *ta->ipft_pchar;
7436 *ta->ipft_pchar = (u_char)(in & 0xff);
7437 }
7438 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7439 }
7440 break;
7441
7442 default :
7443 IPFERROR(80);
7444 error = EINVAL;
7445 break;
7446 }
7447
7448 return error;
7449}
7450
7451
7452/* ------------------------------------------------------------------------ */
7453/* Function: ipf_zerostats */
7454/* Returns: int - 0 = success, else failure */
7455/* Parameters: data(O) - pointer to pointer for copying data back to */
7456/* */
7457/* Copies the current statistics out to userspace and then zero's the */
7458/* current ones in the kernel. The lock is only held across the bzero() as */
7459/* the copyout may result in paging (ie network activity.) */
7460/* ------------------------------------------------------------------------ */
7461int
7462ipf_zerostats(softc, data)
7463 ipf_main_softc_t *softc;
7464 caddr_t data;
7465{
7466 friostat_t fio;
7467 ipfobj_t obj;
7468 int error;
7469
7470 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7471 if (error != 0)
7472 return error;
7473 ipf_getstat(softc, &fio, obj.ipfo_rev);
7474 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7475 if (error != 0)
7476 return error;
7477
7478 WRITE_ENTER(&softc->ipf_mutex);
7479 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7480 RWLOCK_EXIT(&softc->ipf_mutex);
7481
7482 return 0;
7483}
7484
7485
7486/* ------------------------------------------------------------------------ */
7487/* Function: ipf_resolvedest */
7488/* Returns: Nil */
7489/* Parameters: softc(I) - pointer to soft context main structure */
7490/* base(I) - where strings are stored */
7491/* fdp(IO) - pointer to destination information to resolve */
7492/* v(I) - IP protocol version to match */
7493/* */
7494/* Looks up an interface name in the frdest structure pointed to by fdp and */
7495/* if a matching name can be found for the particular IP protocol version */
7496/* then store the interface pointer in the frdest struct. If no match is */
7497/* found, then set the interface pointer to be -1 as NULL is considered to */
7498/* indicate there is no information at all in the structure. */
7499/* ------------------------------------------------------------------------ */
7500int
7501ipf_resolvedest(softc, base, fdp, v)
7502 ipf_main_softc_t *softc;
7503 char *base;
7504 frdest_t *fdp;
7505 int v;
7506{
7507 int errval = 0;
7508 void *ifp;
7509
7510 ifp = NULL;
7511
7512 if (fdp->fd_name != -1) {
7513 if (fdp->fd_type == FRD_DSTLIST) {
7514 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7515 IPLT_DSTLIST,
7516 base + fdp->fd_name,
7517 NULL);
7518 if (ifp == NULL) {
7519 IPFERROR(144);
7520 errval = ESRCH;
7521 }
7522 } else {
7523 ifp = GETIFP(base + fdp->fd_name, v);
7524 if (ifp == NULL)
7525 ifp = (void *)-1;
7526 }
7527 }
7528 fdp->fd_ptr = ifp;
7529
7530 return errval;
7531}
7532
7533
7534/* ------------------------------------------------------------------------ */
7535/* Function: ipf_resolvenic */
7536/* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7537/* pointer to interface structure for NIC */
7538/* Parameters: softc(I)- pointer to soft context main structure */
7539/* name(I) - complete interface name */
7540/* v(I) - IP protocol version */
7541/* */
7542/* Look for a network interface structure that firstly has a matching name */
7543/* to that passed in and that is also being used for that IP protocol */
7544/* version (necessary on some platforms where there are separate listings */
7545/* for both IPv4 and IPv6 on the same physical NIC. */
7546/* ------------------------------------------------------------------------ */
7547void *
7548ipf_resolvenic(softc, name, v)
7549 ipf_main_softc_t *softc;
7550 char *name;
7551 int v;
7552{
7553 void *nic;
7554
7555 softc = softc; /* gcc -Wextra */
7556 if (name[0] == '\0')
7557 return NULL;
7558
7559 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7560 return NULL;
7561 }
7562
7563 nic = GETIFP(name, v);
7564 if (nic == NULL)
7565 nic = (void *)-1;
7566 return nic;
7567}
7568
7569
7570/* ------------------------------------------------------------------------ */
7571/* Function: ipf_token_expire */
7572/* Returns: None. */
7573/* Parameters: softc(I) - pointer to soft context main structure */
7574/* */
7575/* This function is run every ipf tick to see if there are any tokens that */
7576/* have been held for too long and need to be freed up. */
7577/* ------------------------------------------------------------------------ */
7578void
7579ipf_token_expire(softc)
7580 ipf_main_softc_t *softc;
7581{
7582 ipftoken_t *it;
7583
7584 WRITE_ENTER(&softc->ipf_tokens);
7585 while ((it = softc->ipf_token_head) != NULL) {
7586 if (it->ipt_die > softc->ipf_ticks)
7587 break;
7588
7589 ipf_token_deref(softc, it);
7590 }
7591 RWLOCK_EXIT(&softc->ipf_tokens);
7592}
7593
7594
7595/* ------------------------------------------------------------------------ */
7596/* Function: ipf_token_flush */
7597/* Returns: None. */
7598/* Parameters: softc(I) - pointer to soft context main structure */
7599/* */
7600/* Loop through all of the existing tokens and call deref to see if they */
7601/* can be freed. Normally a function like this might just loop on */
7602/* ipf_token_head but there is a chance that a token might have a ref count */
7603/* of greater than one and in that case the the reference would drop twice */
7604/* by code that is only entitled to drop it once. */
7605/* ------------------------------------------------------------------------ */
7606static void
7607ipf_token_flush(softc)
7608 ipf_main_softc_t *softc;
7609{
7610 ipftoken_t *it, *next;
7611
7612 WRITE_ENTER(&softc->ipf_tokens);
7613 for (it = softc->ipf_token_head; it != NULL; it = next) {
7614 next = it->ipt_next;
7615 (void) ipf_token_deref(softc, it);
7616 }
7617 RWLOCK_EXIT(&softc->ipf_tokens);
7618}
7619
7620
7621/* ------------------------------------------------------------------------ */
7622/* Function: ipf_token_del */
7623/* Returns: int - 0 = success, else error */
7624/* Parameters: softc(I)- pointer to soft context main structure */
7625/* type(I) - the token type to match */
7626/* uid(I) - uid owning the token */
7627/* ptr(I) - context pointer for the token */
7628/* */
7629/* This function looks for a a token in the current list that matches up */
7630/* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7631/* call ipf_token_dewref() to remove it from the list. In the event that */
7632/* the token has a reference held elsewhere, setting ipt_complete to 2 */
7633/* enables debugging to distinguish between the two paths that ultimately */
7634/* lead to a token to be deleted. */
7635/* ------------------------------------------------------------------------ */
7636int
7637ipf_token_del(softc, type, uid, ptr)
7638 ipf_main_softc_t *softc;
7639 int type, uid;
7640 void *ptr;
7641{
7642 ipftoken_t *it;
7643 int error;
7644
7645 IPFERROR(82);
7646 error = ESRCH;
7647
7648 WRITE_ENTER(&softc->ipf_tokens);
7649 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7650 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7651 uid == it->ipt_uid) {
7652 it->ipt_complete = 2;
7653 ipf_token_deref(softc, it);
7654 error = 0;
7655 break;
7656 }
7657 }
7658 RWLOCK_EXIT(&softc->ipf_tokens);
7659
7660 return error;
7661}
7662
7663
7664/* ------------------------------------------------------------------------ */
7665/* Function: ipf_token_mark_complete */
7666/* Returns: None. */
7667/* Parameters: token(I) - pointer to token structure */
7668/* */
7669/* Mark a token as being ineligable for being found with ipf_token_find. */
7670/* ------------------------------------------------------------------------ */
7671void
7672ipf_token_mark_complete(token)
7673 ipftoken_t *token;
7674{
7675 if (token->ipt_complete == 0)
7676 token->ipt_complete = 1;
7677}
7678
7679
7680/* ------------------------------------------------------------------------ */
7681/* Function: ipf_token_find */
7682/* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7683/* Parameters: softc(I)- pointer to soft context main structure */
7684/* type(I) - the token type to match */
7685/* uid(I) - uid owning the token */
7686/* ptr(I) - context pointer for the token */
7687/* */
7688/* This function looks for a live token in the list of current tokens that */
7689/* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7690/* allocated. If one is found then it is moved to the top of the list of */
7691/* currently active tokens. */
7692/* ------------------------------------------------------------------------ */
7693ipftoken_t *
7694ipf_token_find(softc, type, uid, ptr)
7695 ipf_main_softc_t *softc;
7696 int type, uid;
7697 void *ptr;
7698{
7699 ipftoken_t *it, *new;
7700
7701 KMALLOC(new, ipftoken_t *);
7702 if (new != NULL)
7703 bzero((char *)new, sizeof(*new));
7704
7705 WRITE_ENTER(&softc->ipf_tokens);
7706 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7707 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7708 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7709 break;
7710 }
7711
7712 if (it == NULL) {
7713 it = new;
7714 new = NULL;
7715 if (it == NULL) {
7716 RWLOCK_EXIT(&softc->ipf_tokens);
7717 return NULL;
7718 }
7719 it->ipt_ctx = ptr;
7720 it->ipt_uid = uid;
7721 it->ipt_type = type;
7722 it->ipt_ref = 1;
7723 } else {
7724 if (new != NULL) {
7725 KFREE(new);
7726 new = NULL;
7727 }
7728
7729 if (it->ipt_complete > 0)
7730 it = NULL;
7731 else
7732 ipf_token_unlink(softc, it);
7733 }
7734
7735 if (it != NULL) {
7736 it->ipt_pnext = softc->ipf_token_tail;
7737 *softc->ipf_token_tail = it;
7738 softc->ipf_token_tail = &it->ipt_next;
7739 it->ipt_next = NULL;
7740 it->ipt_ref++;
7741
7742 it->ipt_die = softc->ipf_ticks + 20;
7743 }
7744
7745 RWLOCK_EXIT(&softc->ipf_tokens);
7746
7747 return it;
7748}
7749
7750
7751/* ------------------------------------------------------------------------ */
7752/* Function: ipf_token_unlink */
7753/* Returns: None. */
7754/* Parameters: softc(I) - pointer to soft context main structure */
7755/* token(I) - pointer to token structure */
7756/* Write Locks: ipf_tokens */
7757/* */
7758/* This function unlinks a token structure from the linked list of tokens */
7759/* that "own" it. The head pointer never needs to be explicitly adjusted */
7760/* but the tail does due to the linked list implementation. */
7761/* ------------------------------------------------------------------------ */
7762static void
7763ipf_token_unlink(softc, token)
7764 ipf_main_softc_t *softc;
7765 ipftoken_t *token;
7766{
7767
7768 if (softc->ipf_token_tail == &token->ipt_next)
7769 softc->ipf_token_tail = token->ipt_pnext;
7770
7771 *token->ipt_pnext = token->ipt_next;
7772 if (token->ipt_next != NULL)
7773 token->ipt_next->ipt_pnext = token->ipt_pnext;
7774 token->ipt_next = NULL;
7775 token->ipt_pnext = NULL;
7776}
7777
7778
7779/* ------------------------------------------------------------------------ */
7780/* Function: ipf_token_deref */
7781/* Returns: int - 0 == token freed, else reference count */
7782/* Parameters: softc(I) - pointer to soft context main structure */
7783/* token(I) - pointer to token structure */
7784/* Write Locks: ipf_tokens */
7785/* */
7786/* Drop the reference count on the token structure and if it drops to zero, */
7787/* call the dereference function for the token type because it is then */
7788/* possible to free the token data structure. */
7789/* ------------------------------------------------------------------------ */
7790int
7791ipf_token_deref(softc, token)
7792 ipf_main_softc_t *softc;
7793 ipftoken_t *token;
7794{
7795 void *data, **datap;
7796
7797 ASSERT(token->ipt_ref > 0);
7798 token->ipt_ref--;
7799 if (token->ipt_ref > 0)
7800 return token->ipt_ref;
7801
7802 data = token->ipt_data;
7803 datap = &data;
7804
7805 if ((data != NULL) && (data != (void *)-1)) {
7806 switch (token->ipt_type)
7807 {
7808 case IPFGENITER_IPF :
7809 (void) ipf_derefrule(softc, (frentry_t **)datap);
7810 break;
7811 case IPFGENITER_IPNAT :
7812 WRITE_ENTER(&softc->ipf_nat);
7813 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7814 RWLOCK_EXIT(&softc->ipf_nat);
7815 break;
7816 case IPFGENITER_NAT :
7817 ipf_nat_deref(softc, (nat_t **)datap);
7818 break;
7819 case IPFGENITER_STATE :
7820 ipf_state_deref(softc, (ipstate_t **)datap);
7821 break;
7822 case IPFGENITER_FRAG :
7823 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7824 break;
7825 case IPFGENITER_NATFRAG :
7826 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7827 break;
7828 case IPFGENITER_HOSTMAP :
7829 WRITE_ENTER(&softc->ipf_nat);
7830 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7831 RWLOCK_EXIT(&softc->ipf_nat);
7832 break;
7833 default :
7834 ipf_lookup_iterderef(softc, token->ipt_type, data);
7835 break;
7836 }
7837 }
7838
7839 ipf_token_unlink(softc, token);
7840 KFREE(token);
7841 return 0;
7842}
7843
7844
7845/* ------------------------------------------------------------------------ */
7846/* Function: ipf_nextrule */
7847/* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7848/* Parameters: softc(I) - pointer to soft context main structure */
7849/* fr(I) - pointer to filter rule */
7850/* out(I) - 1 == out rules, 0 == input rules */
7851/* */
7852/* Starting with "fr", find the next rule to visit. This includes visiting */
7853/* the list of rule groups if either fr is NULL (empty list) or it is the */
7854/* last rule in the list. When walking rule lists, it is either input or */
7855/* output rules that are returned, never both. */
7856/* ------------------------------------------------------------------------ */
7857static frentry_t *
7858ipf_nextrule(softc, active, unit, fr, out)
7859 ipf_main_softc_t *softc;
7860 int active, unit;
7861 frentry_t *fr;
7862 int out;
7863{
7864 frentry_t *next;
7865 frgroup_t *fg;
7866
7867 if (fr != NULL && fr->fr_group != -1) {
7868 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7869 unit, active, NULL);
7870 if (fg != NULL)
7871 fg = fg->fg_next;
7872 } else {
7873 fg = softc->ipf_groups[unit][active];
7874 }
7875
7876 while (fg != NULL) {
7877 next = fg->fg_start;
7878 while (next != NULL) {
7879 if (out) {
7880 if (next->fr_flags & FR_OUTQUE)
7881 return next;
7882 } else if (next->fr_flags & FR_INQUE) {
7883 return next;
7884 }
7885 next = next->fr_next;
7886 }
7887 if (next == NULL)
7888 fg = fg->fg_next;
7889 }
7890
7891 return NULL;
7892}
7893
7894/* ------------------------------------------------------------------------ */
7895/* Function: ipf_getnextrule */
7896/* Returns: int - 0 = success, else error */
7897/* Parameters: softc(I)- pointer to soft context main structure */
7898/* t(I) - pointer to destination information to resolve */
7899/* ptr(I) - pointer to ipfobj_t to copyin from user space */
7900/* */
7901/* This function's first job is to bring in the ipfruleiter_t structure via */
7902/* the ipfobj_t structure to determine what should be the next rule to */
7903/* return. Once the ipfruleiter_t has been brought in, it then tries to */
7904/* find the 'next rule'. This may include searching rule group lists or */
7905/* just be as simple as looking at the 'next' field in the rule structure. */
7906/* When we have found the rule to return, increase its reference count and */
7907/* if we used an existing rule to get here, decrease its reference count. */
7908/* ------------------------------------------------------------------------ */
7909int
7910ipf_getnextrule(softc, t, ptr)
7911 ipf_main_softc_t *softc;
7912 ipftoken_t *t;
7913 void *ptr;
7914{
7915 frentry_t *fr, *next, zero;
7916 ipfruleiter_t it;
7917 int error, out;
7918 frgroup_t *fg;
7919 ipfobj_t obj;
7920 int predict;
7921 char *dst;
7922 int unit;
7923
7924 if (t == NULL || ptr == NULL) {
7925 IPFERROR(84);
7926 return EFAULT;
7927 }
7928
7929 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7930 if (error != 0)
7931 return error;
7932
7933 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7934 IPFERROR(85);
7935 return EINVAL;
7936 }
7937 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7938 IPFERROR(86);
7939 return EINVAL;
7940 }
7941 if (it.iri_nrules == 0) {
7942 IPFERROR(87);
7943 return ENOSPC;
7944 }
7945 if (it.iri_rule == NULL) {
7946 IPFERROR(88);
7947 return EFAULT;
7948 }
7949
7950 fg = NULL;
7951 fr = t->ipt_data;
7952 if ((it.iri_inout & F_OUT) != 0)
7953 out = 1;
7954 else
7955 out = 0;
7956 if ((it.iri_inout & F_ACIN) != 0)
7957 unit = IPL_LOGCOUNT;
7958 else
7959 unit = IPL_LOGIPF;
7960
7961 READ_ENTER(&softc->ipf_mutex);
7962 if (fr == NULL) {
7963 if (*it.iri_group == '\0') {
7964 if (unit == IPL_LOGCOUNT) {
7965 next = softc->ipf_acct[out][it.iri_active];
7966 } else {
7967 next = softc->ipf_rules[out][it.iri_active];
7968 }
7969 if (next == NULL)
7970 next = ipf_nextrule(softc, it.iri_active,
7971 unit, NULL, out);
7972 } else {
7973 fg = ipf_findgroup(softc, it.iri_group, unit,
7974 it.iri_active, NULL);
7975 if (fg != NULL)
7976 next = fg->fg_start;
7977 else
7978 next = NULL;
7979 }
7980 } else {
7981 next = fr->fr_next;
7982 if (next == NULL)
7983 next = ipf_nextrule(softc, it.iri_active, unit,
7984 fr, out);
7985 }
7986
7987 if (next != NULL && next->fr_next != NULL)
7988 predict = 1;
7989 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7990 predict = 1;
7991 else
7992 predict = 0;
7993
7994 if (fr != NULL)
7995 (void) ipf_derefrule(softc, &fr);
7996
7997 obj.ipfo_type = IPFOBJ_FRENTRY;
7998 dst = (char *)it.iri_rule;
7999
8000 if (next != NULL) {
8001 obj.ipfo_size = next->fr_size;
8002 MUTEX_ENTER(&next->fr_lock);
8003 next->fr_ref++;
8004 MUTEX_EXIT(&next->fr_lock);
8005 t->ipt_data = next;
8006 } else {
8007 obj.ipfo_size = sizeof(frentry_t);
8008 bzero(&zero, sizeof(zero));
8009 next = &zero;
8010 t->ipt_data = NULL;
8011 }
8012 it.iri_rule = predict ? next : NULL;
8013 if (predict == 0)
8014 ipf_token_mark_complete(t);
8015
8016 RWLOCK_EXIT(&softc->ipf_mutex);
8017
8018 obj.ipfo_ptr = dst;
8019 error = ipf_outobjk(softc, &obj, next);
8020 if (error == 0 && t->ipt_data != NULL) {
8021 dst += obj.ipfo_size;
8022 if (next->fr_data != NULL) {
8023 ipfobj_t dobj;
8024
8025 if (next->fr_type == FR_T_IPFEXPR)
8026 dobj.ipfo_type = IPFOBJ_IPFEXPR;
8027 else
8028 dobj.ipfo_type = IPFOBJ_FRIPF;
8029 dobj.ipfo_size = next->fr_dsize;
8030 dobj.ipfo_rev = obj.ipfo_rev;
8031 dobj.ipfo_ptr = dst;
8032 error = ipf_outobjk(softc, &dobj, next->fr_data);
8033 }
8034 }
8035
8036 if ((fr != NULL) && (next == &zero))
8037 (void) ipf_derefrule(softc, &fr);
8038
8039 return error;
8040}
8041
8042
8043/* ------------------------------------------------------------------------ */
8044/* Function: ipf_frruleiter */
8045/* Returns: int - 0 = success, else error */
8046/* Parameters: softc(I)- pointer to soft context main structure */
8047/* data(I) - the token type to match */
8048/* uid(I) - uid owning the token */
8049/* ptr(I) - context pointer for the token */
8050/* */
8051/* This function serves as a stepping stone between ipf_ipf_ioctl and */
8052/* ipf_getnextrule. It's role is to find the right token in the kernel for */
8053/* the process doing the ioctl and use that to ask for the next rule. */
8054/* ------------------------------------------------------------------------ */
8055static int
8056ipf_frruleiter(softc, data, uid, ctx)
8057 ipf_main_softc_t *softc;
8058 void *data, *ctx;
8059 int uid;
8060{
8061 ipftoken_t *token;
8062 ipfruleiter_t it;
8063 ipfobj_t obj;
8064 int error;
8065
8066 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8067 if (token != NULL) {
8068 error = ipf_getnextrule(softc, token, data);
8069 WRITE_ENTER(&softc->ipf_tokens);
8070 ipf_token_deref(softc, token);
8071 RWLOCK_EXIT(&softc->ipf_tokens);
8072 } else {
8073 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8074 if (error != 0)
8075 return error;
8076 it.iri_rule = NULL;
8077 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8078 }
8079
8080 return error;
8081}
8082
8083
8084/* ------------------------------------------------------------------------ */
8085/* Function: ipf_geniter */
8086/* Returns: int - 0 = success, else error */
8087/* Parameters: softc(I) - pointer to soft context main structure */
8088/* token(I) - pointer to ipftoken_t structure */
8089/* itp(I) - pointer to iterator data */
8090/* */
8091/* Decide which iterator function to call using information passed through */
8092/* the ipfgeniter_t structure at itp. */
8093/* ------------------------------------------------------------------------ */
8094static int
8095ipf_geniter(softc, token, itp)
8096 ipf_main_softc_t *softc;
8097 ipftoken_t *token;
8098 ipfgeniter_t *itp;
8099{
8100 int error;
8101
8102 switch (itp->igi_type)
8103 {
8104 case IPFGENITER_FRAG :
8105 error = ipf_frag_pkt_next(softc, token, itp);
8106 break;
8107 default :
8108 IPFERROR(92);
8109 error = EINVAL;
8110 break;
8111 }
8112
8113 return error;
8114}
8115
8116
8117/* ------------------------------------------------------------------------ */
8118/* Function: ipf_genericiter */
8119/* Returns: int - 0 = success, else error */
8120/* Parameters: softc(I)- pointer to soft context main structure */
8121/* data(I) - the token type to match */
8122/* uid(I) - uid owning the token */
8123/* ptr(I) - context pointer for the token */
8124/* */
8125/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8126/* ------------------------------------------------------------------------ */
8127int
8128ipf_genericiter(softc, data, uid, ctx)
8129 ipf_main_softc_t *softc;
8130 void *data, *ctx;
8131 int uid;
8132{
8133 ipftoken_t *token;
8134 ipfgeniter_t iter;
8135 int error;
8136
8137 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8138 if (error != 0)
8139 return error;
8140
8141 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8142 if (token != NULL) {
8143 token->ipt_subtype = iter.igi_type;
8144 error = ipf_geniter(softc, token, &iter);
8145 WRITE_ENTER(&softc->ipf_tokens);
8146 ipf_token_deref(softc, token);
8147 RWLOCK_EXIT(&softc->ipf_tokens);
8148 } else {
8149 IPFERROR(93);
8150 error = 0;
8151 }
8152
8153 return error;
8154}
8155
8156
8157/* ------------------------------------------------------------------------ */
8158/* Function: ipf_ipf_ioctl */
8159/* Returns: int - 0 = success, else error */
8160/* Parameters: softc(I)- pointer to soft context main structure */
8161/* data(I) - the token type to match */
8162/* cmd(I) - the ioctl command number */
8163/* mode(I) - mode flags for the ioctl */
8164/* uid(I) - uid owning the token */
8165/* ptr(I) - context pointer for the token */
8166/* */
8167/* This function handles all of the ioctl command that are actually isssued */
8168/* to the /dev/ipl device. */
8169/* ------------------------------------------------------------------------ */
8170int
8171ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8172 ipf_main_softc_t *softc;
8173 caddr_t data;
8174 ioctlcmd_t cmd;
8175 int mode, uid;
8176 void *ctx;
8177{
8178 friostat_t fio;
8179 int error, tmp;
8180 ipfobj_t obj;
8181 SPL_INT(s);
8182
8183 switch (cmd)
8184 {
8185 case SIOCFRENB :
8186 if (!(mode & FWRITE)) {
8187 IPFERROR(94);
8188 error = EPERM;
8189 } else {
8190 error = BCOPYIN(data, &tmp, sizeof(tmp));
8191 if (error != 0) {
8192 IPFERROR(95);
8193 error = EFAULT;
8194 break;
8195 }
8196
8197 WRITE_ENTER(&softc->ipf_global);
8198 if (tmp) {
8199 if (softc->ipf_running > 0)
8200 error = 0;
8201 else
8202 error = ipfattach(softc);
8203 if (error == 0)
8204 softc->ipf_running = 1;
8205 else
8206 (void) ipfdetach(softc);
8207 } else {
8208 if (softc->ipf_running == 1)
8209 error = ipfdetach(softc);
8210 else
8211 error = 0;
8212 if (error == 0)
8213 softc->ipf_running = -1;
8214 }
8215 RWLOCK_EXIT(&softc->ipf_global);
8216 }
8217 break;
8218
8219 case SIOCIPFSET :
8220 if (!(mode & FWRITE)) {
8221 IPFERROR(96);
8222 error = EPERM;
8223 break;
8224 }
8225 /* FALLTHRU */
8226 case SIOCIPFGETNEXT :
8227 case SIOCIPFGET :
8228 error = ipf_ipftune(softc, cmd, (void *)data);
8229 break;
8230
8231 case SIOCSETFF :
8232 if (!(mode & FWRITE)) {
8233 IPFERROR(97);
8234 error = EPERM;
8235 } else {
8236 error = BCOPYIN(data, &softc->ipf_flags,
8237 sizeof(softc->ipf_flags));
8238 if (error != 0) {
8239 IPFERROR(98);
8240 error = EFAULT;
8241 }
8242 }
8243 break;
8244
8245 case SIOCGETFF :
8246 error = BCOPYOUT(&softc->ipf_flags, data,
8247 sizeof(softc->ipf_flags));
8248 if (error != 0) {
8249 IPFERROR(99);
8250 error = EFAULT;
8251 }
8252 break;
8253
8254 case SIOCFUNCL :
8255 error = ipf_resolvefunc(softc, (void *)data);
8256 break;
8257
8258 case SIOCINAFR :
8259 case SIOCRMAFR :
8260 case SIOCADAFR :
8261 case SIOCZRLST :
8262 if (!(mode & FWRITE)) {
8263 IPFERROR(100);
8264 error = EPERM;
8265 } else {
8266 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8267 softc->ipf_active, 1);
8268 }
8269 break;
8270
8271 case SIOCINIFR :
8272 case SIOCRMIFR :
8273 case SIOCADIFR :
8274 if (!(mode & FWRITE)) {
8275 IPFERROR(101);
8276 error = EPERM;
8277 } else {
8278 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8279 1 - softc->ipf_active, 1);
8280 }
8281 break;
8282
8283 case SIOCSWAPA :
8284 if (!(mode & FWRITE)) {
8285 IPFERROR(102);
8286 error = EPERM;
8287 } else {
8288 WRITE_ENTER(&softc->ipf_mutex);
8289 error = BCOPYOUT(&softc->ipf_active, data,
8290 sizeof(softc->ipf_active));
8291 if (error != 0) {
8292 IPFERROR(103);
8293 error = EFAULT;
8294 } else {
8295 softc->ipf_active = 1 - softc->ipf_active;
8296 }
8297 RWLOCK_EXIT(&softc->ipf_mutex);
8298 }
8299 break;
8300
8301 case SIOCGETFS :
8302 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8303 IPFOBJ_IPFSTAT);
8304 if (error != 0)
8305 break;
8306 ipf_getstat(softc, &fio, obj.ipfo_rev);
8307 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8308 break;
8309
8310 case SIOCFRZST :
8311 if (!(mode & FWRITE)) {
8312 IPFERROR(104);
8313 error = EPERM;
8314 } else
8315 error = ipf_zerostats(softc, (caddr_t)data);
8316 break;
8317
8318 case SIOCIPFFL :
8319 if (!(mode & FWRITE)) {
8320 IPFERROR(105);
8321 error = EPERM;
8322 } else {
8323 error = BCOPYIN(data, &tmp, sizeof(tmp));
8324 if (!error) {
8325 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8326 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8327 if (error != 0) {
8328 IPFERROR(106);
8329 error = EFAULT;
8330 }
8331 } else {
8332 IPFERROR(107);
8333 error = EFAULT;
8334 }
8335 }
8336 break;
8337
8338#ifdef USE_INET6
8339 case SIOCIPFL6 :
8340 if (!(mode & FWRITE)) {
8341 IPFERROR(108);
8342 error = EPERM;
8343 } else {
8344 error = BCOPYIN(data, &tmp, sizeof(tmp));
8345 if (!error) {
8346 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8347 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8348 if (error != 0) {
8349 IPFERROR(109);
8350 error = EFAULT;
8351 }
8352 } else {
8353 IPFERROR(110);
8354 error = EFAULT;
8355 }
8356 }
8357 break;
8358#endif
8359
8360 case SIOCSTLCK :
8361 if (!(mode & FWRITE)) {
8362 IPFERROR(122);
8363 error = EPERM;
8364 } else {
8365 error = BCOPYIN(data, &tmp, sizeof(tmp));
8366 if (error == 0) {
8367 ipf_state_setlock(softc->ipf_state_soft, tmp);
8368 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8369 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8370 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8371 } else {
8372 IPFERROR(111);
8373 error = EFAULT;
8374 }
8375 }
8376 break;
8377
8378#ifdef IPFILTER_LOG
8379 case SIOCIPFFB :
8380 if (!(mode & FWRITE)) {
8381 IPFERROR(112);
8382 error = EPERM;
8383 } else {
8384 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8385 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8386 if (error) {
8387 IPFERROR(113);
8388 error = EFAULT;
8389 }
8390 }
8391 break;
8392#endif /* IPFILTER_LOG */
8393
8394 case SIOCFRSYN :
8395 if (!(mode & FWRITE)) {
8396 IPFERROR(114);
8397 error = EPERM;
8398 } else {
8399 WRITE_ENTER(&softc->ipf_global);
8400#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8401 error = ipfsync();
8402#else
8403 ipf_sync(softc, NULL);
8404 error = 0;
8405#endif
8406 RWLOCK_EXIT(&softc->ipf_global);
8407
8408 }
8409 break;
8410
8411 case SIOCGFRST :
8412 error = ipf_outobj(softc, (void *)data,
8413 ipf_frag_stats(softc->ipf_frag_soft),
8414 IPFOBJ_FRAGSTAT);
8415 break;
8416
8417#ifdef IPFILTER_LOG
8418 case FIONREAD :
8419 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8420 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8421 break;
8422#endif
8423
8424 case SIOCIPFITER :
8425 SPL_SCHED(s);
8426 error = ipf_frruleiter(softc, data, uid, ctx);
8427 SPL_X(s);
8428 break;
8429
8430 case SIOCGENITER :
8431 SPL_SCHED(s);
8432 error = ipf_genericiter(softc, data, uid, ctx);
8433 SPL_X(s);
8434 break;
8435
8436 case SIOCIPFDELTOK :
8437 error = BCOPYIN(data, &tmp, sizeof(tmp));
8438 if (error == 0) {
8439 SPL_SCHED(s);
8440 error = ipf_token_del(softc, tmp, uid, ctx);
8441 SPL_X(s);
8442 }
8443 break;
8444
8445 default :
8446 IPFERROR(115);
8447 error = EINVAL;
8448 break;
8449 }
8450
8451 return error;
8452}
8453
8454
8455/* ------------------------------------------------------------------------ */
8456/* Function: ipf_decaps */
8457/* Returns: int - -1 == decapsulation failed, else bit mask of */
8458/* flags indicating packet filtering decision. */
8459/* Parameters: fin(I) - pointer to packet information */
8460/* pass(I) - IP protocol version to match */
8461/* l5proto(I) - layer 5 protocol to decode UDP data as. */
8462/* */
8463/* This function is called for packets that are wrapt up in other packets, */
8464/* for example, an IP packet that is the entire data segment for another IP */
8465/* packet. If the basic constraints for this are satisfied, change the */
8466/* buffer to point to the start of the inner packet and start processing */
8467/* rules belonging to the head group this rule specifies. */
8468/* ------------------------------------------------------------------------ */
8469u_32_t
8470ipf_decaps(fin, pass, l5proto)
8471 fr_info_t *fin;
8472 u_32_t pass;
8473 int l5proto;
8474{
8475 fr_info_t fin2, *fino = NULL;
8476 int elen, hlen, nh;
8477 grehdr_t gre;
8478 ip_t *ip;
8479 mb_t *m;
8480
8481 if ((fin->fin_flx & FI_COALESCE) == 0)
8482 if (ipf_coalesce(fin) == -1)
8483 goto cantdecaps;
8484
8485 m = fin->fin_m;
8486 hlen = fin->fin_hlen;
8487
8488 switch (fin->fin_p)
8489 {
8490 case IPPROTO_UDP :
8491 /*
8492 * In this case, the specific protocol being decapsulated
8493 * inside UDP frames comes from the rule.
8494 */
8495 nh = fin->fin_fr->fr_icode;
8496 break;
8497
8498 case IPPROTO_GRE : /* 47 */
8499 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8500 hlen += sizeof(grehdr_t);
8501 if (gre.gr_R|gre.gr_s)
8502 goto cantdecaps;
8503 if (gre.gr_C)
8504 hlen += 4;
8505 if (gre.gr_K)
8506 hlen += 4;
8507 if (gre.gr_S)
8508 hlen += 4;
8509
8510 nh = IPPROTO_IP;
8511
8512 /*
8513 * If the routing options flag is set, validate that it is
8514 * there and bounce over it.
8515 */
8516#if 0
8517 /* This is really heavy weight and lots of room for error, */
8518 /* so for now, put it off and get the simple stuff right. */
8519 if (gre.gr_R) {
8520 u_char off, len, *s;
8521 u_short af;
8522 int end;
8523
8524 end = 0;
8525 s = fin->fin_dp;
8526 s += hlen;
8527 aplen = fin->fin_plen - hlen;
8528 while (aplen > 3) {
8529 af = (s[0] << 8) | s[1];
8530 off = s[2];
8531 len = s[3];
8532 aplen -= 4;
8533 s += 4;
8534 if (af == 0 && len == 0) {
8535 end = 1;
8536 break;
8537 }
8538 if (aplen < len)
8539 break;
8540 s += len;
8541 aplen -= len;
8542 }
8543 if (end != 1)
8544 goto cantdecaps;
8545 hlen = s - (u_char *)fin->fin_dp;
8546 }
8547#endif
8548 break;
8549
8550#ifdef IPPROTO_IPIP
8551 case IPPROTO_IPIP : /* 4 */
8552#endif
8553 nh = IPPROTO_IP;
8554 break;
8555
8556 default : /* Includes ESP, AH is special for IPv4 */
8557 goto cantdecaps;
8558 }
8559
8560 switch (nh)
8561 {
8562 case IPPROTO_IP :
8563 case IPPROTO_IPV6 :
8564 break;
8565 default :
8566 goto cantdecaps;
8567 }
8568
8569 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8570 fino = fin;
8571 fin = &fin2;
8572 elen = hlen;
8573#if defined(MENTAT) && defined(_KERNEL)
8574 m->b_rptr += elen;
8575#else
8576 m->m_data += elen;
8577 m->m_len -= elen;
8578#endif
8579 fin->fin_plen -= elen;
8580
8581 ip = (ip_t *)((char *)fin->fin_ip + elen);
8582
8583 /*
8584 * Make sure we have at least enough data for the network layer
8585 * header.
8586 */
8587 if (IP_V(ip) == 4)
8588 hlen = IP_HL(ip) << 2;
8589#ifdef USE_INET6
8590 else if (IP_V(ip) == 6)
8591 hlen = sizeof(ip6_t);
8592#endif
8593 else
8594 goto cantdecaps2;
8595
8596 if (fin->fin_plen < hlen)
8597 goto cantdecaps2;
8598
8599 fin->fin_dp = (char *)ip + hlen;
8600
8601 if (IP_V(ip) == 4) {
8602 /*
8603 * Perform IPv4 header checksum validation.
8604 */
8605 if (ipf_cksum((u_short *)ip, hlen))
8606 goto cantdecaps2;
8607 }
8608
8609 if (ipf_makefrip(hlen, ip, fin) == -1) {
8610cantdecaps2:
8611 if (m != NULL) {
8612#if defined(MENTAT) && defined(_KERNEL)
8613 m->b_rptr -= elen;
8614#else
8615 m->m_data -= elen;
8616 m->m_len += elen;
8617#endif
8618 }
8619cantdecaps:
8620 DT1(frb_decapfrip, fr_info_t *, fin);
8621 pass &= ~FR_CMDMASK;
8622 pass |= FR_BLOCK|FR_QUICK;
8623 fin->fin_reason = FRB_DECAPFRIP;
8624 return -1;
8625 }
8626
8627 pass = ipf_scanlist(fin, pass);
8628
8629 /*
8630 * Copy the packet filter "result" fields out of the fr_info_t struct
8631 * that is local to the decapsulation processing and back into the
8632 * one we were called with.
8633 */
8634 fino->fin_flx = fin->fin_flx;
8635 fino->fin_rev = fin->fin_rev;
8636 fino->fin_icode = fin->fin_icode;
8637 fino->fin_rule = fin->fin_rule;
8638 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8639 fino->fin_fr = fin->fin_fr;
8640 fino->fin_error = fin->fin_error;
8641 fino->fin_mp = fin->fin_mp;
8642 fino->fin_m = fin->fin_m;
8643 m = fin->fin_m;
8644 if (m != NULL) {
8645#if defined(MENTAT) && defined(_KERNEL)
8646 m->b_rptr -= elen;
8647#else
8648 m->m_data -= elen;
8649 m->m_len += elen;
8650#endif
8651 }
8652 return pass;
8653}
8654
8655
8656/* ------------------------------------------------------------------------ */
8657/* Function: ipf_matcharray_load */
8658/* Returns: int - 0 = success, else error */
8659/* Parameters: softc(I) - pointer to soft context main structure */
8660/* data(I) - pointer to ioctl data */
8661/* objp(I) - ipfobj_t structure to load data into */
8662/* arrayptr(I) - pointer to location to store array pointer */
8663/* */
8664/* This function loads in a mathing array through the ipfobj_t struct that */
8665/* describes it. Sanity checking and array size limitations are enforced */
8666/* in this function to prevent userspace from trying to load in something */
8667/* that is insanely big. Once the size of the array is known, the memory */
8668/* required is malloc'd and returned through changing *arrayptr. The */
8669/* contents of the array are verified before returning. Only in the event */
8670/* of a successful call is the caller required to free up the malloc area. */
8671/* ------------------------------------------------------------------------ */
8672int
8673ipf_matcharray_load(softc, data, objp, arrayptr)
8674 ipf_main_softc_t *softc;
8675 caddr_t data;
8676 ipfobj_t *objp;
8677 int **arrayptr;
8678{
8679 int arraysize, *array, error;
8680
8681 *arrayptr = NULL;
8682
8683 error = BCOPYIN(data, objp, sizeof(*objp));
8684 if (error != 0) {
8685 IPFERROR(116);
8686 return EFAULT;
8687 }
8688
8689 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8690 IPFERROR(117);
8691 return EINVAL;
8692 }
8693
8694 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8695 (objp->ipfo_size > 1024)) {
8696 IPFERROR(118);
8697 return EINVAL;
8698 }
8699
8700 arraysize = objp->ipfo_size * sizeof(*array);
8701 KMALLOCS(array, int *, arraysize);
8702 if (array == NULL) {
8703 IPFERROR(119);
8704 return ENOMEM;
8705 }
8706
8707 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8708 if (error != 0) {
8709 KFREES(array, arraysize);
8710 IPFERROR(120);
8711 return EFAULT;
8712 }
8713
8714 if (ipf_matcharray_verify(array, arraysize) != 0) {
8715 KFREES(array, arraysize);
8716 IPFERROR(121);
8717 return EINVAL;
8718 }
8719
8720 *arrayptr = array;
8721 return 0;
8722}
8723
8724
8725/* ------------------------------------------------------------------------ */
8726/* Function: ipf_matcharray_verify */
8727/* Returns: Nil */
8728/* Parameters: array(I) - pointer to matching array */
8729/* arraysize(I) - number of elements in the array */
8730/* */
8731/* Verify the contents of a matching array by stepping through each element */
8732/* in it. The actual commands in the array are not verified for */
8733/* correctness, only that all of the sizes are correctly within limits. */
8734/* ------------------------------------------------------------------------ */
8735int
8736ipf_matcharray_verify(array, arraysize)
8737 int *array, arraysize;
8738{
8739 int i, nelem, maxidx;
8740 ipfexp_t *e;
8741
8742 nelem = arraysize / sizeof(*array);
8743
8744 /*
8745 * Currently, it makes no sense to have an array less than 6
8746 * elements long - the initial size at the from, a single operation
8747 * (minimum 4 in length) and a trailer, for a total of 6.
8748 */
8749 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8750 return -1;
8751 }
8752
8753 /*
8754 * Verify the size of data pointed to by array with how long
8755 * the array claims to be itself.
8756 */
8757 if (array[0] * sizeof(*array) != arraysize) {
8758 return -1;
8759 }
8760
8761 maxidx = nelem - 1;
8762 /*
8763 * The last opcode in this array should be an IPF_EXP_END.
8764 */
8765 if (array[maxidx] != IPF_EXP_END) {
8766 return -1;
8767 }
8768
8769 for (i = 1; i < maxidx; ) {
8770 e = (ipfexp_t *)(array + i);
8771
8772 /*
8773 * The length of the bits to check must be at least 1
8774 * (or else there is nothing to comapre with!) and it
8775 * cannot exceed the length of the data present.
8776 */
8777 if ((e->ipfe_size < 1 ) ||
8778 (e->ipfe_size + i > maxidx)) {
8779 return -1;
8780 }
8781 i += e->ipfe_size;
8782 }
8783 return 0;
8784}
8785
8786
8787/* ------------------------------------------------------------------------ */
8788/* Function: ipf_fr_matcharray */
8789/* Returns: int - 0 = match failed, else positive match */
8790/* Parameters: fin(I) - pointer to packet information */
8791/* array(I) - pointer to matching array */
8792/* */
8793/* This function is used to apply a matching array against a packet and */
8794/* return an indication of whether or not the packet successfully matches */
8795/* all of the commands in it. */
8796/* ------------------------------------------------------------------------ */
8797static int
8798ipf_fr_matcharray(fin, array)
8799 fr_info_t *fin;
8800 int *array;
8801{
8802 int i, n, *x, rv, p;
8803 ipfexp_t *e;
8804
8805 rv = 0;
8806 n = array[0];
8807 x = array + 1;
8808
8809 for (; n > 0; x += 3 + x[3], rv = 0) {
8810 e = (ipfexp_t *)x;
8811 if (e->ipfe_cmd == IPF_EXP_END)
8812 break;
8813 n -= e->ipfe_size;
8814
8815 /*
8816 * The upper 16 bits currently store the protocol value.
8817 * This is currently used with TCP and UDP port compares and
8818 * allows "tcp.port = 80" without requiring an explicit
8819 " "ip.pr = tcp" first.
8820 */
8821 p = e->ipfe_cmd >> 16;
8822 if ((p != 0) && (p != fin->fin_p))
8823 break;
8824
8825 switch (e->ipfe_cmd)
8826 {
8827 case IPF_EXP_IP_PR :
8828 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8829 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8830 }
8831 break;
8832
8833 case IPF_EXP_IP_SRCADDR :
8834 if (fin->fin_v != 4)
8835 break;
8836 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8837 rv |= ((fin->fin_saddr &
8838 e->ipfe_arg0[i * 2 + 1]) ==
8839 e->ipfe_arg0[i * 2]);
8840 }
8841 break;
8842
8843 case IPF_EXP_IP_DSTADDR :
8844 if (fin->fin_v != 4)
8845 break;
8846 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8847 rv |= ((fin->fin_daddr &
8848 e->ipfe_arg0[i * 2 + 1]) ==
8849 e->ipfe_arg0[i * 2]);
8850 }
8851 break;
8852
8853 case IPF_EXP_IP_ADDR :
8854 if (fin->fin_v != 4)
8855 break;
8856 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8857 rv |= ((fin->fin_saddr &
8858 e->ipfe_arg0[i * 2 + 1]) ==
8859 e->ipfe_arg0[i * 2]) ||
8860 ((fin->fin_daddr &
8861 e->ipfe_arg0[i * 2 + 1]) ==
8862 e->ipfe_arg0[i * 2]);
8863 }
8864 break;
8865
8866#ifdef USE_INET6
8867 case IPF_EXP_IP6_SRCADDR :
8868 if (fin->fin_v != 6)
8869 break;
8870 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8871 rv |= IP6_MASKEQ(&fin->fin_src6,
8872 &e->ipfe_arg0[i * 8 + 4],
8873 &e->ipfe_arg0[i * 8]);
8874 }
8875 break;
8876
8877 case IPF_EXP_IP6_DSTADDR :
8878 if (fin->fin_v != 6)
8879 break;
8880 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8881 rv |= IP6_MASKEQ(&fin->fin_dst6,
8882 &e->ipfe_arg0[i * 8 + 4],
8883 &e->ipfe_arg0[i * 8]);
8884 }
8885 break;
8886
8887 case IPF_EXP_IP6_ADDR :
8888 if (fin->fin_v != 6)
8889 break;
8890 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8891 rv |= IP6_MASKEQ(&fin->fin_src6,
8892 &e->ipfe_arg0[i * 8 + 4],
8893 &e->ipfe_arg0[i * 8]) ||
8894 IP6_MASKEQ(&fin->fin_dst6,
8895 &e->ipfe_arg0[i * 8 + 4],
8896 &e->ipfe_arg0[i * 8]);
8897 }
8898 break;
8899#endif
8900
8901 case IPF_EXP_UDP_PORT :
8902 case IPF_EXP_TCP_PORT :
8903 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8904 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8905 (fin->fin_dport == e->ipfe_arg0[i]);
8906 }
8907 break;
8908
8909 case IPF_EXP_UDP_SPORT :
8910 case IPF_EXP_TCP_SPORT :
8911 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8912 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8913 }
8914 break;
8915
8916 case IPF_EXP_UDP_DPORT :
8917 case IPF_EXP_TCP_DPORT :
8918 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8919 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8920 }
8921 break;
8922
8923 case IPF_EXP_TCP_FLAGS :
8924 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8925 rv |= ((fin->fin_tcpf &
8926 e->ipfe_arg0[i * 2 + 1]) ==
8927 e->ipfe_arg0[i * 2]);
8928 }
8929 break;
8930 }
8931 rv ^= e->ipfe_not;
8932
8933 if (rv == 0)
8934 break;
8935 }
8936
8937 return rv;
8938}
8939
8940
8941/* ------------------------------------------------------------------------ */
8942/* Function: ipf_queueflush */
8943/* Returns: int - number of entries flushed (0 = none) */
8944/* Parameters: softc(I) - pointer to soft context main structure */
8945/* deletefn(I) - function to call to delete entry */
8946/* ipfqs(I) - top of the list of ipf internal queues */
8947/* userqs(I) - top of the list of user defined timeouts */
8948/* */
8949/* This fucntion gets called when the state/NAT hash tables fill up and we */
8950/* need to try a bit harder to free up some space. The algorithm used here */
8951/* split into two parts but both halves have the same goal: to reduce the */
8952/* number of connections considered to be "active" to the low watermark. */
8953/* There are two steps in doing this: */
8954/* 1) Remove any TCP connections that are already considered to be "closed" */
8955/* but have not yet been removed from the state table. The two states */
8956/* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8957/* candidates for this style of removal. If freeing up entries in */
8958/* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8959/* we do not go on to step 2. */
8960/* */
8961/* 2) Look for the oldest entries on each timeout queue and free them if */
8962/* they are within the given window we are considering. Where the */
8963/* window starts and the steps taken to increase its size depend upon */
8964/* how long ipf has been running (ipf_ticks.) Anything modified in the */
8965/* last 30 seconds is not touched. */
8966/* touched */
8967/* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8968/* | | | | | | */
8969/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8970/* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8971/* */
8972/* Points to note: */
8973/* - tqe_die is the time, in the future, when entries die. */
8974/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8975/* ticks. */
8976/* - tqe_touched is when the entry was last used by NAT/state */
8977/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8978/* ipf_ticks any given timeout queue and vice versa. */
8979/* - both tqe_die and tqe_touched increase over time */
8980/* - timeout queues are sorted with the highest value of tqe_die at the */
8981/* bottom and therefore the smallest values of each are at the top */
8982/* - the pointer passed in as ipfqs should point to an array of timeout */
8983/* queues representing each of the TCP states */
8984/* */
8985/* We start by setting up a maximum range to scan for things to move of */
8986/* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8987/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8988/* we start again with a new value for "iend" and "istart". This is */
8989/* continued until we either finish the scan of 30 second intervals or the */
8990/* low water mark is reached. */
8991/* ------------------------------------------------------------------------ */
8992int
8993ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8994 ipf_main_softc_t *softc;
8995 ipftq_delete_fn_t deletefn;
8996 ipftq_t *ipfqs, *userqs;
8997 u_int *activep;
8998 int size, low;
8999{
9000 u_long interval, istart, iend;
9001 ipftq_t *ifq, *ifqnext;
9002 ipftqent_t *tqe, *tqn;
9003 int removed = 0;
9004
9005 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
9006 tqn = tqe->tqe_next;
9007 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9008 removed++;
9009 }
9010 if ((*activep * 100 / size) > low) {
9011 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
9012 ((tqe = tqn) != NULL); ) {
9013 tqn = tqe->tqe_next;
9014 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9015 removed++;
9016 }
9017 }
9018
9019 if ((*activep * 100 / size) <= low) {
9020 return removed;
9021 }
9022
9023 /*
9024 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
9025 * used then the operations are upgraded to floating point
9026 * and kernels don't like floating point...
9027 */
9028 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
9029 istart = IPF_TTLVAL(86400 * 4);
9030 interval = IPF_TTLVAL(43200);
9031 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9032 istart = IPF_TTLVAL(43200);
9033 interval = IPF_TTLVAL(1800);
9034 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9035 istart = IPF_TTLVAL(1800);
9036 interval = IPF_TTLVAL(30);
9037 } else {
9038 return 0;
9039 }
9040 if (istart > softc->ipf_ticks) {
9041 if (softc->ipf_ticks - interval < interval)
9042 istart = interval;
9043 else
9044 istart = (softc->ipf_ticks / interval) * interval;
9045 }
9046
9047 iend = softc->ipf_ticks - interval;
9048
9049 while ((*activep * 100 / size) > low) {
9050 u_long try;
9051
9052 try = softc->ipf_ticks - istart;
9053
9054 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9055 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9056 if (try < tqe->tqe_touched)
9057 break;
9058 tqn = tqe->tqe_next;
9059 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9060 removed++;
9061 }
9062 }
9063
9064 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9065 ifqnext = ifq->ifq_next;
9066
9067 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9068 if (try < tqe->tqe_touched)
9069 break;
9070 tqn = tqe->tqe_next;
9071 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9072 removed++;
9073 }
9074 }
9075
9076 if (try >= iend) {
9077 if (interval == IPF_TTLVAL(43200)) {
9078 interval = IPF_TTLVAL(1800);
9079 } else if (interval == IPF_TTLVAL(1800)) {
9080 interval = IPF_TTLVAL(30);
9081 } else {
9082 break;
9083 }
9084 if (interval >= softc->ipf_ticks)
9085 break;
9086
9087 iend = softc->ipf_ticks - interval;
9088 }
9089 istart -= interval;
9090 }
9091
9092 return removed;
9093}
9094
9095
9096/* ------------------------------------------------------------------------ */
9097/* Function: ipf_deliverlocal */
9098/* Returns: int - 1 = local address, 0 = non-local address */
9099/* Parameters: softc(I) - pointer to soft context main structure */
9100/* ipversion(I) - IP protocol version (4 or 6) */
9101/* ifp(I) - network interface pointer */
9102/* ipaddr(I) - IPv4/6 destination address */
9103/* */
9104/* This fucntion is used to determine in the address "ipaddr" belongs to */
9105/* the network interface represented by ifp. */
9106/* ------------------------------------------------------------------------ */
9107int
9108ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9109 ipf_main_softc_t *softc;
9110 int ipversion;
9111 void *ifp;
9112 i6addr_t *ipaddr;
9113{
9114 i6addr_t addr;
9115 int islocal = 0;
9116
9117 if (ipversion == 4) {
9118 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9119 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9120 islocal = 1;
9121 }
9122
9123#ifdef USE_INET6
9124 } else if (ipversion == 6) {
9125 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9126 if (IP6_EQ(&addr, ipaddr))
9127 islocal = 1;
9128 }
9129#endif
9130 }
9131
9132 return islocal;
9133}
9134
9135
9136/* ------------------------------------------------------------------------ */
9137/* Function: ipf_settimeout */
9138/* Returns: int - 0 = success, -1 = failure */
9139/* Parameters: softc(I) - pointer to soft context main structure */
9140/* t(I) - pointer to tuneable array entry */
9141/* p(I) - pointer to values passed in to apply */
9142/* */
9143/* This function is called to set the timeout values for each distinct */
9144/* queue timeout that is available. When called, it calls into both the */
9145/* state and NAT code, telling them to update their timeout queues. */
9146/* ------------------------------------------------------------------------ */
9147static int
9148ipf_settimeout(softc, t, p)
9149 struct ipf_main_softc_s *softc;
9150 ipftuneable_t *t;
9151 ipftuneval_t *p;
9152{
9153
9154 /*
9155 * ipf_interror should be set by the functions called here, not
9156 * by this function - it's just a middle man.
9157 */
9158 if (ipf_state_settimeout(softc, t, p) == -1)
9159 return -1;
9160 if (ipf_nat_settimeout(softc, t, p) == -1)
9161 return -1;
9162 return 0;
9163}
9164
9165
9166/* ------------------------------------------------------------------------ */
9167/* Function: ipf_apply_timeout */
9168/* Returns: int - 0 = success, -1 = failure */
9169/* Parameters: head(I) - pointer to tuneable array entry */
9170/* seconds(I) - pointer to values passed in to apply */
9171/* */
9172/* This function applies a timeout of "seconds" to the timeout queue that */
9173/* is pointed to by "head". All entries on this list have an expiration */
9174/* set to be the current tick value of ipf plus the ttl. Given that this */
9175/* function should only be called when the delta is non-zero, the task is */
9176/* to walk the entire list and apply the change. The sort order will not */
9177/* change. The only catch is that this is O(n) across the list, so if the */
9178/* queue has lots of entries (10s of thousands or 100s of thousands), it */
9179/* could take a relatively long time to work through them all. */
9180/* ------------------------------------------------------------------------ */
9181void
9182ipf_apply_timeout(head, seconds)
9183 ipftq_t *head;
9184 u_int seconds;
9185{
9186 u_int oldtimeout, newtimeout;
9187 ipftqent_t *tqe;
9188 int delta;
9189
9190 MUTEX_ENTER(&head->ifq_lock);
9191 oldtimeout = head->ifq_ttl;
9192 newtimeout = IPF_TTLVAL(seconds);
9193 delta = oldtimeout - newtimeout;
9194
9195 head->ifq_ttl = newtimeout;
9196
9197 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9198 tqe->tqe_die += delta;
9199 }
9200 MUTEX_EXIT(&head->ifq_lock);
9201}
9202
9203
9204/* ------------------------------------------------------------------------ */
9205/* Function: ipf_settimeout_tcp */
9206/* Returns: int - 0 = successfully applied, -1 = failed */
9207/* Parameters: t(I) - pointer to tuneable to change */
9208/* p(I) - pointer to new timeout information */
9209/* tab(I) - pointer to table of TCP queues */
9210/* */
9211/* This function applies the new timeout (p) to the TCP tunable (t) and */
9212/* updates all of the entries on the relevant timeout queue by calling */
9213/* ipf_apply_timeout(). */
9214/* ------------------------------------------------------------------------ */
9215int
9216ipf_settimeout_tcp(t, p, tab)
9217 ipftuneable_t *t;
9218 ipftuneval_t *p;
9219 ipftq_t *tab;
9220{
9221 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9222 !strcmp(t->ipft_name, "tcp_established")) {
9223 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9224 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9225 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9226 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9227 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9228 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9229 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9230 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9231 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9232 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9233 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9234 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9235 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9236 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9237 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9238 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9239 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9240 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9241 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9242 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9243 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9244 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9245 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9246 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9247 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9248 } else {
9249 /*
9250 * ipf_interror isn't set here because it should be set
9251 * by whatever called this function.
9252 */
9253 return -1;
9254 }
9255 return 0;
9256}
9257
9258
9259/* ------------------------------------------------------------------------ */
9260/* Function: ipf_main_soft_create */
9261/* Returns: NULL = failure, else success */
9262/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9263/* */
9264/* Create the foundation soft context structure. In circumstances where it */
9265/* is not required to dynamically allocate the context, a pointer can be */
9266/* passed in (rather than NULL) to a structure to be initialised. */
9267/* The main thing of interest is that a number of locks are initialised */
9268/* here instead of in the where might be expected - in the relevant create */
9269/* function elsewhere. This is done because the current locking design has */
9270/* some areas where these locks are used outside of their module. */
9271/* Possibly the most important exercise that is done here is setting of all */
9272/* the timeout values, allowing them to be changed before init(). */
9273/* ------------------------------------------------------------------------ */
9274void *
9275ipf_main_soft_create(arg)
9276 void *arg;
9277{
9278 ipf_main_softc_t *softc;
9279
9280 if (arg == NULL) {
9281 KMALLOC(softc, ipf_main_softc_t *);
9282 if (softc == NULL)
9283 return NULL;
9284 } else {
9285 softc = arg;
9286 }
9287
9288 bzero((char *)softc, sizeof(*softc));
9289
9290 /*
9291 * This serves as a flag as to whether or not the softc should be
9292 * free'd when _destroy is called.
9293 */
9294 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9295
9296 softc->ipf_tuners = ipf_tune_array_copy(softc,
9297 sizeof(ipf_main_tuneables),
9298 ipf_main_tuneables);
9299 if (softc->ipf_tuners == NULL) {
9300 ipf_main_soft_destroy(softc);
9301 return NULL;
9302 }
9303
9304 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9305 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9306 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9307 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9308 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9309 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9310 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9311 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9312 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9313
9314 softc->ipf_token_head = NULL;
9315 softc->ipf_token_tail = &softc->ipf_token_head;
9316
9317 softc->ipf_tcpidletimeout = FIVE_DAYS;
9318 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9319 softc->ipf_tcplastack = IPF_TTLVAL(30);
9320 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9321 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9322 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9323 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9324 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9325 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9326 softc->ipf_udptimeout = IPF_TTLVAL(120);
9327 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9328 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9329 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9330 softc->ipf_iptimeout = IPF_TTLVAL(60);
9331
9332#if defined(IPFILTER_DEFAULT_BLOCK)
9333 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9334#else
9335 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9336#endif
9337 softc->ipf_minttl = 4;
9338 softc->ipf_icmpminfragmtu = 68;
9339 softc->ipf_flags = IPF_LOGGING;
9340
9341 return softc;
9342}
9343
9344/* ------------------------------------------------------------------------ */
9345/* Function: ipf_main_soft_init */
9346/* Returns: 0 = success, -1 = failure */
9347/* Parameters: softc(I) - pointer to soft context main structure */
9348/* */
9349/* A null-op function that exists as a placeholder so that the flow in */
9350/* other functions is obvious. */
9351/* ------------------------------------------------------------------------ */
9352/*ARGSUSED*/
9353int
9354ipf_main_soft_init(softc)
9355 ipf_main_softc_t *softc;
9356{
9357 return 0;
9358}
9359
9360
9361/* ------------------------------------------------------------------------ */
9362/* Function: ipf_main_soft_destroy */
9363/* Returns: void */
9364/* Parameters: softc(I) - pointer to soft context main structure */
9365/* */
9366/* Undo everything that we did in ipf_main_soft_create. */
9367/* */
9368/* The most important check that needs to be made here is whether or not */
9369/* the structure was allocated by ipf_main_soft_create() by checking what */
9370/* value is stored in ipf_dynamic_main. */
9371/* ------------------------------------------------------------------------ */
9372/*ARGSUSED*/
9373void
9374ipf_main_soft_destroy(softc)
9375 ipf_main_softc_t *softc;
9376{
9377
9378 RW_DESTROY(&softc->ipf_frag);
9379 RW_DESTROY(&softc->ipf_poolrw);
9380 RW_DESTROY(&softc->ipf_nat);
9381 RW_DESTROY(&softc->ipf_state);
9382 RW_DESTROY(&softc->ipf_tokens);
9383 RW_DESTROY(&softc->ipf_mutex);
9384 RW_DESTROY(&softc->ipf_global);
9385 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9386 MUTEX_DESTROY(&softc->ipf_rw);
9387
9388 if (softc->ipf_tuners != NULL) {
9389 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9390 }
9391 if (softc->ipf_dynamic_softc == 1) {
9392 KFREE(softc);
9393 }
9394}
9395
9396
9397/* ------------------------------------------------------------------------ */
9398/* Function: ipf_main_soft_fini */
9399/* Returns: 0 = success, -1 = failure */
9400/* Parameters: softc(I) - pointer to soft context main structure */
9401/* */
9402/* Clean out the rules which have been added since _init was last called, */
9403/* the only dynamic part of the mainline. */
9404/* ------------------------------------------------------------------------ */
9405int
9406ipf_main_soft_fini(softc)
9407 ipf_main_softc_t *softc;
9408{
9409 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9410 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9411 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9412 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9413
9414 return 0;
9415}
9416
9417
9418/* ------------------------------------------------------------------------ */
9419/* Function: ipf_main_load */
9420/* Returns: 0 = success, -1 = failure */
9421/* Parameters: none */
9422/* */
9423/* Handle global initialisation that needs to be done for the base part of */
9424/* IPFilter. At present this just amounts to initialising some ICMP lookup */
9425/* arrays that get used by the state/NAT code. */
9426/* ------------------------------------------------------------------------ */
9427int
9428ipf_main_load()
9429{
9430 int i;
9431
9432 /* fill icmp reply type table */
9433 for (i = 0; i <= ICMP_MAXTYPE; i++)
9434 icmpreplytype4[i] = -1;
9435 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9436 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9437 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9438 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9439
9440#ifdef USE_INET6
9441 /* fill icmp reply type table */
9442 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9443 icmpreplytype6[i] = -1;
9444 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9445 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9446 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9447 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9448 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9449#endif
9450
9451 return 0;
9452}
9453
9454
9455/* ------------------------------------------------------------------------ */
9456/* Function: ipf_main_unload */
9457/* Returns: 0 = success, -1 = failure */
9458/* Parameters: none */
9459/* */
9460/* A null-op function that exists as a placeholder so that the flow in */
9461/* other functions is obvious. */
9462/* ------------------------------------------------------------------------ */
9463int
9464ipf_main_unload()
9465{
9466 return 0;
9467}
9468
9469
9470/* ------------------------------------------------------------------------ */
9471/* Function: ipf_load_all */
9472/* Returns: 0 = success, -1 = failure */
9473/* Parameters: none */
9474/* */
9475/* Work through all of the subsystems inside IPFilter and call the load */
9476/* function for each in an order that won't lead to a crash :) */
9477/* ------------------------------------------------------------------------ */
9478int
9479ipf_load_all()
9480{
9481 if (ipf_main_load() == -1)
9482 return -1;
9483
9484 if (ipf_state_main_load() == -1)
9485 return -1;
9486
9487 if (ipf_nat_main_load() == -1)
9488 return -1;
9489
9490 if (ipf_frag_main_load() == -1)
9491 return -1;
9492
9493 if (ipf_auth_main_load() == -1)
9494 return -1;
9495
9496 if (ipf_proxy_main_load() == -1)
9497 return -1;
9498
9499 return 0;
9500}
9501
9502
9503/* ------------------------------------------------------------------------ */
9504/* Function: ipf_unload_all */
9505/* Returns: 0 = success, -1 = failure */
9506/* Parameters: none */
9507/* */
9508/* Work through all of the subsystems inside IPFilter and call the unload */
9509/* function for each in an order that won't lead to a crash :) */
9510/* ------------------------------------------------------------------------ */
9511int
9512ipf_unload_all()
9513{
9514 if (ipf_proxy_main_unload() == -1)
9515 return -1;
9516
9517 if (ipf_auth_main_unload() == -1)
9518 return -1;
9519
9520 if (ipf_frag_main_unload() == -1)
9521 return -1;
9522
9523 if (ipf_nat_main_unload() == -1)
9524 return -1;
9525
9526 if (ipf_state_main_unload() == -1)
9527 return -1;
9528
9529 if (ipf_main_unload() == -1)
9530 return -1;
9531
9532 return 0;
9533}
9534
9535
9536/* ------------------------------------------------------------------------ */
9537/* Function: ipf_create_all */
9538/* Returns: NULL = failure, else success */
9539/* Parameters: arg(I) - pointer to soft context main structure */
9540/* */
9541/* Work through all of the subsystems inside IPFilter and call the create */
9542/* function for each in an order that won't lead to a crash :) */
9543/* ------------------------------------------------------------------------ */
9544ipf_main_softc_t *
9545ipf_create_all(arg)
9546 void *arg;
9547{
9548 ipf_main_softc_t *softc;
9549
9550 softc = ipf_main_soft_create(arg);
9551 if (softc == NULL)
9552 return NULL;
9553
9554#ifdef IPFILTER_LOG
9555 softc->ipf_log_soft = ipf_log_soft_create(softc);
9556 if (softc->ipf_log_soft == NULL) {
9557 ipf_destroy_all(softc);
9558 return NULL;
9559 }
9560#endif
9561
9562 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9563 if (softc->ipf_lookup_soft == NULL) {
9564 ipf_destroy_all(softc);
9565 return NULL;
9566 }
9567
9568 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9569 if (softc->ipf_sync_soft == NULL) {
9570 ipf_destroy_all(softc);
9571 return NULL;
9572 }
9573
9574 softc->ipf_state_soft = ipf_state_soft_create(softc);
9575 if (softc->ipf_state_soft == NULL) {
9576 ipf_destroy_all(softc);
9577 return NULL;
9578 }
9579
9580 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9581 if (softc->ipf_nat_soft == NULL) {
9582 ipf_destroy_all(softc);
9583 return NULL;
9584 }
9585
9586 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9587 if (softc->ipf_frag_soft == NULL) {
9588 ipf_destroy_all(softc);
9589 return NULL;
9590 }
9591
9592 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9593 if (softc->ipf_auth_soft == NULL) {
9594 ipf_destroy_all(softc);
9595 return NULL;
9596 }
9597
9598 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9599 if (softc->ipf_proxy_soft == NULL) {
9600 ipf_destroy_all(softc);
9601 return NULL;
9602 }
9603
9604 return softc;
9605}
9606
9607
9608/* ------------------------------------------------------------------------ */
9609/* Function: ipf_destroy_all */
9610/* Returns: void */
9611/* Parameters: softc(I) - pointer to soft context main structure */
9612/* */
9613/* Work through all of the subsystems inside IPFilter and call the destroy */
9614/* function for each in an order that won't lead to a crash :) */
9615/* */
9616/* Every one of these functions is expected to succeed, so there is no */
9617/* checking of return values. */
9618/* ------------------------------------------------------------------------ */
9619void
9620ipf_destroy_all(softc)
9621 ipf_main_softc_t *softc;
9622{
9623
9624 if (softc->ipf_state_soft != NULL) {
9625 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9626 softc->ipf_state_soft = NULL;
9627 }
9628
9629 if (softc->ipf_nat_soft != NULL) {
9630 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9631 softc->ipf_nat_soft = NULL;
9632 }
9633
9634 if (softc->ipf_frag_soft != NULL) {
9635 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9636 softc->ipf_frag_soft = NULL;
9637 }
9638
9639 if (softc->ipf_auth_soft != NULL) {
9640 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9641 softc->ipf_auth_soft = NULL;
9642 }
9643
9644 if (softc->ipf_proxy_soft != NULL) {
9645 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9646 softc->ipf_proxy_soft = NULL;
9647 }
9648
9649 if (softc->ipf_sync_soft != NULL) {
9650 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9651 softc->ipf_sync_soft = NULL;
9652 }
9653
9654 if (softc->ipf_lookup_soft != NULL) {
9655 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9656 softc->ipf_lookup_soft = NULL;
9657 }
9658
9659#ifdef IPFILTER_LOG
9660 if (softc->ipf_log_soft != NULL) {
9661 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9662 softc->ipf_log_soft = NULL;
9663 }
9664#endif
9665
9666 ipf_main_soft_destroy(softc);
9667}
9668
9669
9670/* ------------------------------------------------------------------------ */
9671/* Function: ipf_init_all */
9672/* Returns: 0 = success, -1 = failure */
9673/* Parameters: softc(I) - pointer to soft context main structure */
9674/* */
9675/* Work through all of the subsystems inside IPFilter and call the init */
9676/* function for each in an order that won't lead to a crash :) */
9677/* ------------------------------------------------------------------------ */
9678int
9679ipf_init_all(softc)
9680 ipf_main_softc_t *softc;
9681{
9682
9683 if (ipf_main_soft_init(softc) == -1)
9684 return -1;
9685
9686#ifdef IPFILTER_LOG
9687 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9688 return -1;
9689#endif
9690
9691 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9692 return -1;
9693
9694 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9695 return -1;
9696
9697 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9698 return -1;
9699
9700 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9701 return -1;
9702
9703 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9704 return -1;
9705
9706 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9707 return -1;
9708
9709 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9710 return -1;
9711
9712 return 0;
9713}
9714
9715
9716/* ------------------------------------------------------------------------ */
9717/* Function: ipf_fini_all */
9718/* Returns: 0 = success, -1 = failure */
9719/* Parameters: softc(I) - pointer to soft context main structure */
9720/* */
9721/* Work through all of the subsystems inside IPFilter and call the fini */
9722/* function for each in an order that won't lead to a crash :) */
9723/* ------------------------------------------------------------------------ */
9724int
9725ipf_fini_all(softc)
9726 ipf_main_softc_t *softc;
9727{
9728
9729 ipf_token_flush(softc);
9730
9731 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9732 return -1;
9733
9734 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9735 return -1;
9736
9737 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9738 return -1;
9739
9740 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9741 return -1;
9742
9743 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9744 return -1;
9745
9746 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9747 return -1;
9748
9749 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9750 return -1;
9751
9752#ifdef IPFILTER_LOG
9753 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9754 return -1;
9755#endif
9756
9757 if (ipf_main_soft_fini(softc) == -1)
9758 return -1;
9759
9760 return 0;
9761}
9762
9763
9764/* ------------------------------------------------------------------------ */
9765/* Function: ipf_rule_expire */
9766/* Returns: Nil */
9767/* Parameters: softc(I) - pointer to soft context main structure */
9768/* */
9769/* At present this function exists just to support temporary addition of */
9770/* firewall rules. Both inactive and active lists are scanned for items to */
9771/* purge, as by rights, the expiration is computed as soon as the rule is */
9772/* loaded in. */
9773/* ------------------------------------------------------------------------ */
9774void
9775ipf_rule_expire(softc)
9776 ipf_main_softc_t *softc;
9777{
9778 frentry_t *fr;
9779
9780 if ((softc->ipf_rule_explist[0] == NULL) &&
9781 (softc->ipf_rule_explist[1] == NULL))
9782 return;
9783
9784 WRITE_ENTER(&softc->ipf_mutex);
9785
9786 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9787 /*
9788 * Because the list is kept sorted on insertion, the fist
9789 * one that dies in the future means no more work to do.
9790 */
9791 if (fr->fr_die > softc->ipf_ticks)
9792 break;
9793 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9794 }
9795
9796 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9797 /*
9798 * Because the list is kept sorted on insertion, the fist
9799 * one that dies in the future means no more work to do.
9800 */
9801 if (fr->fr_die > softc->ipf_ticks)
9802 break;
9803 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9804 }
9805
9806 RWLOCK_EXIT(&softc->ipf_mutex);
9807}
9808
9809
9810static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9811static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9812 i6addr_t *));
9813
9814host_node_t RBI_ZERO(ipf_rb);
9815RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9816
9817
9818/* ------------------------------------------------------------------------ */
9819/* Function: ipf_ht_node_cmp */
9820/* Returns: int - 0 == nodes are the same, .. */
9821/* Parameters: k1(I) - pointer to first key to compare */
9822/* k2(I) - pointer to second key to compare */
9823/* */
9824/* The "key" for the node is a combination of two fields: the address */
9825/* family and the address itself. */
9826/* */
9827/* Because we're not actually interpreting the address data, it isn't */
9828/* necessary to convert them to/from network/host byte order. The mask is */
9829/* just used to remove bits that aren't significant - it doesn't matter */
9830/* where they are, as long as they're always in the same place. */
9831/* */
9832/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9833/* this is where individual ones will differ the most - but not true for */
9834/* for /48's, etc. */
9835/* ------------------------------------------------------------------------ */
9836static int
9837ipf_ht_node_cmp(k1, k2)
9838 struct host_node_s *k1, *k2;
9839{
9840 int i;
9841
9842 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9843 if (i != 0)
9844 return i;
9845
9846 if (k1->hn_addr.adf_family == AF_INET)
9847 return (k2->hn_addr.adf_addr.in4.s_addr -
9848 k1->hn_addr.adf_addr.in4.s_addr);
9849
9850 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9851 if (i != 0)
9852 return i;
9853 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9854 if (i != 0)
9855 return i;
9856 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9857 if (i != 0)
9858 return i;
9859 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9860 return i;
9861}
9862
9863
9864/* ------------------------------------------------------------------------ */
9865/* Function: ipf_ht_node_make_key */
9866/* Returns: Nil */
9867/* parameters: htp(I) - pointer to address tracking structure */
9868/* key(I) - where to store masked address for lookup */
9869/* family(I) - protocol family of address */
9870/* addr(I) - pointer to network address */
9871/* */
9872/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9873/* copy the address passed in into the key structure whilst masking out the */
9874/* bits that we don't want. */
9875/* */
9876/* Because the parser will set ht_netmask to 128 if there is no protocol */
9877/* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9878/* have to be wary of that and not allow 32-128 to happen. */
9879/* ------------------------------------------------------------------------ */
9880static void
9881ipf_ht_node_make_key(htp, key, family, addr)
9882 host_track_t *htp;
9883 host_node_t *key;
9884 int family;
9885 i6addr_t *addr;
9886{
9887 key->hn_addr.adf_family = family;
9888 if (family == AF_INET) {
9889 u_32_t mask;
9890 int bits;
9891
9892 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9893 bits = htp->ht_netmask;
9894 if (bits >= 32) {
9895 mask = 0xffffffff;
9896 } else {
9897 mask = htonl(0xffffffff << (32 - bits));
9898 }
9899 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9900#ifdef USE_INET6
9901 } else {
9902 int bits = htp->ht_netmask;
9903
9904 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9905 if (bits > 96) {
9906 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9907 htonl(0xffffffff << (128 - bits));
9908 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9909 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9910 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9911 } else if (bits > 64) {
9912 key->hn_addr.adf_addr.i6[3] = 0;
9913 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9914 htonl(0xffffffff << (96 - bits));
9915 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9916 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9917 } else if (bits > 32) {
9918 key->hn_addr.adf_addr.i6[3] = 0;
9919 key->hn_addr.adf_addr.i6[2] = 0;
9920 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9921 htonl(0xffffffff << (64 - bits));
9922 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9923 } else {
9924 key->hn_addr.adf_addr.i6[3] = 0;
9925 key->hn_addr.adf_addr.i6[2] = 0;
9926 key->hn_addr.adf_addr.i6[1] = 0;
9927 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9928 htonl(0xffffffff << (32 - bits));
9929 }
9930#endif
9931 }
9932}
9933
9934
9935/* ------------------------------------------------------------------------ */
9936/* Function: ipf_ht_node_add */
9937/* Returns: int - 0 == success, -1 == failure */
9938/* Parameters: softc(I) - pointer to soft context main structure */
9939/* htp(I) - pointer to address tracking structure */
9940/* family(I) - protocol family of address */
9941/* addr(I) - pointer to network address */
9942/* */
9943/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9944/* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9945/* */
9946/* After preparing the key with the address information to find, look in */
9947/* the red-black tree to see if the address is known. A successful call to */
9948/* this function can mean one of two things: a new node was added to the */
9949/* tree or a matching node exists and we're able to bump up its activity. */
9950/* ------------------------------------------------------------------------ */
9951int
9952ipf_ht_node_add(softc, htp, family, addr)
9953 ipf_main_softc_t *softc;
9954 host_track_t *htp;
9955 int family;
9956 i6addr_t *addr;
9957{
9958 host_node_t *h;
9959 host_node_t k;
9960
9961 ipf_ht_node_make_key(htp, &k, family, addr);
9962
9963 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9964 if (h == NULL) {
9965 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9966 return -1;
9967 KMALLOC(h, host_node_t *);
9968 if (h == NULL) {
9969 DT(ipf_rb_no_mem);
9970 LBUMP(ipf_rb_no_mem);
9971 return -1;
9972 }
9973
9974 /*
9975 * If there was a macro to initialise the RB node then that
9976 * would get used here, but there isn't...
9977 */
9978 bzero((char *)h, sizeof(*h));
9979 h->hn_addr = k.hn_addr;
9980 h->hn_addr.adf_family = k.hn_addr.adf_family;
9981 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9982 htp->ht_cur_nodes++;
9983 } else {
9984 if ((htp->ht_max_per_node != 0) &&
9985 (h->hn_active >= htp->ht_max_per_node)) {
9986 DT(ipf_rb_node_max);
9987 LBUMP(ipf_rb_node_max);
9988 return -1;
9989 }
9990 }
9991
9992 h->hn_active++;
9993
9994 return 0;
9995}
9996
9997
9998/* ------------------------------------------------------------------------ */
9999/* Function: ipf_ht_node_del */
10000/* Returns: int - 0 == success, -1 == failure */
10001/* parameters: htp(I) - pointer to address tracking structure */
10002/* family(I) - protocol family of address */
10003/* addr(I) - pointer to network address */
10004/* */
10005/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
10006/* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
10007/* */
10008/* Try and find the address passed in amongst the leavese on this tree to */
10009/* be friend. If found then drop the active account for that node drops by */
10010/* one. If that count reaches 0, it is time to free it all up. */
10011/* ------------------------------------------------------------------------ */
10012int
10013ipf_ht_node_del(htp, family, addr)
10014 host_track_t *htp;
10015 int family;
10016 i6addr_t *addr;
10017{
10018 host_node_t *h;
10019 host_node_t k;
10020
10021 ipf_ht_node_make_key(htp, &k, family, addr);
10022
10023 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
10024 if (h == NULL) {
10025 return -1;
10026 } else {
10027 h->hn_active--;
10028 if (h->hn_active == 0) {
10029 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10030 htp->ht_cur_nodes--;
10031 KFREE(h);
10032 }
10033 }
10034
10035 return 0;
10036}
10037
10038
10039/* ------------------------------------------------------------------------ */
10040/* Function: ipf_rb_ht_init */
10041/* Returns: Nil */
10042/* Parameters: head(I) - pointer to host tracking structure */
10043/* */
10044/* Initialise the host tracking structure to be ready for use above. */
10045/* ------------------------------------------------------------------------ */
10046void
10047ipf_rb_ht_init(head)
10048 host_track_t *head;
10049{
10050 RBI_INIT(ipf_rb, &head->ht_root);
10051}
10052
10053
10054/* ------------------------------------------------------------------------ */
10055/* Function: ipf_rb_ht_freenode */
10056/* Returns: Nil */
10057/* Parameters: head(I) - pointer to host tracking structure */
10058/* arg(I) - additional argument from walk caller */
10059/* */
10060/* Free an actual host_node_t structure. */
10061/* ------------------------------------------------------------------------ */
10062void
10063ipf_rb_ht_freenode(node, arg)
10064 host_node_t *node;
10065 void *arg;
10066{
10067 KFREE(node);
10068}
10069
10070
10071/* ------------------------------------------------------------------------ */
10072/* Function: ipf_rb_ht_flush */
10073/* Returns: Nil */
10074/* Parameters: head(I) - pointer to host tracking structure */
10075/* */
10076/* Remove all of the nodes in the tree tracking hosts by calling a walker */
10077/* and free'ing each one. */
10078/* ------------------------------------------------------------------------ */
10079void
10080ipf_rb_ht_flush(head)
10081 host_track_t *head;
10082{
10083 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10084}
10085
10086
10087/* ------------------------------------------------------------------------ */
10088/* Function: ipf_slowtimer */
10089/* Returns: Nil */
10090/* Parameters: ptr(I) - pointer to main ipf soft context structure */
10091/* */
10092/* Slowly expire held state for fragments. Timeouts are set * in */
10093/* expectation of this being called twice per second. */
10094/* ------------------------------------------------------------------------ */
10095void
10096ipf_slowtimer(softc)
10097 ipf_main_softc_t *softc;
10098{
10099
10100 ipf_token_expire(softc);
10101 ipf_frag_expire(softc);
10102 ipf_state_expire(softc);
10103 ipf_nat_expire(softc);
10104 ipf_auth_expire(softc);
10105 ipf_lookup_expire(softc);
10106 ipf_rule_expire(softc);
10107 ipf_sync_expire(softc);
10108 softc->ipf_ticks++;
10109}
10110
10111
10112/* ------------------------------------------------------------------------ */
10113/* Function: ipf_inet_mask_add */
10114/* Returns: Nil */
10115/* Parameters: bits(I) - pointer to nat context information */
10116/* mtab(I) - pointer to mask hash table structure */
10117/* */
10118/* When called, bits represents the mask of a new NAT rule that has just */
10119/* been added. This function inserts a bitmask into the array of masks to */
10120/* search when searching for a matching NAT rule for a packet. */
10121/* Prevention of duplicate masks is achieved by checking the use count for */
10122/* a given netmask. */
10123/* ------------------------------------------------------------------------ */
10124void
10125ipf_inet_mask_add(bits, mtab)
10126 int bits;
10127 ipf_v4_masktab_t *mtab;
10128{
10129 u_32_t mask;
10130 int i, j;
10131
10132 mtab->imt4_masks[bits]++;
10133 if (mtab->imt4_masks[bits] > 1)
10134 return;
10135
10136 if (bits == 0)
10137 mask = 0;
10138 else
10139 mask = 0xffffffff << (32 - bits);
10140
10141 for (i = 0; i < 33; i++) {
10142 if (ntohl(mtab->imt4_active[i]) < mask) {
10143 for (j = 32; j > i; j--)
10144 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10145 mtab->imt4_active[i] = htonl(mask);
10146 break;
10147 }
10148 }
10149 mtab->imt4_max++;
10150}
10151
10152
10153/* ------------------------------------------------------------------------ */
10154/* Function: ipf_inet_mask_del */
10155/* Returns: Nil */
10156/* Parameters: bits(I) - number of bits set in the netmask */
10157/* mtab(I) - pointer to mask hash table structure */
10158/* */
10159/* Remove the 32bit bitmask represented by "bits" from the collection of */
10160/* netmasks stored inside of mtab. */
10161/* ------------------------------------------------------------------------ */
10162void
10163ipf_inet_mask_del(bits, mtab)
10164 int bits;
10165 ipf_v4_masktab_t *mtab;
10166{
10167 u_32_t mask;
10168 int i, j;
10169
10170 mtab->imt4_masks[bits]--;
10171 if (mtab->imt4_masks[bits] > 0)
10172 return;
10173
10174 mask = htonl(0xffffffff << (32 - bits));
10175 for (i = 0; i < 33; i++) {
10176 if (mtab->imt4_active[i] == mask) {
10177 for (j = i + 1; j < 33; j++)
10178 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10179 break;
10180 }
10181 }
10182 mtab->imt4_max--;
10183 ASSERT(mtab->imt4_max >= 0);
10184}
10185
10186
10187#ifdef USE_INET6
10188/* ------------------------------------------------------------------------ */
10189/* Function: ipf_inet6_mask_add */
10190/* Returns: Nil */
10191/* Parameters: bits(I) - number of bits set in mask */
10192/* mask(I) - pointer to mask to add */
10193/* mtab(I) - pointer to mask hash table structure */
10194/* */
10195/* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10196/* has just been added. This function inserts a bitmask into the array of */
10197/* masks to search when searching for a matching NAT rule for a packet. */
10198/* Prevention of duplicate masks is achieved by checking the use count for */
10199/* a given netmask. */
10200/* ------------------------------------------------------------------------ */
10201void
10202ipf_inet6_mask_add(bits, mask, mtab)
10203 int bits;
10204 i6addr_t *mask;
10205 ipf_v6_masktab_t *mtab;
10206{
10207 i6addr_t zero;
10208 int i, j;
10209
10210 mtab->imt6_masks[bits]++;
10211 if (mtab->imt6_masks[bits] > 1)
10212 return;
10213
10214 if (bits == 0) {
10215 mask = &zero;
10216 zero.i6[0] = 0;
10217 zero.i6[1] = 0;
10218 zero.i6[2] = 0;
10219 zero.i6[3] = 0;
10220 }
10221
10222 for (i = 0; i < 129; i++) {
10223 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10224 for (j = 128; j > i; j--)
10225 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10226 mtab->imt6_active[i] = *mask;
10227 break;
10228 }
10229 }
10230 mtab->imt6_max++;
10231}
10232
10233
10234/* ------------------------------------------------------------------------ */
10235/* Function: ipf_inet6_mask_del */
10236/* Returns: Nil */
10237/* Parameters: bits(I) - number of bits set in mask */
10238/* mask(I) - pointer to mask to remove */
10239/* mtab(I) - pointer to mask hash table structure */
10240/* */
10241/* Remove the 128bit bitmask represented by "bits" from the collection of */
10242/* netmasks stored inside of mtab. */
10243/* ------------------------------------------------------------------------ */
10244void
10245ipf_inet6_mask_del(bits, mask, mtab)
10246 int bits;
10247 i6addr_t *mask;
10248 ipf_v6_masktab_t *mtab;
10249{
10250 i6addr_t zero;
10251 int i, j;
10252
10253 mtab->imt6_masks[bits]--;
10254 if (mtab->imt6_masks[bits] > 0)
10255 return;
10256
10257 if (bits == 0)
10258 mask = &zero;
10259 zero.i6[0] = 0;
10260 zero.i6[1] = 0;
10261 zero.i6[2] = 0;
10262 zero.i6[3] = 0;
10263
10264 for (i = 0; i < 129; i++) {
10265 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10266 for (j = i + 1; j < 129; j++) {
10267 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10268 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10269 break;
10270 }
10271 break;
10272 }
10273 }
10274 mtab->imt6_max--;
10275 ASSERT(mtab->imt6_max >= 0);
10276}
10277#endif
1702 off = ntohs(ip->ip_off);
1703
1704 /* Get both TTL and protocol */
1705 fi->fi_p = ip->ip_p;
1706 fi->fi_ttl = ip->ip_ttl;
1707
1708 /* Zero out bits not used in IPv6 address */
1709 fi->fi_src.i6[1] = 0;
1710 fi->fi_src.i6[2] = 0;
1711 fi->fi_src.i6[3] = 0;
1712 fi->fi_dst.i6[1] = 0;
1713 fi->fi_dst.i6[2] = 0;
1714 fi->fi_dst.i6[3] = 0;
1715
1716 fi->fi_saddr = ip->ip_src.s_addr;
1717 fin->fin_crc += fi->fi_saddr;
1718 fi->fi_daddr = ip->ip_dst.s_addr;
1719 fin->fin_crc += fi->fi_daddr;
1720 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1721 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1722
1723 /*
1724 * set packet attribute flags based on the offset and
1725 * calculate the byte offset that it represents.
1726 */
1727 off &= IP_MF|IP_OFFMASK;
1728 if (off != 0) {
1729 int morefrag = off & IP_MF;
1730
1731 fi->fi_flx |= FI_FRAG;
1732 off &= IP_OFFMASK;
1733 if (off == 1 && p == IPPROTO_TCP) {
1734 fin->fin_flx |= FI_SHORT; /* RFC 3128 */
1735 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1736 }
1737 if (off != 0) {
1738 fin->fin_flx |= FI_FRAGBODY;
1739 off <<= 3;
1740 if ((off + fin->fin_dlen > 65535) ||
1741 (fin->fin_dlen == 0) ||
1742 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1743 /*
1744 * The length of the packet, starting at its
1745 * offset cannot exceed 65535 (0xffff) as the
1746 * length of an IP packet is only 16 bits.
1747 *
1748 * Any fragment that isn't the last fragment
1749 * must have a length greater than 0 and it
1750 * must be an even multiple of 8.
1751 */
1752 fi->fi_flx |= FI_BAD;
1753 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1754 }
1755 }
1756 }
1757 fin->fin_off = off;
1758
1759 /*
1760 * Call per-protocol setup and checking
1761 */
1762 if (p == IPPROTO_AH) {
1763 /*
1764 * Treat AH differently because we expect there to be another
1765 * layer 4 header after it.
1766 */
1767 p = ipf_pr_ah(fin);
1768 }
1769
1770 switch (p)
1771 {
1772 case IPPROTO_UDP :
1773 ipf_pr_udp(fin);
1774 break;
1775 case IPPROTO_TCP :
1776 ipf_pr_tcp(fin);
1777 break;
1778 case IPPROTO_ICMP :
1779 ipf_pr_icmp(fin);
1780 break;
1781 case IPPROTO_ESP :
1782 ipf_pr_esp(fin);
1783 break;
1784 case IPPROTO_GRE :
1785 ipf_pr_gre(fin);
1786 break;
1787 }
1788
1789 ip = fin->fin_ip;
1790 if (ip == NULL)
1791 return;
1792
1793 /*
1794 * If it is a standard IP header (no options), set the flag fields
1795 * which relate to options to 0.
1796 */
1797 if (hlen == sizeof(*ip)) {
1798 fi->fi_optmsk = 0;
1799 fi->fi_secmsk = 0;
1800 fi->fi_auth = 0;
1801 return;
1802 }
1803
1804 /*
1805 * So the IP header has some IP options attached. Walk the entire
1806 * list of options present with this packet and set flags to indicate
1807 * which ones are here and which ones are not. For the somewhat out
1808 * of date and obscure security classification options, set a flag to
1809 * represent which classification is present.
1810 */
1811 fi->fi_flx |= FI_OPTIONS;
1812
1813 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1814 opt = *s;
1815 if (opt == '\0')
1816 break;
1817 else if (opt == IPOPT_NOP)
1818 ol = 1;
1819 else {
1820 if (hlen < 2)
1821 break;
1822 ol = (int)*(s + 1);
1823 if (ol < 2 || ol > hlen)
1824 break;
1825 }
1826 for (i = 9, mv = 4; mv >= 0; ) {
1827 op = ipopts + i;
1828
1829 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1830 u_32_t doi;
1831
1832 switch (opt)
1833 {
1834 case IPOPT_SECURITY :
1835 if (optmsk & op->ol_bit) {
1836 fin->fin_flx |= FI_BAD;
1837 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1838 } else {
1839 doi = ipf_checkripso(s);
1840 secmsk = doi >> 16;
1841 auth = doi & 0xffff;
1842 }
1843 break;
1844
1845 case IPOPT_CIPSO :
1846
1847 if (optmsk & op->ol_bit) {
1848 fin->fin_flx |= FI_BAD;
1849 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1850 } else {
1851 doi = ipf_checkcipso(fin,
1852 s, ol);
1853 secmsk = doi >> 16;
1854 auth = doi & 0xffff;
1855 }
1856 break;
1857 }
1858 optmsk |= op->ol_bit;
1859 }
1860
1861 if (opt < op->ol_val)
1862 i -= mv;
1863 else
1864 i += mv;
1865 mv--;
1866 }
1867 hlen -= ol;
1868 s += ol;
1869 }
1870
1871 /*
1872 *
1873 */
1874 if (auth && !(auth & 0x0100))
1875 auth &= 0xff00;
1876 fi->fi_optmsk = optmsk;
1877 fi->fi_secmsk = secmsk;
1878 fi->fi_auth = auth;
1879}
1880
1881
1882/* ------------------------------------------------------------------------ */
1883/* Function: ipf_checkripso */
1884/* Returns: void */
1885/* Parameters: s(I) - pointer to start of RIPSO option */
1886/* */
1887/* ------------------------------------------------------------------------ */
1888static u_32_t
1889ipf_checkripso(s)
1890 u_char *s;
1891{
1892 const struct optlist *sp;
1893 u_short secmsk = 0, auth = 0;
1894 u_char sec;
1895 int j, m;
1896
1897 sec = *(s + 2); /* classification */
1898 for (j = 3, m = 2; m >= 0; ) {
1899 sp = secopt + j;
1900 if (sec == sp->ol_val) {
1901 secmsk |= sp->ol_bit;
1902 auth = *(s + 3);
1903 auth *= 256;
1904 auth += *(s + 4);
1905 break;
1906 }
1907 if (sec < sp->ol_val)
1908 j -= m;
1909 else
1910 j += m;
1911 m--;
1912 }
1913
1914 return (secmsk << 16) | auth;
1915}
1916
1917
1918/* ------------------------------------------------------------------------ */
1919/* Function: ipf_checkcipso */
1920/* Returns: u_32_t - 0 = failure, else the doi from the header */
1921/* Parameters: fin(IO) - pointer to packet information */
1922/* s(I) - pointer to start of CIPSO option */
1923/* ol(I) - length of CIPSO option field */
1924/* */
1925/* This function returns the domain of integrity (DOI) field from the CIPSO */
1926/* header and returns that whilst also storing the highest sensitivity */
1927/* value found in the fr_info_t structure. */
1928/* */
1929/* No attempt is made to extract the category bitmaps as these are defined */
1930/* by the user (rather than the protocol) and can be rather numerous on the */
1931/* end nodes. */
1932/* ------------------------------------------------------------------------ */
1933static u_32_t
1934ipf_checkcipso(fin, s, ol)
1935 fr_info_t *fin;
1936 u_char *s;
1937 int ol;
1938{
1939 ipf_main_softc_t *softc = fin->fin_main_soft;
1940 fr_ip_t *fi;
1941 u_32_t doi;
1942 u_char *t, tag, tlen, sensitivity;
1943 int len;
1944
1945 if (ol < 6 || ol > 40) {
1946 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1947 fin->fin_flx |= FI_BAD;
1948 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1949 return 0;
1950 }
1951
1952 fi = &fin->fin_fi;
1953 fi->fi_sensitivity = 0;
1954 /*
1955 * The DOI field MUST be there.
1956 */
1957 bcopy(s + 2, &doi, sizeof(doi));
1958
1959 t = (u_char *)s + 6;
1960 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1961 tag = *t;
1962 tlen = *(t + 1);
1963 if (tlen > len || tlen < 4 || tlen > 34) {
1964 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1965 fin->fin_flx |= FI_BAD;
1966 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1967 return 0;
1968 }
1969
1970 sensitivity = 0;
1971 /*
1972 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1973 * draft (16 July 1992) that has expired.
1974 */
1975 if (tag == 0) {
1976 fin->fin_flx |= FI_BAD;
1977 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1978 continue;
1979 } else if (tag == 1) {
1980 if (*(t + 2) != 0) {
1981 fin->fin_flx |= FI_BAD;
1982 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1983 continue;
1984 }
1985 sensitivity = *(t + 3);
1986 /* Category bitmap for categories 0-239 */
1987
1988 } else if (tag == 4) {
1989 if (*(t + 2) != 0) {
1990 fin->fin_flx |= FI_BAD;
1991 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1992 continue;
1993 }
1994 sensitivity = *(t + 3);
1995 /* Enumerated categories, 16bits each, upto 15 */
1996
1997 } else if (tag == 5) {
1998 if (*(t + 2) != 0) {
1999 fin->fin_flx |= FI_BAD;
2000 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
2001 continue;
2002 }
2003 sensitivity = *(t + 3);
2004 /* Range of categories (2*16bits), up to 7 pairs */
2005
2006 } else if (tag > 127) {
2007 /* Custom defined DOI */
2008 ;
2009 } else {
2010 fin->fin_flx |= FI_BAD;
2011 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2012 continue;
2013 }
2014
2015 if (sensitivity > fi->fi_sensitivity)
2016 fi->fi_sensitivity = sensitivity;
2017 }
2018
2019 return doi;
2020}
2021
2022
2023/* ------------------------------------------------------------------------ */
2024/* Function: ipf_makefrip */
2025/* Returns: int - 0 == packet ok, -1 == packet freed */
2026/* Parameters: hlen(I) - length of IP packet header */
2027/* ip(I) - pointer to the IP header */
2028/* fin(IO) - pointer to packet information */
2029/* */
2030/* Compact the IP header into a structure which contains just the info. */
2031/* which is useful for comparing IP headers with and store this information */
2032/* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2033/* this function will be called with either an IPv4 or IPv6 packet. */
2034/* ------------------------------------------------------------------------ */
2035int
2036ipf_makefrip(hlen, ip, fin)
2037 int hlen;
2038 ip_t *ip;
2039 fr_info_t *fin;
2040{
2041 ipf_main_softc_t *softc = fin->fin_main_soft;
2042 int v;
2043
2044 fin->fin_depth = 0;
2045 fin->fin_hlen = (u_short)hlen;
2046 fin->fin_ip = ip;
2047 fin->fin_rule = 0xffffffff;
2048 fin->fin_group[0] = -1;
2049 fin->fin_group[1] = '\0';
2050 fin->fin_dp = (char *)ip + hlen;
2051
2052 v = fin->fin_v;
2053 if (v == 4) {
2054 fin->fin_plen = ntohs(ip->ip_len);
2055 fin->fin_dlen = fin->fin_plen - hlen;
2056 ipf_pr_ipv4hdr(fin);
2057#ifdef USE_INET6
2058 } else if (v == 6) {
2059 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2060 fin->fin_dlen = fin->fin_plen;
2061 fin->fin_plen += hlen;
2062
2063 ipf_pr_ipv6hdr(fin);
2064#endif
2065 }
2066 if (fin->fin_ip == NULL) {
2067 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2068 return -1;
2069 }
2070 return 0;
2071}
2072
2073
2074/* ------------------------------------------------------------------------ */
2075/* Function: ipf_portcheck */
2076/* Returns: int - 1 == port matched, 0 == port match failed */
2077/* Parameters: frp(I) - pointer to port check `expression' */
2078/* pop(I) - port number to evaluate */
2079/* */
2080/* Perform a comparison of a port number against some other(s), using a */
2081/* structure with compare information stored in it. */
2082/* ------------------------------------------------------------------------ */
2083static INLINE int
2084ipf_portcheck(frp, pop)
2085 frpcmp_t *frp;
2086 u_32_t pop;
2087{
2088 int err = 1;
2089 u_32_t po;
2090
2091 po = frp->frp_port;
2092
2093 /*
2094 * Do opposite test to that required and continue if that succeeds.
2095 */
2096 switch (frp->frp_cmp)
2097 {
2098 case FR_EQUAL :
2099 if (pop != po) /* EQUAL */
2100 err = 0;
2101 break;
2102 case FR_NEQUAL :
2103 if (pop == po) /* NOTEQUAL */
2104 err = 0;
2105 break;
2106 case FR_LESST :
2107 if (pop >= po) /* LESSTHAN */
2108 err = 0;
2109 break;
2110 case FR_GREATERT :
2111 if (pop <= po) /* GREATERTHAN */
2112 err = 0;
2113 break;
2114 case FR_LESSTE :
2115 if (pop > po) /* LT or EQ */
2116 err = 0;
2117 break;
2118 case FR_GREATERTE :
2119 if (pop < po) /* GT or EQ */
2120 err = 0;
2121 break;
2122 case FR_OUTRANGE :
2123 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2124 err = 0;
2125 break;
2126 case FR_INRANGE :
2127 if (pop <= po || pop >= frp->frp_top) /* In range */
2128 err = 0;
2129 break;
2130 case FR_INCRANGE :
2131 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2132 err = 0;
2133 break;
2134 default :
2135 break;
2136 }
2137 return err;
2138}
2139
2140
2141/* ------------------------------------------------------------------------ */
2142/* Function: ipf_tcpudpchk */
2143/* Returns: int - 1 == protocol matched, 0 == check failed */
2144/* Parameters: fda(I) - pointer to packet information */
2145/* ft(I) - pointer to structure with comparison data */
2146/* */
2147/* Compares the current pcket (assuming it is TCP/UDP) information with a */
2148/* structure containing information that we want to match against. */
2149/* ------------------------------------------------------------------------ */
2150int
2151ipf_tcpudpchk(fi, ft)
2152 fr_ip_t *fi;
2153 frtuc_t *ft;
2154{
2155 int err = 1;
2156
2157 /*
2158 * Both ports should *always* be in the first fragment.
2159 * So far, I cannot find any cases where they can not be.
2160 *
2161 * compare destination ports
2162 */
2163 if (ft->ftu_dcmp)
2164 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2165
2166 /*
2167 * compare source ports
2168 */
2169 if (err && ft->ftu_scmp)
2170 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2171
2172 /*
2173 * If we don't have all the TCP/UDP header, then how can we
2174 * expect to do any sort of match on it ? If we were looking for
2175 * TCP flags, then NO match. If not, then match (which should
2176 * satisfy the "short" class too).
2177 */
2178 if (err && (fi->fi_p == IPPROTO_TCP)) {
2179 if (fi->fi_flx & FI_SHORT)
2180 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2181 /*
2182 * Match the flags ? If not, abort this match.
2183 */
2184 if (ft->ftu_tcpfm &&
2185 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2186 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2187 ft->ftu_tcpfm, ft->ftu_tcpf));
2188 err = 0;
2189 }
2190 }
2191 return err;
2192}
2193
2194
2195/* ------------------------------------------------------------------------ */
2196/* Function: ipf_check_ipf */
2197/* Returns: int - 0 == match, else no match */
2198/* Parameters: fin(I) - pointer to packet information */
2199/* fr(I) - pointer to filter rule */
2200/* portcmp(I) - flag indicating whether to attempt matching on */
2201/* TCP/UDP port data. */
2202/* */
2203/* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2204/* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2205/* this function. */
2206/* ------------------------------------------------------------------------ */
2207static INLINE int
2208ipf_check_ipf(fin, fr, portcmp)
2209 fr_info_t *fin;
2210 frentry_t *fr;
2211 int portcmp;
2212{
2213 u_32_t *ld, *lm, *lip;
2214 fripf_t *fri;
2215 fr_ip_t *fi;
2216 int i;
2217
2218 fi = &fin->fin_fi;
2219 fri = fr->fr_ipf;
2220 lip = (u_32_t *)fi;
2221 lm = (u_32_t *)&fri->fri_mip;
2222 ld = (u_32_t *)&fri->fri_ip;
2223
2224 /*
2225 * first 32 bits to check coversion:
2226 * IP version, TOS, TTL, protocol
2227 */
2228 i = ((*lip & *lm) != *ld);
2229 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2230 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2231 if (i)
2232 return 1;
2233
2234 /*
2235 * Next 32 bits is a constructed bitmask indicating which IP options
2236 * are present (if any) in this packet.
2237 */
2238 lip++, lm++, ld++;
2239 i = ((*lip & *lm) != *ld);
2240 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2241 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2242 if (i != 0)
2243 return 1;
2244
2245 lip++, lm++, ld++;
2246 /*
2247 * Unrolled loops (4 each, for 32 bits) for address checks.
2248 */
2249 /*
2250 * Check the source address.
2251 */
2252 if (fr->fr_satype == FRI_LOOKUP) {
2253 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2254 fi->fi_v, lip, fin->fin_plen);
2255 if (i == -1)
2256 return 1;
2257 lip += 3;
2258 lm += 3;
2259 ld += 3;
2260 } else {
2261 i = ((*lip & *lm) != *ld);
2262 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2263 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2264 if (fi->fi_v == 6) {
2265 lip++, lm++, ld++;
2266 i |= ((*lip & *lm) != *ld);
2267 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2268 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2269 lip++, lm++, ld++;
2270 i |= ((*lip & *lm) != *ld);
2271 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2272 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2273 lip++, lm++, ld++;
2274 i |= ((*lip & *lm) != *ld);
2275 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2276 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2277 } else {
2278 lip += 3;
2279 lm += 3;
2280 ld += 3;
2281 }
2282 }
2283 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2284 if (i != 0)
2285 return 1;
2286
2287 /*
2288 * Check the destination address.
2289 */
2290 lip++, lm++, ld++;
2291 if (fr->fr_datype == FRI_LOOKUP) {
2292 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2293 fi->fi_v, lip, fin->fin_plen);
2294 if (i == -1)
2295 return 1;
2296 lip += 3;
2297 lm += 3;
2298 ld += 3;
2299 } else {
2300 i = ((*lip & *lm) != *ld);
2301 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2302 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2303 if (fi->fi_v == 6) {
2304 lip++, lm++, ld++;
2305 i |= ((*lip & *lm) != *ld);
2306 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2307 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2308 lip++, lm++, ld++;
2309 i |= ((*lip & *lm) != *ld);
2310 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2311 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2312 lip++, lm++, ld++;
2313 i |= ((*lip & *lm) != *ld);
2314 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2315 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2316 } else {
2317 lip += 3;
2318 lm += 3;
2319 ld += 3;
2320 }
2321 }
2322 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2323 if (i != 0)
2324 return 1;
2325 /*
2326 * IP addresses matched. The next 32bits contains:
2327 * mast of old IP header security & authentication bits.
2328 */
2329 lip++, lm++, ld++;
2330 i = (*ld - (*lip & *lm));
2331 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2332
2333 /*
2334 * Next we have 32 bits of packet flags.
2335 */
2336 lip++, lm++, ld++;
2337 i |= (*ld - (*lip & *lm));
2338 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2339
2340 if (i == 0) {
2341 /*
2342 * If a fragment, then only the first has what we're
2343 * looking for here...
2344 */
2345 if (portcmp) {
2346 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2347 i = 1;
2348 } else {
2349 if (fr->fr_dcmp || fr->fr_scmp ||
2350 fr->fr_tcpf || fr->fr_tcpfm)
2351 i = 1;
2352 if (fr->fr_icmpm || fr->fr_icmp) {
2353 if (((fi->fi_p != IPPROTO_ICMP) &&
2354 (fi->fi_p != IPPROTO_ICMPV6)) ||
2355 fin->fin_off || (fin->fin_dlen < 2))
2356 i = 1;
2357 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2358 fr->fr_icmp) {
2359 FR_DEBUG(("i. %#x & %#x != %#x\n",
2360 fin->fin_data[0],
2361 fr->fr_icmpm, fr->fr_icmp));
2362 i = 1;
2363 }
2364 }
2365 }
2366 }
2367 return i;
2368}
2369
2370
2371/* ------------------------------------------------------------------------ */
2372/* Function: ipf_scanlist */
2373/* Returns: int - result flags of scanning filter list */
2374/* Parameters: fin(I) - pointer to packet information */
2375/* pass(I) - default result to return for filtering */
2376/* */
2377/* Check the input/output list of rules for a match to the current packet. */
2378/* If a match is found, the value of fr_flags from the rule becomes the */
2379/* return value and fin->fin_fr points to the matched rule. */
2380/* */
2381/* This function may be called recusively upto 16 times (limit inbuilt.) */
2382/* When unwinding, it should finish up with fin_depth as 0. */
2383/* */
2384/* Could be per interface, but this gets real nasty when you don't have, */
2385/* or can't easily change, the kernel source code to . */
2386/* ------------------------------------------------------------------------ */
2387int
2388ipf_scanlist(fin, pass)
2389 fr_info_t *fin;
2390 u_32_t pass;
2391{
2392 ipf_main_softc_t *softc = fin->fin_main_soft;
2393 int rulen, portcmp, off, skip;
2394 struct frentry *fr, *fnext;
2395 u_32_t passt, passo;
2396
2397 /*
2398 * Do not allow nesting deeper than 16 levels.
2399 */
2400 if (fin->fin_depth >= 16)
2401 return pass;
2402
2403 fr = fin->fin_fr;
2404
2405 /*
2406 * If there are no rules in this list, return now.
2407 */
2408 if (fr == NULL)
2409 return pass;
2410
2411 skip = 0;
2412 portcmp = 0;
2413 fin->fin_depth++;
2414 fin->fin_fr = NULL;
2415 off = fin->fin_off;
2416
2417 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2418 portcmp = 1;
2419
2420 for (rulen = 0; fr; fr = fnext, rulen++) {
2421 fnext = fr->fr_next;
2422 if (skip != 0) {
2423 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2424 skip--;
2425 continue;
2426 }
2427
2428 /*
2429 * In all checks below, a null (zero) value in the
2430 * filter struture is taken to mean a wildcard.
2431 *
2432 * check that we are working for the right interface
2433 */
2434#ifdef _KERNEL
2435 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2436 continue;
2437#else
2438 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2439 printf("\n");
2440 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2441 FR_ISPASS(pass) ? 'p' :
2442 FR_ISACCOUNT(pass) ? 'A' :
2443 FR_ISAUTH(pass) ? 'a' :
2444 (pass & FR_NOMATCH) ? 'n' :'b'));
2445 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2446 continue;
2447 FR_VERBOSE((":i"));
2448#endif
2449
2450 switch (fr->fr_type)
2451 {
2452 case FR_T_IPF :
2453 case FR_T_IPF_BUILTIN :
2454 if (ipf_check_ipf(fin, fr, portcmp))
2455 continue;
2456 break;
2457#if defined(IPFILTER_BPF)
2458 case FR_T_BPFOPC :
2459 case FR_T_BPFOPC_BUILTIN :
2460 {
2461 u_char *mc;
2462 int wlen;
2463
2464 if (*fin->fin_mp == NULL)
2465 continue;
2466 if (fin->fin_family != fr->fr_family)
2467 continue;
2468 mc = (u_char *)fin->fin_m;
2469 wlen = fin->fin_dlen + fin->fin_hlen;
2470 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2471 continue;
2472 break;
2473 }
2474#endif
2475 case FR_T_CALLFUNC_BUILTIN :
2476 {
2477 frentry_t *f;
2478
2479 f = (*fr->fr_func)(fin, &pass);
2480 if (f != NULL)
2481 fr = f;
2482 else
2483 continue;
2484 break;
2485 }
2486
2487 case FR_T_IPFEXPR :
2488 case FR_T_IPFEXPR_BUILTIN :
2489 if (fin->fin_family != fr->fr_family)
2490 continue;
2491 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2492 continue;
2493 break;
2494
2495 default :
2496 break;
2497 }
2498
2499 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2500 if (fin->fin_nattag == NULL)
2501 continue;
2502 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2503 continue;
2504 }
2505 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2506
2507 passt = fr->fr_flags;
2508
2509 /*
2510 * If the rule is a "call now" rule, then call the function
2511 * in the rule, if it exists and use the results from that.
2512 * If the function pointer is bad, just make like we ignore
2513 * it, except for increasing the hit counter.
2514 */
2515 if ((passt & FR_CALLNOW) != 0) {
2516 frentry_t *frs;
2517
2518 ATOMIC_INC64(fr->fr_hits);
2519 if ((fr->fr_func == NULL) ||
2520 (fr->fr_func == (ipfunc_t)-1))
2521 continue;
2522
2523 frs = fin->fin_fr;
2524 fin->fin_fr = fr;
2525 fr = (*fr->fr_func)(fin, &passt);
2526 if (fr == NULL) {
2527 fin->fin_fr = frs;
2528 continue;
2529 }
2530 passt = fr->fr_flags;
2531 }
2532 fin->fin_fr = fr;
2533
2534#ifdef IPFILTER_LOG
2535 /*
2536 * Just log this packet...
2537 */
2538 if ((passt & FR_LOGMASK) == FR_LOG) {
2539 if (ipf_log_pkt(fin, passt) == -1) {
2540 if (passt & FR_LOGORBLOCK) {
2541 DT(frb_logfail);
2542 passt &= ~FR_CMDMASK;
2543 passt |= FR_BLOCK|FR_QUICK;
2544 fin->fin_reason = FRB_LOGFAIL;
2545 }
2546 }
2547 }
2548#endif /* IPFILTER_LOG */
2549
2550 MUTEX_ENTER(&fr->fr_lock);
2551 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2552 fr->fr_hits++;
2553 MUTEX_EXIT(&fr->fr_lock);
2554 fin->fin_rule = rulen;
2555
2556 passo = pass;
2557 if (FR_ISSKIP(passt)) {
2558 skip = fr->fr_arg;
2559 continue;
2560 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2561 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2562 pass = passt;
2563 }
2564
2565 if (passt & (FR_RETICMP|FR_FAKEICMP))
2566 fin->fin_icode = fr->fr_icode;
2567
2568 if (fr->fr_group != -1) {
2569 (void) strncpy(fin->fin_group,
2570 FR_NAME(fr, fr_group),
2571 strlen(FR_NAME(fr, fr_group)));
2572 } else {
2573 fin->fin_group[0] = '\0';
2574 }
2575
2576 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2577
2578 if (fr->fr_grphead != NULL) {
2579 fin->fin_fr = fr->fr_grphead->fg_start;
2580 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2581
2582 if (FR_ISDECAPS(passt))
2583 passt = ipf_decaps(fin, pass, fr->fr_icode);
2584 else
2585 passt = ipf_scanlist(fin, pass);
2586
2587 if (fin->fin_fr == NULL) {
2588 fin->fin_rule = rulen;
2589 if (fr->fr_group != -1)
2590 (void) strncpy(fin->fin_group,
2591 fr->fr_names +
2592 fr->fr_group,
2593 strlen(fr->fr_names +
2594 fr->fr_group));
2595 fin->fin_fr = fr;
2596 passt = pass;
2597 }
2598 pass = passt;
2599 }
2600
2601 if (pass & FR_QUICK) {
2602 /*
2603 * Finally, if we've asked to track state for this
2604 * packet, set it up. Add state for "quick" rules
2605 * here so that if the action fails we can consider
2606 * the rule to "not match" and keep on processing
2607 * filter rules.
2608 */
2609 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2610 !(fin->fin_flx & FI_STATE)) {
2611 int out = fin->fin_out;
2612
2613 fin->fin_fr = fr;
2614 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2615 LBUMPD(ipf_stats[out], fr_ads);
2616 } else {
2617 LBUMPD(ipf_stats[out], fr_bads);
2618 pass = passo;
2619 continue;
2620 }
2621 }
2622 break;
2623 }
2624 }
2625 fin->fin_depth--;
2626 return pass;
2627}
2628
2629
2630/* ------------------------------------------------------------------------ */
2631/* Function: ipf_acctpkt */
2632/* Returns: frentry_t* - always returns NULL */
2633/* Parameters: fin(I) - pointer to packet information */
2634/* passp(IO) - pointer to current/new filter decision (unused) */
2635/* */
2636/* Checks a packet against accounting rules, if there are any for the given */
2637/* IP protocol version. */
2638/* */
2639/* N.B.: this function returns NULL to match the prototype used by other */
2640/* functions called from the IPFilter "mainline" in ipf_check(). */
2641/* ------------------------------------------------------------------------ */
2642frentry_t *
2643ipf_acctpkt(fin, passp)
2644 fr_info_t *fin;
2645 u_32_t *passp;
2646{
2647 ipf_main_softc_t *softc = fin->fin_main_soft;
2648 char group[FR_GROUPLEN];
2649 frentry_t *fr, *frsave;
2650 u_32_t pass, rulen;
2651
2652 passp = passp;
2653 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2654
2655 if (fr != NULL) {
2656 frsave = fin->fin_fr;
2657 bcopy(fin->fin_group, group, FR_GROUPLEN);
2658 rulen = fin->fin_rule;
2659 fin->fin_fr = fr;
2660 pass = ipf_scanlist(fin, FR_NOMATCH);
2661 if (FR_ISACCOUNT(pass)) {
2662 LBUMPD(ipf_stats[0], fr_acct);
2663 }
2664 fin->fin_fr = frsave;
2665 bcopy(group, fin->fin_group, FR_GROUPLEN);
2666 fin->fin_rule = rulen;
2667 }
2668 return NULL;
2669}
2670
2671
2672/* ------------------------------------------------------------------------ */
2673/* Function: ipf_firewall */
2674/* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2675/* were found, returns NULL. */
2676/* Parameters: fin(I) - pointer to packet information */
2677/* passp(IO) - pointer to current/new filter decision (unused) */
2678/* */
2679/* Applies an appropriate set of firewall rules to the packet, to see if */
2680/* there are any matches. The first check is to see if a match can be seen */
2681/* in the cache. If not, then search an appropriate list of rules. Once a */
2682/* matching rule is found, take any appropriate actions as defined by the */
2683/* rule - except logging. */
2684/* ------------------------------------------------------------------------ */
2685static frentry_t *
2686ipf_firewall(fin, passp)
2687 fr_info_t *fin;
2688 u_32_t *passp;
2689{
2690 ipf_main_softc_t *softc = fin->fin_main_soft;
2691 frentry_t *fr;
2692 u_32_t pass;
2693 int out;
2694
2695 out = fin->fin_out;
2696 pass = *passp;
2697
2698 /*
2699 * This rule cache will only affect packets that are not being
2700 * statefully filtered.
2701 */
2702 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2703 if (fin->fin_fr != NULL)
2704 pass = ipf_scanlist(fin, softc->ipf_pass);
2705
2706 if ((pass & FR_NOMATCH)) {
2707 LBUMPD(ipf_stats[out], fr_nom);
2708 }
2709 fr = fin->fin_fr;
2710
2711 /*
2712 * Apply packets per second rate-limiting to a rule as required.
2713 */
2714 if ((fr != NULL) && (fr->fr_pps != 0) &&
2715 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2716 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2717 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2718 pass |= FR_BLOCK;
2719 LBUMPD(ipf_stats[out], fr_ppshit);
2720 fin->fin_reason = FRB_PPSRATE;
2721 }
2722
2723 /*
2724 * If we fail to add a packet to the authorization queue, then we
2725 * drop the packet later. However, if it was added then pretend
2726 * we've dropped it already.
2727 */
2728 if (FR_ISAUTH(pass)) {
2729 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2730 DT1(frb_authnew, fr_info_t *, fin);
2731 fin->fin_m = *fin->fin_mp = NULL;
2732 fin->fin_reason = FRB_AUTHNEW;
2733 fin->fin_error = 0;
2734 } else {
2735 IPFERROR(1);
2736 fin->fin_error = ENOSPC;
2737 }
2738 }
2739
2740 if ((fr != NULL) && (fr->fr_func != NULL) &&
2741 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2742 (void) (*fr->fr_func)(fin, &pass);
2743
2744 /*
2745 * If a rule is a pre-auth rule, check again in the list of rules
2746 * loaded for authenticated use. It does not particulary matter
2747 * if this search fails because a "preauth" result, from a rule,
2748 * is treated as "not a pass", hence the packet is blocked.
2749 */
2750 if (FR_ISPREAUTH(pass)) {
2751 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2752 }
2753
2754 /*
2755 * If the rule has "keep frag" and the packet is actually a fragment,
2756 * then create a fragment state entry.
2757 */
2758 if (pass & FR_KEEPFRAG) {
2759 if (fin->fin_flx & FI_FRAG) {
2760 if (ipf_frag_new(softc, fin, pass) == -1) {
2761 LBUMP(ipf_stats[out].fr_bnfr);
2762 } else {
2763 LBUMP(ipf_stats[out].fr_nfr);
2764 }
2765 } else {
2766 LBUMP(ipf_stats[out].fr_cfr);
2767 }
2768 }
2769
2770 fr = fin->fin_fr;
2771 *passp = pass;
2772
2773 return fr;
2774}
2775
2776
2777/* ------------------------------------------------------------------------ */
2778/* Function: ipf_check */
2779/* Returns: int - 0 == packet allowed through, */
2780/* User space: */
2781/* -1 == packet blocked */
2782/* 1 == packet not matched */
2783/* -2 == requires authentication */
2784/* Kernel: */
2785/* > 0 == filter error # for packet */
2786/* Parameters: ctx(I) - pointer to the instance context */
2787/* ip(I) - pointer to start of IPv4/6 packet */
2788/* hlen(I) - length of header */
2789/* ifp(I) - pointer to interface this packet is on */
2790/* out(I) - 0 == packet going in, 1 == packet going out */
2791/* mp(IO) - pointer to caller's buffer pointer that holds this */
2792/* IP packet. */
2793/* Solaris: */
2794/* qpi(I) - pointer to STREAMS queue information for this */
2795/* interface & direction. */
2796/* */
2797/* ipf_check() is the master function for all IPFilter packet processing. */
2798/* It orchestrates: Network Address Translation (NAT), checking for packet */
2799/* authorisation (or pre-authorisation), presence of related state info., */
2800/* generating log entries, IP packet accounting, routing of packets as */
2801/* directed by firewall rules and of course whether or not to allow the */
2802/* packet to be further processed by the kernel. */
2803/* */
2804/* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2805/* freed. Packets passed may be returned with the pointer pointed to by */
2806/* by "mp" changed to a new buffer. */
2807/* ------------------------------------------------------------------------ */
2808int
2809ipf_check(ctx, ip, hlen, ifp, out
2810#if defined(_KERNEL) && defined(MENTAT)
2811 , qif, mp)
2812 void *qif;
2813#else
2814 , mp)
2815#endif
2816 mb_t **mp;
2817 ip_t *ip;
2818 int hlen;
2819 struct ifnet *ifp;
2820 int out;
2821 void *ctx;
2822{
2823 /*
2824 * The above really sucks, but short of writing a diff
2825 */
2826 ipf_main_softc_t *softc = ctx;
2827 fr_info_t frinfo;
2828 fr_info_t *fin = &frinfo;
2829 u_32_t pass = softc->ipf_pass;
2830 frentry_t *fr = NULL;
2831 int v = IP_V(ip);
2832 mb_t *mc = NULL;
2833 mb_t *m;
2834 /*
2835 * The first part of ipf_check() deals with making sure that what goes
2836 * into the filtering engine makes some sense. Information about the
2837 * the packet is distilled, collected into a fr_info_t structure and
2838 * the an attempt to ensure the buffer the packet is in is big enough
2839 * to hold all the required packet headers.
2840 */
2841#ifdef _KERNEL
2842# ifdef MENTAT
2843 qpktinfo_t *qpi = qif;
2844
2845# ifdef __sparc
2846 if ((u_int)ip & 0x3)
2847 return 2;
2848# endif
2849# else
2850 SPL_INT(s);
2851# endif
2852
2853 if (softc->ipf_running <= 0) {
2854 return 0;
2855 }
2856
2857 bzero((char *)fin, sizeof(*fin));
2858
2859# ifdef MENTAT
2860 if (qpi->qpi_flags & QF_BROADCAST)
2861 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2862 if (qpi->qpi_flags & QF_MULTICAST)
2863 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2864 m = qpi->qpi_m;
2865 fin->fin_qfm = m;
2866 fin->fin_qpi = qpi;
2867# else /* MENTAT */
2868
2869 m = *mp;
2870
2871# if defined(M_MCAST)
2872 if ((m->m_flags & M_MCAST) != 0)
2873 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2874# endif
2875# if defined(M_MLOOP)
2876 if ((m->m_flags & M_MLOOP) != 0)
2877 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2878# endif
2879# if defined(M_BCAST)
2880 if ((m->m_flags & M_BCAST) != 0)
2881 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2882# endif
2883# ifdef M_CANFASTFWD
2884 /*
2885 * XXX For now, IP Filter and fast-forwarding of cached flows
2886 * XXX are mutually exclusive. Eventually, IP Filter should
2887 * XXX get a "can-fast-forward" filter rule.
2888 */
2889 m->m_flags &= ~M_CANFASTFWD;
2890# endif /* M_CANFASTFWD */
2891# if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2892 /*
2893 * disable delayed checksums.
2894 */
2895 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2896 in_delayed_cksum(m);
2897 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2898 }
2899# endif /* CSUM_DELAY_DATA */
2900# endif /* MENTAT */
2901#else
2902 bzero((char *)fin, sizeof(*fin));
2903 m = *mp;
2904# if defined(M_MCAST)
2905 if ((m->m_flags & M_MCAST) != 0)
2906 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2907# endif
2908# if defined(M_MLOOP)
2909 if ((m->m_flags & M_MLOOP) != 0)
2910 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2911# endif
2912# if defined(M_BCAST)
2913 if ((m->m_flags & M_BCAST) != 0)
2914 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2915# endif
2916#endif /* _KERNEL */
2917
2918 fin->fin_v = v;
2919 fin->fin_m = m;
2920 fin->fin_ip = ip;
2921 fin->fin_mp = mp;
2922 fin->fin_out = out;
2923 fin->fin_ifp = ifp;
2924 fin->fin_error = ENETUNREACH;
2925 fin->fin_hlen = (u_short)hlen;
2926 fin->fin_dp = (char *)ip + hlen;
2927 fin->fin_main_soft = softc;
2928
2929 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2930
2931 SPL_NET(s);
2932
2933#ifdef USE_INET6
2934 if (v == 6) {
2935 LBUMP(ipf_stats[out].fr_ipv6);
2936 /*
2937 * Jumbo grams are quite likely too big for internal buffer
2938 * structures to handle comfortably, for now, so just drop
2939 * them.
2940 */
2941 if (((ip6_t *)ip)->ip6_plen == 0) {
2942 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2943 pass = FR_BLOCK|FR_NOMATCH;
2944 fin->fin_reason = FRB_JUMBO;
2945 goto finished;
2946 }
2947 fin->fin_family = AF_INET6;
2948 } else
2949#endif
2950 {
2951 fin->fin_family = AF_INET;
2952 }
2953
2954 if (ipf_makefrip(hlen, ip, fin) == -1) {
2955 DT1(frb_makefrip, fr_info_t *, fin);
2956 pass = FR_BLOCK|FR_NOMATCH;
2957 fin->fin_reason = FRB_MAKEFRIP;
2958 goto finished;
2959 }
2960
2961 /*
2962 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2963 * becomes NULL and so we have no packet to free.
2964 */
2965 if (*fin->fin_mp == NULL)
2966 goto finished;
2967
2968 if (!out) {
2969 if (v == 4) {
2970 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2971 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2972 fin->fin_flx |= FI_BADSRC;
2973 }
2974 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2975 LBUMPD(ipf_stats[0], fr_v4_badttl);
2976 fin->fin_flx |= FI_LOWTTL;
2977 }
2978 }
2979#ifdef USE_INET6
2980 else if (v == 6) {
2981 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2982 LBUMPD(ipf_stats[0], fr_v6_badttl);
2983 fin->fin_flx |= FI_LOWTTL;
2984 }
2985 }
2986#endif
2987 }
2988
2989 if (fin->fin_flx & FI_SHORT) {
2990 LBUMPD(ipf_stats[out], fr_short);
2991 }
2992
2993 READ_ENTER(&softc->ipf_mutex);
2994
2995 if (!out) {
2996 switch (fin->fin_v)
2997 {
2998 case 4 :
2999 if (ipf_nat_checkin(fin, &pass) == -1) {
3000 goto filterdone;
3001 }
3002 break;
3003#ifdef USE_INET6
3004 case 6 :
3005 if (ipf_nat6_checkin(fin, &pass) == -1) {
3006 goto filterdone;
3007 }
3008 break;
3009#endif
3010 default :
3011 break;
3012 }
3013 }
3014 /*
3015 * Check auth now.
3016 * If a packet is found in the auth table, then skip checking
3017 * the access lists for permission but we do need to consider
3018 * the result as if it were from the ACL's. In addition, being
3019 * found in the auth table means it has been seen before, so do
3020 * not pass it through accounting (again), lest it be counted twice.
3021 */
3022 fr = ipf_auth_check(fin, &pass);
3023 if (!out && (fr == NULL))
3024 (void) ipf_acctpkt(fin, NULL);
3025
3026 if (fr == NULL) {
3027 if ((fin->fin_flx & FI_FRAG) != 0)
3028 fr = ipf_frag_known(fin, &pass);
3029
3030 if (fr == NULL)
3031 fr = ipf_state_check(fin, &pass);
3032 }
3033
3034 if ((pass & FR_NOMATCH) || (fr == NULL))
3035 fr = ipf_firewall(fin, &pass);
3036
3037 /*
3038 * If we've asked to track state for this packet, set it up.
3039 * Here rather than ipf_firewall because ipf_checkauth may decide
3040 * to return a packet for "keep state"
3041 */
3042 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3043 !(fin->fin_flx & FI_STATE)) {
3044 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3045 LBUMP(ipf_stats[out].fr_ads);
3046 } else {
3047 LBUMP(ipf_stats[out].fr_bads);
3048 if (FR_ISPASS(pass)) {
3049 DT(frb_stateadd);
3050 pass &= ~FR_CMDMASK;
3051 pass |= FR_BLOCK;
3052 fin->fin_reason = FRB_STATEADD;
3053 }
3054 }
3055 }
3056
3057 fin->fin_fr = fr;
3058 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3059 fin->fin_dif = &fr->fr_dif;
3060 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3061 }
3062
3063 /*
3064 * Only count/translate packets which will be passed on, out the
3065 * interface.
3066 */
3067 if (out && FR_ISPASS(pass)) {
3068 (void) ipf_acctpkt(fin, NULL);
3069
3070 switch (fin->fin_v)
3071 {
3072 case 4 :
3073 if (ipf_nat_checkout(fin, &pass) == -1) {
3074 ;
3075 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3076 if (ipf_updateipid(fin) == -1) {
3077 DT(frb_updateipid);
3078 LBUMP(ipf_stats[1].fr_ipud);
3079 pass &= ~FR_CMDMASK;
3080 pass |= FR_BLOCK;
3081 fin->fin_reason = FRB_UPDATEIPID;
3082 } else {
3083 LBUMP(ipf_stats[0].fr_ipud);
3084 }
3085 }
3086 break;
3087#ifdef USE_INET6
3088 case 6 :
3089 (void) ipf_nat6_checkout(fin, &pass);
3090 break;
3091#endif
3092 default :
3093 break;
3094 }
3095 }
3096
3097filterdone:
3098#ifdef IPFILTER_LOG
3099 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3100 (void) ipf_dolog(fin, &pass);
3101 }
3102#endif
3103
3104 /*
3105 * The FI_STATE flag is cleared here so that calling ipf_state_check
3106 * will work when called from inside of fr_fastroute. Although
3107 * there is a similar flag, FI_NATED, for NAT, it does have the same
3108 * impact on code execution.
3109 */
3110 fin->fin_flx &= ~FI_STATE;
3111
3112#if defined(FASTROUTE_RECURSION)
3113 /*
3114 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3115 * a packet below can sometimes cause a recursive call into IPFilter.
3116 * On those platforms where that does happen, we need to hang onto
3117 * the filter rule just in case someone decides to remove or flush it
3118 * in the meantime.
3119 */
3120 if (fr != NULL) {
3121 MUTEX_ENTER(&fr->fr_lock);
3122 fr->fr_ref++;
3123 MUTEX_EXIT(&fr->fr_lock);
3124 }
3125
3126 RWLOCK_EXIT(&softc->ipf_mutex);
3127#endif
3128
3129 if ((pass & FR_RETMASK) != 0) {
3130 /*
3131 * Should we return an ICMP packet to indicate error
3132 * status passing through the packet filter ?
3133 * WARNING: ICMP error packets AND TCP RST packets should
3134 * ONLY be sent in repsonse to incoming packets. Sending
3135 * them in response to outbound packets can result in a
3136 * panic on some operating systems.
3137 */
3138 if (!out) {
3139 if (pass & FR_RETICMP) {
3140 int dst;
3141
3142 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3143 dst = 1;
3144 else
3145 dst = 0;
3146 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3147 dst);
3148 LBUMP(ipf_stats[0].fr_ret);
3149 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3150 !(fin->fin_flx & FI_SHORT)) {
3151 if (((fin->fin_flx & FI_OOW) != 0) ||
3152 (ipf_send_reset(fin) == 0)) {
3153 LBUMP(ipf_stats[1].fr_ret);
3154 }
3155 }
3156
3157 /*
3158 * When using return-* with auth rules, the auth code
3159 * takes over disposing of this packet.
3160 */
3161 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3162 DT1(frb_authcapture, fr_info_t *, fin);
3163 fin->fin_m = *fin->fin_mp = NULL;
3164 fin->fin_reason = FRB_AUTHCAPTURE;
3165 m = NULL;
3166 }
3167 } else {
3168 if (pass & FR_RETRST) {
3169 fin->fin_error = ECONNRESET;
3170 }
3171 }
3172 }
3173
3174 /*
3175 * After the above so that ICMP unreachables and TCP RSTs get
3176 * created properly.
3177 */
3178 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3179 ipf_nat_uncreate(fin);
3180
3181 /*
3182 * If we didn't drop off the bottom of the list of rules (and thus
3183 * the 'current' rule fr is not NULL), then we may have some extra
3184 * instructions about what to do with a packet.
3185 * Once we're finished return to our caller, freeing the packet if
3186 * we are dropping it.
3187 */
3188 if (fr != NULL) {
3189 frdest_t *fdp;
3190
3191 /*
3192 * Generate a duplicated packet first because ipf_fastroute
3193 * can lead to fin_m being free'd... not good.
3194 */
3195 fdp = fin->fin_dif;
3196 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3197 (fdp->fd_ptr != (void *)-1)) {
3198 mc = M_COPY(fin->fin_m);
3199 if (mc != NULL)
3200 ipf_fastroute(mc, &mc, fin, fdp);
3201 }
3202
3203 fdp = fin->fin_tif;
3204 if (!out && (pass & FR_FASTROUTE)) {
3205 /*
3206 * For fastroute rule, no destination interface defined
3207 * so pass NULL as the frdest_t parameter
3208 */
3209 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3210 m = *mp = NULL;
3211 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3212 (fdp->fd_ptr != (struct ifnet *)-1)) {
3213 /* this is for to rules: */
3214 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3215 m = *mp = NULL;
3216 }
3217
3218#if defined(FASTROUTE_RECURSION)
3219 (void) ipf_derefrule(softc, &fr);
3220#endif
3221 }
3222#if !defined(FASTROUTE_RECURSION)
3223 RWLOCK_EXIT(&softc->ipf_mutex);
3224#endif
3225
3226finished:
3227 if (!FR_ISPASS(pass)) {
3228 LBUMP(ipf_stats[out].fr_block);
3229 if (*mp != NULL) {
3230#ifdef _KERNEL
3231 FREE_MB_T(*mp);
3232#endif
3233 m = *mp = NULL;
3234 }
3235 } else {
3236 LBUMP(ipf_stats[out].fr_pass);
3237 }
3238
3239 SPL_X(s);
3240
3241#ifdef _KERNEL
3242 if (FR_ISPASS(pass))
3243 return 0;
3244 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3245 return fin->fin_error;
3246#else /* _KERNEL */
3247 if (*mp != NULL)
3248 (*mp)->mb_ifp = fin->fin_ifp;
3249 blockreason = fin->fin_reason;
3250 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3251 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3252 if ((pass & FR_NOMATCH) != 0)
3253 return 1;
3254
3255 if ((pass & FR_RETMASK) != 0)
3256 switch (pass & FR_RETMASK)
3257 {
3258 case FR_RETRST :
3259 return 3;
3260 case FR_RETICMP :
3261 return 4;
3262 case FR_FAKEICMP :
3263 return 5;
3264 }
3265
3266 switch (pass & FR_CMDMASK)
3267 {
3268 case FR_PASS :
3269 return 0;
3270 case FR_BLOCK :
3271 return -1;
3272 case FR_AUTH :
3273 return -2;
3274 case FR_ACCOUNT :
3275 return -3;
3276 case FR_PREAUTH :
3277 return -4;
3278 }
3279 return 2;
3280#endif /* _KERNEL */
3281}
3282
3283
3284#ifdef IPFILTER_LOG
3285/* ------------------------------------------------------------------------ */
3286/* Function: ipf_dolog */
3287/* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3288/* Parameters: fin(I) - pointer to packet information */
3289/* passp(IO) - pointer to current/new filter decision (unused) */
3290/* */
3291/* Checks flags set to see how a packet should be logged, if it is to be */
3292/* logged. Adjust statistics based on its success or not. */
3293/* ------------------------------------------------------------------------ */
3294frentry_t *
3295ipf_dolog(fin, passp)
3296 fr_info_t *fin;
3297 u_32_t *passp;
3298{
3299 ipf_main_softc_t *softc = fin->fin_main_soft;
3300 u_32_t pass;
3301 int out;
3302
3303 out = fin->fin_out;
3304 pass = *passp;
3305
3306 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3307 pass |= FF_LOGNOMATCH;
3308 LBUMPD(ipf_stats[out], fr_npkl);
3309 goto logit;
3310
3311 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3312 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3313 if ((pass & FR_LOGMASK) != FR_LOGP)
3314 pass |= FF_LOGPASS;
3315 LBUMPD(ipf_stats[out], fr_ppkl);
3316 goto logit;
3317
3318 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3319 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3320 if ((pass & FR_LOGMASK) != FR_LOGB)
3321 pass |= FF_LOGBLOCK;
3322 LBUMPD(ipf_stats[out], fr_bpkl);
3323
3324logit:
3325 if (ipf_log_pkt(fin, pass) == -1) {
3326 /*
3327 * If the "or-block" option has been used then
3328 * block the packet if we failed to log it.
3329 */
3330 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3331 DT1(frb_logfail2, u_int, pass);
3332 pass &= ~FR_CMDMASK;
3333 pass |= FR_BLOCK;
3334 fin->fin_reason = FRB_LOGFAIL2;
3335 }
3336 }
3337 *passp = pass;
3338 }
3339
3340 return fin->fin_fr;
3341}
3342#endif /* IPFILTER_LOG */
3343
3344
3345/* ------------------------------------------------------------------------ */
3346/* Function: ipf_cksum */
3347/* Returns: u_short - IP header checksum */
3348/* Parameters: addr(I) - pointer to start of buffer to checksum */
3349/* len(I) - length of buffer in bytes */
3350/* */
3351/* Calculate the two's complement 16 bit checksum of the buffer passed. */
3352/* */
3353/* N.B.: addr should be 16bit aligned. */
3354/* ------------------------------------------------------------------------ */
3355u_short
3356ipf_cksum(addr, len)
3357 u_short *addr;
3358 int len;
3359{
3360 u_32_t sum = 0;
3361
3362 for (sum = 0; len > 1; len -= 2)
3363 sum += *addr++;
3364
3365 /* mop up an odd byte, if necessary */
3366 if (len == 1)
3367 sum += *(u_char *)addr;
3368
3369 /*
3370 * add back carry outs from top 16 bits to low 16 bits
3371 */
3372 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3373 sum += (sum >> 16); /* add carry */
3374 return (u_short)(~sum);
3375}
3376
3377
3378/* ------------------------------------------------------------------------ */
3379/* Function: fr_cksum */
3380/* Returns: u_short - layer 4 checksum */
3381/* Parameters: fin(I) - pointer to packet information */
3382/* ip(I) - pointer to IP header */
3383/* l4proto(I) - protocol to caclulate checksum for */
3384/* l4hdr(I) - pointer to layer 4 header */
3385/* */
3386/* Calculates the TCP checksum for the packet held in "m", using the data */
3387/* in the IP header "ip" to seed it. */
3388/* */
3389/* NB: This function assumes we've pullup'd enough for all of the IP header */
3390/* and the TCP header. We also assume that data blocks aren't allocated in */
3391/* odd sizes. */
3392/* */
3393/* Expects ip_len and ip_off to be in network byte order when called. */
3394/* ------------------------------------------------------------------------ */
3395u_short
3396fr_cksum(fin, ip, l4proto, l4hdr)
3397 fr_info_t *fin;
3398 ip_t *ip;
3399 int l4proto;
3400 void *l4hdr;
3401{
3402 u_short *sp, slen, sumsave, *csump;
3403 u_int sum, sum2;
3404 int hlen;
3405 int off;
3406#ifdef USE_INET6
3407 ip6_t *ip6;
3408#endif
3409
3410 csump = NULL;
3411 sumsave = 0;
3412 sp = NULL;
3413 slen = 0;
3414 hlen = 0;
3415 sum = 0;
3416
3417 sum = htons((u_short)l4proto);
3418 /*
3419 * Add up IP Header portion
3420 */
3421#ifdef USE_INET6
3422 if (IP_V(ip) == 4) {
3423#endif
3424 hlen = IP_HL(ip) << 2;
3425 off = hlen;
3426 sp = (u_short *)&ip->ip_src;
3427 sum += *sp++; /* ip_src */
3428 sum += *sp++;
3429 sum += *sp++; /* ip_dst */
3430 sum += *sp++;
3431 slen = fin->fin_plen - off;
3432 sum += htons(slen);
3433#ifdef USE_INET6
3434 } else if (IP_V(ip) == 6) {
3435 mb_t *m;
3436
3437 m = fin->fin_m;
3438 ip6 = (ip6_t *)ip;
3439 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3440 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3441 return(ipf_pcksum6(m, ip6, off, len));
3442 } else {
3443 return 0xffff;
3444 }
3445#endif
3446
3447 switch (l4proto)
3448 {
3449 case IPPROTO_UDP :
3450 csump = &((udphdr_t *)l4hdr)->uh_sum;
3451 break;
3452
3453 case IPPROTO_TCP :
3454 csump = &((tcphdr_t *)l4hdr)->th_sum;
3455 break;
3456 case IPPROTO_ICMP :
3457 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3458 sum = 0; /* Pseudo-checksum is not included */
3459 break;
3460#ifdef USE_INET6
3461 case IPPROTO_ICMPV6 :
3462 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3463 break;
3464#endif
3465 default :
3466 break;
3467 }
3468
3469 if (csump != NULL) {
3470 sumsave = *csump;
3471 *csump = 0;
3472 }
3473
3474 sum2 = ipf_pcksum(fin, off, sum);
3475 if (csump != NULL)
3476 *csump = sumsave;
3477 return sum2;
3478}
3479
3480
3481/* ------------------------------------------------------------------------ */
3482/* Function: ipf_findgroup */
3483/* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3484/* Parameters: softc(I) - pointer to soft context main structure */
3485/* group(I) - group name to search for */
3486/* unit(I) - device to which this group belongs */
3487/* set(I) - which set of rules (inactive/inactive) this is */
3488/* fgpp(O) - pointer to place to store pointer to the pointer */
3489/* to where to add the next (last) group or where */
3490/* to delete group from. */
3491/* */
3492/* Search amongst the defined groups for a particular group number. */
3493/* ------------------------------------------------------------------------ */
3494frgroup_t *
3495ipf_findgroup(softc, group, unit, set, fgpp)
3496 ipf_main_softc_t *softc;
3497 char *group;
3498 minor_t unit;
3499 int set;
3500 frgroup_t ***fgpp;
3501{
3502 frgroup_t *fg, **fgp;
3503
3504 /*
3505 * Which list of groups to search in is dependent on which list of
3506 * rules are being operated on.
3507 */
3508 fgp = &softc->ipf_groups[unit][set];
3509
3510 while ((fg = *fgp) != NULL) {
3511 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3512 break;
3513 else
3514 fgp = &fg->fg_next;
3515 }
3516 if (fgpp != NULL)
3517 *fgpp = fgp;
3518 return fg;
3519}
3520
3521
3522/* ------------------------------------------------------------------------ */
3523/* Function: ipf_group_add */
3524/* Returns: frgroup_t * - NULL == did not create group, */
3525/* != NULL == pointer to the group */
3526/* Parameters: softc(I) - pointer to soft context main structure */
3527/* num(I) - group number to add */
3528/* head(I) - rule pointer that is using this as the head */
3529/* flags(I) - rule flags which describe the type of rule it is */
3530/* unit(I) - device to which this group will belong to */
3531/* set(I) - which set of rules (inactive/inactive) this is */
3532/* Write Locks: ipf_mutex */
3533/* */
3534/* Add a new group head, or if it already exists, increase the reference */
3535/* count to it. */
3536/* ------------------------------------------------------------------------ */
3537frgroup_t *
3538ipf_group_add(softc, group, head, flags, unit, set)
3539 ipf_main_softc_t *softc;
3540 char *group;
3541 void *head;
3542 u_32_t flags;
3543 minor_t unit;
3544 int set;
3545{
3546 frgroup_t *fg, **fgp;
3547 u_32_t gflags;
3548
3549 if (group == NULL)
3550 return NULL;
3551
3552 if (unit == IPL_LOGIPF && *group == '\0')
3553 return NULL;
3554
3555 fgp = NULL;
3556 gflags = flags & FR_INOUT;
3557
3558 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3559 if (fg != NULL) {
3560 if (fg->fg_head == NULL && head != NULL)
3561 fg->fg_head = head;
3562 if (fg->fg_flags == 0)
3563 fg->fg_flags = gflags;
3564 else if (gflags != fg->fg_flags)
3565 return NULL;
3566 fg->fg_ref++;
3567 return fg;
3568 }
3569
3570 KMALLOC(fg, frgroup_t *);
3571 if (fg != NULL) {
3572 fg->fg_head = head;
3573 fg->fg_start = NULL;
3574 fg->fg_next = *fgp;
3575 bcopy(group, fg->fg_name, strlen(group) + 1);
3576 fg->fg_flags = gflags;
3577 fg->fg_ref = 1;
3578 fg->fg_set = &softc->ipf_groups[unit][set];
3579 *fgp = fg;
3580 }
3581 return fg;
3582}
3583
3584
3585/* ------------------------------------------------------------------------ */
3586/* Function: ipf_group_del */
3587/* Returns: int - number of rules deleted */
3588/* Parameters: softc(I) - pointer to soft context main structure */
3589/* group(I) - group name to delete */
3590/* fr(I) - filter rule from which group is referenced */
3591/* Write Locks: ipf_mutex */
3592/* */
3593/* This function is called whenever a reference to a group is to be dropped */
3594/* and thus its reference count needs to be lowered and the group free'd if */
3595/* the reference count reaches zero. Passing in fr is really for the sole */
3596/* purpose of knowing when the head rule is being deleted. */
3597/* ------------------------------------------------------------------------ */
3598void
3599ipf_group_del(softc, group, fr)
3600 ipf_main_softc_t *softc;
3601 frgroup_t *group;
3602 frentry_t *fr;
3603{
3604
3605 if (group->fg_head == fr)
3606 group->fg_head = NULL;
3607
3608 group->fg_ref--;
3609 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3610 ipf_group_free(group);
3611}
3612
3613
3614/* ------------------------------------------------------------------------ */
3615/* Function: ipf_group_free */
3616/* Returns: Nil */
3617/* Parameters: group(I) - pointer to filter rule group */
3618/* */
3619/* Remove the group from the list of groups and free it. */
3620/* ------------------------------------------------------------------------ */
3621static void
3622ipf_group_free(group)
3623 frgroup_t *group;
3624{
3625 frgroup_t **gp;
3626
3627 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3628 if (*gp == group) {
3629 *gp = group->fg_next;
3630 break;
3631 }
3632 }
3633 KFREE(group);
3634}
3635
3636
3637/* ------------------------------------------------------------------------ */
3638/* Function: ipf_group_flush */
3639/* Returns: int - number of rules flush from group */
3640/* Parameters: softc(I) - pointer to soft context main structure */
3641/* Parameters: group(I) - pointer to filter rule group */
3642/* */
3643/* Remove all of the rules that currently are listed under the given group. */
3644/* ------------------------------------------------------------------------ */
3645static int
3646ipf_group_flush(softc, group)
3647 ipf_main_softc_t *softc;
3648 frgroup_t *group;
3649{
3650 int gone = 0;
3651
3652 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3653
3654 return gone;
3655}
3656
3657
3658/* ------------------------------------------------------------------------ */
3659/* Function: ipf_getrulen */
3660/* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3661/* Parameters: softc(I) - pointer to soft context main structure */
3662/* Parameters: unit(I) - device for which to count the rule's number */
3663/* flags(I) - which set of rules to find the rule in */
3664/* group(I) - group name */
3665/* n(I) - rule number to find */
3666/* */
3667/* Find rule # n in group # g and return a pointer to it. Return NULl if */
3668/* group # g doesn't exist or there are less than n rules in the group. */
3669/* ------------------------------------------------------------------------ */
3670frentry_t *
3671ipf_getrulen(softc, unit, group, n)
3672 ipf_main_softc_t *softc;
3673 int unit;
3674 char *group;
3675 u_32_t n;
3676{
3677 frentry_t *fr;
3678 frgroup_t *fg;
3679
3680 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3681 if (fg == NULL)
3682 return NULL;
3683 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3684 ;
3685 if (n != 0)
3686 return NULL;
3687 return fr;
3688}
3689
3690
3691/* ------------------------------------------------------------------------ */
3692/* Function: ipf_flushlist */
3693/* Returns: int - >= 0 - number of flushed rules */
3694/* Parameters: softc(I) - pointer to soft context main structure */
3695/* nfreedp(O) - pointer to int where flush count is stored */
3696/* listp(I) - pointer to list to flush pointer */
3697/* Write Locks: ipf_mutex */
3698/* */
3699/* Recursively flush rules from the list, descending groups as they are */
3700/* encountered. if a rule is the head of a group and it has lost all its */
3701/* group members, then also delete the group reference. nfreedp is needed */
3702/* to store the accumulating count of rules removed, whereas the returned */
3703/* value is just the number removed from the current list. The latter is */
3704/* needed to correctly adjust reference counts on rules that define groups. */
3705/* */
3706/* NOTE: Rules not loaded from user space cannot be flushed. */
3707/* ------------------------------------------------------------------------ */
3708static int
3709ipf_flushlist(softc, nfreedp, listp)
3710 ipf_main_softc_t *softc;
3711 int *nfreedp;
3712 frentry_t **listp;
3713{
3714 int freed = 0;
3715 frentry_t *fp;
3716
3717 while ((fp = *listp) != NULL) {
3718 if ((fp->fr_type & FR_T_BUILTIN) ||
3719 !(fp->fr_flags & FR_COPIED)) {
3720 listp = &fp->fr_next;
3721 continue;
3722 }
3723 *listp = fp->fr_next;
3724 if (fp->fr_next != NULL)
3725 fp->fr_next->fr_pnext = fp->fr_pnext;
3726 fp->fr_pnext = NULL;
3727
3728 if (fp->fr_grphead != NULL) {
3729 freed += ipf_group_flush(softc, fp->fr_grphead);
3730 fp->fr_names[fp->fr_grhead] = '\0';
3731 }
3732
3733 if (fp->fr_icmpgrp != NULL) {
3734 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3735 fp->fr_names[fp->fr_icmphead] = '\0';
3736 }
3737
3738 if (fp->fr_srctrack.ht_max_nodes)
3739 ipf_rb_ht_flush(&fp->fr_srctrack);
3740
3741 fp->fr_next = NULL;
3742
3743 ASSERT(fp->fr_ref > 0);
3744 if (ipf_derefrule(softc, &fp) == 0)
3745 freed++;
3746 }
3747 *nfreedp += freed;
3748 return freed;
3749}
3750
3751
3752/* ------------------------------------------------------------------------ */
3753/* Function: ipf_flush */
3754/* Returns: int - >= 0 - number of flushed rules */
3755/* Parameters: softc(I) - pointer to soft context main structure */
3756/* unit(I) - device for which to flush rules */
3757/* flags(I) - which set of rules to flush */
3758/* */
3759/* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3760/* and IPv6) as defined by the value of flags. */
3761/* ------------------------------------------------------------------------ */
3762int
3763ipf_flush(softc, unit, flags)
3764 ipf_main_softc_t *softc;
3765 minor_t unit;
3766 int flags;
3767{
3768 int flushed = 0, set;
3769
3770 WRITE_ENTER(&softc->ipf_mutex);
3771
3772 set = softc->ipf_active;
3773 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3774 set = 1 - set;
3775
3776 if (flags & FR_OUTQUE) {
3777 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3778 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3779 }
3780 if (flags & FR_INQUE) {
3781 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3782 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3783 }
3784
3785 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3786 flags & (FR_INQUE|FR_OUTQUE));
3787
3788 RWLOCK_EXIT(&softc->ipf_mutex);
3789
3790 if (unit == IPL_LOGIPF) {
3791 int tmp;
3792
3793 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3794 if (tmp >= 0)
3795 flushed += tmp;
3796 }
3797 return flushed;
3798}
3799
3800
3801/* ------------------------------------------------------------------------ */
3802/* Function: ipf_flush_groups */
3803/* Returns: int - >= 0 - number of flushed rules */
3804/* Parameters: softc(I) - soft context pointerto work with */
3805/* grhead(I) - pointer to the start of the group list to flush */
3806/* flags(I) - which set of rules to flush */
3807/* */
3808/* Walk through all of the groups under the given group head and remove all */
3809/* of those that match the flags passed in. The for loop here is bit more */
3810/* complicated than usual because the removal of a rule with ipf_derefrule */
3811/* may end up removing not only the structure pointed to by "fg" but also */
3812/* what is fg_next and fg_next after that. So if a filter rule is actually */
3813/* removed from the group then it is necessary to start again. */
3814/* ------------------------------------------------------------------------ */
3815static int
3816ipf_flush_groups(softc, grhead, flags)
3817 ipf_main_softc_t *softc;
3818 frgroup_t **grhead;
3819 int flags;
3820{
3821 frentry_t *fr, **frp;
3822 frgroup_t *fg, **fgp;
3823 int flushed = 0;
3824 int removed = 0;
3825
3826 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3827 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3828 fg = fg->fg_next;
3829 if (fg == NULL)
3830 break;
3831 removed = 0;
3832 frp = &fg->fg_start;
3833 while ((removed == 0) && ((fr = *frp) != NULL)) {
3834 if ((fr->fr_flags & flags) == 0) {
3835 frp = &fr->fr_next;
3836 } else {
3837 if (fr->fr_next != NULL)
3838 fr->fr_next->fr_pnext = fr->fr_pnext;
3839 *frp = fr->fr_next;
3840 fr->fr_pnext = NULL;
3841 fr->fr_next = NULL;
3842 (void) ipf_derefrule(softc, &fr);
3843 flushed++;
3844 removed++;
3845 }
3846 }
3847 if (removed == 0)
3848 fgp = &fg->fg_next;
3849 }
3850 return flushed;
3851}
3852
3853
3854/* ------------------------------------------------------------------------ */
3855/* Function: memstr */
3856/* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3857/* Parameters: src(I) - pointer to byte sequence to match */
3858/* dst(I) - pointer to byte sequence to search */
3859/* slen(I) - match length */
3860/* dlen(I) - length available to search in */
3861/* */
3862/* Search dst for a sequence of bytes matching those at src and extend for */
3863/* slen bytes. */
3864/* ------------------------------------------------------------------------ */
3865char *
3866memstr(src, dst, slen, dlen)
3867 const char *src;
3868 char *dst;
3869 size_t slen, dlen;
3870{
3871 char *s = NULL;
3872
3873 while (dlen >= slen) {
3874 if (bcmp(src, dst, slen) == 0) {
3875 s = dst;
3876 break;
3877 }
3878 dst++;
3879 dlen--;
3880 }
3881 return s;
3882}
3883/* ------------------------------------------------------------------------ */
3884/* Function: ipf_fixskip */
3885/* Returns: Nil */
3886/* Parameters: listp(IO) - pointer to start of list with skip rule */
3887/* rp(I) - rule added/removed with skip in it. */
3888/* addremove(I) - adjustment (-1/+1) to make to skip count, */
3889/* depending on whether a rule was just added */
3890/* or removed. */
3891/* */
3892/* Adjust all the rules in a list which would have skip'd past the position */
3893/* where we are inserting to skip to the right place given the change. */
3894/* ------------------------------------------------------------------------ */
3895void
3896ipf_fixskip(listp, rp, addremove)
3897 frentry_t **listp, *rp;
3898 int addremove;
3899{
3900 int rules, rn;
3901 frentry_t *fp;
3902
3903 rules = 0;
3904 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3905 rules++;
3906
3907 if (fp == NULL)
3908 return;
3909
3910 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3911 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3912 fp->fr_arg += addremove;
3913}
3914
3915
3916#ifdef _KERNEL
3917/* ------------------------------------------------------------------------ */
3918/* Function: count4bits */
3919/* Returns: int - >= 0 - number of consecutive bits in input */
3920/* Parameters: ip(I) - 32bit IP address */
3921/* */
3922/* IPv4 ONLY */
3923/* count consecutive 1's in bit mask. If the mask generated by counting */
3924/* consecutive 1's is different to that passed, return -1, else return # */
3925/* of bits. */
3926/* ------------------------------------------------------------------------ */
3927int
3928count4bits(ip)
3929 u_32_t ip;
3930{
3931 u_32_t ipn;
3932 int cnt = 0, i, j;
3933
3934 ip = ipn = ntohl(ip);
3935 for (i = 32; i; i--, ipn *= 2)
3936 if (ipn & 0x80000000)
3937 cnt++;
3938 else
3939 break;
3940 ipn = 0;
3941 for (i = 32, j = cnt; i; i--, j--) {
3942 ipn *= 2;
3943 if (j > 0)
3944 ipn++;
3945 }
3946 if (ipn == ip)
3947 return cnt;
3948 return -1;
3949}
3950
3951
3952/* ------------------------------------------------------------------------ */
3953/* Function: count6bits */
3954/* Returns: int - >= 0 - number of consecutive bits in input */
3955/* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3956/* */
3957/* IPv6 ONLY */
3958/* count consecutive 1's in bit mask. */
3959/* ------------------------------------------------------------------------ */
3960# ifdef USE_INET6
3961int
3962count6bits(msk)
3963 u_32_t *msk;
3964{
3965 int i = 0, k;
3966 u_32_t j;
3967
3968 for (k = 3; k >= 0; k--)
3969 if (msk[k] == 0xffffffff)
3970 i += 32;
3971 else {
3972 for (j = msk[k]; j; j <<= 1)
3973 if (j & 0x80000000)
3974 i++;
3975 }
3976 return i;
3977}
3978# endif
3979#endif /* _KERNEL */
3980
3981
3982/* ------------------------------------------------------------------------ */
3983/* Function: ipf_synclist */
3984/* Returns: int - 0 = no failures, else indication of first failure */
3985/* Parameters: fr(I) - start of filter list to sync interface names for */
3986/* ifp(I) - interface pointer for limiting sync lookups */
3987/* Write Locks: ipf_mutex */
3988/* */
3989/* Walk through a list of filter rules and resolve any interface names into */
3990/* pointers. Where dynamic addresses are used, also update the IP address */
3991/* used in the rule. The interface pointer is used to limit the lookups to */
3992/* a specific set of matching names if it is non-NULL. */
3993/* Errors can occur when resolving the destination name of to/dup-to fields */
3994/* when the name points to a pool and that pool doest not exist. If this */
3995/* does happen then it is necessary to check if there are any lookup refs */
3996/* that need to be dropped before returning with an error. */
3997/* ------------------------------------------------------------------------ */
3998static int
3999ipf_synclist(softc, fr, ifp)
4000 ipf_main_softc_t *softc;
4001 frentry_t *fr;
4002 void *ifp;
4003{
4004 frentry_t *frt, *start = fr;
4005 frdest_t *fdp;
4006 char *name;
4007 int error;
4008 void *ifa;
4009 int v, i;
4010
4011 error = 0;
4012
4013 for (; fr; fr = fr->fr_next) {
4014 if (fr->fr_family == AF_INET)
4015 v = 4;
4016 else if (fr->fr_family == AF_INET6)
4017 v = 6;
4018 else
4019 v = 0;
4020
4021 /*
4022 * Lookup all the interface names that are part of the rule.
4023 */
4024 for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
4025 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4026 continue;
4027 if (fr->fr_ifnames[i] == -1)
4028 continue;
4029 name = FR_NAME(fr, fr_ifnames[i]);
4030 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4031 }
4032
4033 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4034 if (fr->fr_satype != FRI_NORMAL &&
4035 fr->fr_satype != FRI_LOOKUP) {
4036 ifa = ipf_resolvenic(softc, fr->fr_names +
4037 fr->fr_sifpidx, v);
4038 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4039 &fr->fr_src6, &fr->fr_smsk6);
4040 }
4041 if (fr->fr_datype != FRI_NORMAL &&
4042 fr->fr_datype != FRI_LOOKUP) {
4043 ifa = ipf_resolvenic(softc, fr->fr_names +
4044 fr->fr_sifpidx, v);
4045 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4046 &fr->fr_dst6, &fr->fr_dmsk6);
4047 }
4048 }
4049
4050 fdp = &fr->fr_tifs[0];
4051 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4052 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4053 if (error != 0)
4054 goto unwind;
4055 }
4056
4057 fdp = &fr->fr_tifs[1];
4058 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4059 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4060 if (error != 0)
4061 goto unwind;
4062 }
4063
4064 fdp = &fr->fr_dif;
4065 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4066 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4067 if (error != 0)
4068 goto unwind;
4069 }
4070
4071 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4072 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4073 fr->fr_srcptr = ipf_lookup_res_num(softc,
4074 fr->fr_srctype,
4075 IPL_LOGIPF,
4076 fr->fr_srcnum,
4077 &fr->fr_srcfunc);
4078 }
4079 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4080 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4081 fr->fr_dstptr = ipf_lookup_res_num(softc,
4082 fr->fr_dsttype,
4083 IPL_LOGIPF,
4084 fr->fr_dstnum,
4085 &fr->fr_dstfunc);
4086 }
4087 }
4088 return 0;
4089
4090unwind:
4091 for (frt = start; frt != fr; fr = fr->fr_next) {
4092 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4093 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4094 ipf_lookup_deref(softc, frt->fr_srctype,
4095 frt->fr_srcptr);
4096 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4097 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4098 ipf_lookup_deref(softc, frt->fr_dsttype,
4099 frt->fr_dstptr);
4100 }
4101 return error;
4102}
4103
4104
4105/* ------------------------------------------------------------------------ */
4106/* Function: ipf_sync */
4107/* Returns: void */
4108/* Parameters: Nil */
4109/* */
4110/* ipf_sync() is called when we suspect that the interface list or */
4111/* information about interfaces (like IP#) has changed. Go through all */
4112/* filter rules, NAT entries and the state table and check if anything */
4113/* needs to be changed/updated. */
4114/* ------------------------------------------------------------------------ */
4115int
4116ipf_sync(softc, ifp)
4117 ipf_main_softc_t *softc;
4118 void *ifp;
4119{
4120 int i;
4121
4122# if !SOLARIS
4123 ipf_nat_sync(softc, ifp);
4124 ipf_state_sync(softc, ifp);
4125 ipf_lookup_sync(softc, ifp);
4126# endif
4127
4128 WRITE_ENTER(&softc->ipf_mutex);
4129 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4130 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4131 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4132 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4133
4134 for (i = 0; i < IPL_LOGSIZE; i++) {
4135 frgroup_t *g;
4136
4137 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4138 (void) ipf_synclist(softc, g->fg_start, ifp);
4139 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4140 (void) ipf_synclist(softc, g->fg_start, ifp);
4141 }
4142 RWLOCK_EXIT(&softc->ipf_mutex);
4143
4144 return 0;
4145}
4146
4147
4148/*
4149 * In the functions below, bcopy() is called because the pointer being
4150 * copied _from_ in this instance is a pointer to a char buf (which could
4151 * end up being unaligned) and on the kernel's local stack.
4152 */
4153/* ------------------------------------------------------------------------ */
4154/* Function: copyinptr */
4155/* Returns: int - 0 = success, else failure */
4156/* Parameters: src(I) - pointer to the source address */
4157/* dst(I) - destination address */
4158/* size(I) - number of bytes to copy */
4159/* */
4160/* Copy a block of data in from user space, given a pointer to the pointer */
4161/* to start copying from (src) and a pointer to where to store it (dst). */
4162/* NB: src - pointer to user space pointer, dst - kernel space pointer */
4163/* ------------------------------------------------------------------------ */
4164int
4165copyinptr(softc, src, dst, size)
4166 ipf_main_softc_t *softc;
4167 void *src, *dst;
4168 size_t size;
4169{
4170 caddr_t ca;
4171 int error;
4172
4173# if SOLARIS
4174 error = COPYIN(src, &ca, sizeof(ca));
4175 if (error != 0)
4176 return error;
4177# else
4178 bcopy(src, (caddr_t)&ca, sizeof(ca));
4179# endif
4180 error = COPYIN(ca, dst, size);
4181 if (error != 0) {
4182 IPFERROR(3);
4183 error = EFAULT;
4184 }
4185 return error;
4186}
4187
4188
4189/* ------------------------------------------------------------------------ */
4190/* Function: copyoutptr */
4191/* Returns: int - 0 = success, else failure */
4192/* Parameters: src(I) - pointer to the source address */
4193/* dst(I) - destination address */
4194/* size(I) - number of bytes to copy */
4195/* */
4196/* Copy a block of data out to user space, given a pointer to the pointer */
4197/* to start copying from (src) and a pointer to where to store it (dst). */
4198/* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4199/* ------------------------------------------------------------------------ */
4200int
4201copyoutptr(softc, src, dst, size)
4202 ipf_main_softc_t *softc;
4203 void *src, *dst;
4204 size_t size;
4205{
4206 caddr_t ca;
4207 int error;
4208
4209 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4210 error = COPYOUT(src, ca, size);
4211 if (error != 0) {
4212 IPFERROR(4);
4213 error = EFAULT;
4214 }
4215 return error;
4216}
4217
4218
4219/* ------------------------------------------------------------------------ */
4220/* Function: ipf_lock */
4221/* Returns: int - 0 = success, else error */
4222/* Parameters: data(I) - pointer to lock value to set */
4223/* lockp(O) - pointer to location to store old lock value */
4224/* */
4225/* Get the new value for the lock integer, set it and return the old value */
4226/* in *lockp. */
4227/* ------------------------------------------------------------------------ */
4228int
4229ipf_lock(data, lockp)
4230 caddr_t data;
4231 int *lockp;
4232{
4233 int arg, err;
4234
4235 err = BCOPYIN(data, &arg, sizeof(arg));
4236 if (err != 0)
4237 return EFAULT;
4238 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4239 if (err != 0)
4240 return EFAULT;
4241 *lockp = arg;
4242 return 0;
4243}
4244
4245
4246/* ------------------------------------------------------------------------ */
4247/* Function: ipf_getstat */
4248/* Returns: Nil */
4249/* Parameters: softc(I) - pointer to soft context main structure */
4250/* fiop(I) - pointer to ipfilter stats structure */
4251/* rev(I) - version claim by program doing ioctl */
4252/* */
4253/* Stores a copy of current pointers, counters, etc, in the friostat */
4254/* structure. */
4255/* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4256/* program is looking for. This ensure that validation of the version it */
4257/* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4258/* allow older binaries to work but kernels without it will not. */
4259/* ------------------------------------------------------------------------ */
4260/*ARGSUSED*/
4261static void
4262ipf_getstat(softc, fiop, rev)
4263 ipf_main_softc_t *softc;
4264 friostat_t *fiop;
4265 int rev;
4266{
4267 int i;
4268
4269 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4270 sizeof(ipf_statistics_t) * 2);
4271 fiop->f_locks[IPL_LOGSTATE] = -1;
4272 fiop->f_locks[IPL_LOGNAT] = -1;
4273 fiop->f_locks[IPL_LOGIPF] = -1;
4274 fiop->f_locks[IPL_LOGAUTH] = -1;
4275
4276 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4277 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4278 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4279 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4280 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4281 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4282 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4283 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4284
4285 fiop->f_ticks = softc->ipf_ticks;
4286 fiop->f_active = softc->ipf_active;
4287 fiop->f_froute[0] = softc->ipf_frouteok[0];
4288 fiop->f_froute[1] = softc->ipf_frouteok[1];
4289 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4290 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4291
4292 fiop->f_running = softc->ipf_running;
4293 for (i = 0; i < IPL_LOGSIZE; i++) {
4294 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4295 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4296 }
4297#ifdef IPFILTER_LOG
4298 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4299 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4300 fiop->f_logging = 1;
4301#else
4302 fiop->f_log_ok = 0;
4303 fiop->f_log_fail = 0;
4304 fiop->f_logging = 0;
4305#endif
4306 fiop->f_defpass = softc->ipf_pass;
4307 fiop->f_features = ipf_features;
4308
4309#ifdef IPFILTER_COMPAT
4310 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4311 (rev / 1000000) % 100,
4312 (rev / 10000) % 100,
4313 (rev / 100) % 100);
4314#else
4315 rev = rev;
4316 (void) strncpy(fiop->f_version, ipfilter_version,
4317 sizeof(fiop->f_version));
4318#endif
4319}
4320
4321
4322#ifdef USE_INET6
4323int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4324 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4325 -1, /* 1: UNUSED */
4326 -1, /* 2: UNUSED */
4327 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4328 -1, /* 4: ICMP_SOURCEQUENCH */
4329 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4330 -1, /* 6: UNUSED */
4331 -1, /* 7: UNUSED */
4332 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4333 -1, /* 9: UNUSED */
4334 -1, /* 10: UNUSED */
4335 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4336 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4337 -1, /* 13: ICMP_TSTAMP */
4338 -1, /* 14: ICMP_TSTAMPREPLY */
4339 -1, /* 15: ICMP_IREQ */
4340 -1, /* 16: ICMP_IREQREPLY */
4341 -1, /* 17: ICMP_MASKREQ */
4342 -1, /* 18: ICMP_MASKREPLY */
4343};
4344
4345
4346int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4347 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4348 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4349 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4350 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4351 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4352 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4353 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4354 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4355 -1, /* 8: ICMP_UNREACH_ISOLATED */
4356 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4357 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4358 -1, /* 11: ICMP_UNREACH_TOSNET */
4359 -1, /* 12: ICMP_UNREACH_TOSHOST */
4360 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4361};
4362int icmpreplytype6[ICMP6_MAXTYPE + 1];
4363#endif
4364
4365int icmpreplytype4[ICMP_MAXTYPE + 1];
4366
4367
4368/* ------------------------------------------------------------------------ */
4369/* Function: ipf_matchicmpqueryreply */
4370/* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4371/* Parameters: v(I) - IP protocol version (4 or 6) */
4372/* ic(I) - ICMP information */
4373/* icmp(I) - ICMP packet header */
4374/* rev(I) - direction (0 = forward/1 = reverse) of packet */
4375/* */
4376/* Check if the ICMP packet defined by the header pointed to by icmp is a */
4377/* reply to one as described by what's in ic. If it is a match, return 1, */
4378/* else return 0 for no match. */
4379/* ------------------------------------------------------------------------ */
4380int
4381ipf_matchicmpqueryreply(v, ic, icmp, rev)
4382 int v;
4383 icmpinfo_t *ic;
4384 icmphdr_t *icmp;
4385 int rev;
4386{
4387 int ictype;
4388
4389 ictype = ic->ici_type;
4390
4391 if (v == 4) {
4392 /*
4393 * If we matched its type on the way in, then when going out
4394 * it will still be the same type.
4395 */
4396 if ((!rev && (icmp->icmp_type == ictype)) ||
4397 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4398 if (icmp->icmp_type != ICMP_ECHOREPLY)
4399 return 1;
4400 if (icmp->icmp_id == ic->ici_id)
4401 return 1;
4402 }
4403 }
4404#ifdef USE_INET6
4405 else if (v == 6) {
4406 if ((!rev && (icmp->icmp_type == ictype)) ||
4407 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4408 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4409 return 1;
4410 if (icmp->icmp_id == ic->ici_id)
4411 return 1;
4412 }
4413 }
4414#endif
4415 return 0;
4416}
4417
4418
4419/*
4420 * IFNAMES are located in the variable length field starting at
4421 * frentry.fr_names. As pointers within the struct cannot be passed
4422 * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4423 * is unused (invalid). If it is used (valid) it is an offset to the
4424 * character string of an interface name or a comment. The following
4425 * macros will assist those who follow to understand the code.
4426 */
4427#define IPF_IFNAME_VALID(_a) (_a != -1)
4428#define IPF_IFNAME_INVALID(_a) (_a == -1)
4429#define IPF_IFNAMES_DIFFERENT(_a) \
4430 !((IPF_IFNAME_INVALID(fr1->_a) && \
4431 IPF_IFNAME_INVALID(fr2->_a)) || \
4432 (IPF_IFNAME_VALID(fr1->_a) && \
4433 IPF_IFNAME_VALID(fr2->_a) && \
4434 !strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4435#define IPF_FRDEST_DIFFERENT(_a) \
4436 (memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr, \
4437 offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) || \
4438 IPF_IFNAMES_DIFFERENT(_a.fd_name))
4439
4440
4441/* ------------------------------------------------------------------------ */
4442/* Function: ipf_rule_compare */
4443/* Parameters: fr1(I) - first rule structure to compare */
4444/* fr2(I) - second rule structure to compare */
4445/* Returns: int - 0 == rules are the same, else mismatch */
4446/* */
4447/* Compare two rules and return 0 if they match or a number indicating */
4448/* which of the individual checks failed. */
4449/* ------------------------------------------------------------------------ */
4450static int
4451ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4452{
4453 int i;
4454
4455 if (fr1->fr_cksum != fr2->fr_cksum)
4456 return (1);
4457 if (fr1->fr_size != fr2->fr_size)
4458 return (2);
4459 if (fr1->fr_dsize != fr2->fr_dsize)
4460 return (3);
4461 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4462 != 0)
4463 return (4);
4464 /*
4465 * XXX: There is still a bug here as different rules with the
4466 * the same interfaces but in a different order will compare
4467 * differently. But since multiple interfaces in a rule doesn't
4468 * work anyway a simple straightforward compare is performed
4469 * here. Ultimately frentry_t creation will need to be
4470 * revisited in ipf_y.y. While the other issue, recognition
4471 * of only the first interface in a list of interfaces will
4472 * need to be separately addressed along with why only four.
4473 */
4474 for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4475 /*
4476 * XXX: It's either the same index or uninitialized.
4477 * We assume this because multiple interfaces
4478 * referenced by the same rule doesn't work anyway.
4479 */
4480 if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4481 return(5);
4482 }
4483
4484 if (IPF_FRDEST_DIFFERENT(fr_tif))
4485 return (6);
4486 if (IPF_FRDEST_DIFFERENT(fr_rif))
4487 return (7);
4488 if (IPF_FRDEST_DIFFERENT(fr_dif))
4489 return (8);
4490 if (!fr1->fr_data && !fr2->fr_data)
4491 return (0); /* move along, nothing to see here */
4492 if (fr1->fr_data && fr2->fr_data) {
4493 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4494 return (0); /* same */
4495 }
4496 return (9);
4497}
4498
4499
4500/* ------------------------------------------------------------------------ */
4501/* Function: frrequest */
4502/* Returns: int - 0 == success, > 0 == errno value */
4503/* Parameters: unit(I) - device for which this is for */
4504/* req(I) - ioctl command (SIOC*) */
4505/* data(I) - pointr to ioctl data */
4506/* set(I) - 1 or 0 (filter set) */
4507/* makecopy(I) - flag indicating whether data points to a rule */
4508/* in kernel space & hence doesn't need copying. */
4509/* */
4510/* This function handles all the requests which operate on the list of */
4511/* filter rules. This includes adding, deleting, insertion. It is also */
4512/* responsible for creating groups when a "head" rule is loaded. Interface */
4513/* names are resolved here and other sanity checks are made on the content */
4514/* of the rule structure being loaded. If a rule has user defined timeouts */
4515/* then make sure they are created and initialised before exiting. */
4516/* ------------------------------------------------------------------------ */
4517int
4518frrequest(softc, unit, req, data, set, makecopy)
4519 ipf_main_softc_t *softc;
4520 int unit;
4521 ioctlcmd_t req;
4522 int set, makecopy;
4523 caddr_t data;
4524{
4525 int error = 0, in, family, need_free = 0;
4526 enum { OP_ADD, /* add rule */
4527 OP_REM, /* remove rule */
4528 OP_ZERO /* zero statistics and counters */ }
4529 addrem = OP_ADD;
4530 frentry_t frd, *fp, *f, **fprev, **ftail;
4531 void *ptr, *uptr, *cptr;
4532 u_int *p, *pp;
4533 frgroup_t *fg;
4534 char *group;
4535
4536 ptr = NULL;
4537 cptr = NULL;
4538 fg = NULL;
4539 fp = &frd;
4540 if (makecopy != 0) {
4541 bzero(fp, sizeof(frd));
4542 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4543 if (error) {
4544 return error;
4545 }
4546 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4547 IPFERROR(6);
4548 return EINVAL;
4549 }
4550 KMALLOCS(f, frentry_t *, fp->fr_size);
4551 if (f == NULL) {
4552 IPFERROR(131);
4553 return ENOMEM;
4554 }
4555 bzero(f, fp->fr_size);
4556 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4557 fp->fr_size);
4558 if (error) {
4559 KFREES(f, fp->fr_size);
4560 return error;
4561 }
4562
4563 fp = f;
4564 f = NULL;
4565 fp->fr_next = NULL;
4566 fp->fr_dnext = NULL;
4567 fp->fr_pnext = NULL;
4568 fp->fr_pdnext = NULL;
4569 fp->fr_grp = NULL;
4570 fp->fr_grphead = NULL;
4571 fp->fr_icmpgrp = NULL;
4572 fp->fr_isc = (void *)-1;
4573 fp->fr_ptr = NULL;
4574 fp->fr_ref = 0;
4575 fp->fr_flags |= FR_COPIED;
4576 } else {
4577 fp = (frentry_t *)data;
4578 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4579 IPFERROR(7);
4580 return EINVAL;
4581 }
4582 fp->fr_flags &= ~FR_COPIED;
4583 }
4584
4585 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4586 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4587 IPFERROR(8);
4588 error = EINVAL;
4589 goto donenolock;
4590 }
4591
4592 family = fp->fr_family;
4593 uptr = fp->fr_data;
4594
4595 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4596 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4597 addrem = OP_ADD; /* Add rule */
4598 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4599 addrem = OP_REM; /* Remove rule */
4600 else if (req == (ioctlcmd_t)SIOCZRLST)
4601 addrem = OP_ZERO; /* Zero statistics and counters */
4602 else {
4603 IPFERROR(9);
4604 error = EINVAL;
4605 goto donenolock;
4606 }
4607
4608 /*
4609 * Only filter rules for IPv4 or IPv6 are accepted.
4610 */
4611 if (family == AF_INET) {
4612 /*EMPTY*/;
4613#ifdef USE_INET6
4614 } else if (family == AF_INET6) {
4615 /*EMPTY*/;
4616#endif
4617 } else if (family != 0) {
4618 IPFERROR(10);
4619 error = EINVAL;
4620 goto donenolock;
4621 }
4622
4623 /*
4624 * If the rule is being loaded from user space, i.e. we had to copy it
4625 * into kernel space, then do not trust the function pointer in the
4626 * rule.
4627 */
4628 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4629 if (ipf_findfunc(fp->fr_func) == NULL) {
4630 IPFERROR(11);
4631 error = ESRCH;
4632 goto donenolock;
4633 }
4634
4635 if (addrem == OP_ADD) {
4636 error = ipf_funcinit(softc, fp);
4637 if (error != 0)
4638 goto donenolock;
4639 }
4640 }
4641 if ((fp->fr_flags & FR_CALLNOW) &&
4642 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4643 IPFERROR(142);
4644 error = ESRCH;
4645 goto donenolock;
4646 }
4647 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4648 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4649 IPFERROR(143);
4650 error = ESRCH;
4651 goto donenolock;
4652 }
4653
4654 ptr = NULL;
4655 cptr = NULL;
4656
4657 if (FR_ISACCOUNT(fp->fr_flags))
4658 unit = IPL_LOGCOUNT;
4659
4660 /*
4661 * Check that each group name in the rule has a start index that
4662 * is valid.
4663 */
4664 if (fp->fr_icmphead != -1) {
4665 if ((fp->fr_icmphead < 0) ||
4666 (fp->fr_icmphead >= fp->fr_namelen)) {
4667 IPFERROR(136);
4668 error = EINVAL;
4669 goto donenolock;
4670 }
4671 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4672 fp->fr_names[fp->fr_icmphead] = '\0';
4673 }
4674
4675 if (fp->fr_grhead != -1) {
4676 if ((fp->fr_grhead < 0) ||
4677 (fp->fr_grhead >= fp->fr_namelen)) {
4678 IPFERROR(137);
4679 error = EINVAL;
4680 goto donenolock;
4681 }
4682 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4683 fp->fr_names[fp->fr_grhead] = '\0';
4684 }
4685
4686 if (fp->fr_group != -1) {
4687 if ((fp->fr_group < 0) ||
4688 (fp->fr_group >= fp->fr_namelen)) {
4689 IPFERROR(138);
4690 error = EINVAL;
4691 goto donenolock;
4692 }
4693 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4694 /*
4695 * Allow loading rules that are in groups to cause
4696 * them to be created if they don't already exit.
4697 */
4698 group = FR_NAME(fp, fr_group);
4699 if (addrem == OP_ADD) {
4700 fg = ipf_group_add(softc, group, NULL,
4701 fp->fr_flags, unit, set);
4702 fp->fr_grp = fg;
4703 } else {
4704 fg = ipf_findgroup(softc, group, unit,
4705 set, NULL);
4706 if (fg == NULL) {
4707 IPFERROR(12);
4708 error = ESRCH;
4709 goto donenolock;
4710 }
4711 }
4712
4713 if (fg->fg_flags == 0) {
4714 fg->fg_flags = fp->fr_flags & FR_INOUT;
4715 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4716 IPFERROR(13);
4717 error = ESRCH;
4718 goto donenolock;
4719 }
4720 }
4721 } else {
4722 /*
4723 * If a rule is going to be part of a group then it does
4724 * not matter whether it is an in or out rule, but if it
4725 * isn't in a group, then it does...
4726 */
4727 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4728 IPFERROR(14);
4729 error = EINVAL;
4730 goto donenolock;
4731 }
4732 }
4733 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4734
4735 /*
4736 * Work out which rule list this change is being applied to.
4737 */
4738 ftail = NULL;
4739 fprev = NULL;
4740 if (unit == IPL_LOGAUTH) {
4741 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4742 (fp->fr_tifs[1].fd_ptr != NULL) ||
4743 (fp->fr_dif.fd_ptr != NULL) ||
4744 (fp->fr_flags & FR_FASTROUTE)) {
4745 softc->ipf_interror = 145;
4746 error = EINVAL;
4747 goto donenolock;
4748 }
4749 fprev = ipf_auth_rulehead(softc);
4750 } else {
4751 if (FR_ISACCOUNT(fp->fr_flags))
4752 fprev = &softc->ipf_acct[in][set];
4753 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4754 fprev = &softc->ipf_rules[in][set];
4755 }
4756 if (fprev == NULL) {
4757 IPFERROR(15);
4758 error = ESRCH;
4759 goto donenolock;
4760 }
4761
4762 if (fg != NULL)
4763 fprev = &fg->fg_start;
4764
4765 /*
4766 * Copy in extra data for the rule.
4767 */
4768 if (fp->fr_dsize != 0) {
4769 if (makecopy != 0) {
4770 KMALLOCS(ptr, void *, fp->fr_dsize);
4771 if (ptr == NULL) {
4772 IPFERROR(16);
4773 error = ENOMEM;
4774 goto donenolock;
4775 }
4776
4777 /*
4778 * The bcopy case is for when the data is appended
4779 * to the rule by ipf_in_compat().
4780 */
4781 if (uptr >= (void *)fp &&
4782 uptr < (void *)((char *)fp + fp->fr_size)) {
4783 bcopy(uptr, ptr, fp->fr_dsize);
4784 error = 0;
4785 } else {
4786 error = COPYIN(uptr, ptr, fp->fr_dsize);
4787 if (error != 0) {
4788 IPFERROR(17);
4789 error = EFAULT;
4790 goto donenolock;
4791 }
4792 }
4793 } else {
4794 ptr = uptr;
4795 }
4796 fp->fr_data = ptr;
4797 } else {
4798 fp->fr_data = NULL;
4799 }
4800
4801 /*
4802 * Perform per-rule type sanity checks of their members.
4803 * All code after this needs to be aware that allocated memory
4804 * may need to be free'd before exiting.
4805 */
4806 switch (fp->fr_type & ~FR_T_BUILTIN)
4807 {
4808#if defined(IPFILTER_BPF)
4809 case FR_T_BPFOPC :
4810 if (fp->fr_dsize == 0) {
4811 IPFERROR(19);
4812 error = EINVAL;
4813 break;
4814 }
4815 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4816 IPFERROR(20);
4817 error = EINVAL;
4818 break;
4819 }
4820 break;
4821#endif
4822 case FR_T_IPF :
4823 /*
4824 * Preparation for error case at the bottom of this function.
4825 */
4826 if (fp->fr_datype == FRI_LOOKUP)
4827 fp->fr_dstptr = NULL;
4828 if (fp->fr_satype == FRI_LOOKUP)
4829 fp->fr_srcptr = NULL;
4830
4831 if (fp->fr_dsize != sizeof(fripf_t)) {
4832 IPFERROR(21);
4833 error = EINVAL;
4834 break;
4835 }
4836
4837 /*
4838 * Allowing a rule with both "keep state" and "with oow" is
4839 * pointless because adding a state entry to the table will
4840 * fail with the out of window (oow) flag set.
4841 */
4842 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4843 IPFERROR(22);
4844 error = EINVAL;
4845 break;
4846 }
4847
4848 switch (fp->fr_satype)
4849 {
4850 case FRI_BROADCAST :
4851 case FRI_DYNAMIC :
4852 case FRI_NETWORK :
4853 case FRI_NETMASKED :
4854 case FRI_PEERADDR :
4855 if (fp->fr_sifpidx < 0) {
4856 IPFERROR(23);
4857 error = EINVAL;
4858 }
4859 break;
4860 case FRI_LOOKUP :
4861 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4862 &fp->fr_src6,
4863 &fp->fr_smsk6);
4864 if (fp->fr_srcfunc == NULL) {
4865 IPFERROR(132);
4866 error = ESRCH;
4867 break;
4868 }
4869 break;
4870 case FRI_NORMAL :
4871 break;
4872 default :
4873 IPFERROR(133);
4874 error = EINVAL;
4875 break;
4876 }
4877 if (error != 0)
4878 break;
4879
4880 switch (fp->fr_datype)
4881 {
4882 case FRI_BROADCAST :
4883 case FRI_DYNAMIC :
4884 case FRI_NETWORK :
4885 case FRI_NETMASKED :
4886 case FRI_PEERADDR :
4887 if (fp->fr_difpidx < 0) {
4888 IPFERROR(24);
4889 error = EINVAL;
4890 }
4891 break;
4892 case FRI_LOOKUP :
4893 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4894 &fp->fr_dst6,
4895 &fp->fr_dmsk6);
4896 if (fp->fr_dstfunc == NULL) {
4897 IPFERROR(134);
4898 error = ESRCH;
4899 }
4900 break;
4901 case FRI_NORMAL :
4902 break;
4903 default :
4904 IPFERROR(135);
4905 error = EINVAL;
4906 }
4907 break;
4908
4909 case FR_T_NONE :
4910 case FR_T_CALLFUNC :
4911 case FR_T_COMPIPF :
4912 break;
4913
4914 case FR_T_IPFEXPR :
4915 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4916 IPFERROR(25);
4917 error = EINVAL;
4918 }
4919 break;
4920
4921 default :
4922 IPFERROR(26);
4923 error = EINVAL;
4924 break;
4925 }
4926 if (error != 0)
4927 goto donenolock;
4928
4929 if (fp->fr_tif.fd_name != -1) {
4930 if ((fp->fr_tif.fd_name < 0) ||
4931 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4932 IPFERROR(139);
4933 error = EINVAL;
4934 goto donenolock;
4935 }
4936 }
4937
4938 if (fp->fr_dif.fd_name != -1) {
4939 if ((fp->fr_dif.fd_name < 0) ||
4940 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4941 IPFERROR(140);
4942 error = EINVAL;
4943 goto donenolock;
4944 }
4945 }
4946
4947 if (fp->fr_rif.fd_name != -1) {
4948 if ((fp->fr_rif.fd_name < 0) ||
4949 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4950 IPFERROR(141);
4951 error = EINVAL;
4952 goto donenolock;
4953 }
4954 }
4955
4956 /*
4957 * Lookup all the interface names that are part of the rule.
4958 */
4959 error = ipf_synclist(softc, fp, NULL);
4960 if (error != 0)
4961 goto donenolock;
4962 fp->fr_statecnt = 0;
4963 if (fp->fr_srctrack.ht_max_nodes != 0)
4964 ipf_rb_ht_init(&fp->fr_srctrack);
4965
4966 /*
4967 * Look for an existing matching filter rule, but don't include the
4968 * next or interface pointer in the comparison (fr_next, fr_ifa).
4969 * This elminates rules which are indentical being loaded. Checksum
4970 * the constant part of the filter rule to make comparisons quicker
4971 * (this meaning no pointers are included).
4972 */
4973 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4974 for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4975 fp->fr_cksum += *p;
4976
4977 WRITE_ENTER(&softc->ipf_mutex);
4978
4979 /*
4980 * Now that the filter rule lists are locked, we can walk the
4981 * chain of them without fear.
4982 */
4983 ftail = fprev;
4984 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4985 if (fp->fr_collect <= f->fr_collect) {
4986 ftail = fprev;
4987 f = NULL;
4988 break;
4989 }
4990 fprev = ftail;
4991 }
4992
4993 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4994 if (ipf_rule_compare(fp, f) == 0)
4995 break;
4996 }
4997
4998 /*
4999 * If zero'ing statistics, copy current to caller and zero.
5000 */
5001 if (addrem == OP_ZERO) {
5002 if (f == NULL) {
5003 IPFERROR(27);
5004 error = ESRCH;
5005 } else {
5006 /*
5007 * Copy and reduce lock because of impending copyout.
5008 * Well we should, but if we do then the atomicity of
5009 * this call and the correctness of fr_hits and
5010 * fr_bytes cannot be guaranteed. As it is, this code
5011 * only resets them to 0 if they are successfully
5012 * copied out into user space.
5013 */
5014 bcopy((char *)f, (char *)fp, f->fr_size);
5015 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
5016
5017 /*
5018 * When we copy this rule back out, set the data
5019 * pointer to be what it was in user space.
5020 */
5021 fp->fr_data = uptr;
5022 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
5023
5024 if (error == 0) {
5025 if ((f->fr_dsize != 0) && (uptr != NULL)) {
5026 error = COPYOUT(f->fr_data, uptr,
5027 f->fr_dsize);
5028 if (error == 0) {
5029 f->fr_hits = 0;
5030 f->fr_bytes = 0;
5031 } else {
5032 IPFERROR(28);
5033 error = EFAULT;
5034 }
5035 }
5036 }
5037 }
5038
5039 if (makecopy != 0) {
5040 if (ptr != NULL) {
5041 KFREES(ptr, fp->fr_dsize);
5042 }
5043 KFREES(fp, fp->fr_size);
5044 }
5045 RWLOCK_EXIT(&softc->ipf_mutex);
5046 return error;
5047 }
5048
5049 if (f == NULL) {
5050 /*
5051 * At the end of this, ftail must point to the place where the
5052 * new rule is to be saved/inserted/added.
5053 * For SIOCAD*FR, this should be the last rule in the group of
5054 * rules that have equal fr_collect fields.
5055 * For SIOCIN*FR, ...
5056 */
5057 if (req == (ioctlcmd_t)SIOCADAFR ||
5058 req == (ioctlcmd_t)SIOCADIFR) {
5059
5060 for (ftail = fprev; (f = *ftail) != NULL; ) {
5061 if (f->fr_collect > fp->fr_collect)
5062 break;
5063 ftail = &f->fr_next;
5064 fprev = ftail;
5065 }
5066 ftail = fprev;
5067 f = NULL;
5068 ptr = NULL;
5069 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5070 req == (ioctlcmd_t)SIOCINIFR) {
5071 while ((f = *fprev) != NULL) {
5072 if (f->fr_collect >= fp->fr_collect)
5073 break;
5074 fprev = &f->fr_next;
5075 }
5076 ftail = fprev;
5077 if (fp->fr_hits != 0) {
5078 while (fp->fr_hits && (f = *ftail)) {
5079 if (f->fr_collect != fp->fr_collect)
5080 break;
5081 fprev = ftail;
5082 ftail = &f->fr_next;
5083 fp->fr_hits--;
5084 }
5085 }
5086 f = NULL;
5087 ptr = NULL;
5088 }
5089 }
5090
5091 /*
5092 * Request to remove a rule.
5093 */
5094 if (addrem == OP_REM) {
5095 if (f == NULL) {
5096 IPFERROR(29);
5097 error = ESRCH;
5098 } else {
5099 /*
5100 * Do not allow activity from user space to interfere
5101 * with rules not loaded that way.
5102 */
5103 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5104 IPFERROR(30);
5105 error = EPERM;
5106 goto done;
5107 }
5108
5109 /*
5110 * Return EBUSY if the rule is being reference by
5111 * something else (eg state information.)
5112 */
5113 if (f->fr_ref > 1) {
5114 IPFERROR(31);
5115 error = EBUSY;
5116 goto done;
5117 }
5118#ifdef IPFILTER_SCAN
5119 if (f->fr_isctag != -1 &&
5120 (f->fr_isc != (struct ipscan *)-1))
5121 ipf_scan_detachfr(f);
5122#endif
5123
5124 if (unit == IPL_LOGAUTH) {
5125 error = ipf_auth_precmd(softc, req, f, ftail);
5126 goto done;
5127 }
5128
5129 ipf_rule_delete(softc, f, unit, set);
5130
5131 need_free = makecopy;
5132 }
5133 } else {
5134 /*
5135 * Not removing, so we must be adding/inserting a rule.
5136 */
5137 if (f != NULL) {
5138 IPFERROR(32);
5139 error = EEXIST;
5140 goto done;
5141 }
5142 if (unit == IPL_LOGAUTH) {
5143 error = ipf_auth_precmd(softc, req, fp, ftail);
5144 goto done;
5145 }
5146
5147 MUTEX_NUKE(&fp->fr_lock);
5148 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5149 if (fp->fr_die != 0)
5150 ipf_rule_expire_insert(softc, fp, set);
5151
5152 fp->fr_hits = 0;
5153 if (makecopy != 0)
5154 fp->fr_ref = 1;
5155 fp->fr_pnext = ftail;
5156 fp->fr_next = *ftail;
5157 if (fp->fr_next != NULL)
5158 fp->fr_next->fr_pnext = &fp->fr_next;
5159 *ftail = fp;
5160 ipf_fixskip(ftail, fp, 1);
5161
5162 fp->fr_icmpgrp = NULL;
5163 if (fp->fr_icmphead != -1) {
5164 group = FR_NAME(fp, fr_icmphead);
5165 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5166 fp->fr_icmpgrp = fg;
5167 }
5168
5169 fp->fr_grphead = NULL;
5170 if (fp->fr_grhead != -1) {
5171 group = FR_NAME(fp, fr_grhead);
5172 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5173 unit, set);
5174 fp->fr_grphead = fg;
5175 }
5176 }
5177done:
5178 RWLOCK_EXIT(&softc->ipf_mutex);
5179donenolock:
5180 if (need_free || (error != 0)) {
5181 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5182 if ((fp->fr_satype == FRI_LOOKUP) &&
5183 (fp->fr_srcptr != NULL))
5184 ipf_lookup_deref(softc, fp->fr_srctype,
5185 fp->fr_srcptr);
5186 if ((fp->fr_datype == FRI_LOOKUP) &&
5187 (fp->fr_dstptr != NULL))
5188 ipf_lookup_deref(softc, fp->fr_dsttype,
5189 fp->fr_dstptr);
5190 }
5191 if (fp->fr_grp != NULL) {
5192 WRITE_ENTER(&softc->ipf_mutex);
5193 ipf_group_del(softc, fp->fr_grp, fp);
5194 RWLOCK_EXIT(&softc->ipf_mutex);
5195 }
5196 if ((ptr != NULL) && (makecopy != 0)) {
5197 KFREES(ptr, fp->fr_dsize);
5198 }
5199 KFREES(fp, fp->fr_size);
5200 }
5201 return (error);
5202}
5203
5204
5205/* ------------------------------------------------------------------------ */
5206/* Function: ipf_rule_delete */
5207/* Returns: Nil */
5208/* Parameters: softc(I) - pointer to soft context main structure */
5209/* f(I) - pointer to the rule being deleted */
5210/* ftail(I) - pointer to the pointer to f */
5211/* unit(I) - device for which this is for */
5212/* set(I) - 1 or 0 (filter set) */
5213/* */
5214/* This function attempts to do what it can to delete a filter rule: remove */
5215/* it from any linked lists and remove any groups it is responsible for. */
5216/* But in the end, removing a rule can only drop the reference count - we */
5217/* must use that as the guide for whether or not it can be freed. */
5218/* ------------------------------------------------------------------------ */
5219static void
5220ipf_rule_delete(softc, f, unit, set)
5221 ipf_main_softc_t *softc;
5222 frentry_t *f;
5223 int unit, set;
5224{
5225
5226 /*
5227 * If fr_pdnext is set, then the rule is on the expire list, so
5228 * remove it from there.
5229 */
5230 if (f->fr_pdnext != NULL) {
5231 *f->fr_pdnext = f->fr_dnext;
5232 if (f->fr_dnext != NULL)
5233 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5234 f->fr_pdnext = NULL;
5235 f->fr_dnext = NULL;
5236 }
5237
5238 ipf_fixskip(f->fr_pnext, f, -1);
5239 if (f->fr_pnext != NULL)
5240 *f->fr_pnext = f->fr_next;
5241 if (f->fr_next != NULL)
5242 f->fr_next->fr_pnext = f->fr_pnext;
5243 f->fr_pnext = NULL;
5244 f->fr_next = NULL;
5245
5246 (void) ipf_derefrule(softc, &f);
5247}
5248
5249/* ------------------------------------------------------------------------ */
5250/* Function: ipf_rule_expire_insert */
5251/* Returns: Nil */
5252/* Parameters: softc(I) - pointer to soft context main structure */
5253/* f(I) - pointer to rule to be added to expire list */
5254/* set(I) - 1 or 0 (filter set) */
5255/* */
5256/* If the new rule has a given expiration time, insert it into the list of */
5257/* expiring rules with the ones to be removed first added to the front of */
5258/* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5259/* expiration interval checks. */
5260/* ------------------------------------------------------------------------ */
5261static void
5262ipf_rule_expire_insert(softc, f, set)
5263 ipf_main_softc_t *softc;
5264 frentry_t *f;
5265 int set;
5266{
5267 frentry_t *fr;
5268
5269 /*
5270 */
5271
5272 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5273 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5274 fr = fr->fr_dnext) {
5275 if (f->fr_die < fr->fr_die)
5276 break;
5277 if (fr->fr_dnext == NULL) {
5278 /*
5279 * We've got to the last rule and everything
5280 * wanted to be expired before this new node,
5281 * so we have to tack it on the end...
5282 */
5283 fr->fr_dnext = f;
5284 f->fr_pdnext = &fr->fr_dnext;
5285 fr = NULL;
5286 break;
5287 }
5288 }
5289
5290 if (softc->ipf_rule_explist[set] == NULL) {
5291 softc->ipf_rule_explist[set] = f;
5292 f->fr_pdnext = &softc->ipf_rule_explist[set];
5293 } else if (fr != NULL) {
5294 f->fr_dnext = fr;
5295 f->fr_pdnext = fr->fr_pdnext;
5296 fr->fr_pdnext = &f->fr_dnext;
5297 }
5298}
5299
5300
5301/* ------------------------------------------------------------------------ */
5302/* Function: ipf_findlookup */
5303/* Returns: NULL = failure, else success */
5304/* Parameters: softc(I) - pointer to soft context main structure */
5305/* unit(I) - ipf device we want to find match for */
5306/* fp(I) - rule for which lookup is for */
5307/* addrp(I) - pointer to lookup information in address struct */
5308/* maskp(O) - pointer to lookup information for storage */
5309/* */
5310/* When using pools and hash tables to store addresses for matching in */
5311/* rules, it is necessary to resolve both the object referred to by the */
5312/* name or address (and return that pointer) and also provide the means by */
5313/* which to determine if an address belongs to that object to make the */
5314/* packet matching quicker. */
5315/* ------------------------------------------------------------------------ */
5316static void *
5317ipf_findlookup(softc, unit, fr, addrp, maskp)
5318 ipf_main_softc_t *softc;
5319 int unit;
5320 frentry_t *fr;
5321 i6addr_t *addrp, *maskp;
5322{
5323 void *ptr = NULL;
5324
5325 switch (addrp->iplookupsubtype)
5326 {
5327 case 0 :
5328 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5329 addrp->iplookupnum,
5330 &maskp->iplookupfunc);
5331 break;
5332 case 1 :
5333 if (addrp->iplookupname < 0)
5334 break;
5335 if (addrp->iplookupname >= fr->fr_namelen)
5336 break;
5337 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5338 fr->fr_names + addrp->iplookupname,
5339 &maskp->iplookupfunc);
5340 break;
5341 default :
5342 break;
5343 }
5344
5345 return ptr;
5346}
5347
5348
5349/* ------------------------------------------------------------------------ */
5350/* Function: ipf_funcinit */
5351/* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5352/* Parameters: softc(I) - pointer to soft context main structure */
5353/* fr(I) - pointer to filter rule */
5354/* */
5355/* If a rule is a call rule, then check if the function it points to needs */
5356/* an init function to be called now the rule has been loaded. */
5357/* ------------------------------------------------------------------------ */
5358static int
5359ipf_funcinit(softc, fr)
5360 ipf_main_softc_t *softc;
5361 frentry_t *fr;
5362{
5363 ipfunc_resolve_t *ft;
5364 int err;
5365
5366 IPFERROR(34);
5367 err = ESRCH;
5368
5369 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5370 if (ft->ipfu_addr == fr->fr_func) {
5371 err = 0;
5372 if (ft->ipfu_init != NULL)
5373 err = (*ft->ipfu_init)(softc, fr);
5374 break;
5375 }
5376 return err;
5377}
5378
5379
5380/* ------------------------------------------------------------------------ */
5381/* Function: ipf_funcfini */
5382/* Returns: Nil */
5383/* Parameters: softc(I) - pointer to soft context main structure */
5384/* fr(I) - pointer to filter rule */
5385/* */
5386/* For a given filter rule, call the matching "fini" function if the rule */
5387/* is using a known function that would have resulted in the "init" being */
5388/* called for ealier. */
5389/* ------------------------------------------------------------------------ */
5390static void
5391ipf_funcfini(softc, fr)
5392 ipf_main_softc_t *softc;
5393 frentry_t *fr;
5394{
5395 ipfunc_resolve_t *ft;
5396
5397 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5398 if (ft->ipfu_addr == fr->fr_func) {
5399 if (ft->ipfu_fini != NULL)
5400 (void) (*ft->ipfu_fini)(softc, fr);
5401 break;
5402 }
5403}
5404
5405
5406/* ------------------------------------------------------------------------ */
5407/* Function: ipf_findfunc */
5408/* Returns: ipfunc_t - pointer to function if found, else NULL */
5409/* Parameters: funcptr(I) - function pointer to lookup */
5410/* */
5411/* Look for a function in the table of known functions. */
5412/* ------------------------------------------------------------------------ */
5413static ipfunc_t
5414ipf_findfunc(funcptr)
5415 ipfunc_t funcptr;
5416{
5417 ipfunc_resolve_t *ft;
5418
5419 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5420 if (ft->ipfu_addr == funcptr)
5421 return funcptr;
5422 return NULL;
5423}
5424
5425
5426/* ------------------------------------------------------------------------ */
5427/* Function: ipf_resolvefunc */
5428/* Returns: int - 0 == success, else error */
5429/* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5430/* */
5431/* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5432/* This will either be the function name (if the pointer is set) or the */
5433/* function pointer if the name is set. When found, fill in the other one */
5434/* so that the entire, complete, structure can be copied back to user space.*/
5435/* ------------------------------------------------------------------------ */
5436int
5437ipf_resolvefunc(softc, data)
5438 ipf_main_softc_t *softc;
5439 void *data;
5440{
5441 ipfunc_resolve_t res, *ft;
5442 int error;
5443
5444 error = BCOPYIN(data, &res, sizeof(res));
5445 if (error != 0) {
5446 IPFERROR(123);
5447 return EFAULT;
5448 }
5449
5450 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5451 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5452 if (strncmp(res.ipfu_name, ft->ipfu_name,
5453 sizeof(res.ipfu_name)) == 0) {
5454 res.ipfu_addr = ft->ipfu_addr;
5455 res.ipfu_init = ft->ipfu_init;
5456 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5457 IPFERROR(35);
5458 return EFAULT;
5459 }
5460 return 0;
5461 }
5462 }
5463 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5464 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5465 if (ft->ipfu_addr == res.ipfu_addr) {
5466 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5467 sizeof(res.ipfu_name));
5468 res.ipfu_init = ft->ipfu_init;
5469 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5470 IPFERROR(36);
5471 return EFAULT;
5472 }
5473 return 0;
5474 }
5475 }
5476 IPFERROR(37);
5477 return ESRCH;
5478}
5479
5480
5481#if !defined(_KERNEL) || SOLARIS
5482/*
5483 * From: NetBSD
5484 * ppsratecheck(): packets (or events) per second limitation.
5485 */
5486int
5487ppsratecheck(lasttime, curpps, maxpps)
5488 struct timeval *lasttime;
5489 int *curpps;
5490 int maxpps; /* maximum pps allowed */
5491{
5492 struct timeval tv, delta;
5493 int rv;
5494
5495 GETKTIME(&tv);
5496
5497 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5498 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5499 if (delta.tv_usec < 0) {
5500 delta.tv_sec--;
5501 delta.tv_usec += 1000000;
5502 }
5503
5504 /*
5505 * check for 0,0 is so that the message will be seen at least once.
5506 * if more than one second have passed since the last update of
5507 * lasttime, reset the counter.
5508 *
5509 * we do increment *curpps even in *curpps < maxpps case, as some may
5510 * try to use *curpps for stat purposes as well.
5511 */
5512 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5513 delta.tv_sec >= 1) {
5514 *lasttime = tv;
5515 *curpps = 0;
5516 rv = 1;
5517 } else if (maxpps < 0)
5518 rv = 1;
5519 else if (*curpps < maxpps)
5520 rv = 1;
5521 else
5522 rv = 0;
5523 *curpps = *curpps + 1;
5524
5525 return (rv);
5526}
5527#endif
5528
5529
5530/* ------------------------------------------------------------------------ */
5531/* Function: ipf_derefrule */
5532/* Returns: int - 0 == rule freed up, else rule not freed */
5533/* Parameters: fr(I) - pointer to filter rule */
5534/* */
5535/* Decrement the reference counter to a rule by one. If it reaches zero, */
5536/* free it and any associated storage space being used by it. */
5537/* ------------------------------------------------------------------------ */
5538int
5539ipf_derefrule(softc, frp)
5540 ipf_main_softc_t *softc;
5541 frentry_t **frp;
5542{
5543 frentry_t *fr;
5544 frdest_t *fdp;
5545
5546 fr = *frp;
5547 *frp = NULL;
5548
5549 MUTEX_ENTER(&fr->fr_lock);
5550 fr->fr_ref--;
5551 if (fr->fr_ref == 0) {
5552 MUTEX_EXIT(&fr->fr_lock);
5553 MUTEX_DESTROY(&fr->fr_lock);
5554
5555 ipf_funcfini(softc, fr);
5556
5557 fdp = &fr->fr_tif;
5558 if (fdp->fd_type == FRD_DSTLIST)
5559 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5560
5561 fdp = &fr->fr_rif;
5562 if (fdp->fd_type == FRD_DSTLIST)
5563 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5564
5565 fdp = &fr->fr_dif;
5566 if (fdp->fd_type == FRD_DSTLIST)
5567 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5568
5569 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5570 fr->fr_satype == FRI_LOOKUP)
5571 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5572 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5573 fr->fr_datype == FRI_LOOKUP)
5574 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5575
5576 if (fr->fr_grp != NULL)
5577 ipf_group_del(softc, fr->fr_grp, fr);
5578
5579 if (fr->fr_grphead != NULL)
5580 ipf_group_del(softc, fr->fr_grphead, fr);
5581
5582 if (fr->fr_icmpgrp != NULL)
5583 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5584
5585 if ((fr->fr_flags & FR_COPIED) != 0) {
5586 if (fr->fr_dsize) {
5587 KFREES(fr->fr_data, fr->fr_dsize);
5588 }
5589 KFREES(fr, fr->fr_size);
5590 return 0;
5591 }
5592 return 1;
5593 } else {
5594 MUTEX_EXIT(&fr->fr_lock);
5595 }
5596 return -1;
5597}
5598
5599
5600/* ------------------------------------------------------------------------ */
5601/* Function: ipf_grpmapinit */
5602/* Returns: int - 0 == success, else ESRCH because table entry not found*/
5603/* Parameters: fr(I) - pointer to rule to find hash table for */
5604/* */
5605/* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5606/* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5607/* ------------------------------------------------------------------------ */
5608static int
5609ipf_grpmapinit(softc, fr)
5610 ipf_main_softc_t *softc;
5611 frentry_t *fr;
5612{
5613 char name[FR_GROUPLEN];
5614 iphtable_t *iph;
5615
5616#if defined(SNPRINTF) && defined(_KERNEL)
5617 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5618#else
5619 (void) sprintf(name, "%d", fr->fr_arg);
5620#endif
5621 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5622 if (iph == NULL) {
5623 IPFERROR(38);
5624 return ESRCH;
5625 }
5626 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5627 IPFERROR(39);
5628 return ESRCH;
5629 }
5630 iph->iph_ref++;
5631 fr->fr_ptr = iph;
5632 return 0;
5633}
5634
5635
5636/* ------------------------------------------------------------------------ */
5637/* Function: ipf_grpmapfini */
5638/* Returns: int - 0 == success, else ESRCH because table entry not found*/
5639/* Parameters: softc(I) - pointer to soft context main structure */
5640/* fr(I) - pointer to rule to release hash table for */
5641/* */
5642/* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5643/* be called to undo what ipf_grpmapinit caused to be done. */
5644/* ------------------------------------------------------------------------ */
5645static int
5646ipf_grpmapfini(softc, fr)
5647 ipf_main_softc_t *softc;
5648 frentry_t *fr;
5649{
5650 iphtable_t *iph;
5651 iph = fr->fr_ptr;
5652 if (iph != NULL)
5653 ipf_lookup_deref(softc, IPLT_HASH, iph);
5654 return 0;
5655}
5656
5657
5658/* ------------------------------------------------------------------------ */
5659/* Function: ipf_srcgrpmap */
5660/* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5661/* Parameters: fin(I) - pointer to packet information */
5662/* passp(IO) - pointer to current/new filter decision (unused) */
5663/* */
5664/* Look for a rule group head in a hash table, using the source address as */
5665/* the key, and descend into that group and continue matching rules against */
5666/* the packet. */
5667/* ------------------------------------------------------------------------ */
5668frentry_t *
5669ipf_srcgrpmap(fin, passp)
5670 fr_info_t *fin;
5671 u_32_t *passp;
5672{
5673 frgroup_t *fg;
5674 void *rval;
5675
5676 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5677 &fin->fin_src);
5678 if (rval == NULL)
5679 return NULL;
5680
5681 fg = rval;
5682 fin->fin_fr = fg->fg_start;
5683 (void) ipf_scanlist(fin, *passp);
5684 return fin->fin_fr;
5685}
5686
5687
5688/* ------------------------------------------------------------------------ */
5689/* Function: ipf_dstgrpmap */
5690/* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5691/* Parameters: fin(I) - pointer to packet information */
5692/* passp(IO) - pointer to current/new filter decision (unused) */
5693/* */
5694/* Look for a rule group head in a hash table, using the destination */
5695/* address as the key, and descend into that group and continue matching */
5696/* rules against the packet. */
5697/* ------------------------------------------------------------------------ */
5698frentry_t *
5699ipf_dstgrpmap(fin, passp)
5700 fr_info_t *fin;
5701 u_32_t *passp;
5702{
5703 frgroup_t *fg;
5704 void *rval;
5705
5706 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5707 &fin->fin_dst);
5708 if (rval == NULL)
5709 return NULL;
5710
5711 fg = rval;
5712 fin->fin_fr = fg->fg_start;
5713 (void) ipf_scanlist(fin, *passp);
5714 return fin->fin_fr;
5715}
5716
5717/*
5718 * Queue functions
5719 * ===============
5720 * These functions manage objects on queues for efficient timeouts. There
5721 * are a number of system defined queues as well as user defined timeouts.
5722 * It is expected that a lock is held in the domain in which the queue
5723 * belongs (i.e. either state or NAT) when calling any of these functions
5724 * that prevents ipf_freetimeoutqueue() from being called at the same time
5725 * as any other.
5726 */
5727
5728
5729/* ------------------------------------------------------------------------ */
5730/* Function: ipf_addtimeoutqueue */
5731/* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5732/* timeout queue with given interval. */
5733/* Parameters: parent(I) - pointer to pointer to parent node of this list */
5734/* of interface queues. */
5735/* seconds(I) - timeout value in seconds for this queue. */
5736/* */
5737/* This routine first looks for a timeout queue that matches the interval */
5738/* being requested. If it finds one, increments the reference counter and */
5739/* returns a pointer to it. If none are found, it allocates a new one and */
5740/* inserts it at the top of the list. */
5741/* */
5742/* Locking. */
5743/* It is assumed that the caller of this function has an appropriate lock */
5744/* held (exclusively) in the domain that encompases 'parent'. */
5745/* ------------------------------------------------------------------------ */
5746ipftq_t *
5747ipf_addtimeoutqueue(softc, parent, seconds)
5748 ipf_main_softc_t *softc;
5749 ipftq_t **parent;
5750 u_int seconds;
5751{
5752 ipftq_t *ifq;
5753 u_int period;
5754
5755 period = seconds * IPF_HZ_DIVIDE;
5756
5757 MUTEX_ENTER(&softc->ipf_timeoutlock);
5758 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5759 if (ifq->ifq_ttl == period) {
5760 /*
5761 * Reset the delete flag, if set, so the structure
5762 * gets reused rather than freed and reallocated.
5763 */
5764 MUTEX_ENTER(&ifq->ifq_lock);
5765 ifq->ifq_flags &= ~IFQF_DELETE;
5766 ifq->ifq_ref++;
5767 MUTEX_EXIT(&ifq->ifq_lock);
5768 MUTEX_EXIT(&softc->ipf_timeoutlock);
5769
5770 return ifq;
5771 }
5772 }
5773
5774 KMALLOC(ifq, ipftq_t *);
5775 if (ifq != NULL) {
5776 MUTEX_NUKE(&ifq->ifq_lock);
5777 IPFTQ_INIT(ifq, period, "ipftq mutex");
5778 ifq->ifq_next = *parent;
5779 ifq->ifq_pnext = parent;
5780 ifq->ifq_flags = IFQF_USER;
5781 ifq->ifq_ref++;
5782 *parent = ifq;
5783 softc->ipf_userifqs++;
5784 }
5785 MUTEX_EXIT(&softc->ipf_timeoutlock);
5786 return ifq;
5787}
5788
5789
5790/* ------------------------------------------------------------------------ */
5791/* Function: ipf_deletetimeoutqueue */
5792/* Returns: int - new reference count value of the timeout queue */
5793/* Parameters: ifq(I) - timeout queue which is losing a reference. */
5794/* Locks: ifq->ifq_lock */
5795/* */
5796/* This routine must be called when we're discarding a pointer to a timeout */
5797/* queue object, taking care of the reference counter. */
5798/* */
5799/* Now that this just sets a DELETE flag, it requires the expire code to */
5800/* check the list of user defined timeout queues and call the free function */
5801/* below (currently commented out) to stop memory leaking. It is done this */
5802/* way because the locking may not be sufficient to safely do a free when */
5803/* this function is called. */
5804/* ------------------------------------------------------------------------ */
5805int
5806ipf_deletetimeoutqueue(ifq)
5807 ipftq_t *ifq;
5808{
5809
5810 ifq->ifq_ref--;
5811 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5812 ifq->ifq_flags |= IFQF_DELETE;
5813 }
5814
5815 return ifq->ifq_ref;
5816}
5817
5818
5819/* ------------------------------------------------------------------------ */
5820/* Function: ipf_freetimeoutqueue */
5821/* Parameters: ifq(I) - timeout queue which is losing a reference. */
5822/* Returns: Nil */
5823/* */
5824/* Locking: */
5825/* It is assumed that the caller of this function has an appropriate lock */
5826/* held (exclusively) in the domain that encompases the callers "domain". */
5827/* The ifq_lock for this structure should not be held. */
5828/* */
5829/* Remove a user defined timeout queue from the list of queues it is in and */
5830/* tidy up after this is done. */
5831/* ------------------------------------------------------------------------ */
5832void
5833ipf_freetimeoutqueue(softc, ifq)
5834 ipf_main_softc_t *softc;
5835 ipftq_t *ifq;
5836{
5837
5838 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5839 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5840 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5841 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5842 ifq->ifq_ref);
5843 return;
5844 }
5845
5846 /*
5847 * Remove from its position in the list.
5848 */
5849 *ifq->ifq_pnext = ifq->ifq_next;
5850 if (ifq->ifq_next != NULL)
5851 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5852 ifq->ifq_next = NULL;
5853 ifq->ifq_pnext = NULL;
5854
5855 MUTEX_DESTROY(&ifq->ifq_lock);
5856 ATOMIC_DEC(softc->ipf_userifqs);
5857 KFREE(ifq);
5858}
5859
5860
5861/* ------------------------------------------------------------------------ */
5862/* Function: ipf_deletequeueentry */
5863/* Returns: Nil */
5864/* Parameters: tqe(I) - timeout queue entry to delete */
5865/* */
5866/* Remove a tail queue entry from its queue and make it an orphan. */
5867/* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5868/* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5869/* the correct lock(s) may not be held that would make it safe to do so. */
5870/* ------------------------------------------------------------------------ */
5871void
5872ipf_deletequeueentry(tqe)
5873 ipftqent_t *tqe;
5874{
5875 ipftq_t *ifq;
5876
5877 ifq = tqe->tqe_ifq;
5878
5879 MUTEX_ENTER(&ifq->ifq_lock);
5880
5881 if (tqe->tqe_pnext != NULL) {
5882 *tqe->tqe_pnext = tqe->tqe_next;
5883 if (tqe->tqe_next != NULL)
5884 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5885 else /* we must be the tail anyway */
5886 ifq->ifq_tail = tqe->tqe_pnext;
5887
5888 tqe->tqe_pnext = NULL;
5889 tqe->tqe_ifq = NULL;
5890 }
5891
5892 (void) ipf_deletetimeoutqueue(ifq);
5893 ASSERT(ifq->ifq_ref > 0);
5894
5895 MUTEX_EXIT(&ifq->ifq_lock);
5896}
5897
5898
5899/* ------------------------------------------------------------------------ */
5900/* Function: ipf_queuefront */
5901/* Returns: Nil */
5902/* Parameters: tqe(I) - pointer to timeout queue entry */
5903/* */
5904/* Move a queue entry to the front of the queue, if it isn't already there. */
5905/* ------------------------------------------------------------------------ */
5906void
5907ipf_queuefront(tqe)
5908 ipftqent_t *tqe;
5909{
5910 ipftq_t *ifq;
5911
5912 ifq = tqe->tqe_ifq;
5913 if (ifq == NULL)
5914 return;
5915
5916 MUTEX_ENTER(&ifq->ifq_lock);
5917 if (ifq->ifq_head != tqe) {
5918 *tqe->tqe_pnext = tqe->tqe_next;
5919 if (tqe->tqe_next)
5920 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5921 else
5922 ifq->ifq_tail = tqe->tqe_pnext;
5923
5924 tqe->tqe_next = ifq->ifq_head;
5925 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5926 ifq->ifq_head = tqe;
5927 tqe->tqe_pnext = &ifq->ifq_head;
5928 }
5929 MUTEX_EXIT(&ifq->ifq_lock);
5930}
5931
5932
5933/* ------------------------------------------------------------------------ */
5934/* Function: ipf_queueback */
5935/* Returns: Nil */
5936/* Parameters: ticks(I) - ipf tick time to use with this call */
5937/* tqe(I) - pointer to timeout queue entry */
5938/* */
5939/* Move a queue entry to the back of the queue, if it isn't already there. */
5940/* We use use ticks to calculate the expiration and mark for when we last */
5941/* touched the structure. */
5942/* ------------------------------------------------------------------------ */
5943void
5944ipf_queueback(ticks, tqe)
5945 u_long ticks;
5946 ipftqent_t *tqe;
5947{
5948 ipftq_t *ifq;
5949
5950 ifq = tqe->tqe_ifq;
5951 if (ifq == NULL)
5952 return;
5953 tqe->tqe_die = ticks + ifq->ifq_ttl;
5954 tqe->tqe_touched = ticks;
5955
5956 MUTEX_ENTER(&ifq->ifq_lock);
5957 if (tqe->tqe_next != NULL) { /* at the end already ? */
5958 /*
5959 * Remove from list
5960 */
5961 *tqe->tqe_pnext = tqe->tqe_next;
5962 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5963
5964 /*
5965 * Make it the last entry.
5966 */
5967 tqe->tqe_next = NULL;
5968 tqe->tqe_pnext = ifq->ifq_tail;
5969 *ifq->ifq_tail = tqe;
5970 ifq->ifq_tail = &tqe->tqe_next;
5971 }
5972 MUTEX_EXIT(&ifq->ifq_lock);
5973}
5974
5975
5976/* ------------------------------------------------------------------------ */
5977/* Function: ipf_queueappend */
5978/* Returns: Nil */
5979/* Parameters: ticks(I) - ipf tick time to use with this call */
5980/* tqe(I) - pointer to timeout queue entry */
5981/* ifq(I) - pointer to timeout queue */
5982/* parent(I) - owing object pointer */
5983/* */
5984/* Add a new item to this queue and put it on the very end. */
5985/* We use use ticks to calculate the expiration and mark for when we last */
5986/* touched the structure. */
5987/* ------------------------------------------------------------------------ */
5988void
5989ipf_queueappend(ticks, tqe, ifq, parent)
5990 u_long ticks;
5991 ipftqent_t *tqe;
5992 ipftq_t *ifq;
5993 void *parent;
5994{
5995
5996 MUTEX_ENTER(&ifq->ifq_lock);
5997 tqe->tqe_parent = parent;
5998 tqe->tqe_pnext = ifq->ifq_tail;
5999 *ifq->ifq_tail = tqe;
6000 ifq->ifq_tail = &tqe->tqe_next;
6001 tqe->tqe_next = NULL;
6002 tqe->tqe_ifq = ifq;
6003 tqe->tqe_die = ticks + ifq->ifq_ttl;
6004 tqe->tqe_touched = ticks;
6005 ifq->ifq_ref++;
6006 MUTEX_EXIT(&ifq->ifq_lock);
6007}
6008
6009
6010/* ------------------------------------------------------------------------ */
6011/* Function: ipf_movequeue */
6012/* Returns: Nil */
6013/* Parameters: tq(I) - pointer to timeout queue information */
6014/* oifp(I) - old timeout queue entry was on */
6015/* nifp(I) - new timeout queue to put entry on */
6016/* */
6017/* Move a queue entry from one timeout queue to another timeout queue. */
6018/* If it notices that the current entry is already last and does not need */
6019/* to move queue, the return. */
6020/* ------------------------------------------------------------------------ */
6021void
6022ipf_movequeue(ticks, tqe, oifq, nifq)
6023 u_long ticks;
6024 ipftqent_t *tqe;
6025 ipftq_t *oifq, *nifq;
6026{
6027
6028 /*
6029 * If the queue hasn't changed and we last touched this entry at the
6030 * same ipf time, then we're not going to achieve anything by either
6031 * changing the ttl or moving it on the queue.
6032 */
6033 if (oifq == nifq && tqe->tqe_touched == ticks)
6034 return;
6035
6036 /*
6037 * For any of this to be outside the lock, there is a risk that two
6038 * packets entering simultaneously, with one changing to a different
6039 * queue and one not, could end up with things in a bizarre state.
6040 */
6041 MUTEX_ENTER(&oifq->ifq_lock);
6042
6043 tqe->tqe_touched = ticks;
6044 tqe->tqe_die = ticks + nifq->ifq_ttl;
6045 /*
6046 * Is the operation here going to be a no-op ?
6047 */
6048 if (oifq == nifq) {
6049 if ((tqe->tqe_next == NULL) ||
6050 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6051 MUTEX_EXIT(&oifq->ifq_lock);
6052 return;
6053 }
6054 }
6055
6056 /*
6057 * Remove from the old queue
6058 */
6059 *tqe->tqe_pnext = tqe->tqe_next;
6060 if (tqe->tqe_next)
6061 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6062 else
6063 oifq->ifq_tail = tqe->tqe_pnext;
6064 tqe->tqe_next = NULL;
6065
6066 /*
6067 * If we're moving from one queue to another, release the
6068 * lock on the old queue and get a lock on the new queue.
6069 * For user defined queues, if we're moving off it, call
6070 * delete in case it can now be freed.
6071 */
6072 if (oifq != nifq) {
6073 tqe->tqe_ifq = NULL;
6074
6075 (void) ipf_deletetimeoutqueue(oifq);
6076
6077 MUTEX_EXIT(&oifq->ifq_lock);
6078
6079 MUTEX_ENTER(&nifq->ifq_lock);
6080
6081 tqe->tqe_ifq = nifq;
6082 nifq->ifq_ref++;
6083 }
6084
6085 /*
6086 * Add to the bottom of the new queue
6087 */
6088 tqe->tqe_pnext = nifq->ifq_tail;
6089 *nifq->ifq_tail = tqe;
6090 nifq->ifq_tail = &tqe->tqe_next;
6091 MUTEX_EXIT(&nifq->ifq_lock);
6092}
6093
6094
6095/* ------------------------------------------------------------------------ */
6096/* Function: ipf_updateipid */
6097/* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6098/* Parameters: fin(I) - pointer to packet information */
6099/* */
6100/* When we are doing NAT, change the IP of every packet to represent a */
6101/* single sequence of packets coming from the host, hiding any host */
6102/* specific sequencing that might otherwise be revealed. If the packet is */
6103/* a fragment, then store the 'new' IPid in the fragment cache and look up */
6104/* the fragment cache for non-leading fragments. If a non-leading fragment */
6105/* has no match in the cache, return an error. */
6106/* ------------------------------------------------------------------------ */
6107static int
6108ipf_updateipid(fin)
6109 fr_info_t *fin;
6110{
6111 u_short id, ido, sums;
6112 u_32_t sumd, sum;
6113 ip_t *ip;
6114
6115 ip = fin->fin_ip;
6116 ido = ntohs(ip->ip_id);
6117 if (fin->fin_off != 0) {
6118 sum = ipf_frag_ipidknown(fin);
6119 if (sum == 0xffffffff)
6120 return -1;
6121 sum &= 0xffff;
6122 id = (u_short)sum;
6123 ip->ip_id = htons(id);
6124 } else {
6125 ip_fillid(ip);
6126 id = ntohs(ip->ip_id);
6127 if ((fin->fin_flx & FI_FRAG) != 0)
6128 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6129 }
6130
6131 if (id == ido)
6132 return 0;
6133 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6134 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6135 sum += sumd;
6136 sum = (sum >> 16) + (sum & 0xffff);
6137 sum = (sum >> 16) + (sum & 0xffff);
6138 sums = ~(u_short)sum;
6139 ip->ip_sum = htons(sums);
6140 return 0;
6141}
6142
6143
6144#ifdef NEED_FRGETIFNAME
6145/* ------------------------------------------------------------------------ */
6146/* Function: ipf_getifname */
6147/* Returns: char * - pointer to interface name */
6148/* Parameters: ifp(I) - pointer to network interface */
6149/* buffer(O) - pointer to where to store interface name */
6150/* */
6151/* Constructs an interface name in the buffer passed. The buffer passed is */
6152/* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6153/* as a NULL pointer then return a pointer to a static array. */
6154/* ------------------------------------------------------------------------ */
6155char *
6156ipf_getifname(ifp, buffer)
6157 struct ifnet *ifp;
6158 char *buffer;
6159{
6160 static char namebuf[LIFNAMSIZ];
6161# if defined(MENTAT) || defined(__FreeBSD__)
6162 int unit, space;
6163 char temp[20];
6164 char *s;
6165# endif
6166
6167 if (buffer == NULL)
6168 buffer = namebuf;
6169 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6170 buffer[LIFNAMSIZ - 1] = '\0';
6171# if defined(MENTAT) || defined(__FreeBSD__)
6172 for (s = buffer; *s; s++)
6173 ;
6174 unit = ifp->if_unit;
6175 space = LIFNAMSIZ - (s - buffer);
6176 if ((space > 0) && (unit >= 0)) {
6177# if defined(SNPRINTF) && defined(_KERNEL)
6178 SNPRINTF(temp, sizeof(temp), "%d", unit);
6179# else
6180 (void) sprintf(temp, "%d", unit);
6181# endif
6182 (void) strncpy(s, temp, space);
6183 }
6184# endif
6185 return buffer;
6186}
6187#endif
6188
6189
6190/* ------------------------------------------------------------------------ */
6191/* Function: ipf_ioctlswitch */
6192/* Returns: int - -1 continue processing, else ioctl return value */
6193/* Parameters: unit(I) - device unit opened */
6194/* data(I) - pointer to ioctl data */
6195/* cmd(I) - ioctl command */
6196/* mode(I) - mode value */
6197/* uid(I) - uid making the ioctl call */
6198/* ctx(I) - pointer to context data */
6199/* */
6200/* Based on the value of unit, call the appropriate ioctl handler or return */
6201/* EIO if ipfilter is not running. Also checks if write perms are req'd */
6202/* for the device in order to execute the ioctl. A special case is made */
6203/* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6204/* The context data pointer is passed through as this is used as the key */
6205/* for locating a matching token for continued access for walking lists, */
6206/* etc. */
6207/* ------------------------------------------------------------------------ */
6208int
6209ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6210 ipf_main_softc_t *softc;
6211 int unit, mode, uid;
6212 ioctlcmd_t cmd;
6213 void *data, *ctx;
6214{
6215 int error = 0;
6216
6217 switch (cmd)
6218 {
6219 case SIOCIPFINTERROR :
6220 error = BCOPYOUT(&softc->ipf_interror, data,
6221 sizeof(softc->ipf_interror));
6222 if (error != 0) {
6223 IPFERROR(40);
6224 error = EFAULT;
6225 }
6226 return error;
6227 default :
6228 break;
6229 }
6230
6231 switch (unit)
6232 {
6233 case IPL_LOGIPF :
6234 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6235 break;
6236 case IPL_LOGNAT :
6237 if (softc->ipf_running > 0) {
6238 error = ipf_nat_ioctl(softc, data, cmd, mode,
6239 uid, ctx);
6240 } else {
6241 IPFERROR(42);
6242 error = EIO;
6243 }
6244 break;
6245 case IPL_LOGSTATE :
6246 if (softc->ipf_running > 0) {
6247 error = ipf_state_ioctl(softc, data, cmd, mode,
6248 uid, ctx);
6249 } else {
6250 IPFERROR(43);
6251 error = EIO;
6252 }
6253 break;
6254 case IPL_LOGAUTH :
6255 if (softc->ipf_running > 0) {
6256 error = ipf_auth_ioctl(softc, data, cmd, mode,
6257 uid, ctx);
6258 } else {
6259 IPFERROR(44);
6260 error = EIO;
6261 }
6262 break;
6263 case IPL_LOGSYNC :
6264 if (softc->ipf_running > 0) {
6265 error = ipf_sync_ioctl(softc, data, cmd, mode,
6266 uid, ctx);
6267 } else {
6268 error = EIO;
6269 IPFERROR(45);
6270 }
6271 break;
6272 case IPL_LOGSCAN :
6273#ifdef IPFILTER_SCAN
6274 if (softc->ipf_running > 0)
6275 error = ipf_scan_ioctl(softc, data, cmd, mode,
6276 uid, ctx);
6277 else
6278#endif
6279 {
6280 error = EIO;
6281 IPFERROR(46);
6282 }
6283 break;
6284 case IPL_LOGLOOKUP :
6285 if (softc->ipf_running > 0) {
6286 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6287 uid, ctx);
6288 } else {
6289 error = EIO;
6290 IPFERROR(47);
6291 }
6292 break;
6293 default :
6294 IPFERROR(48);
6295 error = EIO;
6296 break;
6297 }
6298
6299 return error;
6300}
6301
6302
6303/*
6304 * This array defines the expected size of objects coming into the kernel
6305 * for the various recognised object types. The first column is flags (see
6306 * below), 2nd column is current size, 3rd column is the version number of
6307 * when the current size became current.
6308 * Flags:
6309 * 1 = minimum size, not absolute size
6310 */
6311static const int ipf_objbytes[IPFOBJ_COUNT][3] = {
6312 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6313 { 1, sizeof(struct friostat), 5010000 },
6314 { 0, sizeof(struct fr_info), 5010000 },
6315 { 0, sizeof(struct ipf_authstat), 4010100 },
6316 { 0, sizeof(struct ipfrstat), 5010000 },
6317 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6318 { 0, sizeof(struct natstat), 5010000 },
6319 { 0, sizeof(struct ipstate_save), 5010000 },
6320 { 1, sizeof(struct nat_save), 5010000 },
6321 { 0, sizeof(struct natlookup), 5010000 },
6322 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6323 { 0, sizeof(struct ips_stat), 5010000 },
6324 { 0, sizeof(struct frauth), 5010000 },
6325 { 0, sizeof(struct ipftune), 4010100 },
6326 { 0, sizeof(struct nat), 5010000 },
6327 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6328 { 0, sizeof(struct ipfgeniter), 4011400 },
6329 { 0, sizeof(struct ipftable), 4011400 },
6330 { 0, sizeof(struct ipflookupiter), 4011400 },
6331 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6332 { 1, 0, 0 }, /* IPFEXPR */
6333 { 0, 0, 0 }, /* PROXYCTL */
6334 { 0, sizeof (struct fripf), 5010000 }
6335};
6336
6337
6338/* ------------------------------------------------------------------------ */
6339/* Function: ipf_inobj */
6340/* Returns: int - 0 = success, else failure */
6341/* Parameters: softc(I) - soft context pointerto work with */
6342/* data(I) - pointer to ioctl data */
6343/* objp(O) - where to store ipfobj structure */
6344/* ptr(I) - pointer to data to copy out */
6345/* type(I) - type of structure being moved */
6346/* */
6347/* Copy in the contents of what the ipfobj_t points to. In future, we */
6348/* add things to check for version numbers, sizes, etc, to make it backward */
6349/* compatible at the ABI for user land. */
6350/* If objp is not NULL then we assume that the caller wants to see what is */
6351/* in the ipfobj_t structure being copied in. As an example, this can tell */
6352/* the caller what version of ipfilter the ioctl program was written to. */
6353/* ------------------------------------------------------------------------ */
6354int
6355ipf_inobj(softc, data, objp, ptr, type)
6356 ipf_main_softc_t *softc;
6357 void *data;
6358 ipfobj_t *objp;
6359 void *ptr;
6360 int type;
6361{
6362 ipfobj_t obj;
6363 int error;
6364 int size;
6365
6366 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6367 IPFERROR(49);
6368 return EINVAL;
6369 }
6370
6371 if (objp == NULL)
6372 objp = &obj;
6373 error = BCOPYIN(data, objp, sizeof(*objp));
6374 if (error != 0) {
6375 IPFERROR(124);
6376 return EFAULT;
6377 }
6378
6379 if (objp->ipfo_type != type) {
6380 IPFERROR(50);
6381 return EINVAL;
6382 }
6383
6384 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6385 if ((ipf_objbytes[type][0] & 1) != 0) {
6386 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6387 IPFERROR(51);
6388 return EINVAL;
6389 }
6390 size = ipf_objbytes[type][1];
6391 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6392 size = objp->ipfo_size;
6393 } else {
6394 IPFERROR(52);
6395 return EINVAL;
6396 }
6397 error = COPYIN(objp->ipfo_ptr, ptr, size);
6398 if (error != 0) {
6399 IPFERROR(55);
6400 error = EFAULT;
6401 }
6402 } else {
6403#ifdef IPFILTER_COMPAT
6404 error = ipf_in_compat(softc, objp, ptr, 0);
6405#else
6406 IPFERROR(54);
6407 error = EINVAL;
6408#endif
6409 }
6410 return error;
6411}
6412
6413
6414/* ------------------------------------------------------------------------ */
6415/* Function: ipf_inobjsz */
6416/* Returns: int - 0 = success, else failure */
6417/* Parameters: softc(I) - soft context pointerto work with */
6418/* data(I) - pointer to ioctl data */
6419/* ptr(I) - pointer to store real data in */
6420/* type(I) - type of structure being moved */
6421/* sz(I) - size of data to copy */
6422/* */
6423/* As per ipf_inobj, except the size of the object to copy in is passed in */
6424/* but it must not be smaller than the size defined for the type and the */
6425/* type must allow for varied sized objects. The extra requirement here is */
6426/* that sz must match the size of the object being passed in - this is not */
6427/* not possible nor required in ipf_inobj(). */
6428/* ------------------------------------------------------------------------ */
6429int
6430ipf_inobjsz(softc, data, ptr, type, sz)
6431 ipf_main_softc_t *softc;
6432 void *data;
6433 void *ptr;
6434 int type, sz;
6435{
6436 ipfobj_t obj;
6437 int error;
6438
6439 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6440 IPFERROR(56);
6441 return EINVAL;
6442 }
6443
6444 error = BCOPYIN(data, &obj, sizeof(obj));
6445 if (error != 0) {
6446 IPFERROR(125);
6447 return EFAULT;
6448 }
6449
6450 if (obj.ipfo_type != type) {
6451 IPFERROR(58);
6452 return EINVAL;
6453 }
6454
6455 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6456 if (((ipf_objbytes[type][0] & 1) == 0) ||
6457 (sz < ipf_objbytes[type][1])) {
6458 IPFERROR(57);
6459 return EINVAL;
6460 }
6461 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6462 if (error != 0) {
6463 IPFERROR(61);
6464 error = EFAULT;
6465 }
6466 } else {
6467#ifdef IPFILTER_COMPAT
6468 error = ipf_in_compat(softc, &obj, ptr, sz);
6469#else
6470 IPFERROR(60);
6471 error = EINVAL;
6472#endif
6473 }
6474 return error;
6475}
6476
6477
6478/* ------------------------------------------------------------------------ */
6479/* Function: ipf_outobjsz */
6480/* Returns: int - 0 = success, else failure */
6481/* Parameters: data(I) - pointer to ioctl data */
6482/* ptr(I) - pointer to store real data in */
6483/* type(I) - type of structure being moved */
6484/* sz(I) - size of data to copy */
6485/* */
6486/* As per ipf_outobj, except the size of the object to copy out is passed in*/
6487/* but it must not be smaller than the size defined for the type and the */
6488/* type must allow for varied sized objects. The extra requirement here is */
6489/* that sz must match the size of the object being passed in - this is not */
6490/* not possible nor required in ipf_outobj(). */
6491/* ------------------------------------------------------------------------ */
6492int
6493ipf_outobjsz(softc, data, ptr, type, sz)
6494 ipf_main_softc_t *softc;
6495 void *data;
6496 void *ptr;
6497 int type, sz;
6498{
6499 ipfobj_t obj;
6500 int error;
6501
6502 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6503 IPFERROR(62);
6504 return EINVAL;
6505 }
6506
6507 error = BCOPYIN(data, &obj, sizeof(obj));
6508 if (error != 0) {
6509 IPFERROR(127);
6510 return EFAULT;
6511 }
6512
6513 if (obj.ipfo_type != type) {
6514 IPFERROR(63);
6515 return EINVAL;
6516 }
6517
6518 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6519 if (((ipf_objbytes[type][0] & 1) == 0) ||
6520 (sz < ipf_objbytes[type][1])) {
6521 IPFERROR(146);
6522 return EINVAL;
6523 }
6524 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6525 if (error != 0) {
6526 IPFERROR(66);
6527 error = EFAULT;
6528 }
6529 } else {
6530#ifdef IPFILTER_COMPAT
6531 error = ipf_out_compat(softc, &obj, ptr);
6532#else
6533 IPFERROR(65);
6534 error = EINVAL;
6535#endif
6536 }
6537 return error;
6538}
6539
6540
6541/* ------------------------------------------------------------------------ */
6542/* Function: ipf_outobj */
6543/* Returns: int - 0 = success, else failure */
6544/* Parameters: data(I) - pointer to ioctl data */
6545/* ptr(I) - pointer to store real data in */
6546/* type(I) - type of structure being moved */
6547/* */
6548/* Copy out the contents of what ptr is to where ipfobj points to. In */
6549/* future, we add things to check for version numbers, sizes, etc, to make */
6550/* it backward compatible at the ABI for user land. */
6551/* ------------------------------------------------------------------------ */
6552int
6553ipf_outobj(softc, data, ptr, type)
6554 ipf_main_softc_t *softc;
6555 void *data;
6556 void *ptr;
6557 int type;
6558{
6559 ipfobj_t obj;
6560 int error;
6561
6562 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6563 IPFERROR(67);
6564 return EINVAL;
6565 }
6566
6567 error = BCOPYIN(data, &obj, sizeof(obj));
6568 if (error != 0) {
6569 IPFERROR(126);
6570 return EFAULT;
6571 }
6572
6573 if (obj.ipfo_type != type) {
6574 IPFERROR(68);
6575 return EINVAL;
6576 }
6577
6578 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6579 if ((ipf_objbytes[type][0] & 1) != 0) {
6580 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6581 IPFERROR(69);
6582 return EINVAL;
6583 }
6584 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6585 IPFERROR(70);
6586 return EINVAL;
6587 }
6588
6589 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6590 if (error != 0) {
6591 IPFERROR(73);
6592 error = EFAULT;
6593 }
6594 } else {
6595#ifdef IPFILTER_COMPAT
6596 error = ipf_out_compat(softc, &obj, ptr);
6597#else
6598 IPFERROR(72);
6599 error = EINVAL;
6600#endif
6601 }
6602 return error;
6603}
6604
6605
6606/* ------------------------------------------------------------------------ */
6607/* Function: ipf_outobjk */
6608/* Returns: int - 0 = success, else failure */
6609/* Parameters: obj(I) - pointer to data description structure */
6610/* ptr(I) - pointer to kernel data to copy out */
6611/* */
6612/* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6613/* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6614/* already populated with information and now we just need to use it. */
6615/* There is no need for this function to have a "type" parameter as there */
6616/* is no point in validating information that comes from the kernel with */
6617/* itself. */
6618/* ------------------------------------------------------------------------ */
6619int
6620ipf_outobjk(softc, obj, ptr)
6621 ipf_main_softc_t *softc;
6622 ipfobj_t *obj;
6623 void *ptr;
6624{
6625 int type = obj->ipfo_type;
6626 int error;
6627
6628 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6629 IPFERROR(147);
6630 return EINVAL;
6631 }
6632
6633 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6634 if ((ipf_objbytes[type][0] & 1) != 0) {
6635 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6636 IPFERROR(148);
6637 return EINVAL;
6638 }
6639
6640 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6641 IPFERROR(149);
6642 return EINVAL;
6643 }
6644
6645 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6646 if (error != 0) {
6647 IPFERROR(150);
6648 error = EFAULT;
6649 }
6650 } else {
6651#ifdef IPFILTER_COMPAT
6652 error = ipf_out_compat(softc, obj, ptr);
6653#else
6654 IPFERROR(151);
6655 error = EINVAL;
6656#endif
6657 }
6658 return error;
6659}
6660
6661
6662/* ------------------------------------------------------------------------ */
6663/* Function: ipf_checkl4sum */
6664/* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6665/* Parameters: fin(I) - pointer to packet information */
6666/* */
6667/* If possible, calculate the layer 4 checksum for the packet. If this is */
6668/* not possible, return without indicating a failure or success but in a */
6669/* way that is ditinguishable. This function should only be called by the */
6670/* ipf_checkv6sum() for each platform. */
6671/* ------------------------------------------------------------------------ */
6672INLINE int
6673ipf_checkl4sum(fin)
6674 fr_info_t *fin;
6675{
6676 u_short sum, hdrsum, *csump;
6677 udphdr_t *udp;
6678 int dosum;
6679
6680 /*
6681 * If the TCP packet isn't a fragment, isn't too short and otherwise
6682 * isn't already considered "bad", then validate the checksum. If
6683 * this check fails then considered the packet to be "bad".
6684 */
6685 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6686 return 1;
6687
6688 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6689 if (fin->fin_out == 1) {
6690 fin->fin_cksum = FI_CK_SUMOK;
6691 return 0;
6692 }
6693
6694 csump = NULL;
6695 hdrsum = 0;
6696 dosum = 0;
6697 sum = 0;
6698
6699 switch (fin->fin_p)
6700 {
6701 case IPPROTO_TCP :
6702 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6703 dosum = 1;
6704 break;
6705
6706 case IPPROTO_UDP :
6707 udp = fin->fin_dp;
6708 if (udp->uh_sum != 0) {
6709 csump = &udp->uh_sum;
6710 dosum = 1;
6711 }
6712 break;
6713
6714#ifdef USE_INET6
6715 case IPPROTO_ICMPV6 :
6716 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6717 dosum = 1;
6718 break;
6719#endif
6720
6721 case IPPROTO_ICMP :
6722 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6723 dosum = 1;
6724 break;
6725
6726 default :
6727 return 1;
6728 /*NOTREACHED*/
6729 }
6730
6731 if (csump != NULL) {
6732 hdrsum = *csump;
6733 if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6734 hdrsum = 0x0000;
6735 }
6736
6737 if (dosum) {
6738 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6739 }
6740#if !defined(_KERNEL)
6741 if (sum == hdrsum) {
6742 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6743 } else {
6744 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6745 }
6746#endif
6747 DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6748#ifdef USE_INET6
6749 if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6750#else
6751 if (hdrsum == sum) {
6752#endif
6753 fin->fin_cksum = FI_CK_SUMOK;
6754 return 0;
6755 }
6756 fin->fin_cksum = FI_CK_BAD;
6757 return -1;
6758}
6759
6760
6761/* ------------------------------------------------------------------------ */
6762/* Function: ipf_ifpfillv4addr */
6763/* Returns: int - 0 = address update, -1 = address not updated */
6764/* Parameters: atype(I) - type of network address update to perform */
6765/* sin(I) - pointer to source of address information */
6766/* mask(I) - pointer to source of netmask information */
6767/* inp(I) - pointer to destination address store */
6768/* inpmask(I) - pointer to destination netmask store */
6769/* */
6770/* Given a type of network address update (atype) to perform, copy */
6771/* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6772/* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6773/* which case the operation fails. For all values of atype other than */
6774/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6775/* value. */
6776/* ------------------------------------------------------------------------ */
6777int
6778ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6779 int atype;
6780 struct sockaddr_in *sin, *mask;
6781 struct in_addr *inp, *inpmask;
6782{
6783 if (inpmask != NULL && atype != FRI_NETMASKED)
6784 inpmask->s_addr = 0xffffffff;
6785
6786 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6787 if (atype == FRI_NETMASKED) {
6788 if (inpmask == NULL)
6789 return -1;
6790 inpmask->s_addr = mask->sin_addr.s_addr;
6791 }
6792 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6793 } else {
6794 inp->s_addr = sin->sin_addr.s_addr;
6795 }
6796 return 0;
6797}
6798
6799
6800#ifdef USE_INET6
6801/* ------------------------------------------------------------------------ */
6802/* Function: ipf_ifpfillv6addr */
6803/* Returns: int - 0 = address update, -1 = address not updated */
6804/* Parameters: atype(I) - type of network address update to perform */
6805/* sin(I) - pointer to source of address information */
6806/* mask(I) - pointer to source of netmask information */
6807/* inp(I) - pointer to destination address store */
6808/* inpmask(I) - pointer to destination netmask store */
6809/* */
6810/* Given a type of network address update (atype) to perform, copy */
6811/* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6812/* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6813/* which case the operation fails. For all values of atype other than */
6814/* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6815/* value. */
6816/* ------------------------------------------------------------------------ */
6817int
6818ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6819 int atype;
6820 struct sockaddr_in6 *sin, *mask;
6821 i6addr_t *inp, *inpmask;
6822{
6823 i6addr_t *src, *and;
6824
6825 src = (i6addr_t *)&sin->sin6_addr;
6826 and = (i6addr_t *)&mask->sin6_addr;
6827
6828 if (inpmask != NULL && atype != FRI_NETMASKED) {
6829 inpmask->i6[0] = 0xffffffff;
6830 inpmask->i6[1] = 0xffffffff;
6831 inpmask->i6[2] = 0xffffffff;
6832 inpmask->i6[3] = 0xffffffff;
6833 }
6834
6835 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6836 if (atype == FRI_NETMASKED) {
6837 if (inpmask == NULL)
6838 return -1;
6839 inpmask->i6[0] = and->i6[0];
6840 inpmask->i6[1] = and->i6[1];
6841 inpmask->i6[2] = and->i6[2];
6842 inpmask->i6[3] = and->i6[3];
6843 }
6844
6845 inp->i6[0] = src->i6[0] & and->i6[0];
6846 inp->i6[1] = src->i6[1] & and->i6[1];
6847 inp->i6[2] = src->i6[2] & and->i6[2];
6848 inp->i6[3] = src->i6[3] & and->i6[3];
6849 } else {
6850 inp->i6[0] = src->i6[0];
6851 inp->i6[1] = src->i6[1];
6852 inp->i6[2] = src->i6[2];
6853 inp->i6[3] = src->i6[3];
6854 }
6855 return 0;
6856}
6857#endif
6858
6859
6860/* ------------------------------------------------------------------------ */
6861/* Function: ipf_matchtag */
6862/* Returns: 0 == mismatch, 1 == match. */
6863/* Parameters: tag1(I) - pointer to first tag to compare */
6864/* tag2(I) - pointer to second tag to compare */
6865/* */
6866/* Returns true (non-zero) or false(0) if the two tag structures can be */
6867/* considered to be a match or not match, respectively. The tag is 16 */
6868/* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6869/* compare the ints instead, for speed. tag1 is the master of the */
6870/* comparison. This function should only be called with both tag1 and tag2 */
6871/* as non-NULL pointers. */
6872/* ------------------------------------------------------------------------ */
6873int
6874ipf_matchtag(tag1, tag2)
6875 ipftag_t *tag1, *tag2;
6876{
6877 if (tag1 == tag2)
6878 return 1;
6879
6880 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6881 return 1;
6882
6883 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6884 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6885 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6886 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6887 return 1;
6888 return 0;
6889}
6890
6891
6892/* ------------------------------------------------------------------------ */
6893/* Function: ipf_coalesce */
6894/* Returns: 1 == success, -1 == failure, 0 == no change */
6895/* Parameters: fin(I) - pointer to packet information */
6896/* */
6897/* Attempt to get all of the packet data into a single, contiguous buffer. */
6898/* If this call returns a failure then the buffers have also been freed. */
6899/* ------------------------------------------------------------------------ */
6900int
6901ipf_coalesce(fin)
6902 fr_info_t *fin;
6903{
6904
6905 if ((fin->fin_flx & FI_COALESCE) != 0)
6906 return 1;
6907
6908 /*
6909 * If the mbuf pointers indicate that there is no mbuf to work with,
6910 * return but do not indicate success or failure.
6911 */
6912 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6913 return 0;
6914
6915#if defined(_KERNEL)
6916 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6917 ipf_main_softc_t *softc = fin->fin_main_soft;
6918
6919 DT1(frb_coalesce, fr_info_t *, fin);
6920 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6921# ifdef MENTAT
6922 FREE_MB_T(*fin->fin_mp);
6923# endif
6924 fin->fin_reason = FRB_COALESCE;
6925 *fin->fin_mp = NULL;
6926 fin->fin_m = NULL;
6927 return -1;
6928 }
6929#else
6930 fin = fin; /* LINT */
6931#endif
6932 return 1;
6933}
6934
6935
6936/*
6937 * The following table lists all of the tunable variables that can be
6938 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6939 * in the table below is as follows:
6940 *
6941 * pointer to value, name of value, minimum, maximum, size of the value's
6942 * container, value attribute flags
6943 *
6944 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6945 * means the value can only be written to when IPFilter is loaded but disabled.
6946 * The obvious implication is if neither of these are set then the value can be
6947 * changed at any time without harm.
6948 */
6949
6950
6951/* ------------------------------------------------------------------------ */
6952/* Function: ipf_tune_findbycookie */
6953/* Returns: NULL = search failed, else pointer to tune struct */
6954/* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6955/* next(O) - pointer to place to store the cookie for the */
6956/* "next" tuneable, if it is desired. */
6957/* */
6958/* This function is used to walk through all of the existing tunables with */
6959/* successive calls. It searches the known tunables for the one which has */
6960/* a matching value for "cookie" - ie its address. When returning a match, */
6961/* the next one to be found may be returned inside next. */
6962/* ------------------------------------------------------------------------ */
6963static ipftuneable_t *
6964ipf_tune_findbycookie(ptop, cookie, next)
6965 ipftuneable_t **ptop;
6966 void *cookie, **next;
6967{
6968 ipftuneable_t *ta, **tap;
6969
6970 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6971 if (ta == cookie) {
6972 if (next != NULL) {
6973 /*
6974 * If the next entry in the array has a name
6975 * present, then return a pointer to it for
6976 * where to go next, else return a pointer to
6977 * the dynaminc list as a key to search there
6978 * next. This facilitates a weak linking of
6979 * the two "lists" together.
6980 */
6981 if ((ta + 1)->ipft_name != NULL)
6982 *next = ta + 1;
6983 else
6984 *next = ptop;
6985 }
6986 return ta;
6987 }
6988
6989 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6990 if (tap == cookie) {
6991 if (next != NULL)
6992 *next = &ta->ipft_next;
6993 return ta;
6994 }
6995
6996 if (next != NULL)
6997 *next = NULL;
6998 return NULL;
6999}
7000
7001
7002/* ------------------------------------------------------------------------ */
7003/* Function: ipf_tune_findbyname */
7004/* Returns: NULL = search failed, else pointer to tune struct */
7005/* Parameters: name(I) - name of the tuneable entry to find. */
7006/* */
7007/* Search the static array of tuneables and the list of dynamic tuneables */
7008/* for an entry with a matching name. If we can find one, return a pointer */
7009/* to the matching structure. */
7010/* ------------------------------------------------------------------------ */
7011static ipftuneable_t *
7012ipf_tune_findbyname(top, name)
7013 ipftuneable_t *top;
7014 const char *name;
7015{
7016 ipftuneable_t *ta;
7017
7018 for (ta = top; ta != NULL; ta = ta->ipft_next)
7019 if (!strcmp(ta->ipft_name, name)) {
7020 return ta;
7021 }
7022
7023 return NULL;
7024}
7025
7026
7027/* ------------------------------------------------------------------------ */
7028/* Function: ipf_tune_add_array */
7029/* Returns: int - 0 == success, else failure */
7030/* Parameters: newtune - pointer to new tune array to add to tuneables */
7031/* */
7032/* Appends tune structures from the array passed in (newtune) to the end of */
7033/* the current list of "dynamic" tuneable parameters. */
7034/* If any entry to be added is already present (by name) then the operation */
7035/* is aborted - entries that have been added are removed before returning. */
7036/* An entry with no name (NULL) is used as the indication that the end of */
7037/* the array has been reached. */
7038/* ------------------------------------------------------------------------ */
7039int
7040ipf_tune_add_array(softc, newtune)
7041 ipf_main_softc_t *softc;
7042 ipftuneable_t *newtune;
7043{
7044 ipftuneable_t *nt, *dt;
7045 int error = 0;
7046
7047 for (nt = newtune; nt->ipft_name != NULL; nt++) {
7048 error = ipf_tune_add(softc, nt);
7049 if (error != 0) {
7050 for (dt = newtune; dt != nt; dt++) {
7051 (void) ipf_tune_del(softc, dt);
7052 }
7053 }
7054 }
7055
7056 return error;
7057}
7058
7059
7060/* ------------------------------------------------------------------------ */
7061/* Function: ipf_tune_array_link */
7062/* Returns: 0 == success, -1 == failure */
7063/* Parameters: softc(I) - soft context pointerto work with */
7064/* array(I) - pointer to an array of tuneables */
7065/* */
7066/* Given an array of tunables (array), append them to the current list of */
7067/* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7068/* the array for being appended to the list, initialise all of the next */
7069/* pointers so we don't need to walk parts of it with ++ and others with */
7070/* next. The array is expected to have an entry with a NULL name as the */
7071/* terminator. Trying to add an array with no non-NULL names will return as */
7072/* a failure. */
7073/* ------------------------------------------------------------------------ */
7074int
7075ipf_tune_array_link(softc, array)
7076 ipf_main_softc_t *softc;
7077 ipftuneable_t *array;
7078{
7079 ipftuneable_t *t, **p;
7080
7081 t = array;
7082 if (t->ipft_name == NULL)
7083 return -1;
7084
7085 for (; t[1].ipft_name != NULL; t++)
7086 t[0].ipft_next = &t[1];
7087 t->ipft_next = NULL;
7088
7089 /*
7090 * Since a pointer to the last entry isn't kept, we need to find it
7091 * each time we want to add new variables to the list.
7092 */
7093 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7094 if (t->ipft_name == NULL)
7095 break;
7096 *p = array;
7097
7098 return 0;
7099}
7100
7101
7102/* ------------------------------------------------------------------------ */
7103/* Function: ipf_tune_array_unlink */
7104/* Returns: 0 == success, -1 == failure */
7105/* Parameters: softc(I) - soft context pointerto work with */
7106/* array(I) - pointer to an array of tuneables */
7107/* */
7108/* ------------------------------------------------------------------------ */
7109int
7110ipf_tune_array_unlink(softc, array)
7111 ipf_main_softc_t *softc;
7112 ipftuneable_t *array;
7113{
7114 ipftuneable_t *t, **p;
7115
7116 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7117 if (t == array)
7118 break;
7119 if (t == NULL)
7120 return -1;
7121
7122 for (; t[1].ipft_name != NULL; t++)
7123 ;
7124
7125 *p = t->ipft_next;
7126
7127 return 0;
7128}
7129
7130
7131/* ------------------------------------------------------------------------ */
7132/* Function: ipf_tune_array_copy */
7133/* Returns: NULL = failure, else pointer to new array */
7134/* Parameters: base(I) - pointer to structure base */
7135/* size(I) - size of the array at template */
7136/* template(I) - original array to copy */
7137/* */
7138/* Allocate memory for a new set of tuneable values and copy everything */
7139/* from template into the new region of memory. The new region is full of */
7140/* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7141/* */
7142/* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7143/* In the array template, ipftp_offset is the offset (in bytes) of the */
7144/* location of the tuneable value inside the structure pointed to by base. */
7145/* As ipftp_offset is a union over the pointers to the tuneable values, if */
7146/* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7147/* ipftp_void that points to the stored value. */
7148/* ------------------------------------------------------------------------ */
7149ipftuneable_t *
7150ipf_tune_array_copy(base, size, template)
7151 void *base;
7152 size_t size;
7153 ipftuneable_t *template;
7154{
7155 ipftuneable_t *copy;
7156 int i;
7157
7158
7159 KMALLOCS(copy, ipftuneable_t *, size);
7160 if (copy == NULL) {
7161 return NULL;
7162 }
7163 bcopy(template, copy, size);
7164
7165 for (i = 0; copy[i].ipft_name; i++) {
7166 copy[i].ipft_una.ipftp_offset += (u_long)base;
7167 copy[i].ipft_next = copy + i + 1;
7168 }
7169
7170 return copy;
7171}
7172
7173
7174/* ------------------------------------------------------------------------ */
7175/* Function: ipf_tune_add */
7176/* Returns: int - 0 == success, else failure */
7177/* Parameters: newtune - pointer to new tune entry to add to tuneables */
7178/* */
7179/* Appends tune structures from the array passed in (newtune) to the end of */
7180/* the current list of "dynamic" tuneable parameters. Once added, the */
7181/* owner of the object is not expected to ever change "ipft_next". */
7182/* ------------------------------------------------------------------------ */
7183int
7184ipf_tune_add(softc, newtune)
7185 ipf_main_softc_t *softc;
7186 ipftuneable_t *newtune;
7187{
7188 ipftuneable_t *ta, **tap;
7189
7190 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7191 if (ta != NULL) {
7192 IPFERROR(74);
7193 return EEXIST;
7194 }
7195
7196 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7197 ;
7198
7199 newtune->ipft_next = NULL;
7200 *tap = newtune;
7201 return 0;
7202}
7203
7204
7205/* ------------------------------------------------------------------------ */
7206/* Function: ipf_tune_del */
7207/* Returns: int - 0 == success, else failure */
7208/* Parameters: oldtune - pointer to tune entry to remove from the list of */
7209/* current dynamic tuneables */
7210/* */
7211/* Search for the tune structure, by pointer, in the list of those that are */
7212/* dynamically added at run time. If found, adjust the list so that this */
7213/* structure is no longer part of it. */
7214/* ------------------------------------------------------------------------ */
7215int
7216ipf_tune_del(softc, oldtune)
7217 ipf_main_softc_t *softc;
7218 ipftuneable_t *oldtune;
7219{
7220 ipftuneable_t *ta, **tap;
7221 int error = 0;
7222
7223 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7224 tap = &ta->ipft_next) {
7225 if (ta == oldtune) {
7226 *tap = oldtune->ipft_next;
7227 oldtune->ipft_next = NULL;
7228 break;
7229 }
7230 }
7231
7232 if (ta == NULL) {
7233 error = ESRCH;
7234 IPFERROR(75);
7235 }
7236 return error;
7237}
7238
7239
7240/* ------------------------------------------------------------------------ */
7241/* Function: ipf_tune_del_array */
7242/* Returns: int - 0 == success, else failure */
7243/* Parameters: oldtune - pointer to tuneables array */
7244/* */
7245/* Remove each tuneable entry in the array from the list of "dynamic" */
7246/* tunables. If one entry should fail to be found, an error will be */
7247/* returned and no further ones removed. */
7248/* An entry with a NULL name is used as the indicator of the last entry in */
7249/* the array. */
7250/* ------------------------------------------------------------------------ */
7251int
7252ipf_tune_del_array(softc, oldtune)
7253 ipf_main_softc_t *softc;
7254 ipftuneable_t *oldtune;
7255{
7256 ipftuneable_t *ot;
7257 int error = 0;
7258
7259 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7260 error = ipf_tune_del(softc, ot);
7261 if (error != 0)
7262 break;
7263 }
7264
7265 return error;
7266
7267}
7268
7269
7270/* ------------------------------------------------------------------------ */
7271/* Function: ipf_tune */
7272/* Returns: int - 0 == success, else failure */
7273/* Parameters: cmd(I) - ioctl command number */
7274/* data(I) - pointer to ioctl data structure */
7275/* */
7276/* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7277/* three ioctls provide the means to access and control global variables */
7278/* within IPFilter, allowing (for example) timeouts and table sizes to be */
7279/* changed without rebooting, reloading or recompiling. The initialisation */
7280/* and 'destruction' routines of the various components of ipfilter are all */
7281/* each responsible for handling their own values being too big. */
7282/* ------------------------------------------------------------------------ */
7283int
7284ipf_ipftune(softc, cmd, data)
7285 ipf_main_softc_t *softc;
7286 ioctlcmd_t cmd;
7287 void *data;
7288{
7289 ipftuneable_t *ta;
7290 ipftune_t tu;
7291 void *cookie;
7292 int error;
7293
7294 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7295 if (error != 0)
7296 return error;
7297
7298 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7299 cookie = tu.ipft_cookie;
7300 ta = NULL;
7301
7302 switch (cmd)
7303 {
7304 case SIOCIPFGETNEXT :
7305 /*
7306 * If cookie is non-NULL, assume it to be a pointer to the last
7307 * entry we looked at, so find it (if possible) and return a
7308 * pointer to the next one after it. The last entry in the
7309 * the table is a NULL entry, so when we get to it, set cookie
7310 * to NULL and return that, indicating end of list, erstwhile
7311 * if we come in with cookie set to NULL, we are starting anew
7312 * at the front of the list.
7313 */
7314 if (cookie != NULL) {
7315 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7316 cookie, &tu.ipft_cookie);
7317 } else {
7318 ta = softc->ipf_tuners;
7319 tu.ipft_cookie = ta + 1;
7320 }
7321 if (ta != NULL) {
7322 /*
7323 * Entry found, but does the data pointed to by that
7324 * row fit in what we can return?
7325 */
7326 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7327 IPFERROR(76);
7328 return EINVAL;
7329 }
7330
7331 tu.ipft_vlong = 0;
7332 if (ta->ipft_sz == sizeof(u_long))
7333 tu.ipft_vlong = *ta->ipft_plong;
7334 else if (ta->ipft_sz == sizeof(u_int))
7335 tu.ipft_vint = *ta->ipft_pint;
7336 else if (ta->ipft_sz == sizeof(u_short))
7337 tu.ipft_vshort = *ta->ipft_pshort;
7338 else if (ta->ipft_sz == sizeof(u_char))
7339 tu.ipft_vchar = *ta->ipft_pchar;
7340
7341 tu.ipft_sz = ta->ipft_sz;
7342 tu.ipft_min = ta->ipft_min;
7343 tu.ipft_max = ta->ipft_max;
7344 tu.ipft_flags = ta->ipft_flags;
7345 bcopy(ta->ipft_name, tu.ipft_name,
7346 MIN(sizeof(tu.ipft_name),
7347 strlen(ta->ipft_name) + 1));
7348 }
7349 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7350 break;
7351
7352 case SIOCIPFGET :
7353 case SIOCIPFSET :
7354 /*
7355 * Search by name or by cookie value for a particular entry
7356 * in the tuning paramter table.
7357 */
7358 IPFERROR(77);
7359 error = ESRCH;
7360 if (cookie != NULL) {
7361 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7362 cookie, NULL);
7363 if (ta != NULL)
7364 error = 0;
7365 } else if (tu.ipft_name[0] != '\0') {
7366 ta = ipf_tune_findbyname(softc->ipf_tuners,
7367 tu.ipft_name);
7368 if (ta != NULL)
7369 error = 0;
7370 }
7371 if (error != 0)
7372 break;
7373
7374 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7375 /*
7376 * Fetch the tuning parameters for a particular value
7377 */
7378 tu.ipft_vlong = 0;
7379 if (ta->ipft_sz == sizeof(u_long))
7380 tu.ipft_vlong = *ta->ipft_plong;
7381 else if (ta->ipft_sz == sizeof(u_int))
7382 tu.ipft_vint = *ta->ipft_pint;
7383 else if (ta->ipft_sz == sizeof(u_short))
7384 tu.ipft_vshort = *ta->ipft_pshort;
7385 else if (ta->ipft_sz == sizeof(u_char))
7386 tu.ipft_vchar = *ta->ipft_pchar;
7387 tu.ipft_cookie = ta;
7388 tu.ipft_sz = ta->ipft_sz;
7389 tu.ipft_min = ta->ipft_min;
7390 tu.ipft_max = ta->ipft_max;
7391 tu.ipft_flags = ta->ipft_flags;
7392 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7393
7394 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7395 /*
7396 * Set an internal parameter. The hard part here is
7397 * getting the new value safely and correctly out of
7398 * the kernel (given we only know its size, not type.)
7399 */
7400 u_long in;
7401
7402 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7403 (softc->ipf_running > 0)) {
7404 IPFERROR(78);
7405 error = EBUSY;
7406 break;
7407 }
7408
7409 in = tu.ipft_vlong;
7410 if (in < ta->ipft_min || in > ta->ipft_max) {
7411 IPFERROR(79);
7412 error = EINVAL;
7413 break;
7414 }
7415
7416 if (ta->ipft_func != NULL) {
7417 SPL_INT(s);
7418
7419 SPL_NET(s);
7420 error = (*ta->ipft_func)(softc, ta,
7421 &tu.ipft_un);
7422 SPL_X(s);
7423
7424 } else if (ta->ipft_sz == sizeof(u_long)) {
7425 tu.ipft_vlong = *ta->ipft_plong;
7426 *ta->ipft_plong = in;
7427
7428 } else if (ta->ipft_sz == sizeof(u_int)) {
7429 tu.ipft_vint = *ta->ipft_pint;
7430 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7431
7432 } else if (ta->ipft_sz == sizeof(u_short)) {
7433 tu.ipft_vshort = *ta->ipft_pshort;
7434 *ta->ipft_pshort = (u_short)(in & 0xffff);
7435
7436 } else if (ta->ipft_sz == sizeof(u_char)) {
7437 tu.ipft_vchar = *ta->ipft_pchar;
7438 *ta->ipft_pchar = (u_char)(in & 0xff);
7439 }
7440 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7441 }
7442 break;
7443
7444 default :
7445 IPFERROR(80);
7446 error = EINVAL;
7447 break;
7448 }
7449
7450 return error;
7451}
7452
7453
7454/* ------------------------------------------------------------------------ */
7455/* Function: ipf_zerostats */
7456/* Returns: int - 0 = success, else failure */
7457/* Parameters: data(O) - pointer to pointer for copying data back to */
7458/* */
7459/* Copies the current statistics out to userspace and then zero's the */
7460/* current ones in the kernel. The lock is only held across the bzero() as */
7461/* the copyout may result in paging (ie network activity.) */
7462/* ------------------------------------------------------------------------ */
7463int
7464ipf_zerostats(softc, data)
7465 ipf_main_softc_t *softc;
7466 caddr_t data;
7467{
7468 friostat_t fio;
7469 ipfobj_t obj;
7470 int error;
7471
7472 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7473 if (error != 0)
7474 return error;
7475 ipf_getstat(softc, &fio, obj.ipfo_rev);
7476 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7477 if (error != 0)
7478 return error;
7479
7480 WRITE_ENTER(&softc->ipf_mutex);
7481 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7482 RWLOCK_EXIT(&softc->ipf_mutex);
7483
7484 return 0;
7485}
7486
7487
7488/* ------------------------------------------------------------------------ */
7489/* Function: ipf_resolvedest */
7490/* Returns: Nil */
7491/* Parameters: softc(I) - pointer to soft context main structure */
7492/* base(I) - where strings are stored */
7493/* fdp(IO) - pointer to destination information to resolve */
7494/* v(I) - IP protocol version to match */
7495/* */
7496/* Looks up an interface name in the frdest structure pointed to by fdp and */
7497/* if a matching name can be found for the particular IP protocol version */
7498/* then store the interface pointer in the frdest struct. If no match is */
7499/* found, then set the interface pointer to be -1 as NULL is considered to */
7500/* indicate there is no information at all in the structure. */
7501/* ------------------------------------------------------------------------ */
7502int
7503ipf_resolvedest(softc, base, fdp, v)
7504 ipf_main_softc_t *softc;
7505 char *base;
7506 frdest_t *fdp;
7507 int v;
7508{
7509 int errval = 0;
7510 void *ifp;
7511
7512 ifp = NULL;
7513
7514 if (fdp->fd_name != -1) {
7515 if (fdp->fd_type == FRD_DSTLIST) {
7516 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7517 IPLT_DSTLIST,
7518 base + fdp->fd_name,
7519 NULL);
7520 if (ifp == NULL) {
7521 IPFERROR(144);
7522 errval = ESRCH;
7523 }
7524 } else {
7525 ifp = GETIFP(base + fdp->fd_name, v);
7526 if (ifp == NULL)
7527 ifp = (void *)-1;
7528 }
7529 }
7530 fdp->fd_ptr = ifp;
7531
7532 return errval;
7533}
7534
7535
7536/* ------------------------------------------------------------------------ */
7537/* Function: ipf_resolvenic */
7538/* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7539/* pointer to interface structure for NIC */
7540/* Parameters: softc(I)- pointer to soft context main structure */
7541/* name(I) - complete interface name */
7542/* v(I) - IP protocol version */
7543/* */
7544/* Look for a network interface structure that firstly has a matching name */
7545/* to that passed in and that is also being used for that IP protocol */
7546/* version (necessary on some platforms where there are separate listings */
7547/* for both IPv4 and IPv6 on the same physical NIC. */
7548/* ------------------------------------------------------------------------ */
7549void *
7550ipf_resolvenic(softc, name, v)
7551 ipf_main_softc_t *softc;
7552 char *name;
7553 int v;
7554{
7555 void *nic;
7556
7557 softc = softc; /* gcc -Wextra */
7558 if (name[0] == '\0')
7559 return NULL;
7560
7561 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7562 return NULL;
7563 }
7564
7565 nic = GETIFP(name, v);
7566 if (nic == NULL)
7567 nic = (void *)-1;
7568 return nic;
7569}
7570
7571
7572/* ------------------------------------------------------------------------ */
7573/* Function: ipf_token_expire */
7574/* Returns: None. */
7575/* Parameters: softc(I) - pointer to soft context main structure */
7576/* */
7577/* This function is run every ipf tick to see if there are any tokens that */
7578/* have been held for too long and need to be freed up. */
7579/* ------------------------------------------------------------------------ */
7580void
7581ipf_token_expire(softc)
7582 ipf_main_softc_t *softc;
7583{
7584 ipftoken_t *it;
7585
7586 WRITE_ENTER(&softc->ipf_tokens);
7587 while ((it = softc->ipf_token_head) != NULL) {
7588 if (it->ipt_die > softc->ipf_ticks)
7589 break;
7590
7591 ipf_token_deref(softc, it);
7592 }
7593 RWLOCK_EXIT(&softc->ipf_tokens);
7594}
7595
7596
7597/* ------------------------------------------------------------------------ */
7598/* Function: ipf_token_flush */
7599/* Returns: None. */
7600/* Parameters: softc(I) - pointer to soft context main structure */
7601/* */
7602/* Loop through all of the existing tokens and call deref to see if they */
7603/* can be freed. Normally a function like this might just loop on */
7604/* ipf_token_head but there is a chance that a token might have a ref count */
7605/* of greater than one and in that case the the reference would drop twice */
7606/* by code that is only entitled to drop it once. */
7607/* ------------------------------------------------------------------------ */
7608static void
7609ipf_token_flush(softc)
7610 ipf_main_softc_t *softc;
7611{
7612 ipftoken_t *it, *next;
7613
7614 WRITE_ENTER(&softc->ipf_tokens);
7615 for (it = softc->ipf_token_head; it != NULL; it = next) {
7616 next = it->ipt_next;
7617 (void) ipf_token_deref(softc, it);
7618 }
7619 RWLOCK_EXIT(&softc->ipf_tokens);
7620}
7621
7622
7623/* ------------------------------------------------------------------------ */
7624/* Function: ipf_token_del */
7625/* Returns: int - 0 = success, else error */
7626/* Parameters: softc(I)- pointer to soft context main structure */
7627/* type(I) - the token type to match */
7628/* uid(I) - uid owning the token */
7629/* ptr(I) - context pointer for the token */
7630/* */
7631/* This function looks for a a token in the current list that matches up */
7632/* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7633/* call ipf_token_dewref() to remove it from the list. In the event that */
7634/* the token has a reference held elsewhere, setting ipt_complete to 2 */
7635/* enables debugging to distinguish between the two paths that ultimately */
7636/* lead to a token to be deleted. */
7637/* ------------------------------------------------------------------------ */
7638int
7639ipf_token_del(softc, type, uid, ptr)
7640 ipf_main_softc_t *softc;
7641 int type, uid;
7642 void *ptr;
7643{
7644 ipftoken_t *it;
7645 int error;
7646
7647 IPFERROR(82);
7648 error = ESRCH;
7649
7650 WRITE_ENTER(&softc->ipf_tokens);
7651 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7652 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7653 uid == it->ipt_uid) {
7654 it->ipt_complete = 2;
7655 ipf_token_deref(softc, it);
7656 error = 0;
7657 break;
7658 }
7659 }
7660 RWLOCK_EXIT(&softc->ipf_tokens);
7661
7662 return error;
7663}
7664
7665
7666/* ------------------------------------------------------------------------ */
7667/* Function: ipf_token_mark_complete */
7668/* Returns: None. */
7669/* Parameters: token(I) - pointer to token structure */
7670/* */
7671/* Mark a token as being ineligable for being found with ipf_token_find. */
7672/* ------------------------------------------------------------------------ */
7673void
7674ipf_token_mark_complete(token)
7675 ipftoken_t *token;
7676{
7677 if (token->ipt_complete == 0)
7678 token->ipt_complete = 1;
7679}
7680
7681
7682/* ------------------------------------------------------------------------ */
7683/* Function: ipf_token_find */
7684/* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7685/* Parameters: softc(I)- pointer to soft context main structure */
7686/* type(I) - the token type to match */
7687/* uid(I) - uid owning the token */
7688/* ptr(I) - context pointer for the token */
7689/* */
7690/* This function looks for a live token in the list of current tokens that */
7691/* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7692/* allocated. If one is found then it is moved to the top of the list of */
7693/* currently active tokens. */
7694/* ------------------------------------------------------------------------ */
7695ipftoken_t *
7696ipf_token_find(softc, type, uid, ptr)
7697 ipf_main_softc_t *softc;
7698 int type, uid;
7699 void *ptr;
7700{
7701 ipftoken_t *it, *new;
7702
7703 KMALLOC(new, ipftoken_t *);
7704 if (new != NULL)
7705 bzero((char *)new, sizeof(*new));
7706
7707 WRITE_ENTER(&softc->ipf_tokens);
7708 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7709 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7710 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7711 break;
7712 }
7713
7714 if (it == NULL) {
7715 it = new;
7716 new = NULL;
7717 if (it == NULL) {
7718 RWLOCK_EXIT(&softc->ipf_tokens);
7719 return NULL;
7720 }
7721 it->ipt_ctx = ptr;
7722 it->ipt_uid = uid;
7723 it->ipt_type = type;
7724 it->ipt_ref = 1;
7725 } else {
7726 if (new != NULL) {
7727 KFREE(new);
7728 new = NULL;
7729 }
7730
7731 if (it->ipt_complete > 0)
7732 it = NULL;
7733 else
7734 ipf_token_unlink(softc, it);
7735 }
7736
7737 if (it != NULL) {
7738 it->ipt_pnext = softc->ipf_token_tail;
7739 *softc->ipf_token_tail = it;
7740 softc->ipf_token_tail = &it->ipt_next;
7741 it->ipt_next = NULL;
7742 it->ipt_ref++;
7743
7744 it->ipt_die = softc->ipf_ticks + 20;
7745 }
7746
7747 RWLOCK_EXIT(&softc->ipf_tokens);
7748
7749 return it;
7750}
7751
7752
7753/* ------------------------------------------------------------------------ */
7754/* Function: ipf_token_unlink */
7755/* Returns: None. */
7756/* Parameters: softc(I) - pointer to soft context main structure */
7757/* token(I) - pointer to token structure */
7758/* Write Locks: ipf_tokens */
7759/* */
7760/* This function unlinks a token structure from the linked list of tokens */
7761/* that "own" it. The head pointer never needs to be explicitly adjusted */
7762/* but the tail does due to the linked list implementation. */
7763/* ------------------------------------------------------------------------ */
7764static void
7765ipf_token_unlink(softc, token)
7766 ipf_main_softc_t *softc;
7767 ipftoken_t *token;
7768{
7769
7770 if (softc->ipf_token_tail == &token->ipt_next)
7771 softc->ipf_token_tail = token->ipt_pnext;
7772
7773 *token->ipt_pnext = token->ipt_next;
7774 if (token->ipt_next != NULL)
7775 token->ipt_next->ipt_pnext = token->ipt_pnext;
7776 token->ipt_next = NULL;
7777 token->ipt_pnext = NULL;
7778}
7779
7780
7781/* ------------------------------------------------------------------------ */
7782/* Function: ipf_token_deref */
7783/* Returns: int - 0 == token freed, else reference count */
7784/* Parameters: softc(I) - pointer to soft context main structure */
7785/* token(I) - pointer to token structure */
7786/* Write Locks: ipf_tokens */
7787/* */
7788/* Drop the reference count on the token structure and if it drops to zero, */
7789/* call the dereference function for the token type because it is then */
7790/* possible to free the token data structure. */
7791/* ------------------------------------------------------------------------ */
7792int
7793ipf_token_deref(softc, token)
7794 ipf_main_softc_t *softc;
7795 ipftoken_t *token;
7796{
7797 void *data, **datap;
7798
7799 ASSERT(token->ipt_ref > 0);
7800 token->ipt_ref--;
7801 if (token->ipt_ref > 0)
7802 return token->ipt_ref;
7803
7804 data = token->ipt_data;
7805 datap = &data;
7806
7807 if ((data != NULL) && (data != (void *)-1)) {
7808 switch (token->ipt_type)
7809 {
7810 case IPFGENITER_IPF :
7811 (void) ipf_derefrule(softc, (frentry_t **)datap);
7812 break;
7813 case IPFGENITER_IPNAT :
7814 WRITE_ENTER(&softc->ipf_nat);
7815 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7816 RWLOCK_EXIT(&softc->ipf_nat);
7817 break;
7818 case IPFGENITER_NAT :
7819 ipf_nat_deref(softc, (nat_t **)datap);
7820 break;
7821 case IPFGENITER_STATE :
7822 ipf_state_deref(softc, (ipstate_t **)datap);
7823 break;
7824 case IPFGENITER_FRAG :
7825 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7826 break;
7827 case IPFGENITER_NATFRAG :
7828 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7829 break;
7830 case IPFGENITER_HOSTMAP :
7831 WRITE_ENTER(&softc->ipf_nat);
7832 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7833 RWLOCK_EXIT(&softc->ipf_nat);
7834 break;
7835 default :
7836 ipf_lookup_iterderef(softc, token->ipt_type, data);
7837 break;
7838 }
7839 }
7840
7841 ipf_token_unlink(softc, token);
7842 KFREE(token);
7843 return 0;
7844}
7845
7846
7847/* ------------------------------------------------------------------------ */
7848/* Function: ipf_nextrule */
7849/* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7850/* Parameters: softc(I) - pointer to soft context main structure */
7851/* fr(I) - pointer to filter rule */
7852/* out(I) - 1 == out rules, 0 == input rules */
7853/* */
7854/* Starting with "fr", find the next rule to visit. This includes visiting */
7855/* the list of rule groups if either fr is NULL (empty list) or it is the */
7856/* last rule in the list. When walking rule lists, it is either input or */
7857/* output rules that are returned, never both. */
7858/* ------------------------------------------------------------------------ */
7859static frentry_t *
7860ipf_nextrule(softc, active, unit, fr, out)
7861 ipf_main_softc_t *softc;
7862 int active, unit;
7863 frentry_t *fr;
7864 int out;
7865{
7866 frentry_t *next;
7867 frgroup_t *fg;
7868
7869 if (fr != NULL && fr->fr_group != -1) {
7870 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7871 unit, active, NULL);
7872 if (fg != NULL)
7873 fg = fg->fg_next;
7874 } else {
7875 fg = softc->ipf_groups[unit][active];
7876 }
7877
7878 while (fg != NULL) {
7879 next = fg->fg_start;
7880 while (next != NULL) {
7881 if (out) {
7882 if (next->fr_flags & FR_OUTQUE)
7883 return next;
7884 } else if (next->fr_flags & FR_INQUE) {
7885 return next;
7886 }
7887 next = next->fr_next;
7888 }
7889 if (next == NULL)
7890 fg = fg->fg_next;
7891 }
7892
7893 return NULL;
7894}
7895
7896/* ------------------------------------------------------------------------ */
7897/* Function: ipf_getnextrule */
7898/* Returns: int - 0 = success, else error */
7899/* Parameters: softc(I)- pointer to soft context main structure */
7900/* t(I) - pointer to destination information to resolve */
7901/* ptr(I) - pointer to ipfobj_t to copyin from user space */
7902/* */
7903/* This function's first job is to bring in the ipfruleiter_t structure via */
7904/* the ipfobj_t structure to determine what should be the next rule to */
7905/* return. Once the ipfruleiter_t has been brought in, it then tries to */
7906/* find the 'next rule'. This may include searching rule group lists or */
7907/* just be as simple as looking at the 'next' field in the rule structure. */
7908/* When we have found the rule to return, increase its reference count and */
7909/* if we used an existing rule to get here, decrease its reference count. */
7910/* ------------------------------------------------------------------------ */
7911int
7912ipf_getnextrule(softc, t, ptr)
7913 ipf_main_softc_t *softc;
7914 ipftoken_t *t;
7915 void *ptr;
7916{
7917 frentry_t *fr, *next, zero;
7918 ipfruleiter_t it;
7919 int error, out;
7920 frgroup_t *fg;
7921 ipfobj_t obj;
7922 int predict;
7923 char *dst;
7924 int unit;
7925
7926 if (t == NULL || ptr == NULL) {
7927 IPFERROR(84);
7928 return EFAULT;
7929 }
7930
7931 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7932 if (error != 0)
7933 return error;
7934
7935 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7936 IPFERROR(85);
7937 return EINVAL;
7938 }
7939 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7940 IPFERROR(86);
7941 return EINVAL;
7942 }
7943 if (it.iri_nrules == 0) {
7944 IPFERROR(87);
7945 return ENOSPC;
7946 }
7947 if (it.iri_rule == NULL) {
7948 IPFERROR(88);
7949 return EFAULT;
7950 }
7951
7952 fg = NULL;
7953 fr = t->ipt_data;
7954 if ((it.iri_inout & F_OUT) != 0)
7955 out = 1;
7956 else
7957 out = 0;
7958 if ((it.iri_inout & F_ACIN) != 0)
7959 unit = IPL_LOGCOUNT;
7960 else
7961 unit = IPL_LOGIPF;
7962
7963 READ_ENTER(&softc->ipf_mutex);
7964 if (fr == NULL) {
7965 if (*it.iri_group == '\0') {
7966 if (unit == IPL_LOGCOUNT) {
7967 next = softc->ipf_acct[out][it.iri_active];
7968 } else {
7969 next = softc->ipf_rules[out][it.iri_active];
7970 }
7971 if (next == NULL)
7972 next = ipf_nextrule(softc, it.iri_active,
7973 unit, NULL, out);
7974 } else {
7975 fg = ipf_findgroup(softc, it.iri_group, unit,
7976 it.iri_active, NULL);
7977 if (fg != NULL)
7978 next = fg->fg_start;
7979 else
7980 next = NULL;
7981 }
7982 } else {
7983 next = fr->fr_next;
7984 if (next == NULL)
7985 next = ipf_nextrule(softc, it.iri_active, unit,
7986 fr, out);
7987 }
7988
7989 if (next != NULL && next->fr_next != NULL)
7990 predict = 1;
7991 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7992 predict = 1;
7993 else
7994 predict = 0;
7995
7996 if (fr != NULL)
7997 (void) ipf_derefrule(softc, &fr);
7998
7999 obj.ipfo_type = IPFOBJ_FRENTRY;
8000 dst = (char *)it.iri_rule;
8001
8002 if (next != NULL) {
8003 obj.ipfo_size = next->fr_size;
8004 MUTEX_ENTER(&next->fr_lock);
8005 next->fr_ref++;
8006 MUTEX_EXIT(&next->fr_lock);
8007 t->ipt_data = next;
8008 } else {
8009 obj.ipfo_size = sizeof(frentry_t);
8010 bzero(&zero, sizeof(zero));
8011 next = &zero;
8012 t->ipt_data = NULL;
8013 }
8014 it.iri_rule = predict ? next : NULL;
8015 if (predict == 0)
8016 ipf_token_mark_complete(t);
8017
8018 RWLOCK_EXIT(&softc->ipf_mutex);
8019
8020 obj.ipfo_ptr = dst;
8021 error = ipf_outobjk(softc, &obj, next);
8022 if (error == 0 && t->ipt_data != NULL) {
8023 dst += obj.ipfo_size;
8024 if (next->fr_data != NULL) {
8025 ipfobj_t dobj;
8026
8027 if (next->fr_type == FR_T_IPFEXPR)
8028 dobj.ipfo_type = IPFOBJ_IPFEXPR;
8029 else
8030 dobj.ipfo_type = IPFOBJ_FRIPF;
8031 dobj.ipfo_size = next->fr_dsize;
8032 dobj.ipfo_rev = obj.ipfo_rev;
8033 dobj.ipfo_ptr = dst;
8034 error = ipf_outobjk(softc, &dobj, next->fr_data);
8035 }
8036 }
8037
8038 if ((fr != NULL) && (next == &zero))
8039 (void) ipf_derefrule(softc, &fr);
8040
8041 return error;
8042}
8043
8044
8045/* ------------------------------------------------------------------------ */
8046/* Function: ipf_frruleiter */
8047/* Returns: int - 0 = success, else error */
8048/* Parameters: softc(I)- pointer to soft context main structure */
8049/* data(I) - the token type to match */
8050/* uid(I) - uid owning the token */
8051/* ptr(I) - context pointer for the token */
8052/* */
8053/* This function serves as a stepping stone between ipf_ipf_ioctl and */
8054/* ipf_getnextrule. It's role is to find the right token in the kernel for */
8055/* the process doing the ioctl and use that to ask for the next rule. */
8056/* ------------------------------------------------------------------------ */
8057static int
8058ipf_frruleiter(softc, data, uid, ctx)
8059 ipf_main_softc_t *softc;
8060 void *data, *ctx;
8061 int uid;
8062{
8063 ipftoken_t *token;
8064 ipfruleiter_t it;
8065 ipfobj_t obj;
8066 int error;
8067
8068 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8069 if (token != NULL) {
8070 error = ipf_getnextrule(softc, token, data);
8071 WRITE_ENTER(&softc->ipf_tokens);
8072 ipf_token_deref(softc, token);
8073 RWLOCK_EXIT(&softc->ipf_tokens);
8074 } else {
8075 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8076 if (error != 0)
8077 return error;
8078 it.iri_rule = NULL;
8079 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8080 }
8081
8082 return error;
8083}
8084
8085
8086/* ------------------------------------------------------------------------ */
8087/* Function: ipf_geniter */
8088/* Returns: int - 0 = success, else error */
8089/* Parameters: softc(I) - pointer to soft context main structure */
8090/* token(I) - pointer to ipftoken_t structure */
8091/* itp(I) - pointer to iterator data */
8092/* */
8093/* Decide which iterator function to call using information passed through */
8094/* the ipfgeniter_t structure at itp. */
8095/* ------------------------------------------------------------------------ */
8096static int
8097ipf_geniter(softc, token, itp)
8098 ipf_main_softc_t *softc;
8099 ipftoken_t *token;
8100 ipfgeniter_t *itp;
8101{
8102 int error;
8103
8104 switch (itp->igi_type)
8105 {
8106 case IPFGENITER_FRAG :
8107 error = ipf_frag_pkt_next(softc, token, itp);
8108 break;
8109 default :
8110 IPFERROR(92);
8111 error = EINVAL;
8112 break;
8113 }
8114
8115 return error;
8116}
8117
8118
8119/* ------------------------------------------------------------------------ */
8120/* Function: ipf_genericiter */
8121/* Returns: int - 0 = success, else error */
8122/* Parameters: softc(I)- pointer to soft context main structure */
8123/* data(I) - the token type to match */
8124/* uid(I) - uid owning the token */
8125/* ptr(I) - context pointer for the token */
8126/* */
8127/* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8128/* ------------------------------------------------------------------------ */
8129int
8130ipf_genericiter(softc, data, uid, ctx)
8131 ipf_main_softc_t *softc;
8132 void *data, *ctx;
8133 int uid;
8134{
8135 ipftoken_t *token;
8136 ipfgeniter_t iter;
8137 int error;
8138
8139 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8140 if (error != 0)
8141 return error;
8142
8143 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8144 if (token != NULL) {
8145 token->ipt_subtype = iter.igi_type;
8146 error = ipf_geniter(softc, token, &iter);
8147 WRITE_ENTER(&softc->ipf_tokens);
8148 ipf_token_deref(softc, token);
8149 RWLOCK_EXIT(&softc->ipf_tokens);
8150 } else {
8151 IPFERROR(93);
8152 error = 0;
8153 }
8154
8155 return error;
8156}
8157
8158
8159/* ------------------------------------------------------------------------ */
8160/* Function: ipf_ipf_ioctl */
8161/* Returns: int - 0 = success, else error */
8162/* Parameters: softc(I)- pointer to soft context main structure */
8163/* data(I) - the token type to match */
8164/* cmd(I) - the ioctl command number */
8165/* mode(I) - mode flags for the ioctl */
8166/* uid(I) - uid owning the token */
8167/* ptr(I) - context pointer for the token */
8168/* */
8169/* This function handles all of the ioctl command that are actually isssued */
8170/* to the /dev/ipl device. */
8171/* ------------------------------------------------------------------------ */
8172int
8173ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8174 ipf_main_softc_t *softc;
8175 caddr_t data;
8176 ioctlcmd_t cmd;
8177 int mode, uid;
8178 void *ctx;
8179{
8180 friostat_t fio;
8181 int error, tmp;
8182 ipfobj_t obj;
8183 SPL_INT(s);
8184
8185 switch (cmd)
8186 {
8187 case SIOCFRENB :
8188 if (!(mode & FWRITE)) {
8189 IPFERROR(94);
8190 error = EPERM;
8191 } else {
8192 error = BCOPYIN(data, &tmp, sizeof(tmp));
8193 if (error != 0) {
8194 IPFERROR(95);
8195 error = EFAULT;
8196 break;
8197 }
8198
8199 WRITE_ENTER(&softc->ipf_global);
8200 if (tmp) {
8201 if (softc->ipf_running > 0)
8202 error = 0;
8203 else
8204 error = ipfattach(softc);
8205 if (error == 0)
8206 softc->ipf_running = 1;
8207 else
8208 (void) ipfdetach(softc);
8209 } else {
8210 if (softc->ipf_running == 1)
8211 error = ipfdetach(softc);
8212 else
8213 error = 0;
8214 if (error == 0)
8215 softc->ipf_running = -1;
8216 }
8217 RWLOCK_EXIT(&softc->ipf_global);
8218 }
8219 break;
8220
8221 case SIOCIPFSET :
8222 if (!(mode & FWRITE)) {
8223 IPFERROR(96);
8224 error = EPERM;
8225 break;
8226 }
8227 /* FALLTHRU */
8228 case SIOCIPFGETNEXT :
8229 case SIOCIPFGET :
8230 error = ipf_ipftune(softc, cmd, (void *)data);
8231 break;
8232
8233 case SIOCSETFF :
8234 if (!(mode & FWRITE)) {
8235 IPFERROR(97);
8236 error = EPERM;
8237 } else {
8238 error = BCOPYIN(data, &softc->ipf_flags,
8239 sizeof(softc->ipf_flags));
8240 if (error != 0) {
8241 IPFERROR(98);
8242 error = EFAULT;
8243 }
8244 }
8245 break;
8246
8247 case SIOCGETFF :
8248 error = BCOPYOUT(&softc->ipf_flags, data,
8249 sizeof(softc->ipf_flags));
8250 if (error != 0) {
8251 IPFERROR(99);
8252 error = EFAULT;
8253 }
8254 break;
8255
8256 case SIOCFUNCL :
8257 error = ipf_resolvefunc(softc, (void *)data);
8258 break;
8259
8260 case SIOCINAFR :
8261 case SIOCRMAFR :
8262 case SIOCADAFR :
8263 case SIOCZRLST :
8264 if (!(mode & FWRITE)) {
8265 IPFERROR(100);
8266 error = EPERM;
8267 } else {
8268 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8269 softc->ipf_active, 1);
8270 }
8271 break;
8272
8273 case SIOCINIFR :
8274 case SIOCRMIFR :
8275 case SIOCADIFR :
8276 if (!(mode & FWRITE)) {
8277 IPFERROR(101);
8278 error = EPERM;
8279 } else {
8280 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8281 1 - softc->ipf_active, 1);
8282 }
8283 break;
8284
8285 case SIOCSWAPA :
8286 if (!(mode & FWRITE)) {
8287 IPFERROR(102);
8288 error = EPERM;
8289 } else {
8290 WRITE_ENTER(&softc->ipf_mutex);
8291 error = BCOPYOUT(&softc->ipf_active, data,
8292 sizeof(softc->ipf_active));
8293 if (error != 0) {
8294 IPFERROR(103);
8295 error = EFAULT;
8296 } else {
8297 softc->ipf_active = 1 - softc->ipf_active;
8298 }
8299 RWLOCK_EXIT(&softc->ipf_mutex);
8300 }
8301 break;
8302
8303 case SIOCGETFS :
8304 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8305 IPFOBJ_IPFSTAT);
8306 if (error != 0)
8307 break;
8308 ipf_getstat(softc, &fio, obj.ipfo_rev);
8309 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8310 break;
8311
8312 case SIOCFRZST :
8313 if (!(mode & FWRITE)) {
8314 IPFERROR(104);
8315 error = EPERM;
8316 } else
8317 error = ipf_zerostats(softc, (caddr_t)data);
8318 break;
8319
8320 case SIOCIPFFL :
8321 if (!(mode & FWRITE)) {
8322 IPFERROR(105);
8323 error = EPERM;
8324 } else {
8325 error = BCOPYIN(data, &tmp, sizeof(tmp));
8326 if (!error) {
8327 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8328 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8329 if (error != 0) {
8330 IPFERROR(106);
8331 error = EFAULT;
8332 }
8333 } else {
8334 IPFERROR(107);
8335 error = EFAULT;
8336 }
8337 }
8338 break;
8339
8340#ifdef USE_INET6
8341 case SIOCIPFL6 :
8342 if (!(mode & FWRITE)) {
8343 IPFERROR(108);
8344 error = EPERM;
8345 } else {
8346 error = BCOPYIN(data, &tmp, sizeof(tmp));
8347 if (!error) {
8348 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8349 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8350 if (error != 0) {
8351 IPFERROR(109);
8352 error = EFAULT;
8353 }
8354 } else {
8355 IPFERROR(110);
8356 error = EFAULT;
8357 }
8358 }
8359 break;
8360#endif
8361
8362 case SIOCSTLCK :
8363 if (!(mode & FWRITE)) {
8364 IPFERROR(122);
8365 error = EPERM;
8366 } else {
8367 error = BCOPYIN(data, &tmp, sizeof(tmp));
8368 if (error == 0) {
8369 ipf_state_setlock(softc->ipf_state_soft, tmp);
8370 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8371 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8372 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8373 } else {
8374 IPFERROR(111);
8375 error = EFAULT;
8376 }
8377 }
8378 break;
8379
8380#ifdef IPFILTER_LOG
8381 case SIOCIPFFB :
8382 if (!(mode & FWRITE)) {
8383 IPFERROR(112);
8384 error = EPERM;
8385 } else {
8386 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8387 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8388 if (error) {
8389 IPFERROR(113);
8390 error = EFAULT;
8391 }
8392 }
8393 break;
8394#endif /* IPFILTER_LOG */
8395
8396 case SIOCFRSYN :
8397 if (!(mode & FWRITE)) {
8398 IPFERROR(114);
8399 error = EPERM;
8400 } else {
8401 WRITE_ENTER(&softc->ipf_global);
8402#if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8403 error = ipfsync();
8404#else
8405 ipf_sync(softc, NULL);
8406 error = 0;
8407#endif
8408 RWLOCK_EXIT(&softc->ipf_global);
8409
8410 }
8411 break;
8412
8413 case SIOCGFRST :
8414 error = ipf_outobj(softc, (void *)data,
8415 ipf_frag_stats(softc->ipf_frag_soft),
8416 IPFOBJ_FRAGSTAT);
8417 break;
8418
8419#ifdef IPFILTER_LOG
8420 case FIONREAD :
8421 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8422 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8423 break;
8424#endif
8425
8426 case SIOCIPFITER :
8427 SPL_SCHED(s);
8428 error = ipf_frruleiter(softc, data, uid, ctx);
8429 SPL_X(s);
8430 break;
8431
8432 case SIOCGENITER :
8433 SPL_SCHED(s);
8434 error = ipf_genericiter(softc, data, uid, ctx);
8435 SPL_X(s);
8436 break;
8437
8438 case SIOCIPFDELTOK :
8439 error = BCOPYIN(data, &tmp, sizeof(tmp));
8440 if (error == 0) {
8441 SPL_SCHED(s);
8442 error = ipf_token_del(softc, tmp, uid, ctx);
8443 SPL_X(s);
8444 }
8445 break;
8446
8447 default :
8448 IPFERROR(115);
8449 error = EINVAL;
8450 break;
8451 }
8452
8453 return error;
8454}
8455
8456
8457/* ------------------------------------------------------------------------ */
8458/* Function: ipf_decaps */
8459/* Returns: int - -1 == decapsulation failed, else bit mask of */
8460/* flags indicating packet filtering decision. */
8461/* Parameters: fin(I) - pointer to packet information */
8462/* pass(I) - IP protocol version to match */
8463/* l5proto(I) - layer 5 protocol to decode UDP data as. */
8464/* */
8465/* This function is called for packets that are wrapt up in other packets, */
8466/* for example, an IP packet that is the entire data segment for another IP */
8467/* packet. If the basic constraints for this are satisfied, change the */
8468/* buffer to point to the start of the inner packet and start processing */
8469/* rules belonging to the head group this rule specifies. */
8470/* ------------------------------------------------------------------------ */
8471u_32_t
8472ipf_decaps(fin, pass, l5proto)
8473 fr_info_t *fin;
8474 u_32_t pass;
8475 int l5proto;
8476{
8477 fr_info_t fin2, *fino = NULL;
8478 int elen, hlen, nh;
8479 grehdr_t gre;
8480 ip_t *ip;
8481 mb_t *m;
8482
8483 if ((fin->fin_flx & FI_COALESCE) == 0)
8484 if (ipf_coalesce(fin) == -1)
8485 goto cantdecaps;
8486
8487 m = fin->fin_m;
8488 hlen = fin->fin_hlen;
8489
8490 switch (fin->fin_p)
8491 {
8492 case IPPROTO_UDP :
8493 /*
8494 * In this case, the specific protocol being decapsulated
8495 * inside UDP frames comes from the rule.
8496 */
8497 nh = fin->fin_fr->fr_icode;
8498 break;
8499
8500 case IPPROTO_GRE : /* 47 */
8501 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8502 hlen += sizeof(grehdr_t);
8503 if (gre.gr_R|gre.gr_s)
8504 goto cantdecaps;
8505 if (gre.gr_C)
8506 hlen += 4;
8507 if (gre.gr_K)
8508 hlen += 4;
8509 if (gre.gr_S)
8510 hlen += 4;
8511
8512 nh = IPPROTO_IP;
8513
8514 /*
8515 * If the routing options flag is set, validate that it is
8516 * there and bounce over it.
8517 */
8518#if 0
8519 /* This is really heavy weight and lots of room for error, */
8520 /* so for now, put it off and get the simple stuff right. */
8521 if (gre.gr_R) {
8522 u_char off, len, *s;
8523 u_short af;
8524 int end;
8525
8526 end = 0;
8527 s = fin->fin_dp;
8528 s += hlen;
8529 aplen = fin->fin_plen - hlen;
8530 while (aplen > 3) {
8531 af = (s[0] << 8) | s[1];
8532 off = s[2];
8533 len = s[3];
8534 aplen -= 4;
8535 s += 4;
8536 if (af == 0 && len == 0) {
8537 end = 1;
8538 break;
8539 }
8540 if (aplen < len)
8541 break;
8542 s += len;
8543 aplen -= len;
8544 }
8545 if (end != 1)
8546 goto cantdecaps;
8547 hlen = s - (u_char *)fin->fin_dp;
8548 }
8549#endif
8550 break;
8551
8552#ifdef IPPROTO_IPIP
8553 case IPPROTO_IPIP : /* 4 */
8554#endif
8555 nh = IPPROTO_IP;
8556 break;
8557
8558 default : /* Includes ESP, AH is special for IPv4 */
8559 goto cantdecaps;
8560 }
8561
8562 switch (nh)
8563 {
8564 case IPPROTO_IP :
8565 case IPPROTO_IPV6 :
8566 break;
8567 default :
8568 goto cantdecaps;
8569 }
8570
8571 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8572 fino = fin;
8573 fin = &fin2;
8574 elen = hlen;
8575#if defined(MENTAT) && defined(_KERNEL)
8576 m->b_rptr += elen;
8577#else
8578 m->m_data += elen;
8579 m->m_len -= elen;
8580#endif
8581 fin->fin_plen -= elen;
8582
8583 ip = (ip_t *)((char *)fin->fin_ip + elen);
8584
8585 /*
8586 * Make sure we have at least enough data for the network layer
8587 * header.
8588 */
8589 if (IP_V(ip) == 4)
8590 hlen = IP_HL(ip) << 2;
8591#ifdef USE_INET6
8592 else if (IP_V(ip) == 6)
8593 hlen = sizeof(ip6_t);
8594#endif
8595 else
8596 goto cantdecaps2;
8597
8598 if (fin->fin_plen < hlen)
8599 goto cantdecaps2;
8600
8601 fin->fin_dp = (char *)ip + hlen;
8602
8603 if (IP_V(ip) == 4) {
8604 /*
8605 * Perform IPv4 header checksum validation.
8606 */
8607 if (ipf_cksum((u_short *)ip, hlen))
8608 goto cantdecaps2;
8609 }
8610
8611 if (ipf_makefrip(hlen, ip, fin) == -1) {
8612cantdecaps2:
8613 if (m != NULL) {
8614#if defined(MENTAT) && defined(_KERNEL)
8615 m->b_rptr -= elen;
8616#else
8617 m->m_data -= elen;
8618 m->m_len += elen;
8619#endif
8620 }
8621cantdecaps:
8622 DT1(frb_decapfrip, fr_info_t *, fin);
8623 pass &= ~FR_CMDMASK;
8624 pass |= FR_BLOCK|FR_QUICK;
8625 fin->fin_reason = FRB_DECAPFRIP;
8626 return -1;
8627 }
8628
8629 pass = ipf_scanlist(fin, pass);
8630
8631 /*
8632 * Copy the packet filter "result" fields out of the fr_info_t struct
8633 * that is local to the decapsulation processing and back into the
8634 * one we were called with.
8635 */
8636 fino->fin_flx = fin->fin_flx;
8637 fino->fin_rev = fin->fin_rev;
8638 fino->fin_icode = fin->fin_icode;
8639 fino->fin_rule = fin->fin_rule;
8640 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8641 fino->fin_fr = fin->fin_fr;
8642 fino->fin_error = fin->fin_error;
8643 fino->fin_mp = fin->fin_mp;
8644 fino->fin_m = fin->fin_m;
8645 m = fin->fin_m;
8646 if (m != NULL) {
8647#if defined(MENTAT) && defined(_KERNEL)
8648 m->b_rptr -= elen;
8649#else
8650 m->m_data -= elen;
8651 m->m_len += elen;
8652#endif
8653 }
8654 return pass;
8655}
8656
8657
8658/* ------------------------------------------------------------------------ */
8659/* Function: ipf_matcharray_load */
8660/* Returns: int - 0 = success, else error */
8661/* Parameters: softc(I) - pointer to soft context main structure */
8662/* data(I) - pointer to ioctl data */
8663/* objp(I) - ipfobj_t structure to load data into */
8664/* arrayptr(I) - pointer to location to store array pointer */
8665/* */
8666/* This function loads in a mathing array through the ipfobj_t struct that */
8667/* describes it. Sanity checking and array size limitations are enforced */
8668/* in this function to prevent userspace from trying to load in something */
8669/* that is insanely big. Once the size of the array is known, the memory */
8670/* required is malloc'd and returned through changing *arrayptr. The */
8671/* contents of the array are verified before returning. Only in the event */
8672/* of a successful call is the caller required to free up the malloc area. */
8673/* ------------------------------------------------------------------------ */
8674int
8675ipf_matcharray_load(softc, data, objp, arrayptr)
8676 ipf_main_softc_t *softc;
8677 caddr_t data;
8678 ipfobj_t *objp;
8679 int **arrayptr;
8680{
8681 int arraysize, *array, error;
8682
8683 *arrayptr = NULL;
8684
8685 error = BCOPYIN(data, objp, sizeof(*objp));
8686 if (error != 0) {
8687 IPFERROR(116);
8688 return EFAULT;
8689 }
8690
8691 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8692 IPFERROR(117);
8693 return EINVAL;
8694 }
8695
8696 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8697 (objp->ipfo_size > 1024)) {
8698 IPFERROR(118);
8699 return EINVAL;
8700 }
8701
8702 arraysize = objp->ipfo_size * sizeof(*array);
8703 KMALLOCS(array, int *, arraysize);
8704 if (array == NULL) {
8705 IPFERROR(119);
8706 return ENOMEM;
8707 }
8708
8709 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8710 if (error != 0) {
8711 KFREES(array, arraysize);
8712 IPFERROR(120);
8713 return EFAULT;
8714 }
8715
8716 if (ipf_matcharray_verify(array, arraysize) != 0) {
8717 KFREES(array, arraysize);
8718 IPFERROR(121);
8719 return EINVAL;
8720 }
8721
8722 *arrayptr = array;
8723 return 0;
8724}
8725
8726
8727/* ------------------------------------------------------------------------ */
8728/* Function: ipf_matcharray_verify */
8729/* Returns: Nil */
8730/* Parameters: array(I) - pointer to matching array */
8731/* arraysize(I) - number of elements in the array */
8732/* */
8733/* Verify the contents of a matching array by stepping through each element */
8734/* in it. The actual commands in the array are not verified for */
8735/* correctness, only that all of the sizes are correctly within limits. */
8736/* ------------------------------------------------------------------------ */
8737int
8738ipf_matcharray_verify(array, arraysize)
8739 int *array, arraysize;
8740{
8741 int i, nelem, maxidx;
8742 ipfexp_t *e;
8743
8744 nelem = arraysize / sizeof(*array);
8745
8746 /*
8747 * Currently, it makes no sense to have an array less than 6
8748 * elements long - the initial size at the from, a single operation
8749 * (minimum 4 in length) and a trailer, for a total of 6.
8750 */
8751 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8752 return -1;
8753 }
8754
8755 /*
8756 * Verify the size of data pointed to by array with how long
8757 * the array claims to be itself.
8758 */
8759 if (array[0] * sizeof(*array) != arraysize) {
8760 return -1;
8761 }
8762
8763 maxidx = nelem - 1;
8764 /*
8765 * The last opcode in this array should be an IPF_EXP_END.
8766 */
8767 if (array[maxidx] != IPF_EXP_END) {
8768 return -1;
8769 }
8770
8771 for (i = 1; i < maxidx; ) {
8772 e = (ipfexp_t *)(array + i);
8773
8774 /*
8775 * The length of the bits to check must be at least 1
8776 * (or else there is nothing to comapre with!) and it
8777 * cannot exceed the length of the data present.
8778 */
8779 if ((e->ipfe_size < 1 ) ||
8780 (e->ipfe_size + i > maxidx)) {
8781 return -1;
8782 }
8783 i += e->ipfe_size;
8784 }
8785 return 0;
8786}
8787
8788
8789/* ------------------------------------------------------------------------ */
8790/* Function: ipf_fr_matcharray */
8791/* Returns: int - 0 = match failed, else positive match */
8792/* Parameters: fin(I) - pointer to packet information */
8793/* array(I) - pointer to matching array */
8794/* */
8795/* This function is used to apply a matching array against a packet and */
8796/* return an indication of whether or not the packet successfully matches */
8797/* all of the commands in it. */
8798/* ------------------------------------------------------------------------ */
8799static int
8800ipf_fr_matcharray(fin, array)
8801 fr_info_t *fin;
8802 int *array;
8803{
8804 int i, n, *x, rv, p;
8805 ipfexp_t *e;
8806
8807 rv = 0;
8808 n = array[0];
8809 x = array + 1;
8810
8811 for (; n > 0; x += 3 + x[3], rv = 0) {
8812 e = (ipfexp_t *)x;
8813 if (e->ipfe_cmd == IPF_EXP_END)
8814 break;
8815 n -= e->ipfe_size;
8816
8817 /*
8818 * The upper 16 bits currently store the protocol value.
8819 * This is currently used with TCP and UDP port compares and
8820 * allows "tcp.port = 80" without requiring an explicit
8821 " "ip.pr = tcp" first.
8822 */
8823 p = e->ipfe_cmd >> 16;
8824 if ((p != 0) && (p != fin->fin_p))
8825 break;
8826
8827 switch (e->ipfe_cmd)
8828 {
8829 case IPF_EXP_IP_PR :
8830 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8831 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8832 }
8833 break;
8834
8835 case IPF_EXP_IP_SRCADDR :
8836 if (fin->fin_v != 4)
8837 break;
8838 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8839 rv |= ((fin->fin_saddr &
8840 e->ipfe_arg0[i * 2 + 1]) ==
8841 e->ipfe_arg0[i * 2]);
8842 }
8843 break;
8844
8845 case IPF_EXP_IP_DSTADDR :
8846 if (fin->fin_v != 4)
8847 break;
8848 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8849 rv |= ((fin->fin_daddr &
8850 e->ipfe_arg0[i * 2 + 1]) ==
8851 e->ipfe_arg0[i * 2]);
8852 }
8853 break;
8854
8855 case IPF_EXP_IP_ADDR :
8856 if (fin->fin_v != 4)
8857 break;
8858 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8859 rv |= ((fin->fin_saddr &
8860 e->ipfe_arg0[i * 2 + 1]) ==
8861 e->ipfe_arg0[i * 2]) ||
8862 ((fin->fin_daddr &
8863 e->ipfe_arg0[i * 2 + 1]) ==
8864 e->ipfe_arg0[i * 2]);
8865 }
8866 break;
8867
8868#ifdef USE_INET6
8869 case IPF_EXP_IP6_SRCADDR :
8870 if (fin->fin_v != 6)
8871 break;
8872 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8873 rv |= IP6_MASKEQ(&fin->fin_src6,
8874 &e->ipfe_arg0[i * 8 + 4],
8875 &e->ipfe_arg0[i * 8]);
8876 }
8877 break;
8878
8879 case IPF_EXP_IP6_DSTADDR :
8880 if (fin->fin_v != 6)
8881 break;
8882 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8883 rv |= IP6_MASKEQ(&fin->fin_dst6,
8884 &e->ipfe_arg0[i * 8 + 4],
8885 &e->ipfe_arg0[i * 8]);
8886 }
8887 break;
8888
8889 case IPF_EXP_IP6_ADDR :
8890 if (fin->fin_v != 6)
8891 break;
8892 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8893 rv |= IP6_MASKEQ(&fin->fin_src6,
8894 &e->ipfe_arg0[i * 8 + 4],
8895 &e->ipfe_arg0[i * 8]) ||
8896 IP6_MASKEQ(&fin->fin_dst6,
8897 &e->ipfe_arg0[i * 8 + 4],
8898 &e->ipfe_arg0[i * 8]);
8899 }
8900 break;
8901#endif
8902
8903 case IPF_EXP_UDP_PORT :
8904 case IPF_EXP_TCP_PORT :
8905 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8906 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8907 (fin->fin_dport == e->ipfe_arg0[i]);
8908 }
8909 break;
8910
8911 case IPF_EXP_UDP_SPORT :
8912 case IPF_EXP_TCP_SPORT :
8913 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8914 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8915 }
8916 break;
8917
8918 case IPF_EXP_UDP_DPORT :
8919 case IPF_EXP_TCP_DPORT :
8920 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8921 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8922 }
8923 break;
8924
8925 case IPF_EXP_TCP_FLAGS :
8926 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8927 rv |= ((fin->fin_tcpf &
8928 e->ipfe_arg0[i * 2 + 1]) ==
8929 e->ipfe_arg0[i * 2]);
8930 }
8931 break;
8932 }
8933 rv ^= e->ipfe_not;
8934
8935 if (rv == 0)
8936 break;
8937 }
8938
8939 return rv;
8940}
8941
8942
8943/* ------------------------------------------------------------------------ */
8944/* Function: ipf_queueflush */
8945/* Returns: int - number of entries flushed (0 = none) */
8946/* Parameters: softc(I) - pointer to soft context main structure */
8947/* deletefn(I) - function to call to delete entry */
8948/* ipfqs(I) - top of the list of ipf internal queues */
8949/* userqs(I) - top of the list of user defined timeouts */
8950/* */
8951/* This fucntion gets called when the state/NAT hash tables fill up and we */
8952/* need to try a bit harder to free up some space. The algorithm used here */
8953/* split into two parts but both halves have the same goal: to reduce the */
8954/* number of connections considered to be "active" to the low watermark. */
8955/* There are two steps in doing this: */
8956/* 1) Remove any TCP connections that are already considered to be "closed" */
8957/* but have not yet been removed from the state table. The two states */
8958/* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8959/* candidates for this style of removal. If freeing up entries in */
8960/* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8961/* we do not go on to step 2. */
8962/* */
8963/* 2) Look for the oldest entries on each timeout queue and free them if */
8964/* they are within the given window we are considering. Where the */
8965/* window starts and the steps taken to increase its size depend upon */
8966/* how long ipf has been running (ipf_ticks.) Anything modified in the */
8967/* last 30 seconds is not touched. */
8968/* touched */
8969/* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8970/* | | | | | | */
8971/* future <--+----------+--------+-----------+-----+-----+-----------> past */
8972/* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8973/* */
8974/* Points to note: */
8975/* - tqe_die is the time, in the future, when entries die. */
8976/* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8977/* ticks. */
8978/* - tqe_touched is when the entry was last used by NAT/state */
8979/* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8980/* ipf_ticks any given timeout queue and vice versa. */
8981/* - both tqe_die and tqe_touched increase over time */
8982/* - timeout queues are sorted with the highest value of tqe_die at the */
8983/* bottom and therefore the smallest values of each are at the top */
8984/* - the pointer passed in as ipfqs should point to an array of timeout */
8985/* queues representing each of the TCP states */
8986/* */
8987/* We start by setting up a maximum range to scan for things to move of */
8988/* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8989/* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8990/* we start again with a new value for "iend" and "istart". This is */
8991/* continued until we either finish the scan of 30 second intervals or the */
8992/* low water mark is reached. */
8993/* ------------------------------------------------------------------------ */
8994int
8995ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8996 ipf_main_softc_t *softc;
8997 ipftq_delete_fn_t deletefn;
8998 ipftq_t *ipfqs, *userqs;
8999 u_int *activep;
9000 int size, low;
9001{
9002 u_long interval, istart, iend;
9003 ipftq_t *ifq, *ifqnext;
9004 ipftqent_t *tqe, *tqn;
9005 int removed = 0;
9006
9007 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
9008 tqn = tqe->tqe_next;
9009 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9010 removed++;
9011 }
9012 if ((*activep * 100 / size) > low) {
9013 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
9014 ((tqe = tqn) != NULL); ) {
9015 tqn = tqe->tqe_next;
9016 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9017 removed++;
9018 }
9019 }
9020
9021 if ((*activep * 100 / size) <= low) {
9022 return removed;
9023 }
9024
9025 /*
9026 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
9027 * used then the operations are upgraded to floating point
9028 * and kernels don't like floating point...
9029 */
9030 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
9031 istart = IPF_TTLVAL(86400 * 4);
9032 interval = IPF_TTLVAL(43200);
9033 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9034 istart = IPF_TTLVAL(43200);
9035 interval = IPF_TTLVAL(1800);
9036 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9037 istart = IPF_TTLVAL(1800);
9038 interval = IPF_TTLVAL(30);
9039 } else {
9040 return 0;
9041 }
9042 if (istart > softc->ipf_ticks) {
9043 if (softc->ipf_ticks - interval < interval)
9044 istart = interval;
9045 else
9046 istart = (softc->ipf_ticks / interval) * interval;
9047 }
9048
9049 iend = softc->ipf_ticks - interval;
9050
9051 while ((*activep * 100 / size) > low) {
9052 u_long try;
9053
9054 try = softc->ipf_ticks - istart;
9055
9056 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9057 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9058 if (try < tqe->tqe_touched)
9059 break;
9060 tqn = tqe->tqe_next;
9061 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9062 removed++;
9063 }
9064 }
9065
9066 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9067 ifqnext = ifq->ifq_next;
9068
9069 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9070 if (try < tqe->tqe_touched)
9071 break;
9072 tqn = tqe->tqe_next;
9073 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9074 removed++;
9075 }
9076 }
9077
9078 if (try >= iend) {
9079 if (interval == IPF_TTLVAL(43200)) {
9080 interval = IPF_TTLVAL(1800);
9081 } else if (interval == IPF_TTLVAL(1800)) {
9082 interval = IPF_TTLVAL(30);
9083 } else {
9084 break;
9085 }
9086 if (interval >= softc->ipf_ticks)
9087 break;
9088
9089 iend = softc->ipf_ticks - interval;
9090 }
9091 istart -= interval;
9092 }
9093
9094 return removed;
9095}
9096
9097
9098/* ------------------------------------------------------------------------ */
9099/* Function: ipf_deliverlocal */
9100/* Returns: int - 1 = local address, 0 = non-local address */
9101/* Parameters: softc(I) - pointer to soft context main structure */
9102/* ipversion(I) - IP protocol version (4 or 6) */
9103/* ifp(I) - network interface pointer */
9104/* ipaddr(I) - IPv4/6 destination address */
9105/* */
9106/* This fucntion is used to determine in the address "ipaddr" belongs to */
9107/* the network interface represented by ifp. */
9108/* ------------------------------------------------------------------------ */
9109int
9110ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9111 ipf_main_softc_t *softc;
9112 int ipversion;
9113 void *ifp;
9114 i6addr_t *ipaddr;
9115{
9116 i6addr_t addr;
9117 int islocal = 0;
9118
9119 if (ipversion == 4) {
9120 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9121 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9122 islocal = 1;
9123 }
9124
9125#ifdef USE_INET6
9126 } else if (ipversion == 6) {
9127 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9128 if (IP6_EQ(&addr, ipaddr))
9129 islocal = 1;
9130 }
9131#endif
9132 }
9133
9134 return islocal;
9135}
9136
9137
9138/* ------------------------------------------------------------------------ */
9139/* Function: ipf_settimeout */
9140/* Returns: int - 0 = success, -1 = failure */
9141/* Parameters: softc(I) - pointer to soft context main structure */
9142/* t(I) - pointer to tuneable array entry */
9143/* p(I) - pointer to values passed in to apply */
9144/* */
9145/* This function is called to set the timeout values for each distinct */
9146/* queue timeout that is available. When called, it calls into both the */
9147/* state and NAT code, telling them to update their timeout queues. */
9148/* ------------------------------------------------------------------------ */
9149static int
9150ipf_settimeout(softc, t, p)
9151 struct ipf_main_softc_s *softc;
9152 ipftuneable_t *t;
9153 ipftuneval_t *p;
9154{
9155
9156 /*
9157 * ipf_interror should be set by the functions called here, not
9158 * by this function - it's just a middle man.
9159 */
9160 if (ipf_state_settimeout(softc, t, p) == -1)
9161 return -1;
9162 if (ipf_nat_settimeout(softc, t, p) == -1)
9163 return -1;
9164 return 0;
9165}
9166
9167
9168/* ------------------------------------------------------------------------ */
9169/* Function: ipf_apply_timeout */
9170/* Returns: int - 0 = success, -1 = failure */
9171/* Parameters: head(I) - pointer to tuneable array entry */
9172/* seconds(I) - pointer to values passed in to apply */
9173/* */
9174/* This function applies a timeout of "seconds" to the timeout queue that */
9175/* is pointed to by "head". All entries on this list have an expiration */
9176/* set to be the current tick value of ipf plus the ttl. Given that this */
9177/* function should only be called when the delta is non-zero, the task is */
9178/* to walk the entire list and apply the change. The sort order will not */
9179/* change. The only catch is that this is O(n) across the list, so if the */
9180/* queue has lots of entries (10s of thousands or 100s of thousands), it */
9181/* could take a relatively long time to work through them all. */
9182/* ------------------------------------------------------------------------ */
9183void
9184ipf_apply_timeout(head, seconds)
9185 ipftq_t *head;
9186 u_int seconds;
9187{
9188 u_int oldtimeout, newtimeout;
9189 ipftqent_t *tqe;
9190 int delta;
9191
9192 MUTEX_ENTER(&head->ifq_lock);
9193 oldtimeout = head->ifq_ttl;
9194 newtimeout = IPF_TTLVAL(seconds);
9195 delta = oldtimeout - newtimeout;
9196
9197 head->ifq_ttl = newtimeout;
9198
9199 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9200 tqe->tqe_die += delta;
9201 }
9202 MUTEX_EXIT(&head->ifq_lock);
9203}
9204
9205
9206/* ------------------------------------------------------------------------ */
9207/* Function: ipf_settimeout_tcp */
9208/* Returns: int - 0 = successfully applied, -1 = failed */
9209/* Parameters: t(I) - pointer to tuneable to change */
9210/* p(I) - pointer to new timeout information */
9211/* tab(I) - pointer to table of TCP queues */
9212/* */
9213/* This function applies the new timeout (p) to the TCP tunable (t) and */
9214/* updates all of the entries on the relevant timeout queue by calling */
9215/* ipf_apply_timeout(). */
9216/* ------------------------------------------------------------------------ */
9217int
9218ipf_settimeout_tcp(t, p, tab)
9219 ipftuneable_t *t;
9220 ipftuneval_t *p;
9221 ipftq_t *tab;
9222{
9223 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9224 !strcmp(t->ipft_name, "tcp_established")) {
9225 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9226 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9227 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9228 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9229 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9230 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9231 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9232 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9233 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9234 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9235 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9236 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9237 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9238 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9239 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9240 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9241 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9242 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9243 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9244 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9245 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9246 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9247 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9248 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9249 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9250 } else {
9251 /*
9252 * ipf_interror isn't set here because it should be set
9253 * by whatever called this function.
9254 */
9255 return -1;
9256 }
9257 return 0;
9258}
9259
9260
9261/* ------------------------------------------------------------------------ */
9262/* Function: ipf_main_soft_create */
9263/* Returns: NULL = failure, else success */
9264/* Parameters: arg(I) - pointer to soft context structure if already allocd */
9265/* */
9266/* Create the foundation soft context structure. In circumstances where it */
9267/* is not required to dynamically allocate the context, a pointer can be */
9268/* passed in (rather than NULL) to a structure to be initialised. */
9269/* The main thing of interest is that a number of locks are initialised */
9270/* here instead of in the where might be expected - in the relevant create */
9271/* function elsewhere. This is done because the current locking design has */
9272/* some areas where these locks are used outside of their module. */
9273/* Possibly the most important exercise that is done here is setting of all */
9274/* the timeout values, allowing them to be changed before init(). */
9275/* ------------------------------------------------------------------------ */
9276void *
9277ipf_main_soft_create(arg)
9278 void *arg;
9279{
9280 ipf_main_softc_t *softc;
9281
9282 if (arg == NULL) {
9283 KMALLOC(softc, ipf_main_softc_t *);
9284 if (softc == NULL)
9285 return NULL;
9286 } else {
9287 softc = arg;
9288 }
9289
9290 bzero((char *)softc, sizeof(*softc));
9291
9292 /*
9293 * This serves as a flag as to whether or not the softc should be
9294 * free'd when _destroy is called.
9295 */
9296 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9297
9298 softc->ipf_tuners = ipf_tune_array_copy(softc,
9299 sizeof(ipf_main_tuneables),
9300 ipf_main_tuneables);
9301 if (softc->ipf_tuners == NULL) {
9302 ipf_main_soft_destroy(softc);
9303 return NULL;
9304 }
9305
9306 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9307 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9308 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9309 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9310 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9311 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9312 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9313 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9314 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9315
9316 softc->ipf_token_head = NULL;
9317 softc->ipf_token_tail = &softc->ipf_token_head;
9318
9319 softc->ipf_tcpidletimeout = FIVE_DAYS;
9320 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9321 softc->ipf_tcplastack = IPF_TTLVAL(30);
9322 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9323 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9324 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9325 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9326 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9327 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9328 softc->ipf_udptimeout = IPF_TTLVAL(120);
9329 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9330 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9331 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9332 softc->ipf_iptimeout = IPF_TTLVAL(60);
9333
9334#if defined(IPFILTER_DEFAULT_BLOCK)
9335 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9336#else
9337 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9338#endif
9339 softc->ipf_minttl = 4;
9340 softc->ipf_icmpminfragmtu = 68;
9341 softc->ipf_flags = IPF_LOGGING;
9342
9343 return softc;
9344}
9345
9346/* ------------------------------------------------------------------------ */
9347/* Function: ipf_main_soft_init */
9348/* Returns: 0 = success, -1 = failure */
9349/* Parameters: softc(I) - pointer to soft context main structure */
9350/* */
9351/* A null-op function that exists as a placeholder so that the flow in */
9352/* other functions is obvious. */
9353/* ------------------------------------------------------------------------ */
9354/*ARGSUSED*/
9355int
9356ipf_main_soft_init(softc)
9357 ipf_main_softc_t *softc;
9358{
9359 return 0;
9360}
9361
9362
9363/* ------------------------------------------------------------------------ */
9364/* Function: ipf_main_soft_destroy */
9365/* Returns: void */
9366/* Parameters: softc(I) - pointer to soft context main structure */
9367/* */
9368/* Undo everything that we did in ipf_main_soft_create. */
9369/* */
9370/* The most important check that needs to be made here is whether or not */
9371/* the structure was allocated by ipf_main_soft_create() by checking what */
9372/* value is stored in ipf_dynamic_main. */
9373/* ------------------------------------------------------------------------ */
9374/*ARGSUSED*/
9375void
9376ipf_main_soft_destroy(softc)
9377 ipf_main_softc_t *softc;
9378{
9379
9380 RW_DESTROY(&softc->ipf_frag);
9381 RW_DESTROY(&softc->ipf_poolrw);
9382 RW_DESTROY(&softc->ipf_nat);
9383 RW_DESTROY(&softc->ipf_state);
9384 RW_DESTROY(&softc->ipf_tokens);
9385 RW_DESTROY(&softc->ipf_mutex);
9386 RW_DESTROY(&softc->ipf_global);
9387 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9388 MUTEX_DESTROY(&softc->ipf_rw);
9389
9390 if (softc->ipf_tuners != NULL) {
9391 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9392 }
9393 if (softc->ipf_dynamic_softc == 1) {
9394 KFREE(softc);
9395 }
9396}
9397
9398
9399/* ------------------------------------------------------------------------ */
9400/* Function: ipf_main_soft_fini */
9401/* Returns: 0 = success, -1 = failure */
9402/* Parameters: softc(I) - pointer to soft context main structure */
9403/* */
9404/* Clean out the rules which have been added since _init was last called, */
9405/* the only dynamic part of the mainline. */
9406/* ------------------------------------------------------------------------ */
9407int
9408ipf_main_soft_fini(softc)
9409 ipf_main_softc_t *softc;
9410{
9411 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9412 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9413 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9414 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9415
9416 return 0;
9417}
9418
9419
9420/* ------------------------------------------------------------------------ */
9421/* Function: ipf_main_load */
9422/* Returns: 0 = success, -1 = failure */
9423/* Parameters: none */
9424/* */
9425/* Handle global initialisation that needs to be done for the base part of */
9426/* IPFilter. At present this just amounts to initialising some ICMP lookup */
9427/* arrays that get used by the state/NAT code. */
9428/* ------------------------------------------------------------------------ */
9429int
9430ipf_main_load()
9431{
9432 int i;
9433
9434 /* fill icmp reply type table */
9435 for (i = 0; i <= ICMP_MAXTYPE; i++)
9436 icmpreplytype4[i] = -1;
9437 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9438 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9439 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9440 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9441
9442#ifdef USE_INET6
9443 /* fill icmp reply type table */
9444 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9445 icmpreplytype6[i] = -1;
9446 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9447 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9448 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9449 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9450 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9451#endif
9452
9453 return 0;
9454}
9455
9456
9457/* ------------------------------------------------------------------------ */
9458/* Function: ipf_main_unload */
9459/* Returns: 0 = success, -1 = failure */
9460/* Parameters: none */
9461/* */
9462/* A null-op function that exists as a placeholder so that the flow in */
9463/* other functions is obvious. */
9464/* ------------------------------------------------------------------------ */
9465int
9466ipf_main_unload()
9467{
9468 return 0;
9469}
9470
9471
9472/* ------------------------------------------------------------------------ */
9473/* Function: ipf_load_all */
9474/* Returns: 0 = success, -1 = failure */
9475/* Parameters: none */
9476/* */
9477/* Work through all of the subsystems inside IPFilter and call the load */
9478/* function for each in an order that won't lead to a crash :) */
9479/* ------------------------------------------------------------------------ */
9480int
9481ipf_load_all()
9482{
9483 if (ipf_main_load() == -1)
9484 return -1;
9485
9486 if (ipf_state_main_load() == -1)
9487 return -1;
9488
9489 if (ipf_nat_main_load() == -1)
9490 return -1;
9491
9492 if (ipf_frag_main_load() == -1)
9493 return -1;
9494
9495 if (ipf_auth_main_load() == -1)
9496 return -1;
9497
9498 if (ipf_proxy_main_load() == -1)
9499 return -1;
9500
9501 return 0;
9502}
9503
9504
9505/* ------------------------------------------------------------------------ */
9506/* Function: ipf_unload_all */
9507/* Returns: 0 = success, -1 = failure */
9508/* Parameters: none */
9509/* */
9510/* Work through all of the subsystems inside IPFilter and call the unload */
9511/* function for each in an order that won't lead to a crash :) */
9512/* ------------------------------------------------------------------------ */
9513int
9514ipf_unload_all()
9515{
9516 if (ipf_proxy_main_unload() == -1)
9517 return -1;
9518
9519 if (ipf_auth_main_unload() == -1)
9520 return -1;
9521
9522 if (ipf_frag_main_unload() == -1)
9523 return -1;
9524
9525 if (ipf_nat_main_unload() == -1)
9526 return -1;
9527
9528 if (ipf_state_main_unload() == -1)
9529 return -1;
9530
9531 if (ipf_main_unload() == -1)
9532 return -1;
9533
9534 return 0;
9535}
9536
9537
9538/* ------------------------------------------------------------------------ */
9539/* Function: ipf_create_all */
9540/* Returns: NULL = failure, else success */
9541/* Parameters: arg(I) - pointer to soft context main structure */
9542/* */
9543/* Work through all of the subsystems inside IPFilter and call the create */
9544/* function for each in an order that won't lead to a crash :) */
9545/* ------------------------------------------------------------------------ */
9546ipf_main_softc_t *
9547ipf_create_all(arg)
9548 void *arg;
9549{
9550 ipf_main_softc_t *softc;
9551
9552 softc = ipf_main_soft_create(arg);
9553 if (softc == NULL)
9554 return NULL;
9555
9556#ifdef IPFILTER_LOG
9557 softc->ipf_log_soft = ipf_log_soft_create(softc);
9558 if (softc->ipf_log_soft == NULL) {
9559 ipf_destroy_all(softc);
9560 return NULL;
9561 }
9562#endif
9563
9564 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9565 if (softc->ipf_lookup_soft == NULL) {
9566 ipf_destroy_all(softc);
9567 return NULL;
9568 }
9569
9570 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9571 if (softc->ipf_sync_soft == NULL) {
9572 ipf_destroy_all(softc);
9573 return NULL;
9574 }
9575
9576 softc->ipf_state_soft = ipf_state_soft_create(softc);
9577 if (softc->ipf_state_soft == NULL) {
9578 ipf_destroy_all(softc);
9579 return NULL;
9580 }
9581
9582 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9583 if (softc->ipf_nat_soft == NULL) {
9584 ipf_destroy_all(softc);
9585 return NULL;
9586 }
9587
9588 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9589 if (softc->ipf_frag_soft == NULL) {
9590 ipf_destroy_all(softc);
9591 return NULL;
9592 }
9593
9594 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9595 if (softc->ipf_auth_soft == NULL) {
9596 ipf_destroy_all(softc);
9597 return NULL;
9598 }
9599
9600 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9601 if (softc->ipf_proxy_soft == NULL) {
9602 ipf_destroy_all(softc);
9603 return NULL;
9604 }
9605
9606 return softc;
9607}
9608
9609
9610/* ------------------------------------------------------------------------ */
9611/* Function: ipf_destroy_all */
9612/* Returns: void */
9613/* Parameters: softc(I) - pointer to soft context main structure */
9614/* */
9615/* Work through all of the subsystems inside IPFilter and call the destroy */
9616/* function for each in an order that won't lead to a crash :) */
9617/* */
9618/* Every one of these functions is expected to succeed, so there is no */
9619/* checking of return values. */
9620/* ------------------------------------------------------------------------ */
9621void
9622ipf_destroy_all(softc)
9623 ipf_main_softc_t *softc;
9624{
9625
9626 if (softc->ipf_state_soft != NULL) {
9627 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9628 softc->ipf_state_soft = NULL;
9629 }
9630
9631 if (softc->ipf_nat_soft != NULL) {
9632 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9633 softc->ipf_nat_soft = NULL;
9634 }
9635
9636 if (softc->ipf_frag_soft != NULL) {
9637 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9638 softc->ipf_frag_soft = NULL;
9639 }
9640
9641 if (softc->ipf_auth_soft != NULL) {
9642 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9643 softc->ipf_auth_soft = NULL;
9644 }
9645
9646 if (softc->ipf_proxy_soft != NULL) {
9647 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9648 softc->ipf_proxy_soft = NULL;
9649 }
9650
9651 if (softc->ipf_sync_soft != NULL) {
9652 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9653 softc->ipf_sync_soft = NULL;
9654 }
9655
9656 if (softc->ipf_lookup_soft != NULL) {
9657 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9658 softc->ipf_lookup_soft = NULL;
9659 }
9660
9661#ifdef IPFILTER_LOG
9662 if (softc->ipf_log_soft != NULL) {
9663 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9664 softc->ipf_log_soft = NULL;
9665 }
9666#endif
9667
9668 ipf_main_soft_destroy(softc);
9669}
9670
9671
9672/* ------------------------------------------------------------------------ */
9673/* Function: ipf_init_all */
9674/* Returns: 0 = success, -1 = failure */
9675/* Parameters: softc(I) - pointer to soft context main structure */
9676/* */
9677/* Work through all of the subsystems inside IPFilter and call the init */
9678/* function for each in an order that won't lead to a crash :) */
9679/* ------------------------------------------------------------------------ */
9680int
9681ipf_init_all(softc)
9682 ipf_main_softc_t *softc;
9683{
9684
9685 if (ipf_main_soft_init(softc) == -1)
9686 return -1;
9687
9688#ifdef IPFILTER_LOG
9689 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9690 return -1;
9691#endif
9692
9693 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9694 return -1;
9695
9696 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9697 return -1;
9698
9699 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9700 return -1;
9701
9702 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9703 return -1;
9704
9705 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9706 return -1;
9707
9708 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9709 return -1;
9710
9711 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9712 return -1;
9713
9714 return 0;
9715}
9716
9717
9718/* ------------------------------------------------------------------------ */
9719/* Function: ipf_fini_all */
9720/* Returns: 0 = success, -1 = failure */
9721/* Parameters: softc(I) - pointer to soft context main structure */
9722/* */
9723/* Work through all of the subsystems inside IPFilter and call the fini */
9724/* function for each in an order that won't lead to a crash :) */
9725/* ------------------------------------------------------------------------ */
9726int
9727ipf_fini_all(softc)
9728 ipf_main_softc_t *softc;
9729{
9730
9731 ipf_token_flush(softc);
9732
9733 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9734 return -1;
9735
9736 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9737 return -1;
9738
9739 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9740 return -1;
9741
9742 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9743 return -1;
9744
9745 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9746 return -1;
9747
9748 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9749 return -1;
9750
9751 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9752 return -1;
9753
9754#ifdef IPFILTER_LOG
9755 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9756 return -1;
9757#endif
9758
9759 if (ipf_main_soft_fini(softc) == -1)
9760 return -1;
9761
9762 return 0;
9763}
9764
9765
9766/* ------------------------------------------------------------------------ */
9767/* Function: ipf_rule_expire */
9768/* Returns: Nil */
9769/* Parameters: softc(I) - pointer to soft context main structure */
9770/* */
9771/* At present this function exists just to support temporary addition of */
9772/* firewall rules. Both inactive and active lists are scanned for items to */
9773/* purge, as by rights, the expiration is computed as soon as the rule is */
9774/* loaded in. */
9775/* ------------------------------------------------------------------------ */
9776void
9777ipf_rule_expire(softc)
9778 ipf_main_softc_t *softc;
9779{
9780 frentry_t *fr;
9781
9782 if ((softc->ipf_rule_explist[0] == NULL) &&
9783 (softc->ipf_rule_explist[1] == NULL))
9784 return;
9785
9786 WRITE_ENTER(&softc->ipf_mutex);
9787
9788 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9789 /*
9790 * Because the list is kept sorted on insertion, the fist
9791 * one that dies in the future means no more work to do.
9792 */
9793 if (fr->fr_die > softc->ipf_ticks)
9794 break;
9795 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9796 }
9797
9798 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9799 /*
9800 * Because the list is kept sorted on insertion, the fist
9801 * one that dies in the future means no more work to do.
9802 */
9803 if (fr->fr_die > softc->ipf_ticks)
9804 break;
9805 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9806 }
9807
9808 RWLOCK_EXIT(&softc->ipf_mutex);
9809}
9810
9811
9812static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9813static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9814 i6addr_t *));
9815
9816host_node_t RBI_ZERO(ipf_rb);
9817RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9818
9819
9820/* ------------------------------------------------------------------------ */
9821/* Function: ipf_ht_node_cmp */
9822/* Returns: int - 0 == nodes are the same, .. */
9823/* Parameters: k1(I) - pointer to first key to compare */
9824/* k2(I) - pointer to second key to compare */
9825/* */
9826/* The "key" for the node is a combination of two fields: the address */
9827/* family and the address itself. */
9828/* */
9829/* Because we're not actually interpreting the address data, it isn't */
9830/* necessary to convert them to/from network/host byte order. The mask is */
9831/* just used to remove bits that aren't significant - it doesn't matter */
9832/* where they are, as long as they're always in the same place. */
9833/* */
9834/* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9835/* this is where individual ones will differ the most - but not true for */
9836/* for /48's, etc. */
9837/* ------------------------------------------------------------------------ */
9838static int
9839ipf_ht_node_cmp(k1, k2)
9840 struct host_node_s *k1, *k2;
9841{
9842 int i;
9843
9844 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9845 if (i != 0)
9846 return i;
9847
9848 if (k1->hn_addr.adf_family == AF_INET)
9849 return (k2->hn_addr.adf_addr.in4.s_addr -
9850 k1->hn_addr.adf_addr.in4.s_addr);
9851
9852 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9853 if (i != 0)
9854 return i;
9855 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9856 if (i != 0)
9857 return i;
9858 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9859 if (i != 0)
9860 return i;
9861 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9862 return i;
9863}
9864
9865
9866/* ------------------------------------------------------------------------ */
9867/* Function: ipf_ht_node_make_key */
9868/* Returns: Nil */
9869/* parameters: htp(I) - pointer to address tracking structure */
9870/* key(I) - where to store masked address for lookup */
9871/* family(I) - protocol family of address */
9872/* addr(I) - pointer to network address */
9873/* */
9874/* Using the "netmask" (number of bits) stored parent host tracking struct, */
9875/* copy the address passed in into the key structure whilst masking out the */
9876/* bits that we don't want. */
9877/* */
9878/* Because the parser will set ht_netmask to 128 if there is no protocol */
9879/* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9880/* have to be wary of that and not allow 32-128 to happen. */
9881/* ------------------------------------------------------------------------ */
9882static void
9883ipf_ht_node_make_key(htp, key, family, addr)
9884 host_track_t *htp;
9885 host_node_t *key;
9886 int family;
9887 i6addr_t *addr;
9888{
9889 key->hn_addr.adf_family = family;
9890 if (family == AF_INET) {
9891 u_32_t mask;
9892 int bits;
9893
9894 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9895 bits = htp->ht_netmask;
9896 if (bits >= 32) {
9897 mask = 0xffffffff;
9898 } else {
9899 mask = htonl(0xffffffff << (32 - bits));
9900 }
9901 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9902#ifdef USE_INET6
9903 } else {
9904 int bits = htp->ht_netmask;
9905
9906 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9907 if (bits > 96) {
9908 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9909 htonl(0xffffffff << (128 - bits));
9910 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9911 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9912 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9913 } else if (bits > 64) {
9914 key->hn_addr.adf_addr.i6[3] = 0;
9915 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9916 htonl(0xffffffff << (96 - bits));
9917 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9918 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9919 } else if (bits > 32) {
9920 key->hn_addr.adf_addr.i6[3] = 0;
9921 key->hn_addr.adf_addr.i6[2] = 0;
9922 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9923 htonl(0xffffffff << (64 - bits));
9924 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9925 } else {
9926 key->hn_addr.adf_addr.i6[3] = 0;
9927 key->hn_addr.adf_addr.i6[2] = 0;
9928 key->hn_addr.adf_addr.i6[1] = 0;
9929 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9930 htonl(0xffffffff << (32 - bits));
9931 }
9932#endif
9933 }
9934}
9935
9936
9937/* ------------------------------------------------------------------------ */
9938/* Function: ipf_ht_node_add */
9939/* Returns: int - 0 == success, -1 == failure */
9940/* Parameters: softc(I) - pointer to soft context main structure */
9941/* htp(I) - pointer to address tracking structure */
9942/* family(I) - protocol family of address */
9943/* addr(I) - pointer to network address */
9944/* */
9945/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9946/* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9947/* */
9948/* After preparing the key with the address information to find, look in */
9949/* the red-black tree to see if the address is known. A successful call to */
9950/* this function can mean one of two things: a new node was added to the */
9951/* tree or a matching node exists and we're able to bump up its activity. */
9952/* ------------------------------------------------------------------------ */
9953int
9954ipf_ht_node_add(softc, htp, family, addr)
9955 ipf_main_softc_t *softc;
9956 host_track_t *htp;
9957 int family;
9958 i6addr_t *addr;
9959{
9960 host_node_t *h;
9961 host_node_t k;
9962
9963 ipf_ht_node_make_key(htp, &k, family, addr);
9964
9965 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9966 if (h == NULL) {
9967 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9968 return -1;
9969 KMALLOC(h, host_node_t *);
9970 if (h == NULL) {
9971 DT(ipf_rb_no_mem);
9972 LBUMP(ipf_rb_no_mem);
9973 return -1;
9974 }
9975
9976 /*
9977 * If there was a macro to initialise the RB node then that
9978 * would get used here, but there isn't...
9979 */
9980 bzero((char *)h, sizeof(*h));
9981 h->hn_addr = k.hn_addr;
9982 h->hn_addr.adf_family = k.hn_addr.adf_family;
9983 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9984 htp->ht_cur_nodes++;
9985 } else {
9986 if ((htp->ht_max_per_node != 0) &&
9987 (h->hn_active >= htp->ht_max_per_node)) {
9988 DT(ipf_rb_node_max);
9989 LBUMP(ipf_rb_node_max);
9990 return -1;
9991 }
9992 }
9993
9994 h->hn_active++;
9995
9996 return 0;
9997}
9998
9999
10000/* ------------------------------------------------------------------------ */
10001/* Function: ipf_ht_node_del */
10002/* Returns: int - 0 == success, -1 == failure */
10003/* parameters: htp(I) - pointer to address tracking structure */
10004/* family(I) - protocol family of address */
10005/* addr(I) - pointer to network address */
10006/* */
10007/* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
10008/* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
10009/* */
10010/* Try and find the address passed in amongst the leavese on this tree to */
10011/* be friend. If found then drop the active account for that node drops by */
10012/* one. If that count reaches 0, it is time to free it all up. */
10013/* ------------------------------------------------------------------------ */
10014int
10015ipf_ht_node_del(htp, family, addr)
10016 host_track_t *htp;
10017 int family;
10018 i6addr_t *addr;
10019{
10020 host_node_t *h;
10021 host_node_t k;
10022
10023 ipf_ht_node_make_key(htp, &k, family, addr);
10024
10025 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
10026 if (h == NULL) {
10027 return -1;
10028 } else {
10029 h->hn_active--;
10030 if (h->hn_active == 0) {
10031 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10032 htp->ht_cur_nodes--;
10033 KFREE(h);
10034 }
10035 }
10036
10037 return 0;
10038}
10039
10040
10041/* ------------------------------------------------------------------------ */
10042/* Function: ipf_rb_ht_init */
10043/* Returns: Nil */
10044/* Parameters: head(I) - pointer to host tracking structure */
10045/* */
10046/* Initialise the host tracking structure to be ready for use above. */
10047/* ------------------------------------------------------------------------ */
10048void
10049ipf_rb_ht_init(head)
10050 host_track_t *head;
10051{
10052 RBI_INIT(ipf_rb, &head->ht_root);
10053}
10054
10055
10056/* ------------------------------------------------------------------------ */
10057/* Function: ipf_rb_ht_freenode */
10058/* Returns: Nil */
10059/* Parameters: head(I) - pointer to host tracking structure */
10060/* arg(I) - additional argument from walk caller */
10061/* */
10062/* Free an actual host_node_t structure. */
10063/* ------------------------------------------------------------------------ */
10064void
10065ipf_rb_ht_freenode(node, arg)
10066 host_node_t *node;
10067 void *arg;
10068{
10069 KFREE(node);
10070}
10071
10072
10073/* ------------------------------------------------------------------------ */
10074/* Function: ipf_rb_ht_flush */
10075/* Returns: Nil */
10076/* Parameters: head(I) - pointer to host tracking structure */
10077/* */
10078/* Remove all of the nodes in the tree tracking hosts by calling a walker */
10079/* and free'ing each one. */
10080/* ------------------------------------------------------------------------ */
10081void
10082ipf_rb_ht_flush(head)
10083 host_track_t *head;
10084{
10085 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10086}
10087
10088
10089/* ------------------------------------------------------------------------ */
10090/* Function: ipf_slowtimer */
10091/* Returns: Nil */
10092/* Parameters: ptr(I) - pointer to main ipf soft context structure */
10093/* */
10094/* Slowly expire held state for fragments. Timeouts are set * in */
10095/* expectation of this being called twice per second. */
10096/* ------------------------------------------------------------------------ */
10097void
10098ipf_slowtimer(softc)
10099 ipf_main_softc_t *softc;
10100{
10101
10102 ipf_token_expire(softc);
10103 ipf_frag_expire(softc);
10104 ipf_state_expire(softc);
10105 ipf_nat_expire(softc);
10106 ipf_auth_expire(softc);
10107 ipf_lookup_expire(softc);
10108 ipf_rule_expire(softc);
10109 ipf_sync_expire(softc);
10110 softc->ipf_ticks++;
10111}
10112
10113
10114/* ------------------------------------------------------------------------ */
10115/* Function: ipf_inet_mask_add */
10116/* Returns: Nil */
10117/* Parameters: bits(I) - pointer to nat context information */
10118/* mtab(I) - pointer to mask hash table structure */
10119/* */
10120/* When called, bits represents the mask of a new NAT rule that has just */
10121/* been added. This function inserts a bitmask into the array of masks to */
10122/* search when searching for a matching NAT rule for a packet. */
10123/* Prevention of duplicate masks is achieved by checking the use count for */
10124/* a given netmask. */
10125/* ------------------------------------------------------------------------ */
10126void
10127ipf_inet_mask_add(bits, mtab)
10128 int bits;
10129 ipf_v4_masktab_t *mtab;
10130{
10131 u_32_t mask;
10132 int i, j;
10133
10134 mtab->imt4_masks[bits]++;
10135 if (mtab->imt4_masks[bits] > 1)
10136 return;
10137
10138 if (bits == 0)
10139 mask = 0;
10140 else
10141 mask = 0xffffffff << (32 - bits);
10142
10143 for (i = 0; i < 33; i++) {
10144 if (ntohl(mtab->imt4_active[i]) < mask) {
10145 for (j = 32; j > i; j--)
10146 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10147 mtab->imt4_active[i] = htonl(mask);
10148 break;
10149 }
10150 }
10151 mtab->imt4_max++;
10152}
10153
10154
10155/* ------------------------------------------------------------------------ */
10156/* Function: ipf_inet_mask_del */
10157/* Returns: Nil */
10158/* Parameters: bits(I) - number of bits set in the netmask */
10159/* mtab(I) - pointer to mask hash table structure */
10160/* */
10161/* Remove the 32bit bitmask represented by "bits" from the collection of */
10162/* netmasks stored inside of mtab. */
10163/* ------------------------------------------------------------------------ */
10164void
10165ipf_inet_mask_del(bits, mtab)
10166 int bits;
10167 ipf_v4_masktab_t *mtab;
10168{
10169 u_32_t mask;
10170 int i, j;
10171
10172 mtab->imt4_masks[bits]--;
10173 if (mtab->imt4_masks[bits] > 0)
10174 return;
10175
10176 mask = htonl(0xffffffff << (32 - bits));
10177 for (i = 0; i < 33; i++) {
10178 if (mtab->imt4_active[i] == mask) {
10179 for (j = i + 1; j < 33; j++)
10180 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10181 break;
10182 }
10183 }
10184 mtab->imt4_max--;
10185 ASSERT(mtab->imt4_max >= 0);
10186}
10187
10188
10189#ifdef USE_INET6
10190/* ------------------------------------------------------------------------ */
10191/* Function: ipf_inet6_mask_add */
10192/* Returns: Nil */
10193/* Parameters: bits(I) - number of bits set in mask */
10194/* mask(I) - pointer to mask to add */
10195/* mtab(I) - pointer to mask hash table structure */
10196/* */
10197/* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10198/* has just been added. This function inserts a bitmask into the array of */
10199/* masks to search when searching for a matching NAT rule for a packet. */
10200/* Prevention of duplicate masks is achieved by checking the use count for */
10201/* a given netmask. */
10202/* ------------------------------------------------------------------------ */
10203void
10204ipf_inet6_mask_add(bits, mask, mtab)
10205 int bits;
10206 i6addr_t *mask;
10207 ipf_v6_masktab_t *mtab;
10208{
10209 i6addr_t zero;
10210 int i, j;
10211
10212 mtab->imt6_masks[bits]++;
10213 if (mtab->imt6_masks[bits] > 1)
10214 return;
10215
10216 if (bits == 0) {
10217 mask = &zero;
10218 zero.i6[0] = 0;
10219 zero.i6[1] = 0;
10220 zero.i6[2] = 0;
10221 zero.i6[3] = 0;
10222 }
10223
10224 for (i = 0; i < 129; i++) {
10225 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10226 for (j = 128; j > i; j--)
10227 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10228 mtab->imt6_active[i] = *mask;
10229 break;
10230 }
10231 }
10232 mtab->imt6_max++;
10233}
10234
10235
10236/* ------------------------------------------------------------------------ */
10237/* Function: ipf_inet6_mask_del */
10238/* Returns: Nil */
10239/* Parameters: bits(I) - number of bits set in mask */
10240/* mask(I) - pointer to mask to remove */
10241/* mtab(I) - pointer to mask hash table structure */
10242/* */
10243/* Remove the 128bit bitmask represented by "bits" from the collection of */
10244/* netmasks stored inside of mtab. */
10245/* ------------------------------------------------------------------------ */
10246void
10247ipf_inet6_mask_del(bits, mask, mtab)
10248 int bits;
10249 i6addr_t *mask;
10250 ipf_v6_masktab_t *mtab;
10251{
10252 i6addr_t zero;
10253 int i, j;
10254
10255 mtab->imt6_masks[bits]--;
10256 if (mtab->imt6_masks[bits] > 0)
10257 return;
10258
10259 if (bits == 0)
10260 mask = &zero;
10261 zero.i6[0] = 0;
10262 zero.i6[1] = 0;
10263 zero.i6[2] = 0;
10264 zero.i6[3] = 0;
10265
10266 for (i = 0; i < 129; i++) {
10267 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10268 for (j = i + 1; j < 129; j++) {
10269 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10270 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10271 break;
10272 }
10273 break;
10274 }
10275 }
10276 mtab->imt6_max--;
10277 ASSERT(mtab->imt6_max >= 0);
10278}
10279#endif