4 * Copyright (C) 2012 by Darren Reed.
6 * See the IPFILTER.LICENCE file for details on licencing.
8 * Copyright 2008 Sun Microsystems.
13 #if defined(KERNEL) || defined(_KERNEL)
19 #include <sys/errno.h>
20 #include <sys/types.h>
21 #include <sys/param.h>
23 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
24 (__FreeBSD_version >= 220000)
25 # if (__FreeBSD_version >= 400000)
26 # if !defined(IPFILTER_LKM)
27 # include "opt_inet6.h"
29 # if (__FreeBSD_version == 400019)
30 # define CSUM_DELAY_DATA
33 # include <sys/filio.h>
35 # include <sys/ioctl.h>
37 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
38 # include <sys/filio.h>
41 # include <sys/fcntl.h>
44 # include <sys/systm.h>
45 # include <sys/file.h>
51 # include <sys/file.h>
59 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
61 # include <sys/mbuf.h>
64 # include <sys/byteorder.h>
66 # if (SOLARIS2 < 5) && defined(sun)
67 # include <sys/dditypes.h>
71 # define _NET_ROUTE_INCLUDED
74 # include <sys/protosw.h>
76 #include <sys/socket.h>
81 #include <netinet/in.h>
82 #include <netinet/in_systm.h>
83 #include <netinet/ip.h>
84 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
85 # include <sys/hashing.h>
86 # include <netinet/in_var.h>
88 #include <netinet/tcp.h>
89 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
90 # include <netinet/udp.h>
91 # include <netinet/ip_icmp.h>
94 # undef _NET_ROUTE_INCLUDED
99 #include "netinet/ip_compat.h"
101 # include <netinet/icmp6.h>
102 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
103 # include <netinet6/in6_var.h>
106 #include "netinet/ip_fil.h"
107 #include "netinet/ip_nat.h"
108 #include "netinet/ip_frag.h"
109 #include "netinet/ip_state.h"
110 #include "netinet/ip_proxy.h"
111 #include "netinet/ip_auth.h"
113 # include "netinet/ip_scan.h"
115 #include "netinet/ip_sync.h"
116 #include "netinet/ip_lookup.h"
117 #include "netinet/ip_pool.h"
118 #include "netinet/ip_htable.h"
119 #ifdef IPFILTER_COMPILED
120 # include "netinet/ip_rules.h"
122 #if defined(IPFILTER_BPF) && defined(_KERNEL)
123 # include <net/bpf.h>
125 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
126 # include <sys/malloc.h>
128 #include "netinet/ipl.h"
130 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
131 # include <sys/callout.h>
132 extern struct callout ipf_slowtimer_ch;
134 #if defined(__OpenBSD__)
135 # include <sys/timeout.h>
136 extern struct timeout ipf_slowtimer_ch;
138 /* END OF INCLUDES */
141 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
142 static const char rcsid[] = "@(#)$FreeBSD$";
143 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
150 extern int blockreason;
153 #define LBUMP(x) softc->x++
154 #define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
156 static INLINE int ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
157 static u_32_t ipf_checkcipso __P((fr_info_t *, u_char *, int));
158 static u_32_t ipf_checkripso __P((u_char *));
159 static u_32_t ipf_decaps __P((fr_info_t *, u_32_t, int));
161 static frentry_t *ipf_dolog __P((fr_info_t *, u_32_t *));
163 static int ipf_flushlist __P((ipf_main_softc_t *, int *,
165 static int ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
167 static ipfunc_t ipf_findfunc __P((ipfunc_t));
168 static void *ipf_findlookup __P((ipf_main_softc_t *, int,
170 i6addr_t *, i6addr_t *));
171 static frentry_t *ipf_firewall __P((fr_info_t *, u_32_t *));
172 static int ipf_fr_matcharray __P((fr_info_t *, int *));
173 static int ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
175 static void ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
176 static int ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
177 static int ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
179 static void ipf_getstat __P((ipf_main_softc_t *,
180 struct friostat *, int));
181 static int ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
182 static void ipf_group_free __P((frgroup_t *));
183 static int ipf_grpmapfini __P((struct ipf_main_softc_s *,
185 static int ipf_grpmapinit __P((struct ipf_main_softc_s *,
187 static frentry_t *ipf_nextrule __P((ipf_main_softc_t *, int, int,
189 static int ipf_portcheck __P((frpcmp_t *, u_32_t));
190 static INLINE int ipf_pr_ah __P((fr_info_t *));
191 static INLINE void ipf_pr_esp __P((fr_info_t *));
192 static INLINE void ipf_pr_gre __P((fr_info_t *));
193 static INLINE void ipf_pr_udp __P((fr_info_t *));
194 static INLINE void ipf_pr_tcp __P((fr_info_t *));
195 static INLINE void ipf_pr_icmp __P((fr_info_t *));
196 static INLINE void ipf_pr_ipv4hdr __P((fr_info_t *));
197 static INLINE void ipf_pr_short __P((fr_info_t *, int));
198 static INLINE int ipf_pr_tcpcommon __P((fr_info_t *));
199 static INLINE int ipf_pr_udpcommon __P((fr_info_t *));
200 static void ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
202 static void ipf_rule_expire_insert __P((ipf_main_softc_t *,
204 static int ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
206 static void ipf_token_flush __P((ipf_main_softc_t *));
207 static void ipf_token_unlink __P((ipf_main_softc_t *,
209 static ipftuneable_t *ipf_tune_findbyname __P((ipftuneable_t *,
211 static ipftuneable_t *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
213 static int ipf_updateipid __P((fr_info_t *));
214 static int ipf_settimeout __P((struct ipf_main_softc_s *,
215 struct ipftuneable *,
217 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
218 !defined(__FreeBSD__)) || \
219 FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
220 OPENBSD_LT_REV(200006)
221 static int ppsratecheck(struct timeval *, int *, int);
226 * bit values for identifying presence of individual IP options
227 * All of these tables should be ordered by increasing key value on the left
228 * hand side to allow for binary searching of the array and include a trailer
229 * with a 0 for the bitmask for linear searches to easily find the end with.
231 static const struct optlist ipopts[20] = {
232 { IPOPT_NOP, 0x000001 },
233 { IPOPT_RR, 0x000002 },
234 { IPOPT_ZSU, 0x000004 },
235 { IPOPT_MTUP, 0x000008 },
236 { IPOPT_MTUR, 0x000010 },
237 { IPOPT_ENCODE, 0x000020 },
238 { IPOPT_TS, 0x000040 },
239 { IPOPT_TR, 0x000080 },
240 { IPOPT_SECURITY, 0x000100 },
241 { IPOPT_LSRR, 0x000200 },
242 { IPOPT_E_SEC, 0x000400 },
243 { IPOPT_CIPSO, 0x000800 },
244 { IPOPT_SATID, 0x001000 },
245 { IPOPT_SSRR, 0x002000 },
246 { IPOPT_ADDEXT, 0x004000 },
247 { IPOPT_VISA, 0x008000 },
248 { IPOPT_IMITD, 0x010000 },
249 { IPOPT_EIP, 0x020000 },
250 { IPOPT_FINN, 0x040000 },
255 static struct optlist ip6exthdr[] = {
256 { IPPROTO_HOPOPTS, 0x000001 },
257 { IPPROTO_IPV6, 0x000002 },
258 { IPPROTO_ROUTING, 0x000004 },
259 { IPPROTO_FRAGMENT, 0x000008 },
260 { IPPROTO_ESP, 0x000010 },
261 { IPPROTO_AH, 0x000020 },
262 { IPPROTO_NONE, 0x000040 },
263 { IPPROTO_DSTOPTS, 0x000080 },
264 { IPPROTO_MOBILITY, 0x000100 },
270 * bit values for identifying presence of individual IP security options
272 static const struct optlist secopt[8] = {
273 { IPSO_CLASS_RES4, 0x01 },
274 { IPSO_CLASS_TOPS, 0x02 },
275 { IPSO_CLASS_SECR, 0x04 },
276 { IPSO_CLASS_RES3, 0x08 },
277 { IPSO_CLASS_CONF, 0x10 },
278 { IPSO_CLASS_UNCL, 0x20 },
279 { IPSO_CLASS_RES2, 0x40 },
280 { IPSO_CLASS_RES1, 0x80 }
283 char ipfilter_version[] = IPL_VERSION;
296 #ifdef IPFILTER_COMPILED
299 #ifdef IPFILTER_CKSUM
313 * Table of functions available for use with call rules.
315 static ipfunc_resolve_t ipf_availfuncs[] = {
316 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
317 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
318 { "", NULL, NULL, NULL }
321 static ipftuneable_t ipf_main_tuneables[] = {
322 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
323 "ipf_flags", 0, 0xffffffff,
324 stsizeof(ipf_main_softc_t, ipf_flags),
326 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
328 stsizeof(ipf_main_softc_t, ipf_active),
329 IPFT_RDONLY, NULL, NULL },
330 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
331 "control_forwarding", 0, 1,
332 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
334 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
336 stsizeof(ipf_main_softc_t, ipf_update_ipid),
338 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
340 stsizeof(ipf_main_softc_t, ipf_chksrc),
342 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
344 stsizeof(ipf_main_softc_t, ipf_minttl),
346 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
347 "icmp_minfragmtu", 0, 1,
348 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
350 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
351 "default_pass", 0, 0xffffffff,
352 stsizeof(ipf_main_softc_t, ipf_pass),
354 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
355 "tcp_idle_timeout", 1, 0x7fffffff,
356 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
357 0, NULL, ipf_settimeout },
358 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
359 "tcp_close_wait", 1, 0x7fffffff,
360 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
361 0, NULL, ipf_settimeout },
362 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
363 "tcp_last_ack", 1, 0x7fffffff,
364 stsizeof(ipf_main_softc_t, ipf_tcplastack),
365 0, NULL, ipf_settimeout },
366 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
367 "tcp_timeout", 1, 0x7fffffff,
368 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
369 0, NULL, ipf_settimeout },
370 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
371 "tcp_syn_sent", 1, 0x7fffffff,
372 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
373 0, NULL, ipf_settimeout },
374 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
375 "tcp_syn_received", 1, 0x7fffffff,
376 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
377 0, NULL, ipf_settimeout },
378 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
379 "tcp_closed", 1, 0x7fffffff,
380 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
381 0, NULL, ipf_settimeout },
382 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
383 "tcp_half_closed", 1, 0x7fffffff,
384 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
385 0, NULL, ipf_settimeout },
386 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
387 "tcp_time_wait", 1, 0x7fffffff,
388 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
389 0, NULL, ipf_settimeout },
390 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
391 "udp_timeout", 1, 0x7fffffff,
392 stsizeof(ipf_main_softc_t, ipf_udptimeout),
393 0, NULL, ipf_settimeout },
394 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
395 "udp_ack_timeout", 1, 0x7fffffff,
396 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
397 0, NULL, ipf_settimeout },
398 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
399 "icmp_timeout", 1, 0x7fffffff,
400 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
401 0, NULL, ipf_settimeout },
402 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
403 "icmp_ack_timeout", 1, 0x7fffffff,
404 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
405 0, NULL, ipf_settimeout },
406 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
407 "ip_timeout", 1, 0x7fffffff,
408 stsizeof(ipf_main_softc_t, ipf_iptimeout),
409 0, NULL, ipf_settimeout },
410 #if defined(INSTANCES) && defined(_KERNEL)
411 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
412 "intercept_loopback", 0, 1,
413 stsizeof(ipf_main_softc_t, ipf_get_loopback),
414 0, NULL, ipf_set_loopback },
424 * The next section of code is a a collection of small routines that set
425 * fields in the fr_info_t structure passed based on properties of the
426 * current packet. There are different routines for the same protocol
427 * for each of IPv4 and IPv6. Adding a new protocol, for which there
428 * will "special" inspection for setup, is now more easily done by adding
429 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
430 * adding more code to a growing switch statement.
433 static INLINE int ipf_pr_ah6 __P((fr_info_t *));
434 static INLINE void ipf_pr_esp6 __P((fr_info_t *));
435 static INLINE void ipf_pr_gre6 __P((fr_info_t *));
436 static INLINE void ipf_pr_udp6 __P((fr_info_t *));
437 static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
438 static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
439 static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
440 static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
441 static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
442 static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
443 static INLINE int ipf_pr_routing6 __P((fr_info_t *));
444 static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
445 static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
446 static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
449 /* ------------------------------------------------------------------------ */
450 /* Function: ipf_pr_short6 */
452 /* Parameters: fin(I) - pointer to packet information */
453 /* xmin(I) - minimum header size */
456 /* This is function enforces the 'is a packet too short to be legit' rule */
457 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
458 /* for ipf_pr_short() for more details. */
459 /* ------------------------------------------------------------------------ */
461 ipf_pr_short6(fin, xmin)
466 if (fin->fin_dlen < xmin)
467 fin->fin_flx |= FI_SHORT;
471 /* ------------------------------------------------------------------------ */
472 /* Function: ipf_pr_ipv6hdr */
474 /* Parameters: fin(I) - pointer to packet information */
477 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
478 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
479 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
480 /* of that possibility arising. */
481 /* ------------------------------------------------------------------------ */
486 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
487 int p, go = 1, i, hdrcount;
488 fr_ip_t *fi = &fin->fin_fi;
499 fi->fi_ttl = ip6->ip6_hlim;
500 fi->fi_src.in6 = ip6->ip6_src;
501 fin->fin_crc += fi->fi_src.i6[0];
502 fin->fin_crc += fi->fi_src.i6[1];
503 fin->fin_crc += fi->fi_src.i6[2];
504 fin->fin_crc += fi->fi_src.i6[3];
505 fi->fi_dst.in6 = ip6->ip6_dst;
506 fin->fin_crc += fi->fi_dst.i6[0];
507 fin->fin_crc += fi->fi_dst.i6[1];
508 fin->fin_crc += fi->fi_dst.i6[2];
509 fin->fin_crc += fi->fi_dst.i6[3];
511 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
512 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
515 while (go && !(fin->fin_flx & FI_SHORT)) {
528 case IPPROTO_ICMPV6 :
538 case IPPROTO_HOPOPTS :
539 p = ipf_pr_hopopts6(fin);
542 case IPPROTO_MOBILITY :
543 p = ipf_pr_mobility6(fin);
546 case IPPROTO_DSTOPTS :
547 p = ipf_pr_dstopts6(fin);
550 case IPPROTO_ROUTING :
551 p = ipf_pr_routing6(fin);
564 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
565 if (ip6exthdr[i].ol_val == p) {
566 fin->fin_flx |= ip6exthdr[i].ol_bit;
576 case IPPROTO_FRAGMENT :
577 p = ipf_pr_fragment6(fin);
579 * Given that the only fragments we want to let through
580 * (where fin_off != 0) are those where the non-first
581 * fragments only have data, we can safely stop looking
582 * at headers if this is a non-leading fragment.
584 if (fin->fin_off != 0)
595 * It is important to note that at this point, for the
596 * extension headers (go != 0), the entire header may not have
597 * been pulled up when the code gets to this point. This is
598 * only done for "go != 0" because the other header handlers
599 * will all pullup their complete header. The other indicator
600 * of an incomplete packet is that this was just an extension
603 if ((go != 0) && (p != IPPROTO_NONE) &&
604 (ipf_pr_pullup(fin, 0) == -1)) {
611 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
612 * and destroy whatever packet was here. The caller of this function
613 * expects us to return if there is a problem with ipf_pullup.
615 if (fin->fin_m == NULL) {
616 ipf_main_softc_t *softc = fin->fin_main_soft;
618 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
625 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
626 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
628 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
629 ipf_main_softc_t *softc = fin->fin_main_soft;
631 fin->fin_flx |= FI_BAD;
632 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
633 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
638 /* ------------------------------------------------------------------------ */
639 /* Function: ipf_pr_ipv6exthdr */
640 /* Returns: struct ip6_ext * - pointer to the start of the next header */
641 /* or NULL if there is a prolblem. */
642 /* Parameters: fin(I) - pointer to packet information */
643 /* multiple(I) - flag indicating yes/no if multiple occurances */
644 /* of this extension header are allowed. */
645 /* proto(I) - protocol number for this extension header */
648 /* This function embodies a number of common checks that all IPv6 extension */
649 /* headers must be subjected to. For example, making sure the packet is */
650 /* big enough for it to be in, checking if it is repeated and setting a */
651 /* flag to indicate its presence. */
652 /* ------------------------------------------------------------------------ */
653 static INLINE struct ip6_ext *
654 ipf_pr_ipv6exthdr(fin, multiple, proto)
658 ipf_main_softc_t *softc = fin->fin_main_soft;
663 fin->fin_flx |= FI_V6EXTHDR;
665 /* 8 is default length of extension hdr */
666 if ((fin->fin_dlen - 8) < 0) {
667 fin->fin_flx |= FI_SHORT;
668 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
672 if (ipf_pr_pullup(fin, 8) == -1) {
673 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
680 case IPPROTO_FRAGMENT :
684 shift = 8 + (hdr->ip6e_len << 3);
688 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
689 fin->fin_flx |= FI_BAD;
690 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
694 fin->fin_dp = (char *)fin->fin_dp + shift;
695 fin->fin_dlen -= shift;
698 * If we have seen a fragment header, do not set any flags to indicate
699 * the presence of this extension header as it has no impact on the
700 * end result until after it has been defragmented.
702 if (fin->fin_flx & FI_FRAG)
705 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
706 if (ip6exthdr[i].ol_val == proto) {
708 * Most IPv6 extension headers are only allowed once.
710 if ((multiple == 0) &&
711 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
712 fin->fin_flx |= FI_BAD;
714 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
722 /* ------------------------------------------------------------------------ */
723 /* Function: ipf_pr_hopopts6 */
724 /* Returns: int - value of the next header or IPPROTO_NONE if error */
725 /* Parameters: fin(I) - pointer to packet information */
728 /* This is function checks pending hop by hop options extension header */
729 /* ------------------------------------------------------------------------ */
736 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
739 return hdr->ip6e_nxt;
743 /* ------------------------------------------------------------------------ */
744 /* Function: ipf_pr_mobility6 */
745 /* Returns: int - value of the next header or IPPROTO_NONE if error */
746 /* Parameters: fin(I) - pointer to packet information */
749 /* This is function checks the IPv6 mobility extension header */
750 /* ------------------------------------------------------------------------ */
752 ipf_pr_mobility6(fin)
757 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
760 return hdr->ip6e_nxt;
764 /* ------------------------------------------------------------------------ */
765 /* Function: ipf_pr_routing6 */
766 /* Returns: int - value of the next header or IPPROTO_NONE if error */
767 /* Parameters: fin(I) - pointer to packet information */
770 /* This is function checks pending routing extension header */
771 /* ------------------------------------------------------------------------ */
776 struct ip6_routing *hdr;
778 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
782 switch (hdr->ip6r_type)
786 * Nasty extension header length?
788 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
789 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
790 ipf_main_softc_t *softc = fin->fin_main_soft;
792 fin->fin_flx |= FI_BAD;
793 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
802 return hdr->ip6r_nxt;
806 /* ------------------------------------------------------------------------ */
807 /* Function: ipf_pr_fragment6 */
808 /* Returns: int - value of the next header or IPPROTO_NONE if error */
809 /* Parameters: fin(I) - pointer to packet information */
812 /* Examine the IPv6 fragment header and extract fragment offset information.*/
814 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
815 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
816 /* packets with a fragment header can fit into. They are as follows: */
818 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
819 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
820 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
821 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
822 /* 5. [IPV6][0-n EH][FH][data] */
824 /* IPV6 = IPv6 header, FH = Fragment Header, */
825 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
827 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
828 /* scenario in which they happen is in extreme circumstances that are most */
829 /* likely to be an indication of an attack rather than normal traffic. */
830 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
831 /* are two rules that can be used to guard against type 3 packets: L4 */
832 /* headers must always be in a packet that has the offset field set to 0 */
833 /* and no packet is allowed to overlay that where offset = 0. */
834 /* ------------------------------------------------------------------------ */
836 ipf_pr_fragment6(fin)
839 ipf_main_softc_t *softc = fin->fin_main_soft;
840 struct ip6_frag *frag;
842 fin->fin_flx |= FI_FRAG;
844 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
846 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
850 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
852 * Any fragment that isn't the last fragment must have its
853 * length as a multiple of 8.
855 if ((fin->fin_plen & 7) != 0)
856 fin->fin_flx |= FI_BAD;
859 fin->fin_fraghdr = frag;
860 fin->fin_id = frag->ip6f_ident;
861 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
862 if (fin->fin_off != 0)
863 fin->fin_flx |= FI_FRAGBODY;
866 * Jumbograms aren't handled, so the max. length is 64k
868 if ((fin->fin_off << 3) + fin->fin_dlen > 65535)
869 fin->fin_flx |= FI_BAD;
872 * We don't know where the transport layer header (or whatever is next
873 * is), as it could be behind destination options (amongst others) so
874 * return the fragment header as the type of packet this is. Note that
875 * this effectively disables the fragment cache for > 1 protocol at a
878 return frag->ip6f_nxt;
882 /* ------------------------------------------------------------------------ */
883 /* Function: ipf_pr_dstopts6 */
884 /* Returns: int - value of the next header or IPPROTO_NONE if error */
885 /* Parameters: fin(I) - pointer to packet information */
888 /* This is function checks pending destination options extension header */
889 /* ------------------------------------------------------------------------ */
894 ipf_main_softc_t *softc = fin->fin_main_soft;
897 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
899 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
902 return hdr->ip6e_nxt;
906 /* ------------------------------------------------------------------------ */
907 /* Function: ipf_pr_icmp6 */
909 /* Parameters: fin(I) - pointer to packet information */
912 /* This routine is mainly concerned with determining the minimum valid size */
913 /* for an ICMPv6 packet. */
914 /* ------------------------------------------------------------------------ */
919 int minicmpsz = sizeof(struct icmp6_hdr);
920 struct icmp6_hdr *icmp6;
922 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
923 ipf_main_softc_t *softc = fin->fin_main_soft;
925 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
929 if (fin->fin_dlen > 1) {
934 fin->fin_data[0] = *(u_short *)icmp6;
936 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
937 fin->fin_flx |= FI_ICMPQUERY;
939 switch (icmp6->icmp6_type)
941 case ICMP6_ECHO_REPLY :
942 case ICMP6_ECHO_REQUEST :
943 if (fin->fin_dlen >= 6)
944 fin->fin_data[1] = icmp6->icmp6_id;
945 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
948 case ICMP6_DST_UNREACH :
949 case ICMP6_PACKET_TOO_BIG :
950 case ICMP6_TIME_EXCEEDED :
951 case ICMP6_PARAM_PROB :
952 fin->fin_flx |= FI_ICMPERR;
953 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
954 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
957 if (M_LEN(fin->fin_m) < fin->fin_plen) {
958 if (ipf_coalesce(fin) != 1)
962 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
966 * If the destination of this packet doesn't match the
967 * source of the original packet then this packet is
971 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
972 if (IP6_NEQ(&fin->fin_fi.fi_dst,
973 (i6addr_t *)&ip6->ip6_src))
974 fin->fin_flx |= FI_BAD;
981 ipf_pr_short6(fin, minicmpsz);
982 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
983 u_char p = fin->fin_p;
985 fin->fin_p = IPPROTO_ICMPV6;
992 /* ------------------------------------------------------------------------ */
993 /* Function: ipf_pr_udp6 */
995 /* Parameters: fin(I) - pointer to packet information */
998 /* Analyse the packet for IPv6/UDP properties. */
999 /* Is not expected to be called for fragmented packets. */
1000 /* ------------------------------------------------------------------------ */
1006 if (ipf_pr_udpcommon(fin) == 0) {
1007 u_char p = fin->fin_p;
1009 fin->fin_p = IPPROTO_UDP;
1010 ipf_checkv6sum(fin);
1016 /* ------------------------------------------------------------------------ */
1017 /* Function: ipf_pr_tcp6 */
1019 /* Parameters: fin(I) - pointer to packet information */
1022 /* Analyse the packet for IPv6/TCP properties. */
1023 /* Is not expected to be called for fragmented packets. */
1024 /* ------------------------------------------------------------------------ */
1030 if (ipf_pr_tcpcommon(fin) == 0) {
1031 u_char p = fin->fin_p;
1033 fin->fin_p = IPPROTO_TCP;
1034 ipf_checkv6sum(fin);
1040 /* ------------------------------------------------------------------------ */
1041 /* Function: ipf_pr_esp6 */
1043 /* Parameters: fin(I) - pointer to packet information */
1046 /* Analyse the packet for ESP properties. */
1047 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1048 /* even though the newer ESP packets must also have a sequence number that */
1049 /* is 32bits as well, it is not possible(?) to determine the version from a */
1050 /* simple packet header. */
1051 /* ------------------------------------------------------------------------ */
1057 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1058 ipf_main_softc_t *softc = fin->fin_main_soft;
1060 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1066 /* ------------------------------------------------------------------------ */
1067 /* Function: ipf_pr_ah6 */
1068 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1069 /* Parameters: fin(I) - pointer to packet information */
1072 /* Analyse the packet for AH properties. */
1073 /* The minimum length is taken to be the combination of all fields in the */
1074 /* header being present and no authentication data (null algorithm used.) */
1075 /* ------------------------------------------------------------------------ */
1082 fin->fin_flx |= FI_AH;
1084 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1086 ipf_main_softc_t *softc = fin->fin_main_soft;
1088 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1089 return IPPROTO_NONE;
1092 ipf_pr_short6(fin, sizeof(*ah));
1095 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1096 * enough data to satisfy ah_next (the very first one.)
1102 /* ------------------------------------------------------------------------ */
1103 /* Function: ipf_pr_gre6 */
1105 /* Parameters: fin(I) - pointer to packet information */
1107 /* Analyse the packet for GRE properties. */
1108 /* ------------------------------------------------------------------------ */
1115 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1116 ipf_main_softc_t *softc = fin->fin_main_soft;
1118 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1123 if (GRE_REV(gre->gr_flags) == 1)
1124 fin->fin_data[0] = gre->gr_call;
1126 #endif /* USE_INET6 */
1129 /* ------------------------------------------------------------------------ */
1130 /* Function: ipf_pr_pullup */
1131 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1132 /* Parameters: fin(I) - pointer to packet information */
1133 /* plen(I) - length (excluding L3 header) to pullup */
1135 /* Short inline function to cut down on code duplication to perform a call */
1136 /* to ipf_pullup to ensure there is the required amount of data, */
1137 /* consecutively in the packet buffer. */
1139 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1140 /* points to the first byte after the complete layer 3 header, which will */
1141 /* include all of the known extension headers for IPv6 or options for IPv4. */
1143 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1144 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1145 /* - fin_ip) to what is passed through. */
1146 /* ------------------------------------------------------------------------ */
1148 ipf_pr_pullup(fin, plen)
1152 ipf_main_softc_t *softc = fin->fin_main_soft;
1154 if (fin->fin_m != NULL) {
1155 if (fin->fin_dp != NULL)
1156 plen += (char *)fin->fin_dp -
1157 ((char *)fin->fin_ip + fin->fin_hlen);
1158 plen += fin->fin_hlen;
1159 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1160 #if defined(_KERNEL)
1161 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1162 DT(ipf_pullup_fail);
1163 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1166 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1168 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1170 * Fake ipf_pullup failing
1172 fin->fin_reason = FRB_PULLUP;
1173 *fin->fin_mp = NULL;
1184 /* ------------------------------------------------------------------------ */
1185 /* Function: ipf_pr_short */
1187 /* Parameters: fin(I) - pointer to packet information */
1188 /* xmin(I) - minimum header size */
1190 /* Check if a packet is "short" as defined by xmin. The rule we are */
1191 /* applying here is that the packet must not be fragmented within the layer */
1192 /* 4 header. That is, it must not be a fragment that has its offset set to */
1193 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1194 /* entire layer 4 header must be present (min). */
1195 /* ------------------------------------------------------------------------ */
1197 ipf_pr_short(fin, xmin)
1202 if (fin->fin_off == 0) {
1203 if (fin->fin_dlen < xmin)
1204 fin->fin_flx |= FI_SHORT;
1205 } else if (fin->fin_off < xmin) {
1206 fin->fin_flx |= FI_SHORT;
1211 /* ------------------------------------------------------------------------ */
1212 /* Function: ipf_pr_icmp */
1214 /* Parameters: fin(I) - pointer to packet information */
1217 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1218 /* except extrememly bad packets, both type and code will be present. */
1219 /* The expected minimum size of an ICMP packet is very much dependent on */
1220 /* the type of it. */
1222 /* XXX - other ICMP sanity checks? */
1223 /* ------------------------------------------------------------------------ */
1228 ipf_main_softc_t *softc = fin->fin_main_soft;
1229 int minicmpsz = sizeof(struct icmp);
1233 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1235 if (fin->fin_off != 0) {
1236 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1240 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1241 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1247 fin->fin_data[0] = *(u_short *)icmp;
1248 fin->fin_data[1] = icmp->icmp_id;
1250 switch (icmp->icmp_type)
1252 case ICMP_ECHOREPLY :
1254 /* Router discovery messaes - RFC 1256 */
1255 case ICMP_ROUTERADVERT :
1256 case ICMP_ROUTERSOLICIT :
1257 fin->fin_flx |= FI_ICMPQUERY;
1258 minicmpsz = ICMP_MINLEN;
1261 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1262 * 3 * timestamp(3 * 4)
1265 case ICMP_TSTAMPREPLY :
1266 fin->fin_flx |= FI_ICMPQUERY;
1270 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1274 case ICMP_IREQREPLY :
1276 case ICMP_MASKREPLY :
1277 fin->fin_flx |= FI_ICMPQUERY;
1281 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1285 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1286 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu)
1287 fin->fin_flx |= FI_BAD;
1290 case ICMP_SOURCEQUENCH :
1291 case ICMP_REDIRECT :
1292 case ICMP_TIMXCEED :
1293 case ICMP_PARAMPROB :
1294 fin->fin_flx |= FI_ICMPERR;
1295 if (ipf_coalesce(fin) != 1) {
1296 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1301 * ICMP error packets should not be generated for IP
1302 * packets that are a fragment that isn't the first
1305 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1306 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1307 fin->fin_flx |= FI_BAD;
1310 * If the destination of this packet doesn't match the
1311 * source of the original packet then this packet is
1314 if (oip->ip_src.s_addr != fin->fin_daddr)
1315 fin->fin_flx |= FI_BAD;
1321 ipf_pr_short(fin, minicmpsz);
1323 ipf_checkv4sum(fin);
1327 /* ------------------------------------------------------------------------ */
1328 /* Function: ipf_pr_tcpcommon */
1329 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1330 /* Parameters: fin(I) - pointer to packet information */
1332 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1333 /* and make some checks with how they interact with other fields. */
1334 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1335 /* valid and mark the packet as bad if not. */
1336 /* ------------------------------------------------------------------------ */
1338 ipf_pr_tcpcommon(fin)
1341 ipf_main_softc_t *softc = fin->fin_main_soft;
1345 fin->fin_flx |= FI_TCPUDP;
1346 if (fin->fin_off != 0) {
1347 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1351 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1352 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1357 if (fin->fin_dlen > 3) {
1358 fin->fin_sport = ntohs(tcp->th_sport);
1359 fin->fin_dport = ntohs(tcp->th_dport);
1362 if ((fin->fin_flx & FI_SHORT) != 0) {
1363 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1368 * Use of the TCP data offset *must* result in a value that is at
1369 * least the same size as the TCP header.
1371 tlen = TCP_OFF(tcp) << 2;
1372 if (tlen < sizeof(tcphdr_t)) {
1373 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1374 fin->fin_flx |= FI_BAD;
1378 flags = tcp->th_flags;
1379 fin->fin_tcpf = tcp->th_flags;
1382 * If the urgent flag is set, then the urgent pointer must
1383 * also be set and vice versa. Good TCP packets do not have
1384 * just one of these set.
1386 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1387 fin->fin_flx |= FI_BAD;
1389 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1391 * Ignore this case (#if 0) as it shows up in "real"
1392 * traffic with bogus values in the urgent pointer field.
1394 fin->fin_flx |= FI_BAD;
1396 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1397 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1398 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1399 fin->fin_flx |= FI_BAD;
1401 } else if (((flags & TH_SYN) != 0) &&
1402 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1404 * SYN with URG and PUSH set is not for normal TCP but it is
1405 * possible(?) with T/TCP...but who uses T/TCP?
1407 fin->fin_flx |= FI_BAD;
1409 } else if (!(flags & TH_ACK)) {
1411 * If the ack bit isn't set, then either the SYN or
1412 * RST bit must be set. If the SYN bit is set, then
1413 * we expect the ACK field to be 0. If the ACK is
1414 * not set and if URG, PSH or FIN are set, consdier
1415 * that to indicate a bad TCP packet.
1417 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1419 * Cisco PIX sets the ACK field to a random value.
1420 * In light of this, do not set FI_BAD until a patch
1421 * is available from Cisco to ensure that
1422 * interoperability between existing systems is
1425 /*fin->fin_flx |= FI_BAD*/;
1426 } else if (!(flags & (TH_RST|TH_SYN))) {
1427 fin->fin_flx |= FI_BAD;
1428 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1429 fin->fin_flx |= FI_BAD;
1432 if (fin->fin_flx & FI_BAD) {
1433 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1438 * At this point, it's not exactly clear what is to be gained by
1439 * marking up which TCP options are and are not present. The one we
1440 * are most interested in is the TCP window scale. This is only in
1441 * a SYN packet [RFC1323] so we don't need this here...?
1442 * Now if we were to analyse the header for passive fingerprinting,
1443 * then that might add some weight to adding this...
1445 if (tlen == sizeof(tcphdr_t)) {
1449 if (ipf_pr_pullup(fin, tlen) == -1) {
1450 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1457 s = (u_char *)(tcp + 1);
1458 off = IP_HL(ip) << 2;
1460 if (fin->fin_mp != NULL) {
1461 mb_t *m = *fin->fin_mp;
1463 if (off + tlen > M_LEN(m))
1467 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1471 else if (opt == TCPOPT_NOP)
1477 if (ol < 2 || ol > tlen)
1481 for (i = 9, mv = 4; mv >= 0; ) {
1483 if (opt == (u_char)op->ol_val) {
1484 optmsk |= op->ol_bit;
1498 /* ------------------------------------------------------------------------ */
1499 /* Function: ipf_pr_udpcommon */
1500 /* Returns: int - 0 = header ok, 1 = bad packet */
1501 /* Parameters: fin(I) - pointer to packet information */
1503 /* Extract the UDP source and destination ports, if present. If compiled */
1504 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1505 /* ------------------------------------------------------------------------ */
1507 ipf_pr_udpcommon(fin)
1512 fin->fin_flx |= FI_TCPUDP;
1514 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1515 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1516 ipf_main_softc_t *softc = fin->fin_main_soft;
1518 fin->fin_flx |= FI_SHORT;
1519 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1525 fin->fin_sport = ntohs(udp->uh_sport);
1526 fin->fin_dport = ntohs(udp->uh_dport);
1533 /* ------------------------------------------------------------------------ */
1534 /* Function: ipf_pr_tcp */
1536 /* Parameters: fin(I) - pointer to packet information */
1539 /* Analyse the packet for IPv4/TCP properties. */
1540 /* ------------------------------------------------------------------------ */
1546 ipf_pr_short(fin, sizeof(tcphdr_t));
1548 if (ipf_pr_tcpcommon(fin) == 0)
1549 ipf_checkv4sum(fin);
1553 /* ------------------------------------------------------------------------ */
1554 /* Function: ipf_pr_udp */
1556 /* Parameters: fin(I) - pointer to packet information */
1559 /* Analyse the packet for IPv4/UDP properties. */
1560 /* ------------------------------------------------------------------------ */
1566 ipf_pr_short(fin, sizeof(udphdr_t));
1568 if (ipf_pr_udpcommon(fin) == 0)
1569 ipf_checkv4sum(fin);
1573 /* ------------------------------------------------------------------------ */
1574 /* Function: ipf_pr_esp */
1576 /* Parameters: fin(I) - pointer to packet information */
1578 /* Analyse the packet for ESP properties. */
1579 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1580 /* even though the newer ESP packets must also have a sequence number that */
1581 /* is 32bits as well, it is not possible(?) to determine the version from a */
1582 /* simple packet header. */
1583 /* ------------------------------------------------------------------------ */
1589 if (fin->fin_off == 0) {
1590 ipf_pr_short(fin, 8);
1591 if (ipf_pr_pullup(fin, 8) == -1) {
1592 ipf_main_softc_t *softc = fin->fin_main_soft;
1594 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1600 /* ------------------------------------------------------------------------ */
1601 /* Function: ipf_pr_ah */
1602 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1603 /* Parameters: fin(I) - pointer to packet information */
1605 /* Analyse the packet for AH properties. */
1606 /* The minimum length is taken to be the combination of all fields in the */
1607 /* header being present and no authentication data (null algorithm used.) */
1608 /* ------------------------------------------------------------------------ */
1613 ipf_main_softc_t *softc = fin->fin_main_soft;
1617 fin->fin_flx |= FI_AH;
1618 ipf_pr_short(fin, sizeof(*ah));
1620 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1621 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1622 return IPPROTO_NONE;
1625 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1626 DT(fr_v4_ah_pullup_1);
1627 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1628 return IPPROTO_NONE;
1631 ah = (authhdr_t *)fin->fin_dp;
1633 len = (ah->ah_plen + 2) << 2;
1634 ipf_pr_short(fin, len);
1635 if (ipf_pr_pullup(fin, len) == -1) {
1636 DT(fr_v4_ah_pullup_2);
1637 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1638 return IPPROTO_NONE;
1642 * Adjust fin_dp and fin_dlen for skipping over the authentication
1645 fin->fin_dp = (char *)fin->fin_dp + len;
1646 fin->fin_dlen -= len;
1651 /* ------------------------------------------------------------------------ */
1652 /* Function: ipf_pr_gre */
1654 /* Parameters: fin(I) - pointer to packet information */
1656 /* Analyse the packet for GRE properties. */
1657 /* ------------------------------------------------------------------------ */
1662 ipf_main_softc_t *softc = fin->fin_main_soft;
1665 ipf_pr_short(fin, sizeof(grehdr_t));
1667 if (fin->fin_off != 0) {
1668 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1672 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1673 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1678 if (GRE_REV(gre->gr_flags) == 1)
1679 fin->fin_data[0] = gre->gr_call;
1683 /* ------------------------------------------------------------------------ */
1684 /* Function: ipf_pr_ipv4hdr */
1686 /* Parameters: fin(I) - pointer to packet information */
1689 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1690 /* Check all options present and flag their presence if any exist. */
1691 /* ------------------------------------------------------------------------ */
1696 u_short optmsk = 0, secmsk = 0, auth = 0;
1697 int hlen, ol, mv, p, i;
1698 const struct optlist *op;
1705 hlen = fin->fin_hlen;
1711 fi->fi_tos = ip->ip_tos;
1712 fin->fin_id = ip->ip_id;
1713 off = ntohs(ip->ip_off);
1715 /* Get both TTL and protocol */
1716 fi->fi_p = ip->ip_p;
1717 fi->fi_ttl = ip->ip_ttl;
1719 /* Zero out bits not used in IPv6 address */
1720 fi->fi_src.i6[1] = 0;
1721 fi->fi_src.i6[2] = 0;
1722 fi->fi_src.i6[3] = 0;
1723 fi->fi_dst.i6[1] = 0;
1724 fi->fi_dst.i6[2] = 0;
1725 fi->fi_dst.i6[3] = 0;
1727 fi->fi_saddr = ip->ip_src.s_addr;
1728 fin->fin_crc += fi->fi_saddr;
1729 fi->fi_daddr = ip->ip_dst.s_addr;
1730 fin->fin_crc += fi->fi_daddr;
1731 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1732 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1735 * set packet attribute flags based on the offset and
1736 * calculate the byte offset that it represents.
1738 off &= IP_MF|IP_OFFMASK;
1740 int morefrag = off & IP_MF;
1742 fi->fi_flx |= FI_FRAG;
1745 fin->fin_flx |= FI_FRAGBODY;
1747 if ((off + fin->fin_dlen > 65535) ||
1748 (fin->fin_dlen == 0) ||
1749 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1751 * The length of the packet, starting at its
1752 * offset cannot exceed 65535 (0xffff) as the
1753 * length of an IP packet is only 16 bits.
1755 * Any fragment that isn't the last fragment
1756 * must have a length greater than 0 and it
1757 * must be an even multiple of 8.
1759 fi->fi_flx |= FI_BAD;
1766 * Call per-protocol setup and checking
1768 if (p == IPPROTO_AH) {
1770 * Treat AH differently because we expect there to be another
1771 * layer 4 header after it.
1800 * If it is a standard IP header (no options), set the flag fields
1801 * which relate to options to 0.
1803 if (hlen == sizeof(*ip)) {
1811 * So the IP header has some IP options attached. Walk the entire
1812 * list of options present with this packet and set flags to indicate
1813 * which ones are here and which ones are not. For the somewhat out
1814 * of date and obscure security classification options, set a flag to
1815 * represent which classification is present.
1817 fi->fi_flx |= FI_OPTIONS;
1819 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1823 else if (opt == IPOPT_NOP)
1829 if (ol < 2 || ol > hlen)
1832 for (i = 9, mv = 4; mv >= 0; ) {
1835 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1840 case IPOPT_SECURITY :
1841 if (optmsk & op->ol_bit) {
1842 fin->fin_flx |= FI_BAD;
1844 doi = ipf_checkripso(s);
1846 auth = doi & 0xffff;
1852 if (optmsk & op->ol_bit) {
1853 fin->fin_flx |= FI_BAD;
1855 doi = ipf_checkcipso(fin,
1858 auth = doi & 0xffff;
1862 optmsk |= op->ol_bit;
1865 if (opt < op->ol_val)
1878 if (auth && !(auth & 0x0100))
1880 fi->fi_optmsk = optmsk;
1881 fi->fi_secmsk = secmsk;
1886 /* ------------------------------------------------------------------------ */
1887 /* Function: ipf_checkripso */
1889 /* Parameters: s(I) - pointer to start of RIPSO option */
1891 /* ------------------------------------------------------------------------ */
1896 const struct optlist *sp;
1897 u_short secmsk = 0, auth = 0;
1901 sec = *(s + 2); /* classification */
1902 for (j = 3, m = 2; m >= 0; ) {
1904 if (sec == sp->ol_val) {
1905 secmsk |= sp->ol_bit;
1911 if (sec < sp->ol_val)
1918 return (secmsk << 16) | auth;
1922 /* ------------------------------------------------------------------------ */
1923 /* Function: ipf_checkcipso */
1924 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1925 /* Parameters: fin(IO) - pointer to packet information */
1926 /* s(I) - pointer to start of CIPSO option */
1927 /* ol(I) - length of CIPSO option field */
1929 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1930 /* header and returns that whilst also storing the highest sensitivity */
1931 /* value found in the fr_info_t structure. */
1933 /* No attempt is made to extract the category bitmaps as these are defined */
1934 /* by the user (rather than the protocol) and can be rather numerous on the */
1936 /* ------------------------------------------------------------------------ */
1938 ipf_checkcipso(fin, s, ol)
1943 ipf_main_softc_t *softc = fin->fin_main_soft;
1946 u_char *t, tag, tlen, sensitivity;
1949 if (ol < 6 || ol > 40) {
1950 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1951 fin->fin_flx |= FI_BAD;
1956 fi->fi_sensitivity = 0;
1958 * The DOI field MUST be there.
1960 bcopy(s + 2, &doi, sizeof(doi));
1962 t = (u_char *)s + 6;
1963 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1966 if (tlen > len || tlen < 4 || tlen > 34) {
1967 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1968 fin->fin_flx |= FI_BAD;
1974 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1975 * draft (16 July 1992) that has expired.
1978 fin->fin_flx |= FI_BAD;
1980 } else if (tag == 1) {
1981 if (*(t + 2) != 0) {
1982 fin->fin_flx |= FI_BAD;
1985 sensitivity = *(t + 3);
1986 /* Category bitmap for categories 0-239 */
1988 } else if (tag == 4) {
1989 if (*(t + 2) != 0) {
1990 fin->fin_flx |= FI_BAD;
1993 sensitivity = *(t + 3);
1994 /* Enumerated categories, 16bits each, upto 15 */
1996 } else if (tag == 5) {
1997 if (*(t + 2) != 0) {
1998 fin->fin_flx |= FI_BAD;
2001 sensitivity = *(t + 3);
2002 /* Range of categories (2*16bits), up to 7 pairs */
2004 } else if (tag > 127) {
2005 /* Custom defined DOI */
2008 fin->fin_flx |= FI_BAD;
2012 if (sensitivity > fi->fi_sensitivity)
2013 fi->fi_sensitivity = sensitivity;
2020 /* ------------------------------------------------------------------------ */
2021 /* Function: ipf_makefrip */
2022 /* Returns: int - 0 == packet ok, -1 == packet freed */
2023 /* Parameters: hlen(I) - length of IP packet header */
2024 /* ip(I) - pointer to the IP header */
2025 /* fin(IO) - pointer to packet information */
2027 /* Compact the IP header into a structure which contains just the info. */
2028 /* which is useful for comparing IP headers with and store this information */
2029 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2030 /* this function will be called with either an IPv4 or IPv6 packet. */
2031 /* ------------------------------------------------------------------------ */
2033 ipf_makefrip(hlen, ip, fin)
2038 ipf_main_softc_t *softc = fin->fin_main_soft;
2042 fin->fin_hlen = (u_short)hlen;
2044 fin->fin_rule = 0xffffffff;
2045 fin->fin_group[0] = -1;
2046 fin->fin_group[1] = '\0';
2047 fin->fin_dp = (char *)ip + hlen;
2051 fin->fin_plen = ntohs(ip->ip_len);
2052 fin->fin_dlen = fin->fin_plen - hlen;
2053 ipf_pr_ipv4hdr(fin);
2055 } else if (v == 6) {
2056 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2057 fin->fin_dlen = fin->fin_plen;
2058 fin->fin_plen += hlen;
2060 ipf_pr_ipv6hdr(fin);
2063 if (fin->fin_ip == NULL) {
2064 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2071 /* ------------------------------------------------------------------------ */
2072 /* Function: ipf_portcheck */
2073 /* Returns: int - 1 == port matched, 0 == port match failed */
2074 /* Parameters: frp(I) - pointer to port check `expression' */
2075 /* pop(I) - port number to evaluate */
2077 /* Perform a comparison of a port number against some other(s), using a */
2078 /* structure with compare information stored in it. */
2079 /* ------------------------------------------------------------------------ */
2081 ipf_portcheck(frp, pop)
2091 * Do opposite test to that required and continue if that succeeds.
2093 switch (frp->frp_cmp)
2096 if (pop != po) /* EQUAL */
2100 if (pop == po) /* NOTEQUAL */
2104 if (pop >= po) /* LESSTHAN */
2108 if (pop <= po) /* GREATERTHAN */
2112 if (pop > po) /* LT or EQ */
2116 if (pop < po) /* GT or EQ */
2120 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2124 if (pop <= po || pop >= frp->frp_top) /* In range */
2128 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2138 /* ------------------------------------------------------------------------ */
2139 /* Function: ipf_tcpudpchk */
2140 /* Returns: int - 1 == protocol matched, 0 == check failed */
2141 /* Parameters: fda(I) - pointer to packet information */
2142 /* ft(I) - pointer to structure with comparison data */
2144 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2145 /* structure containing information that we want to match against. */
2146 /* ------------------------------------------------------------------------ */
2148 ipf_tcpudpchk(fi, ft)
2155 * Both ports should *always* be in the first fragment.
2156 * So far, I cannot find any cases where they can not be.
2158 * compare destination ports
2161 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2164 * compare source ports
2166 if (err && ft->ftu_scmp)
2167 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2170 * If we don't have all the TCP/UDP header, then how can we
2171 * expect to do any sort of match on it ? If we were looking for
2172 * TCP flags, then NO match. If not, then match (which should
2173 * satisfy the "short" class too).
2175 if (err && (fi->fi_p == IPPROTO_TCP)) {
2176 if (fi->fi_flx & FI_SHORT)
2177 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2179 * Match the flags ? If not, abort this match.
2181 if (ft->ftu_tcpfm &&
2182 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2183 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2184 ft->ftu_tcpfm, ft->ftu_tcpf));
2192 /* ------------------------------------------------------------------------ */
2193 /* Function: ipf_check_ipf */
2194 /* Returns: int - 0 == match, else no match */
2195 /* Parameters: fin(I) - pointer to packet information */
2196 /* fr(I) - pointer to filter rule */
2197 /* portcmp(I) - flag indicating whether to attempt matching on */
2198 /* TCP/UDP port data. */
2200 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2201 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2202 /* this function. */
2203 /* ------------------------------------------------------------------------ */
2205 ipf_check_ipf(fin, fr, portcmp)
2210 u_32_t *ld, *lm, *lip;
2218 lm = (u_32_t *)&fri->fri_mip;
2219 ld = (u_32_t *)&fri->fri_ip;
2222 * first 32 bits to check coversion:
2223 * IP version, TOS, TTL, protocol
2225 i = ((*lip & *lm) != *ld);
2226 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2227 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2232 * Next 32 bits is a constructed bitmask indicating which IP options
2233 * are present (if any) in this packet.
2236 i = ((*lip & *lm) != *ld);
2237 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2238 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2244 * Unrolled loops (4 each, for 32 bits) for address checks.
2247 * Check the source address.
2249 if (fr->fr_satype == FRI_LOOKUP) {
2250 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2251 fi->fi_v, lip, fin->fin_plen);
2258 i = ((*lip & *lm) != *ld);
2259 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2260 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2261 if (fi->fi_v == 6) {
2263 i |= ((*lip & *lm) != *ld);
2264 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2265 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2267 i |= ((*lip & *lm) != *ld);
2268 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2269 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271 i |= ((*lip & *lm) != *ld);
2272 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2273 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2280 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2285 * Check the destination address.
2288 if (fr->fr_datype == FRI_LOOKUP) {
2289 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2290 fi->fi_v, lip, fin->fin_plen);
2297 i = ((*lip & *lm) != *ld);
2298 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2299 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2300 if (fi->fi_v == 6) {
2302 i |= ((*lip & *lm) != *ld);
2303 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2304 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2306 i |= ((*lip & *lm) != *ld);
2307 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2308 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310 i |= ((*lip & *lm) != *ld);
2311 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2312 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2319 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2323 * IP addresses matched. The next 32bits contains:
2324 * mast of old IP header security & authentication bits.
2327 i = (*ld - (*lip & *lm));
2328 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2331 * Next we have 32 bits of packet flags.
2334 i |= (*ld - (*lip & *lm));
2335 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2339 * If a fragment, then only the first has what we're
2340 * looking for here...
2343 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2346 if (fr->fr_dcmp || fr->fr_scmp ||
2347 fr->fr_tcpf || fr->fr_tcpfm)
2349 if (fr->fr_icmpm || fr->fr_icmp) {
2350 if (((fi->fi_p != IPPROTO_ICMP) &&
2351 (fi->fi_p != IPPROTO_ICMPV6)) ||
2352 fin->fin_off || (fin->fin_dlen < 2))
2354 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2356 FR_DEBUG(("i. %#x & %#x != %#x\n",
2358 fr->fr_icmpm, fr->fr_icmp));
2368 /* ------------------------------------------------------------------------ */
2369 /* Function: ipf_scanlist */
2370 /* Returns: int - result flags of scanning filter list */
2371 /* Parameters: fin(I) - pointer to packet information */
2372 /* pass(I) - default result to return for filtering */
2374 /* Check the input/output list of rules for a match to the current packet. */
2375 /* If a match is found, the value of fr_flags from the rule becomes the */
2376 /* return value and fin->fin_fr points to the matched rule. */
2378 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2379 /* When unwinding, it should finish up with fin_depth as 0. */
2381 /* Could be per interface, but this gets real nasty when you don't have, */
2382 /* or can't easily change, the kernel source code to . */
2383 /* ------------------------------------------------------------------------ */
2385 ipf_scanlist(fin, pass)
2389 ipf_main_softc_t *softc = fin->fin_main_soft;
2390 int rulen, portcmp, off, skip;
2391 struct frentry *fr, *fnext;
2392 u_32_t passt, passo;
2395 * Do not allow nesting deeper than 16 levels.
2397 if (fin->fin_depth >= 16)
2403 * If there are no rules in this list, return now.
2414 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2417 for (rulen = 0; fr; fr = fnext, rulen++) {
2418 fnext = fr->fr_next;
2420 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2426 * In all checks below, a null (zero) value in the
2427 * filter struture is taken to mean a wildcard.
2429 * check that we are working for the right interface
2432 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2435 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2437 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2438 FR_ISPASS(pass) ? 'p' :
2439 FR_ISACCOUNT(pass) ? 'A' :
2440 FR_ISAUTH(pass) ? 'a' :
2441 (pass & FR_NOMATCH) ? 'n' :'b'));
2442 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2447 switch (fr->fr_type)
2450 case FR_T_IPF_BUILTIN :
2451 if (ipf_check_ipf(fin, fr, portcmp))
2454 #if defined(IPFILTER_BPF)
2456 case FR_T_BPFOPC_BUILTIN :
2461 if (*fin->fin_mp == NULL)
2463 if (fin->fin_family != fr->fr_family)
2465 mc = (u_char *)fin->fin_m;
2466 wlen = fin->fin_dlen + fin->fin_hlen;
2467 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2472 case FR_T_CALLFUNC_BUILTIN :
2476 f = (*fr->fr_func)(fin, &pass);
2485 case FR_T_IPFEXPR_BUILTIN :
2486 if (fin->fin_family != fr->fr_family)
2488 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2496 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2497 if (fin->fin_nattag == NULL)
2499 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2502 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2504 passt = fr->fr_flags;
2507 * If the rule is a "call now" rule, then call the function
2508 * in the rule, if it exists and use the results from that.
2509 * If the function pointer is bad, just make like we ignore
2510 * it, except for increasing the hit counter.
2512 if ((passt & FR_CALLNOW) != 0) {
2515 ATOMIC_INC64(fr->fr_hits);
2516 if ((fr->fr_func == NULL) ||
2517 (fr->fr_func == (ipfunc_t)-1))
2522 fr = (*fr->fr_func)(fin, &passt);
2527 passt = fr->fr_flags;
2533 * Just log this packet...
2535 if ((passt & FR_LOGMASK) == FR_LOG) {
2536 if (ipf_log_pkt(fin, passt) == -1) {
2537 if (passt & FR_LOGORBLOCK) {
2539 passt &= ~FR_CMDMASK;
2540 passt |= FR_BLOCK|FR_QUICK;
2541 fin->fin_reason = FRB_LOGFAIL;
2545 #endif /* IPFILTER_LOG */
2547 MUTEX_ENTER(&fr->fr_lock);
2548 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2550 MUTEX_EXIT(&fr->fr_lock);
2551 fin->fin_rule = rulen;
2554 if (FR_ISSKIP(passt)) {
2557 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2558 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2562 if (passt & (FR_RETICMP|FR_FAKEICMP))
2563 fin->fin_icode = fr->fr_icode;
2565 if (fr->fr_group != -1) {
2566 (void) strncpy(fin->fin_group,
2567 FR_NAME(fr, fr_group),
2568 strlen(FR_NAME(fr, fr_group)));
2570 fin->fin_group[0] = '\0';
2573 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2575 if (fr->fr_grphead != NULL) {
2576 fin->fin_fr = fr->fr_grphead->fg_start;
2577 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2579 if (FR_ISDECAPS(passt))
2580 passt = ipf_decaps(fin, pass, fr->fr_icode);
2582 passt = ipf_scanlist(fin, pass);
2584 if (fin->fin_fr == NULL) {
2585 fin->fin_rule = rulen;
2586 if (fr->fr_group != -1)
2587 (void) strncpy(fin->fin_group,
2590 strlen(fr->fr_names +
2598 if (pass & FR_QUICK) {
2600 * Finally, if we've asked to track state for this
2601 * packet, set it up. Add state for "quick" rules
2602 * here so that if the action fails we can consider
2603 * the rule to "not match" and keep on processing
2606 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2607 !(fin->fin_flx & FI_STATE)) {
2608 int out = fin->fin_out;
2611 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2612 LBUMPD(ipf_stats[out], fr_ads);
2614 LBUMPD(ipf_stats[out], fr_bads);
2627 /* ------------------------------------------------------------------------ */
2628 /* Function: ipf_acctpkt */
2629 /* Returns: frentry_t* - always returns NULL */
2630 /* Parameters: fin(I) - pointer to packet information */
2631 /* passp(IO) - pointer to current/new filter decision (unused) */
2633 /* Checks a packet against accounting rules, if there are any for the given */
2634 /* IP protocol version. */
2636 /* N.B.: this function returns NULL to match the prototype used by other */
2637 /* functions called from the IPFilter "mainline" in ipf_check(). */
2638 /* ------------------------------------------------------------------------ */
2640 ipf_acctpkt(fin, passp)
2644 ipf_main_softc_t *softc = fin->fin_main_soft;
2645 char group[FR_GROUPLEN];
2646 frentry_t *fr, *frsave;
2650 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2653 frsave = fin->fin_fr;
2654 bcopy(fin->fin_group, group, FR_GROUPLEN);
2655 rulen = fin->fin_rule;
2657 pass = ipf_scanlist(fin, FR_NOMATCH);
2658 if (FR_ISACCOUNT(pass)) {
2659 LBUMPD(ipf_stats[0], fr_acct);
2661 fin->fin_fr = frsave;
2662 bcopy(group, fin->fin_group, FR_GROUPLEN);
2663 fin->fin_rule = rulen;
2669 /* ------------------------------------------------------------------------ */
2670 /* Function: ipf_firewall */
2671 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2672 /* were found, returns NULL. */
2673 /* Parameters: fin(I) - pointer to packet information */
2674 /* passp(IO) - pointer to current/new filter decision (unused) */
2676 /* Applies an appropriate set of firewall rules to the packet, to see if */
2677 /* there are any matches. The first check is to see if a match can be seen */
2678 /* in the cache. If not, then search an appropriate list of rules. Once a */
2679 /* matching rule is found, take any appropriate actions as defined by the */
2680 /* rule - except logging. */
2681 /* ------------------------------------------------------------------------ */
2683 ipf_firewall(fin, passp)
2687 ipf_main_softc_t *softc = fin->fin_main_soft;
2696 * This rule cache will only affect packets that are not being
2697 * statefully filtered.
2699 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2700 if (fin->fin_fr != NULL)
2701 pass = ipf_scanlist(fin, softc->ipf_pass);
2703 if ((pass & FR_NOMATCH)) {
2704 LBUMPD(ipf_stats[out], fr_nom);
2709 * Apply packets per second rate-limiting to a rule as required.
2711 if ((fr != NULL) && (fr->fr_pps != 0) &&
2712 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2713 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2714 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2716 LBUMPD(ipf_stats[out], fr_ppshit);
2717 fin->fin_reason = FRB_PPSRATE;
2721 * If we fail to add a packet to the authorization queue, then we
2722 * drop the packet later. However, if it was added then pretend
2723 * we've dropped it already.
2725 if (FR_ISAUTH(pass)) {
2726 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2727 DT1(frb_authnew, fr_info_t *, fin);
2728 fin->fin_m = *fin->fin_mp = NULL;
2729 fin->fin_reason = FRB_AUTHNEW;
2733 fin->fin_error = ENOSPC;
2737 if ((fr != NULL) && (fr->fr_func != NULL) &&
2738 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2739 (void) (*fr->fr_func)(fin, &pass);
2742 * If a rule is a pre-auth rule, check again in the list of rules
2743 * loaded for authenticated use. It does not particulary matter
2744 * if this search fails because a "preauth" result, from a rule,
2745 * is treated as "not a pass", hence the packet is blocked.
2747 if (FR_ISPREAUTH(pass)) {
2748 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2752 * If the rule has "keep frag" and the packet is actually a fragment,
2753 * then create a fragment state entry.
2755 if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2756 if (fin->fin_flx & FI_FRAG) {
2757 if (ipf_frag_new(softc, fin, pass) == -1) {
2758 LBUMP(ipf_stats[out].fr_bnfr);
2760 LBUMP(ipf_stats[out].fr_nfr);
2763 LBUMP(ipf_stats[out].fr_cfr);
2774 /* ------------------------------------------------------------------------ */
2775 /* Function: ipf_check */
2776 /* Returns: int - 0 == packet allowed through, */
2778 /* -1 == packet blocked */
2779 /* 1 == packet not matched */
2780 /* -2 == requires authentication */
2782 /* > 0 == filter error # for packet */
2783 /* Parameters: ip(I) - pointer to start of IPv4/6 packet */
2784 /* hlen(I) - length of header */
2785 /* ifp(I) - pointer to interface this packet is on */
2786 /* out(I) - 0 == packet going in, 1 == packet going out */
2787 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2789 /* Solaris & HP-UX ONLY : */
2790 /* qpi(I) - pointer to STREAMS queue information for this */
2791 /* interface & direction. */
2793 /* ipf_check() is the master function for all IPFilter packet processing. */
2794 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2795 /* authorisation (or pre-authorisation), presence of related state info., */
2796 /* generating log entries, IP packet accounting, routing of packets as */
2797 /* directed by firewall rules and of course whether or not to allow the */
2798 /* packet to be further processed by the kernel. */
2800 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2801 /* freed. Packets passed may be returned with the pointer pointed to by */
2802 /* by "mp" changed to a new buffer. */
2803 /* ------------------------------------------------------------------------ */
2805 ipf_check(ctx, ip, hlen, ifp, out
2806 #if defined(_KERNEL) && defined(MENTAT)
2820 * The above really sucks, but short of writing a diff
2822 ipf_main_softc_t *softc = ctx;
2824 fr_info_t *fin = &frinfo;
2825 u_32_t pass = softc->ipf_pass;
2826 frentry_t *fr = NULL;
2831 * The first part of ipf_check() deals with making sure that what goes
2832 * into the filtering engine makes some sense. Information about the
2833 * the packet is distilled, collected into a fr_info_t structure and
2834 * the an attempt to ensure the buffer the packet is in is big enough
2835 * to hold all the required packet headers.
2839 qpktinfo_t *qpi = qif;
2842 if ((u_int)ip & 0x3)
2849 if (softc->ipf_running <= 0) {
2853 bzero((char *)fin, sizeof(*fin));
2856 if (qpi->qpi_flags & QF_BROADCAST)
2857 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2858 if (qpi->qpi_flags & QF_MULTICAST)
2859 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2867 # if defined(M_MCAST)
2868 if ((m->m_flags & M_MCAST) != 0)
2869 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2871 # if defined(M_MLOOP)
2872 if ((m->m_flags & M_MLOOP) != 0)
2873 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2875 # if defined(M_BCAST)
2876 if ((m->m_flags & M_BCAST) != 0)
2877 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2879 # ifdef M_CANFASTFWD
2881 * XXX For now, IP Filter and fast-forwarding of cached flows
2882 * XXX are mutually exclusive. Eventually, IP Filter should
2883 * XXX get a "can-fast-forward" filter rule.
2885 m->m_flags &= ~M_CANFASTFWD;
2886 # endif /* M_CANFASTFWD */
2887 # if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2888 (__FreeBSD_version < 501108))
2890 * disable delayed checksums.
2892 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2893 in_delayed_cksum(m);
2894 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2896 # endif /* CSUM_DELAY_DATA */
2897 # endif /* MENTAT */
2899 bzero((char *)fin, sizeof(*fin));
2901 # if defined(M_MCAST)
2902 if ((m->m_flags & M_MCAST) != 0)
2903 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2905 # if defined(M_MLOOP)
2906 if ((m->m_flags & M_MLOOP) != 0)
2907 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2909 # if defined(M_BCAST)
2910 if ((m->m_flags & M_BCAST) != 0)
2911 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2913 #endif /* _KERNEL */
2921 fin->fin_error = ENETUNREACH;
2922 fin->fin_hlen = (u_short)hlen;
2923 fin->fin_dp = (char *)ip + hlen;
2924 fin->fin_main_soft = softc;
2926 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2932 LBUMP(ipf_stats[out].fr_ipv6);
2934 * Jumbo grams are quite likely too big for internal buffer
2935 * structures to handle comfortably, for now, so just drop
2938 if (((ip6_t *)ip)->ip6_plen == 0) {
2939 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2940 pass = FR_BLOCK|FR_NOMATCH;
2941 fin->fin_reason = FRB_JUMBO;
2944 fin->fin_family = AF_INET6;
2948 fin->fin_family = AF_INET;
2951 if (ipf_makefrip(hlen, ip, fin) == -1) {
2952 DT1(frb_makefrip, fr_info_t *, fin);
2953 pass = FR_BLOCK|FR_NOMATCH;
2954 fin->fin_reason = FRB_MAKEFRIP;
2959 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2960 * becomes NULL and so we have no packet to free.
2962 if (*fin->fin_mp == NULL)
2967 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2968 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2969 fin->fin_flx |= FI_BADSRC;
2971 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2972 LBUMPD(ipf_stats[0], fr_v4_badttl);
2973 fin->fin_flx |= FI_LOWTTL;
2978 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2979 LBUMPD(ipf_stats[0], fr_v6_badttl);
2980 fin->fin_flx |= FI_LOWTTL;
2986 if (fin->fin_flx & FI_SHORT) {
2987 LBUMPD(ipf_stats[out], fr_short);
2990 READ_ENTER(&softc->ipf_mutex);
2996 if (ipf_nat_checkin(fin, &pass) == -1) {
3002 if (ipf_nat6_checkin(fin, &pass) == -1) {
3013 * If a packet is found in the auth table, then skip checking
3014 * the access lists for permission but we do need to consider
3015 * the result as if it were from the ACL's. In addition, being
3016 * found in the auth table means it has been seen before, so do
3017 * not pass it through accounting (again), lest it be counted twice.
3019 fr = ipf_auth_check(fin, &pass);
3020 if (!out && (fr == NULL))
3021 (void) ipf_acctpkt(fin, NULL);
3024 if ((fin->fin_flx & FI_FRAG) != 0)
3025 fr = ipf_frag_known(fin, &pass);
3028 fr = ipf_state_check(fin, &pass);
3031 if ((pass & FR_NOMATCH) || (fr == NULL))
3032 fr = ipf_firewall(fin, &pass);
3035 * If we've asked to track state for this packet, set it up.
3036 * Here rather than ipf_firewall because ipf_checkauth may decide
3037 * to return a packet for "keep state"
3039 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3040 !(fin->fin_flx & FI_STATE)) {
3041 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3042 LBUMP(ipf_stats[out].fr_ads);
3044 LBUMP(ipf_stats[out].fr_bads);
3045 if (FR_ISPASS(pass)) {
3047 pass &= ~FR_CMDMASK;
3049 fin->fin_reason = FRB_STATEADD;
3055 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3056 fin->fin_dif = &fr->fr_dif;
3057 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3061 * Only count/translate packets which will be passed on, out the
3064 if (out && FR_ISPASS(pass)) {
3065 (void) ipf_acctpkt(fin, NULL);
3070 if (ipf_nat_checkout(fin, &pass) == -1) {
3072 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3073 if (ipf_updateipid(fin) == -1) {
3075 LBUMP(ipf_stats[1].fr_ipud);
3076 pass &= ~FR_CMDMASK;
3078 fin->fin_reason = FRB_UPDATEIPID;
3080 LBUMP(ipf_stats[0].fr_ipud);
3086 (void) ipf_nat6_checkout(fin, &pass);
3096 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3097 (void) ipf_dolog(fin, &pass);
3102 * The FI_STATE flag is cleared here so that calling ipf_state_check
3103 * will work when called from inside of fr_fastroute. Although
3104 * there is a similar flag, FI_NATED, for NAT, it does have the same
3105 * impact on code execution.
3107 fin->fin_flx &= ~FI_STATE;
3109 #if defined(FASTROUTE_RECURSION)
3111 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3112 * a packet below can sometimes cause a recursive call into IPFilter.
3113 * On those platforms where that does happen, we need to hang onto
3114 * the filter rule just in case someone decides to remove or flush it
3118 MUTEX_ENTER(&fr->fr_lock);
3120 MUTEX_EXIT(&fr->fr_lock);
3123 RWLOCK_EXIT(&softc->ipf_mutex);
3126 if ((pass & FR_RETMASK) != 0) {
3128 * Should we return an ICMP packet to indicate error
3129 * status passing through the packet filter ?
3130 * WARNING: ICMP error packets AND TCP RST packets should
3131 * ONLY be sent in repsonse to incoming packets. Sending
3132 * them in response to outbound packets can result in a
3133 * panic on some operating systems.
3136 if (pass & FR_RETICMP) {
3139 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3143 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3145 LBUMP(ipf_stats[0].fr_ret);
3146 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3147 !(fin->fin_flx & FI_SHORT)) {
3148 if (((fin->fin_flx & FI_OOW) != 0) ||
3149 (ipf_send_reset(fin) == 0)) {
3150 LBUMP(ipf_stats[1].fr_ret);
3155 * When using return-* with auth rules, the auth code
3156 * takes over disposing of this packet.
3158 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3159 DT1(frb_authcapture, fr_info_t *, fin);
3160 fin->fin_m = *fin->fin_mp = NULL;
3161 fin->fin_reason = FRB_AUTHCAPTURE;
3165 if (pass & FR_RETRST) {
3166 fin->fin_error = ECONNRESET;
3172 * After the above so that ICMP unreachables and TCP RSTs get
3175 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3176 ipf_nat_uncreate(fin);
3179 * If we didn't drop off the bottom of the list of rules (and thus
3180 * the 'current' rule fr is not NULL), then we may have some extra
3181 * instructions about what to do with a packet.
3182 * Once we're finished return to our caller, freeing the packet if
3183 * we are dropping it.
3189 * Generate a duplicated packet first because ipf_fastroute
3190 * can lead to fin_m being free'd... not good.
3193 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3194 (fdp->fd_ptr != (void *)-1)) {
3195 mc = M_COPY(fin->fin_m);
3197 ipf_fastroute(mc, &mc, fin, fdp);
3201 if (!out && (pass & FR_FASTROUTE)) {
3203 * For fastroute rule, no destination interface defined
3204 * so pass NULL as the frdest_t parameter
3206 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3208 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3209 (fdp->fd_ptr != (struct ifnet *)-1)) {
3210 /* this is for to rules: */
3211 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3215 #if defined(FASTROUTE_RECURSION)
3216 (void) ipf_derefrule(softc, &fr);
3219 #if !defined(FASTROUTE_RECURSION)
3220 RWLOCK_EXIT(&softc->ipf_mutex);
3224 if (!FR_ISPASS(pass)) {
3225 LBUMP(ipf_stats[out].fr_block);
3233 LBUMP(ipf_stats[out].fr_pass);
3234 #if defined(_KERNEL) && defined(__sgi)
3235 if ((fin->fin_hbuf != NULL) &&
3236 (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3237 COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3245 if (FR_ISPASS(pass))
3247 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3248 return fin->fin_error;
3251 (*mp)->mb_ifp = fin->fin_ifp;
3252 blockreason = fin->fin_reason;
3253 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3254 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3255 if ((pass & FR_NOMATCH) != 0)
3258 if ((pass & FR_RETMASK) != 0)
3259 switch (pass & FR_RETMASK)
3269 switch (pass & FR_CMDMASK)
3283 #endif /* _KERNEL */
3288 /* ------------------------------------------------------------------------ */
3289 /* Function: ipf_dolog */
3290 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3291 /* Parameters: fin(I) - pointer to packet information */
3292 /* passp(IO) - pointer to current/new filter decision (unused) */
3294 /* Checks flags set to see how a packet should be logged, if it is to be */
3295 /* logged. Adjust statistics based on its success or not. */
3296 /* ------------------------------------------------------------------------ */
3298 ipf_dolog(fin, passp)
3302 ipf_main_softc_t *softc = fin->fin_main_soft;
3309 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3310 pass |= FF_LOGNOMATCH;
3311 LBUMPD(ipf_stats[out], fr_npkl);
3314 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3315 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3316 if ((pass & FR_LOGMASK) != FR_LOGP)
3318 LBUMPD(ipf_stats[out], fr_ppkl);
3321 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3322 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3323 if ((pass & FR_LOGMASK) != FR_LOGB)
3324 pass |= FF_LOGBLOCK;
3325 LBUMPD(ipf_stats[out], fr_bpkl);
3328 if (ipf_log_pkt(fin, pass) == -1) {
3330 * If the "or-block" option has been used then
3331 * block the packet if we failed to log it.
3333 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3334 DT1(frb_logfail2, u_int, pass);
3335 pass &= ~FR_CMDMASK;
3337 fin->fin_reason = FRB_LOGFAIL2;
3345 #endif /* IPFILTER_LOG */
3348 /* ------------------------------------------------------------------------ */
3349 /* Function: ipf_cksum */
3350 /* Returns: u_short - IP header checksum */
3351 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3352 /* len(I) - length of buffer in bytes */
3354 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3356 /* N.B.: addr should be 16bit aligned. */
3357 /* ------------------------------------------------------------------------ */
3359 ipf_cksum(addr, len)
3365 for (sum = 0; len > 1; len -= 2)
3368 /* mop up an odd byte, if necessary */
3370 sum += *(u_char *)addr;
3373 * add back carry outs from top 16 bits to low 16 bits
3375 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3376 sum += (sum >> 16); /* add carry */
3377 return (u_short)(~sum);
3381 /* ------------------------------------------------------------------------ */
3382 /* Function: fr_cksum */
3383 /* Returns: u_short - layer 4 checksum */
3384 /* Parameters: fin(I) - pointer to packet information */
3385 /* ip(I) - pointer to IP header */
3386 /* l4proto(I) - protocol to caclulate checksum for */
3387 /* l4hdr(I) - pointer to layer 4 header */
3389 /* Calculates the TCP checksum for the packet held in "m", using the data */
3390 /* in the IP header "ip" to seed it. */
3392 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3393 /* and the TCP header. We also assume that data blocks aren't allocated in */
3396 /* Expects ip_len and ip_off to be in network byte order when called. */
3397 /* ------------------------------------------------------------------------ */
3399 fr_cksum(fin, ip, l4proto, l4hdr)
3405 u_short *sp, slen, sumsave, *csump;
3420 sum = htons((u_short)l4proto);
3422 * Add up IP Header portion
3425 if (IP_V(ip) == 4) {
3427 hlen = IP_HL(ip) << 2;
3429 sp = (u_short *)&ip->ip_src;
3430 sum += *sp++; /* ip_src */
3432 sum += *sp++; /* ip_dst */
3435 } else if (IP_V(ip) == 6) {
3437 hlen = sizeof(*ip6);
3438 off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3439 sp = (u_short *)&ip6->ip6_src;
3440 sum += *sp++; /* ip6_src */
3448 /* This needs to be routing header aware. */
3449 sum += *sp++; /* ip6_dst */
3461 slen = fin->fin_plen - off;
3467 csump = &((udphdr_t *)l4hdr)->uh_sum;
3471 csump = &((tcphdr_t *)l4hdr)->th_sum;
3474 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3475 sum = 0; /* Pseudo-checksum is not included */
3478 case IPPROTO_ICMPV6 :
3479 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3486 if (csump != NULL) {
3491 sum2 = ipf_pcksum(fin, off, sum);
3498 /* ------------------------------------------------------------------------ */
3499 /* Function: ipf_findgroup */
3500 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3501 /* Parameters: softc(I) - pointer to soft context main structure */
3502 /* group(I) - group name to search for */
3503 /* unit(I) - device to which this group belongs */
3504 /* set(I) - which set of rules (inactive/inactive) this is */
3505 /* fgpp(O) - pointer to place to store pointer to the pointer */
3506 /* to where to add the next (last) group or where */
3507 /* to delete group from. */
3509 /* Search amongst the defined groups for a particular group number. */
3510 /* ------------------------------------------------------------------------ */
3512 ipf_findgroup(softc, group, unit, set, fgpp)
3513 ipf_main_softc_t *softc;
3519 frgroup_t *fg, **fgp;
3522 * Which list of groups to search in is dependent on which list of
3523 * rules are being operated on.
3525 fgp = &softc->ipf_groups[unit][set];
3527 while ((fg = *fgp) != NULL) {
3528 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3539 /* ------------------------------------------------------------------------ */
3540 /* Function: ipf_group_add */
3541 /* Returns: frgroup_t * - NULL == did not create group, */
3542 /* != NULL == pointer to the group */
3543 /* Parameters: softc(I) - pointer to soft context main structure */
3544 /* num(I) - group number to add */
3545 /* head(I) - rule pointer that is using this as the head */
3546 /* flags(I) - rule flags which describe the type of rule it is */
3547 /* unit(I) - device to which this group will belong to */
3548 /* set(I) - which set of rules (inactive/inactive) this is */
3549 /* Write Locks: ipf_mutex */
3551 /* Add a new group head, or if it already exists, increase the reference */
3553 /* ------------------------------------------------------------------------ */
3555 ipf_group_add(softc, group, head, flags, unit, set)
3556 ipf_main_softc_t *softc;
3563 frgroup_t *fg, **fgp;
3569 if (unit == IPL_LOGIPF && *group == '\0')
3573 gflags = flags & FR_INOUT;
3575 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3577 if (fg->fg_head == NULL && head != NULL)
3579 if (fg->fg_flags == 0)
3580 fg->fg_flags = gflags;
3581 else if (gflags != fg->fg_flags)
3587 KMALLOC(fg, frgroup_t *);
3590 fg->fg_start = NULL;
3592 bcopy(group, fg->fg_name, strlen(group) + 1);
3593 fg->fg_flags = gflags;
3595 fg->fg_set = &softc->ipf_groups[unit][set];
3602 /* ------------------------------------------------------------------------ */
3603 /* Function: ipf_group_del */
3604 /* Returns: int - number of rules deleted */
3605 /* Parameters: softc(I) - pointer to soft context main structure */
3606 /* group(I) - group name to delete */
3607 /* fr(I) - filter rule from which group is referenced */
3608 /* Write Locks: ipf_mutex */
3610 /* This function is called whenever a reference to a group is to be dropped */
3611 /* and thus its reference count needs to be lowered and the group free'd if */
3612 /* the reference count reaches zero. Passing in fr is really for the sole */
3613 /* purpose of knowing when the head rule is being deleted. */
3614 /* ------------------------------------------------------------------------ */
3616 ipf_group_del(softc, group, fr)
3617 ipf_main_softc_t *softc;
3622 if (group->fg_head == fr)
3623 group->fg_head = NULL;
3626 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3627 ipf_group_free(group);
3631 /* ------------------------------------------------------------------------ */
3632 /* Function: ipf_group_free */
3634 /* Parameters: group(I) - pointer to filter rule group */
3636 /* Remove the group from the list of groups and free it. */
3637 /* ------------------------------------------------------------------------ */
3639 ipf_group_free(group)
3644 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3646 *gp = group->fg_next;
3654 /* ------------------------------------------------------------------------ */
3655 /* Function: ipf_group_flush */
3656 /* Returns: int - number of rules flush from group */
3657 /* Parameters: softc(I) - pointer to soft context main structure */
3658 /* Parameters: group(I) - pointer to filter rule group */
3660 /* Remove all of the rules that currently are listed under the given group. */
3661 /* ------------------------------------------------------------------------ */
3663 ipf_group_flush(softc, group)
3664 ipf_main_softc_t *softc;
3669 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3675 /* ------------------------------------------------------------------------ */
3676 /* Function: ipf_getrulen */
3677 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3678 /* Parameters: softc(I) - pointer to soft context main structure */
3679 /* Parameters: unit(I) - device for which to count the rule's number */
3680 /* flags(I) - which set of rules to find the rule in */
3681 /* group(I) - group name */
3682 /* n(I) - rule number to find */
3684 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3685 /* group # g doesn't exist or there are less than n rules in the group. */
3686 /* ------------------------------------------------------------------------ */
3688 ipf_getrulen(softc, unit, group, n)
3689 ipf_main_softc_t *softc;
3697 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3700 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3708 /* ------------------------------------------------------------------------ */
3709 /* Function: ipf_flushlist */
3710 /* Returns: int - >= 0 - number of flushed rules */
3711 /* Parameters: softc(I) - pointer to soft context main structure */
3712 /* nfreedp(O) - pointer to int where flush count is stored */
3713 /* listp(I) - pointer to list to flush pointer */
3714 /* Write Locks: ipf_mutex */
3716 /* Recursively flush rules from the list, descending groups as they are */
3717 /* encountered. if a rule is the head of a group and it has lost all its */
3718 /* group members, then also delete the group reference. nfreedp is needed */
3719 /* to store the accumulating count of rules removed, whereas the returned */
3720 /* value is just the number removed from the current list. The latter is */
3721 /* needed to correctly adjust reference counts on rules that define groups. */
3723 /* NOTE: Rules not loaded from user space cannot be flushed. */
3724 /* ------------------------------------------------------------------------ */
3726 ipf_flushlist(softc, nfreedp, listp)
3727 ipf_main_softc_t *softc;
3734 while ((fp = *listp) != NULL) {
3735 if ((fp->fr_type & FR_T_BUILTIN) ||
3736 !(fp->fr_flags & FR_COPIED)) {
3737 listp = &fp->fr_next;
3740 *listp = fp->fr_next;
3741 if (fp->fr_next != NULL)
3742 fp->fr_next->fr_pnext = fp->fr_pnext;
3743 fp->fr_pnext = NULL;
3745 if (fp->fr_grphead != NULL) {
3746 freed += ipf_group_flush(softc, fp->fr_grphead);
3747 fp->fr_names[fp->fr_grhead] = '\0';
3750 if (fp->fr_icmpgrp != NULL) {
3751 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3752 fp->fr_names[fp->fr_icmphead] = '\0';
3755 if (fp->fr_srctrack.ht_max_nodes)
3756 ipf_rb_ht_flush(&fp->fr_srctrack);
3760 ASSERT(fp->fr_ref > 0);
3761 if (ipf_derefrule(softc, &fp) == 0)
3769 /* ------------------------------------------------------------------------ */
3770 /* Function: ipf_flush */
3771 /* Returns: int - >= 0 - number of flushed rules */
3772 /* Parameters: softc(I) - pointer to soft context main structure */
3773 /* unit(I) - device for which to flush rules */
3774 /* flags(I) - which set of rules to flush */
3776 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3777 /* and IPv6) as defined by the value of flags. */
3778 /* ------------------------------------------------------------------------ */
3780 ipf_flush(softc, unit, flags)
3781 ipf_main_softc_t *softc;
3785 int flushed = 0, set;
3787 WRITE_ENTER(&softc->ipf_mutex);
3789 set = softc->ipf_active;
3790 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3793 if (flags & FR_OUTQUE) {
3794 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3795 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3797 if (flags & FR_INQUE) {
3798 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3799 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3802 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3803 flags & (FR_INQUE|FR_OUTQUE));
3805 RWLOCK_EXIT(&softc->ipf_mutex);
3807 if (unit == IPL_LOGIPF) {
3810 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3818 /* ------------------------------------------------------------------------ */
3819 /* Function: ipf_flush_groups */
3820 /* Returns: int - >= 0 - number of flushed rules */
3821 /* Parameters: softc(I) - soft context pointerto work with */
3822 /* grhead(I) - pointer to the start of the group list to flush */
3823 /* flags(I) - which set of rules to flush */
3825 /* Walk through all of the groups under the given group head and remove all */
3826 /* of those that match the flags passed in. The for loop here is bit more */
3827 /* complicated than usual because the removal of a rule with ipf_derefrule */
3828 /* may end up removing not only the structure pointed to by "fg" but also */
3829 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3830 /* removed from the group then it is necessary to start again. */
3831 /* ------------------------------------------------------------------------ */
3833 ipf_flush_groups(softc, grhead, flags)
3834 ipf_main_softc_t *softc;
3838 frentry_t *fr, **frp;
3839 frgroup_t *fg, **fgp;
3843 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3844 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3849 frp = &fg->fg_start;
3850 while ((removed == 0) && ((fr = *frp) != NULL)) {
3851 if ((fr->fr_flags & flags) == 0) {
3854 if (fr->fr_next != NULL)
3855 fr->fr_next->fr_pnext = fr->fr_pnext;
3857 fr->fr_pnext = NULL;
3859 (void) ipf_derefrule(softc, &fr);
3871 /* ------------------------------------------------------------------------ */
3872 /* Function: memstr */
3873 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3874 /* Parameters: src(I) - pointer to byte sequence to match */
3875 /* dst(I) - pointer to byte sequence to search */
3876 /* slen(I) - match length */
3877 /* dlen(I) - length available to search in */
3879 /* Search dst for a sequence of bytes matching those at src and extend for */
3881 /* ------------------------------------------------------------------------ */
3883 memstr(src, dst, slen, dlen)
3890 while (dlen >= slen) {
3891 if (bcmp(src, dst, slen) == 0) {
3900 /* ------------------------------------------------------------------------ */
3901 /* Function: ipf_fixskip */
3903 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3904 /* rp(I) - rule added/removed with skip in it. */
3905 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3906 /* depending on whether a rule was just added */
3909 /* Adjust all the rules in a list which would have skip'd past the position */
3910 /* where we are inserting to skip to the right place given the change. */
3911 /* ------------------------------------------------------------------------ */
3913 ipf_fixskip(listp, rp, addremove)
3914 frentry_t **listp, *rp;
3921 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3927 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3928 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3929 fp->fr_arg += addremove;
3934 /* ------------------------------------------------------------------------ */
3935 /* Function: count4bits */
3936 /* Returns: int - >= 0 - number of consecutive bits in input */
3937 /* Parameters: ip(I) - 32bit IP address */
3940 /* count consecutive 1's in bit mask. If the mask generated by counting */
3941 /* consecutive 1's is different to that passed, return -1, else return # */
3943 /* ------------------------------------------------------------------------ */
3951 ip = ipn = ntohl(ip);
3952 for (i = 32; i; i--, ipn *= 2)
3953 if (ipn & 0x80000000)
3958 for (i = 32, j = cnt; i; i--, j--) {
3969 /* ------------------------------------------------------------------------ */
3970 /* Function: count6bits */
3971 /* Returns: int - >= 0 - number of consecutive bits in input */
3972 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3975 /* count consecutive 1's in bit mask. */
3976 /* ------------------------------------------------------------------------ */
3985 for (k = 3; k >= 0; k--)
3986 if (msk[k] == 0xffffffff)
3989 for (j = msk[k]; j; j <<= 1)
3996 #endif /* _KERNEL */
3999 /* ------------------------------------------------------------------------ */
4000 /* Function: ipf_synclist */
4001 /* Returns: int - 0 = no failures, else indication of first failure */
4002 /* Parameters: fr(I) - start of filter list to sync interface names for */
4003 /* ifp(I) - interface pointer for limiting sync lookups */
4004 /* Write Locks: ipf_mutex */
4006 /* Walk through a list of filter rules and resolve any interface names into */
4007 /* pointers. Where dynamic addresses are used, also update the IP address */
4008 /* used in the rule. The interface pointer is used to limit the lookups to */
4009 /* a specific set of matching names if it is non-NULL. */
4010 /* Errors can occur when resolving the destination name of to/dup-to fields */
4011 /* when the name points to a pool and that pool doest not exist. If this */
4012 /* does happen then it is necessary to check if there are any lookup refs */
4013 /* that need to be dropped before returning with an error. */
4014 /* ------------------------------------------------------------------------ */
4016 ipf_synclist(softc, fr, ifp)
4017 ipf_main_softc_t *softc;
4021 frentry_t *frt, *start = fr;
4030 for (; fr; fr = fr->fr_next) {
4031 if (fr->fr_family == AF_INET)
4033 else if (fr->fr_family == AF_INET6)
4039 * Lookup all the interface names that are part of the rule.
4041 for (i = 0; i < 4; i++) {
4042 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4044 if (fr->fr_ifnames[i] == -1)
4046 name = FR_NAME(fr, fr_ifnames[i]);
4047 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4050 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4051 if (fr->fr_satype != FRI_NORMAL &&
4052 fr->fr_satype != FRI_LOOKUP) {
4053 ifa = ipf_resolvenic(softc, fr->fr_names +
4055 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4056 &fr->fr_src6, &fr->fr_smsk6);
4058 if (fr->fr_datype != FRI_NORMAL &&
4059 fr->fr_datype != FRI_LOOKUP) {
4060 ifa = ipf_resolvenic(softc, fr->fr_names +
4062 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4063 &fr->fr_dst6, &fr->fr_dmsk6);
4067 fdp = &fr->fr_tifs[0];
4068 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4069 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4074 fdp = &fr->fr_tifs[1];
4075 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4076 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4082 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4083 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4088 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4089 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4090 fr->fr_srcptr = ipf_lookup_res_num(softc,
4096 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4097 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4098 fr->fr_dstptr = ipf_lookup_res_num(softc,
4108 for (frt = start; frt != fr; fr = fr->fr_next) {
4109 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4110 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4111 ipf_lookup_deref(softc, frt->fr_srctype,
4113 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4114 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4115 ipf_lookup_deref(softc, frt->fr_dsttype,
4122 /* ------------------------------------------------------------------------ */
4123 /* Function: ipf_sync */
4125 /* Parameters: Nil */
4127 /* ipf_sync() is called when we suspect that the interface list or */
4128 /* information about interfaces (like IP#) has changed. Go through all */
4129 /* filter rules, NAT entries and the state table and check if anything */
4130 /* needs to be changed/updated. */
4131 /* ------------------------------------------------------------------------ */
4133 ipf_sync(softc, ifp)
4134 ipf_main_softc_t *softc;
4140 ipf_nat_sync(softc, ifp);
4141 ipf_state_sync(softc, ifp);
4142 ipf_lookup_sync(softc, ifp);
4145 WRITE_ENTER(&softc->ipf_mutex);
4146 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4147 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4148 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4149 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4151 for (i = 0; i < IPL_LOGSIZE; i++) {
4154 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4155 (void) ipf_synclist(softc, g->fg_start, ifp);
4156 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4157 (void) ipf_synclist(softc, g->fg_start, ifp);
4159 RWLOCK_EXIT(&softc->ipf_mutex);
4166 * In the functions below, bcopy() is called because the pointer being
4167 * copied _from_ in this instance is a pointer to a char buf (which could
4168 * end up being unaligned) and on the kernel's local stack.
4170 /* ------------------------------------------------------------------------ */
4171 /* Function: copyinptr */
4172 /* Returns: int - 0 = success, else failure */
4173 /* Parameters: src(I) - pointer to the source address */
4174 /* dst(I) - destination address */
4175 /* size(I) - number of bytes to copy */
4177 /* Copy a block of data in from user space, given a pointer to the pointer */
4178 /* to start copying from (src) and a pointer to where to store it (dst). */
4179 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4180 /* ------------------------------------------------------------------------ */
4182 copyinptr(softc, src, dst, size)
4183 ipf_main_softc_t *softc;
4191 error = COPYIN(src, &ca, sizeof(ca));
4195 bcopy(src, (caddr_t)&ca, sizeof(ca));
4197 error = COPYIN(ca, dst, size);
4206 /* ------------------------------------------------------------------------ */
4207 /* Function: copyoutptr */
4208 /* Returns: int - 0 = success, else failure */
4209 /* Parameters: src(I) - pointer to the source address */
4210 /* dst(I) - destination address */
4211 /* size(I) - number of bytes to copy */
4213 /* Copy a block of data out to user space, given a pointer to the pointer */
4214 /* to start copying from (src) and a pointer to where to store it (dst). */
4215 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4216 /* ------------------------------------------------------------------------ */
4218 copyoutptr(softc, src, dst, size)
4219 ipf_main_softc_t *softc;
4226 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4227 error = COPYOUT(src, ca, size);
4238 /* ------------------------------------------------------------------------ */
4239 /* Function: ipf_lock */
4240 /* Returns: int - 0 = success, else error */
4241 /* Parameters: data(I) - pointer to lock value to set */
4242 /* lockp(O) - pointer to location to store old lock value */
4244 /* Get the new value for the lock integer, set it and return the old value */
4246 /* ------------------------------------------------------------------------ */
4248 ipf_lock(data, lockp)
4254 err = BCOPYIN(data, &arg, sizeof(arg));
4257 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4265 /* ------------------------------------------------------------------------ */
4266 /* Function: ipf_getstat */
4268 /* Parameters: softc(I) - pointer to soft context main structure */
4269 /* fiop(I) - pointer to ipfilter stats structure */
4270 /* rev(I) - version claim by program doing ioctl */
4272 /* Stores a copy of current pointers, counters, etc, in the friostat */
4274 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4275 /* program is looking for. This ensure that validation of the version it */
4276 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4277 /* allow older binaries to work but kernels without it will not. */
4278 /* ------------------------------------------------------------------------ */
4281 ipf_getstat(softc, fiop, rev)
4282 ipf_main_softc_t *softc;
4288 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4289 sizeof(ipf_statistics_t) * 2);
4290 fiop->f_locks[IPL_LOGSTATE] = -1;
4291 fiop->f_locks[IPL_LOGNAT] = -1;
4292 fiop->f_locks[IPL_LOGIPF] = -1;
4293 fiop->f_locks[IPL_LOGAUTH] = -1;
4295 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4296 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4297 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4298 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4299 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4300 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4301 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4302 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4304 fiop->f_ticks = softc->ipf_ticks;
4305 fiop->f_active = softc->ipf_active;
4306 fiop->f_froute[0] = softc->ipf_frouteok[0];
4307 fiop->f_froute[1] = softc->ipf_frouteok[1];
4308 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4309 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4311 fiop->f_running = softc->ipf_running;
4312 for (i = 0; i < IPL_LOGSIZE; i++) {
4313 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4314 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4317 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4318 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4319 fiop->f_logging = 1;
4322 fiop->f_log_fail = 0;
4323 fiop->f_logging = 0;
4325 fiop->f_defpass = softc->ipf_pass;
4326 fiop->f_features = ipf_features;
4328 #ifdef IPFILTER_COMPAT
4329 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4330 (rev / 1000000) % 100,
4331 (rev / 10000) % 100,
4335 (void) strncpy(fiop->f_version, ipfilter_version,
4336 sizeof(fiop->f_version));
4342 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4343 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4346 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4347 -1, /* 4: ICMP_SOURCEQUENCH */
4348 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4351 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4353 -1, /* 10: UNUSED */
4354 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4355 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4356 -1, /* 13: ICMP_TSTAMP */
4357 -1, /* 14: ICMP_TSTAMPREPLY */
4358 -1, /* 15: ICMP_IREQ */
4359 -1, /* 16: ICMP_IREQREPLY */
4360 -1, /* 17: ICMP_MASKREQ */
4361 -1, /* 18: ICMP_MASKREPLY */
4365 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4366 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4367 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4368 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4369 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4370 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4371 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4372 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4373 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4374 -1, /* 8: ICMP_UNREACH_ISOLATED */
4375 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4376 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4377 -1, /* 11: ICMP_UNREACH_TOSNET */
4378 -1, /* 12: ICMP_UNREACH_TOSHOST */
4379 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4381 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4384 int icmpreplytype4[ICMP_MAXTYPE + 1];
4387 /* ------------------------------------------------------------------------ */
4388 /* Function: ipf_matchicmpqueryreply */
4389 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4390 /* Parameters: v(I) - IP protocol version (4 or 6) */
4391 /* ic(I) - ICMP information */
4392 /* icmp(I) - ICMP packet header */
4393 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4395 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4396 /* reply to one as described by what's in ic. If it is a match, return 1, */
4397 /* else return 0 for no match. */
4398 /* ------------------------------------------------------------------------ */
4400 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4408 ictype = ic->ici_type;
4412 * If we matched its type on the way in, then when going out
4413 * it will still be the same type.
4415 if ((!rev && (icmp->icmp_type == ictype)) ||
4416 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4417 if (icmp->icmp_type != ICMP_ECHOREPLY)
4419 if (icmp->icmp_id == ic->ici_id)
4425 if ((!rev && (icmp->icmp_type == ictype)) ||
4426 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4427 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4429 if (icmp->icmp_id == ic->ici_id)
4438 /* ------------------------------------------------------------------------ */
4439 /* Function: frrequest */
4440 /* Returns: int - 0 == success, > 0 == errno value */
4441 /* Parameters: unit(I) - device for which this is for */
4442 /* req(I) - ioctl command (SIOC*) */
4443 /* data(I) - pointr to ioctl data */
4444 /* set(I) - 1 or 0 (filter set) */
4445 /* makecopy(I) - flag indicating whether data points to a rule */
4446 /* in kernel space & hence doesn't need copying. */
4448 /* This function handles all the requests which operate on the list of */
4449 /* filter rules. This includes adding, deleting, insertion. It is also */
4450 /* responsible for creating groups when a "head" rule is loaded. Interface */
4451 /* names are resolved here and other sanity checks are made on the content */
4452 /* of the rule structure being loaded. If a rule has user defined timeouts */
4453 /* then make sure they are created and initialised before exiting. */
4454 /* ------------------------------------------------------------------------ */
4456 frrequest(softc, unit, req, data, set, makecopy)
4457 ipf_main_softc_t *softc;
4463 int error = 0, in, family, addrem, need_free = 0;
4464 frentry_t frd, *fp, *f, **fprev, **ftail;
4465 void *ptr, *uptr, *cptr;
4474 if (makecopy != 0) {
4475 bzero(fp, sizeof(frd));
4476 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4480 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4484 KMALLOCS(f, frentry_t *, fp->fr_size);
4489 bzero(f, fp->fr_size);
4490 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4493 KFREES(f, fp->fr_size);
4499 fp->fr_dnext = NULL;
4501 fp->fr_flags |= FR_COPIED;
4503 fp = (frentry_t *)data;
4504 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4508 fp->fr_flags &= ~FR_COPIED;
4511 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4512 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4518 family = fp->fr_family;
4521 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4522 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4524 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4526 else if (req == (ioctlcmd_t)SIOCZRLST)
4535 * Only filter rules for IPv4 or IPv6 are accepted.
4537 if (family == AF_INET) {
4540 } else if (family == AF_INET6) {
4543 } else if (family != 0) {
4550 * If the rule is being loaded from user space, i.e. we had to copy it
4551 * into kernel space, then do not trust the function pointer in the
4554 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4555 if (ipf_findfunc(fp->fr_func) == NULL) {
4562 error = ipf_funcinit(softc, fp);
4567 if ((fp->fr_flags & FR_CALLNOW) &&
4568 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4573 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4574 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4583 if (FR_ISACCOUNT(fp->fr_flags))
4584 unit = IPL_LOGCOUNT;
4587 * Check that each group name in the rule has a start index that
4590 if (fp->fr_icmphead != -1) {
4591 if ((fp->fr_icmphead < 0) ||
4592 (fp->fr_icmphead >= fp->fr_namelen)) {
4597 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4598 fp->fr_names[fp->fr_icmphead] = '\0';
4601 if (fp->fr_grhead != -1) {
4602 if ((fp->fr_grhead < 0) ||
4603 (fp->fr_grhead >= fp->fr_namelen)) {
4608 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4609 fp->fr_names[fp->fr_grhead] = '\0';
4612 if (fp->fr_group != -1) {
4613 if ((fp->fr_group < 0) ||
4614 (fp->fr_group >= fp->fr_namelen)) {
4619 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4621 * Allow loading rules that are in groups to cause
4622 * them to be created if they don't already exit.
4624 group = FR_NAME(fp, fr_group);
4626 fg = ipf_group_add(softc, group, NULL,
4627 fp->fr_flags, unit, set);
4630 fg = ipf_findgroup(softc, group, unit,
4639 if (fg->fg_flags == 0) {
4640 fg->fg_flags = fp->fr_flags & FR_INOUT;
4641 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4649 * If a rule is going to be part of a group then it does
4650 * not matter whether it is an in or out rule, but if it
4651 * isn't in a group, then it does...
4653 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4659 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4662 * Work out which rule list this change is being applied to.
4666 if (unit == IPL_LOGAUTH) {
4667 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4668 (fp->fr_tifs[1].fd_ptr != NULL) ||
4669 (fp->fr_dif.fd_ptr != NULL) ||
4670 (fp->fr_flags & FR_FASTROUTE)) {
4671 softc->ipf_interror = 145;
4675 fprev = ipf_auth_rulehead(softc);
4677 if (FR_ISACCOUNT(fp->fr_flags))
4678 fprev = &softc->ipf_acct[in][set];
4679 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4680 fprev = &softc->ipf_rules[in][set];
4682 if (fprev == NULL) {
4689 fprev = &fg->fg_start;
4692 * Copy in extra data for the rule.
4694 if (fp->fr_dsize != 0) {
4695 if (makecopy != 0) {
4696 KMALLOCS(ptr, void *, fp->fr_dsize);
4704 * The bcopy case is for when the data is appended
4705 * to the rule by ipf_in_compat().
4707 if (uptr >= (void *)fp &&
4708 uptr < (void *)((char *)fp + fp->fr_size)) {
4709 bcopy(uptr, ptr, fp->fr_dsize);
4712 error = COPYIN(uptr, ptr, fp->fr_dsize);
4728 * Perform per-rule type sanity checks of their members.
4729 * All code after this needs to be aware that allocated memory
4730 * may need to be free'd before exiting.
4732 switch (fp->fr_type & ~FR_T_BUILTIN)
4734 #if defined(IPFILTER_BPF)
4736 if (fp->fr_dsize == 0) {
4741 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4750 * Preparation for error case at the bottom of this function.
4752 if (fp->fr_datype == FRI_LOOKUP)
4753 fp->fr_dstptr = NULL;
4754 if (fp->fr_satype == FRI_LOOKUP)
4755 fp->fr_srcptr = NULL;
4757 if (fp->fr_dsize != sizeof(fripf_t)) {
4764 * Allowing a rule with both "keep state" and "with oow" is
4765 * pointless because adding a state entry to the table will
4766 * fail with the out of window (oow) flag set.
4768 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4774 switch (fp->fr_satype)
4776 case FRI_BROADCAST :
4779 case FRI_NETMASKED :
4781 if (fp->fr_sifpidx < 0) {
4787 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4790 if (fp->fr_srcfunc == NULL) {
4806 switch (fp->fr_datype)
4808 case FRI_BROADCAST :
4811 case FRI_NETMASKED :
4813 if (fp->fr_difpidx < 0) {
4819 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4822 if (fp->fr_dstfunc == NULL) {
4836 case FR_T_CALLFUNC :
4841 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4855 if (fp->fr_tif.fd_name != -1) {
4856 if ((fp->fr_tif.fd_name < 0) ||
4857 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4864 if (fp->fr_dif.fd_name != -1) {
4865 if ((fp->fr_dif.fd_name < 0) ||
4866 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4873 if (fp->fr_rif.fd_name != -1) {
4874 if ((fp->fr_rif.fd_name < 0) ||
4875 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4883 * Lookup all the interface names that are part of the rule.
4885 error = ipf_synclist(softc, fp, NULL);
4888 fp->fr_statecnt = 0;
4889 if (fp->fr_srctrack.ht_max_nodes != 0)
4890 ipf_rb_ht_init(&fp->fr_srctrack);
4893 * Look for an existing matching filter rule, but don't include the
4894 * next or interface pointer in the comparison (fr_next, fr_ifa).
4895 * This elminates rules which are indentical being loaded. Checksum
4896 * the constant part of the filter rule to make comparisons quicker
4897 * (this meaning no pointers are included).
4899 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4902 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4903 for (p = (u_int *)fp->fr_data; p < pp; p++)
4906 WRITE_ENTER(&softc->ipf_mutex);
4909 * Now that the filter rule lists are locked, we can walk the
4910 * chain of them without fear.
4913 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4914 if (fp->fr_collect <= f->fr_collect) {
4922 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4923 DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
4924 if ((fp->fr_cksum != f->fr_cksum) ||
4925 (fp->fr_size != f->fr_size) ||
4926 (f->fr_dsize != fp->fr_dsize))
4928 if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func,
4929 fp->fr_size - offsetof(struct frentry, fr_func)) != 0)
4931 if ((!ptr && !f->fr_data) ||
4932 (ptr && f->fr_data &&
4933 !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4938 * If zero'ing statistics, copy current to caller and zero.
4946 * Copy and reduce lock because of impending copyout.
4947 * Well we should, but if we do then the atomicity of
4948 * this call and the correctness of fr_hits and
4949 * fr_bytes cannot be guaranteed. As it is, this code
4950 * only resets them to 0 if they are successfully
4951 * copied out into user space.
4953 bcopy((char *)f, (char *)fp, f->fr_size);
4954 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4957 * When we copy this rule back out, set the data
4958 * pointer to be what it was in user space.
4961 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4964 if ((f->fr_dsize != 0) && (uptr != NULL))
4965 error = COPYOUT(f->fr_data, uptr,
4978 if (makecopy != 0) {
4980 KFREES(ptr, fp->fr_dsize);
4982 KFREES(fp, fp->fr_size);
4984 RWLOCK_EXIT(&softc->ipf_mutex);
4990 * At the end of this, ftail must point to the place where the
4991 * new rule is to be saved/inserted/added.
4992 * For SIOCAD*FR, this should be the last rule in the group of
4993 * rules that have equal fr_collect fields.
4994 * For SIOCIN*FR, ...
4996 if (req == (ioctlcmd_t)SIOCADAFR ||
4997 req == (ioctlcmd_t)SIOCADIFR) {
4999 for (ftail = fprev; (f = *ftail) != NULL; ) {
5000 if (f->fr_collect > fp->fr_collect)
5002 ftail = &f->fr_next;
5006 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5007 req == (ioctlcmd_t)SIOCINIFR) {
5008 while ((f = *fprev) != NULL) {
5009 if (f->fr_collect >= fp->fr_collect)
5011 fprev = &f->fr_next;
5014 if (fp->fr_hits != 0) {
5015 while (fp->fr_hits && (f = *ftail)) {
5016 if (f->fr_collect != fp->fr_collect)
5019 ftail = &f->fr_next;
5029 * Request to remove a rule.
5037 * Do not allow activity from user space to interfere
5038 * with rules not loaded that way.
5040 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5047 * Return EBUSY if the rule is being reference by
5048 * something else (eg state information.)
5050 if (f->fr_ref > 1) {
5055 #ifdef IPFILTER_SCAN
5056 if (f->fr_isctag != -1 &&
5057 (f->fr_isc != (struct ipscan *)-1))
5058 ipf_scan_detachfr(f);
5061 if (unit == IPL_LOGAUTH) {
5062 error = ipf_auth_precmd(softc, req, f, ftail);
5066 ipf_rule_delete(softc, f, unit, set);
5068 need_free = makecopy;
5072 * Not removing, so we must be adding/inserting a rule.
5079 if (unit == IPL_LOGAUTH) {
5080 error = ipf_auth_precmd(softc, req, fp, ftail);
5084 MUTEX_NUKE(&fp->fr_lock);
5085 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5086 if (fp->fr_die != 0)
5087 ipf_rule_expire_insert(softc, fp, set);
5092 fp->fr_pnext = ftail;
5093 fp->fr_next = *ftail;
5096 ipf_fixskip(ftail, fp, 1);
5098 fp->fr_icmpgrp = NULL;
5099 if (fp->fr_icmphead != -1) {
5100 group = FR_NAME(fp, fr_icmphead);
5101 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5102 fp->fr_icmpgrp = fg;
5105 fp->fr_grphead = NULL;
5106 if (fp->fr_grhead != -1) {
5107 group = FR_NAME(fp, fr_grhead);
5108 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5110 fp->fr_grphead = fg;
5114 RWLOCK_EXIT(&softc->ipf_mutex);
5116 if (need_free || (error != 0)) {
5117 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5118 if ((fp->fr_satype == FRI_LOOKUP) &&
5119 (fp->fr_srcptr != NULL))
5120 ipf_lookup_deref(softc, fp->fr_srctype,
5122 if ((fp->fr_datype == FRI_LOOKUP) &&
5123 (fp->fr_dstptr != NULL))
5124 ipf_lookup_deref(softc, fp->fr_dsttype,
5127 if (fp->fr_grp != NULL) {
5128 WRITE_ENTER(&softc->ipf_mutex);
5129 ipf_group_del(softc, fp->fr_grp, fp);
5130 RWLOCK_EXIT(&softc->ipf_mutex);
5132 if ((ptr != NULL) && (makecopy != 0)) {
5133 KFREES(ptr, fp->fr_dsize);
5135 KFREES(fp, fp->fr_size);
5141 /* ------------------------------------------------------------------------ */
5142 /* Function: ipf_rule_delete */
5144 /* Parameters: softc(I) - pointer to soft context main structure */
5145 /* f(I) - pointer to the rule being deleted */
5146 /* ftail(I) - pointer to the pointer to f */
5147 /* unit(I) - device for which this is for */
5148 /* set(I) - 1 or 0 (filter set) */
5150 /* This function attempts to do what it can to delete a filter rule: remove */
5151 /* it from any linked lists and remove any groups it is responsible for. */
5152 /* But in the end, removing a rule can only drop the reference count - we */
5153 /* must use that as the guide for whether or not it can be freed. */
5154 /* ------------------------------------------------------------------------ */
5156 ipf_rule_delete(softc, f, unit, set)
5157 ipf_main_softc_t *softc;
5163 * If fr_pdnext is set, then the rule is on the expire list, so
5164 * remove it from there.
5166 if (f->fr_pdnext != NULL) {
5167 *f->fr_pdnext = f->fr_dnext;
5168 if (f->fr_dnext != NULL)
5169 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5170 f->fr_pdnext = NULL;
5174 ipf_fixskip(f->fr_pnext, f, -1);
5175 if (f->fr_pnext != NULL)
5176 *f->fr_pnext = f->fr_next;
5177 if (f->fr_next != NULL)
5178 f->fr_next->fr_pnext = f->fr_pnext;
5182 (void) ipf_derefrule(softc, &f);
5185 /* ------------------------------------------------------------------------ */
5186 /* Function: ipf_rule_expire_insert */
5188 /* Parameters: softc(I) - pointer to soft context main structure */
5189 /* f(I) - pointer to rule to be added to expire list */
5190 /* set(I) - 1 or 0 (filter set) */
5192 /* If the new rule has a given expiration time, insert it into the list of */
5193 /* expiring rules with the ones to be removed first added to the front of */
5194 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5195 /* expiration interval checks. */
5196 /* ------------------------------------------------------------------------ */
5198 ipf_rule_expire_insert(softc, f, set)
5199 ipf_main_softc_t *softc;
5208 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5209 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5210 fr = fr->fr_dnext) {
5211 if (f->fr_die < fr->fr_die)
5213 if (fr->fr_dnext == NULL) {
5215 * We've got to the last rule and everything
5216 * wanted to be expired before this new node,
5217 * so we have to tack it on the end...
5220 f->fr_pdnext = &fr->fr_dnext;
5226 if (softc->ipf_rule_explist[set] == NULL) {
5227 softc->ipf_rule_explist[set] = f;
5228 f->fr_pdnext = &softc->ipf_rule_explist[set];
5229 } else if (fr != NULL) {
5231 f->fr_pdnext = fr->fr_pdnext;
5232 fr->fr_pdnext = &f->fr_dnext;
5237 /* ------------------------------------------------------------------------ */
5238 /* Function: ipf_findlookup */
5239 /* Returns: NULL = failure, else success */
5240 /* Parameters: softc(I) - pointer to soft context main structure */
5241 /* unit(I) - ipf device we want to find match for */
5242 /* fp(I) - rule for which lookup is for */
5243 /* addrp(I) - pointer to lookup information in address struct */
5244 /* maskp(O) - pointer to lookup information for storage */
5246 /* When using pools and hash tables to store addresses for matching in */
5247 /* rules, it is necessary to resolve both the object referred to by the */
5248 /* name or address (and return that pointer) and also provide the means by */
5249 /* which to determine if an address belongs to that object to make the */
5250 /* packet matching quicker. */
5251 /* ------------------------------------------------------------------------ */
5253 ipf_findlookup(softc, unit, fr, addrp, maskp)
5254 ipf_main_softc_t *softc;
5257 i6addr_t *addrp, *maskp;
5261 switch (addrp->iplookupsubtype)
5264 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5266 &maskp->iplookupfunc);
5269 if (addrp->iplookupname < 0)
5271 if (addrp->iplookupname >= fr->fr_namelen)
5273 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5274 fr->fr_names + addrp->iplookupname,
5275 &maskp->iplookupfunc);
5285 /* ------------------------------------------------------------------------ */
5286 /* Function: ipf_funcinit */
5287 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5288 /* Parameters: softc(I) - pointer to soft context main structure */
5289 /* fr(I) - pointer to filter rule */
5291 /* If a rule is a call rule, then check if the function it points to needs */
5292 /* an init function to be called now the rule has been loaded. */
5293 /* ------------------------------------------------------------------------ */
5295 ipf_funcinit(softc, fr)
5296 ipf_main_softc_t *softc;
5299 ipfunc_resolve_t *ft;
5305 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5306 if (ft->ipfu_addr == fr->fr_func) {
5308 if (ft->ipfu_init != NULL)
5309 err = (*ft->ipfu_init)(softc, fr);
5316 /* ------------------------------------------------------------------------ */
5317 /* Function: ipf_funcfini */
5319 /* Parameters: softc(I) - pointer to soft context main structure */
5320 /* fr(I) - pointer to filter rule */
5322 /* For a given filter rule, call the matching "fini" function if the rule */
5323 /* is using a known function that would have resulted in the "init" being */
5324 /* called for ealier. */
5325 /* ------------------------------------------------------------------------ */
5327 ipf_funcfini(softc, fr)
5328 ipf_main_softc_t *softc;
5331 ipfunc_resolve_t *ft;
5333 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5334 if (ft->ipfu_addr == fr->fr_func) {
5335 if (ft->ipfu_fini != NULL)
5336 (void) (*ft->ipfu_fini)(softc, fr);
5342 /* ------------------------------------------------------------------------ */
5343 /* Function: ipf_findfunc */
5344 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5345 /* Parameters: funcptr(I) - function pointer to lookup */
5347 /* Look for a function in the table of known functions. */
5348 /* ------------------------------------------------------------------------ */
5350 ipf_findfunc(funcptr)
5353 ipfunc_resolve_t *ft;
5355 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5356 if (ft->ipfu_addr == funcptr)
5362 /* ------------------------------------------------------------------------ */
5363 /* Function: ipf_resolvefunc */
5364 /* Returns: int - 0 == success, else error */
5365 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5367 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5368 /* This will either be the function name (if the pointer is set) or the */
5369 /* function pointer if the name is set. When found, fill in the other one */
5370 /* so that the entire, complete, structure can be copied back to user space.*/
5371 /* ------------------------------------------------------------------------ */
5373 ipf_resolvefunc(softc, data)
5374 ipf_main_softc_t *softc;
5377 ipfunc_resolve_t res, *ft;
5380 error = BCOPYIN(data, &res, sizeof(res));
5386 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5387 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5388 if (strncmp(res.ipfu_name, ft->ipfu_name,
5389 sizeof(res.ipfu_name)) == 0) {
5390 res.ipfu_addr = ft->ipfu_addr;
5391 res.ipfu_init = ft->ipfu_init;
5392 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5399 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5400 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5401 if (ft->ipfu_addr == res.ipfu_addr) {
5402 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5403 sizeof(res.ipfu_name));
5404 res.ipfu_init = ft->ipfu_init;
5405 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5417 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5418 !defined(__FreeBSD__)) || \
5419 FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5420 OPENBSD_LT_REV(200006)
5423 * ppsratecheck(): packets (or events) per second limitation.
5426 ppsratecheck(lasttime, curpps, maxpps)
5427 struct timeval *lasttime;
5429 int maxpps; /* maximum pps allowed */
5431 struct timeval tv, delta;
5436 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5437 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5438 if (delta.tv_usec < 0) {
5440 delta.tv_usec += 1000000;
5444 * check for 0,0 is so that the message will be seen at least once.
5445 * if more than one second have passed since the last update of
5446 * lasttime, reset the counter.
5448 * we do increment *curpps even in *curpps < maxpps case, as some may
5449 * try to use *curpps for stat purposes as well.
5451 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5452 delta.tv_sec >= 1) {
5456 } else if (maxpps < 0)
5458 else if (*curpps < maxpps)
5462 *curpps = *curpps + 1;
5469 /* ------------------------------------------------------------------------ */
5470 /* Function: ipf_derefrule */
5471 /* Returns: int - 0 == rule freed up, else rule not freed */
5472 /* Parameters: fr(I) - pointer to filter rule */
5474 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5475 /* free it and any associated storage space being used by it. */
5476 /* ------------------------------------------------------------------------ */
5478 ipf_derefrule(softc, frp)
5479 ipf_main_softc_t *softc;
5488 MUTEX_ENTER(&fr->fr_lock);
5490 if (fr->fr_ref == 0) {
5491 MUTEX_EXIT(&fr->fr_lock);
5492 MUTEX_DESTROY(&fr->fr_lock);
5494 ipf_funcfini(softc, fr);
5497 if (fdp->fd_type == FRD_DSTLIST)
5498 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5501 if (fdp->fd_type == FRD_DSTLIST)
5502 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5505 if (fdp->fd_type == FRD_DSTLIST)
5506 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5508 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5509 fr->fr_satype == FRI_LOOKUP)
5510 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5511 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5512 fr->fr_datype == FRI_LOOKUP)
5513 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5515 if (fr->fr_grp != NULL)
5516 ipf_group_del(softc, fr->fr_grp, fr);
5518 if (fr->fr_grphead != NULL)
5519 ipf_group_del(softc, fr->fr_grphead, fr);
5521 if (fr->fr_icmpgrp != NULL)
5522 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5524 if ((fr->fr_flags & FR_COPIED) != 0) {
5526 KFREES(fr->fr_data, fr->fr_dsize);
5528 KFREES(fr, fr->fr_size);
5533 MUTEX_EXIT(&fr->fr_lock);
5539 /* ------------------------------------------------------------------------ */
5540 /* Function: ipf_grpmapinit */
5541 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5542 /* Parameters: fr(I) - pointer to rule to find hash table for */
5544 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5545 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5546 /* ------------------------------------------------------------------------ */
5548 ipf_grpmapinit(softc, fr)
5549 ipf_main_softc_t *softc;
5552 char name[FR_GROUPLEN];
5555 #if defined(SNPRINTF) && defined(_KERNEL)
5556 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5558 (void) sprintf(name, "%d", fr->fr_arg);
5560 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5565 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5575 /* ------------------------------------------------------------------------ */
5576 /* Function: ipf_grpmapfini */
5577 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5578 /* Parameters: softc(I) - pointer to soft context main structure */
5579 /* fr(I) - pointer to rule to release hash table for */
5581 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5582 /* be called to undo what ipf_grpmapinit caused to be done. */
5583 /* ------------------------------------------------------------------------ */
5585 ipf_grpmapfini(softc, fr)
5586 ipf_main_softc_t *softc;
5592 ipf_lookup_deref(softc, IPLT_HASH, iph);
5597 /* ------------------------------------------------------------------------ */
5598 /* Function: ipf_srcgrpmap */
5599 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5600 /* Parameters: fin(I) - pointer to packet information */
5601 /* passp(IO) - pointer to current/new filter decision (unused) */
5603 /* Look for a rule group head in a hash table, using the source address as */
5604 /* the key, and descend into that group and continue matching rules against */
5606 /* ------------------------------------------------------------------------ */
5608 ipf_srcgrpmap(fin, passp)
5615 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5621 fin->fin_fr = fg->fg_start;
5622 (void) ipf_scanlist(fin, *passp);
5627 /* ------------------------------------------------------------------------ */
5628 /* Function: ipf_dstgrpmap */
5629 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5630 /* Parameters: fin(I) - pointer to packet information */
5631 /* passp(IO) - pointer to current/new filter decision (unused) */
5633 /* Look for a rule group head in a hash table, using the destination */
5634 /* address as the key, and descend into that group and continue matching */
5635 /* rules against the packet. */
5636 /* ------------------------------------------------------------------------ */
5638 ipf_dstgrpmap(fin, passp)
5645 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5651 fin->fin_fr = fg->fg_start;
5652 (void) ipf_scanlist(fin, *passp);
5659 * These functions manage objects on queues for efficient timeouts. There
5660 * are a number of system defined queues as well as user defined timeouts.
5661 * It is expected that a lock is held in the domain in which the queue
5662 * belongs (i.e. either state or NAT) when calling any of these functions
5663 * that prevents ipf_freetimeoutqueue() from being called at the same time
5668 /* ------------------------------------------------------------------------ */
5669 /* Function: ipf_addtimeoutqueue */
5670 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5671 /* timeout queue with given interval. */
5672 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5673 /* of interface queues. */
5674 /* seconds(I) - timeout value in seconds for this queue. */
5676 /* This routine first looks for a timeout queue that matches the interval */
5677 /* being requested. If it finds one, increments the reference counter and */
5678 /* returns a pointer to it. If none are found, it allocates a new one and */
5679 /* inserts it at the top of the list. */
5682 /* It is assumed that the caller of this function has an appropriate lock */
5683 /* held (exclusively) in the domain that encompases 'parent'. */
5684 /* ------------------------------------------------------------------------ */
5686 ipf_addtimeoutqueue(softc, parent, seconds)
5687 ipf_main_softc_t *softc;
5694 period = seconds * IPF_HZ_DIVIDE;
5696 MUTEX_ENTER(&softc->ipf_timeoutlock);
5697 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5698 if (ifq->ifq_ttl == period) {
5700 * Reset the delete flag, if set, so the structure
5701 * gets reused rather than freed and reallocated.
5703 MUTEX_ENTER(&ifq->ifq_lock);
5704 ifq->ifq_flags &= ~IFQF_DELETE;
5706 MUTEX_EXIT(&ifq->ifq_lock);
5707 MUTEX_EXIT(&softc->ipf_timeoutlock);
5713 KMALLOC(ifq, ipftq_t *);
5715 MUTEX_NUKE(&ifq->ifq_lock);
5716 IPFTQ_INIT(ifq, period, "ipftq mutex");
5717 ifq->ifq_next = *parent;
5718 ifq->ifq_pnext = parent;
5719 ifq->ifq_flags = IFQF_USER;
5722 softc->ipf_userifqs++;
5724 MUTEX_EXIT(&softc->ipf_timeoutlock);
5729 /* ------------------------------------------------------------------------ */
5730 /* Function: ipf_deletetimeoutqueue */
5731 /* Returns: int - new reference count value of the timeout queue */
5732 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5733 /* Locks: ifq->ifq_lock */
5735 /* This routine must be called when we're discarding a pointer to a timeout */
5736 /* queue object, taking care of the reference counter. */
5738 /* Now that this just sets a DELETE flag, it requires the expire code to */
5739 /* check the list of user defined timeout queues and call the free function */
5740 /* below (currently commented out) to stop memory leaking. It is done this */
5741 /* way because the locking may not be sufficient to safely do a free when */
5742 /* this function is called. */
5743 /* ------------------------------------------------------------------------ */
5745 ipf_deletetimeoutqueue(ifq)
5750 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5751 ifq->ifq_flags |= IFQF_DELETE;
5754 return ifq->ifq_ref;
5758 /* ------------------------------------------------------------------------ */
5759 /* Function: ipf_freetimeoutqueue */
5760 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5764 /* It is assumed that the caller of this function has an appropriate lock */
5765 /* held (exclusively) in the domain that encompases the callers "domain". */
5766 /* The ifq_lock for this structure should not be held. */
5768 /* Remove a user defined timeout queue from the list of queues it is in and */
5769 /* tidy up after this is done. */
5770 /* ------------------------------------------------------------------------ */
5772 ipf_freetimeoutqueue(softc, ifq)
5773 ipf_main_softc_t *softc;
5777 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5778 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5779 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5780 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5786 * Remove from its position in the list.
5788 *ifq->ifq_pnext = ifq->ifq_next;
5789 if (ifq->ifq_next != NULL)
5790 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5791 ifq->ifq_next = NULL;
5792 ifq->ifq_pnext = NULL;
5794 MUTEX_DESTROY(&ifq->ifq_lock);
5795 ATOMIC_DEC(softc->ipf_userifqs);
5800 /* ------------------------------------------------------------------------ */
5801 /* Function: ipf_deletequeueentry */
5803 /* Parameters: tqe(I) - timeout queue entry to delete */
5805 /* Remove a tail queue entry from its queue and make it an orphan. */
5806 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5807 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5808 /* the correct lock(s) may not be held that would make it safe to do so. */
5809 /* ------------------------------------------------------------------------ */
5811 ipf_deletequeueentry(tqe)
5818 MUTEX_ENTER(&ifq->ifq_lock);
5820 if (tqe->tqe_pnext != NULL) {
5821 *tqe->tqe_pnext = tqe->tqe_next;
5822 if (tqe->tqe_next != NULL)
5823 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5824 else /* we must be the tail anyway */
5825 ifq->ifq_tail = tqe->tqe_pnext;
5827 tqe->tqe_pnext = NULL;
5828 tqe->tqe_ifq = NULL;
5831 (void) ipf_deletetimeoutqueue(ifq);
5832 ASSERT(ifq->ifq_ref > 0);
5834 MUTEX_EXIT(&ifq->ifq_lock);
5838 /* ------------------------------------------------------------------------ */
5839 /* Function: ipf_queuefront */
5841 /* Parameters: tqe(I) - pointer to timeout queue entry */
5843 /* Move a queue entry to the front of the queue, if it isn't already there. */
5844 /* ------------------------------------------------------------------------ */
5855 MUTEX_ENTER(&ifq->ifq_lock);
5856 if (ifq->ifq_head != tqe) {
5857 *tqe->tqe_pnext = tqe->tqe_next;
5859 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5861 ifq->ifq_tail = tqe->tqe_pnext;
5863 tqe->tqe_next = ifq->ifq_head;
5864 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5865 ifq->ifq_head = tqe;
5866 tqe->tqe_pnext = &ifq->ifq_head;
5868 MUTEX_EXIT(&ifq->ifq_lock);
5872 /* ------------------------------------------------------------------------ */
5873 /* Function: ipf_queueback */
5875 /* Parameters: ticks(I) - ipf tick time to use with this call */
5876 /* tqe(I) - pointer to timeout queue entry */
5878 /* Move a queue entry to the back of the queue, if it isn't already there. */
5879 /* We use use ticks to calculate the expiration and mark for when we last */
5880 /* touched the structure. */
5881 /* ------------------------------------------------------------------------ */
5883 ipf_queueback(ticks, tqe)
5892 tqe->tqe_die = ticks + ifq->ifq_ttl;
5893 tqe->tqe_touched = ticks;
5895 MUTEX_ENTER(&ifq->ifq_lock);
5896 if (tqe->tqe_next != NULL) { /* at the end already ? */
5900 *tqe->tqe_pnext = tqe->tqe_next;
5901 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5904 * Make it the last entry.
5906 tqe->tqe_next = NULL;
5907 tqe->tqe_pnext = ifq->ifq_tail;
5908 *ifq->ifq_tail = tqe;
5909 ifq->ifq_tail = &tqe->tqe_next;
5911 MUTEX_EXIT(&ifq->ifq_lock);
5915 /* ------------------------------------------------------------------------ */
5916 /* Function: ipf_queueappend */
5918 /* Parameters: ticks(I) - ipf tick time to use with this call */
5919 /* tqe(I) - pointer to timeout queue entry */
5920 /* ifq(I) - pointer to timeout queue */
5921 /* parent(I) - owing object pointer */
5923 /* Add a new item to this queue and put it on the very end. */
5924 /* We use use ticks to calculate the expiration and mark for when we last */
5925 /* touched the structure. */
5926 /* ------------------------------------------------------------------------ */
5928 ipf_queueappend(ticks, tqe, ifq, parent)
5935 MUTEX_ENTER(&ifq->ifq_lock);
5936 tqe->tqe_parent = parent;
5937 tqe->tqe_pnext = ifq->ifq_tail;
5938 *ifq->ifq_tail = tqe;
5939 ifq->ifq_tail = &tqe->tqe_next;
5940 tqe->tqe_next = NULL;
5942 tqe->tqe_die = ticks + ifq->ifq_ttl;
5943 tqe->tqe_touched = ticks;
5945 MUTEX_EXIT(&ifq->ifq_lock);
5949 /* ------------------------------------------------------------------------ */
5950 /* Function: ipf_movequeue */
5952 /* Parameters: tq(I) - pointer to timeout queue information */
5953 /* oifp(I) - old timeout queue entry was on */
5954 /* nifp(I) - new timeout queue to put entry on */
5956 /* Move a queue entry from one timeout queue to another timeout queue. */
5957 /* If it notices that the current entry is already last and does not need */
5958 /* to move queue, the return. */
5959 /* ------------------------------------------------------------------------ */
5961 ipf_movequeue(ticks, tqe, oifq, nifq)
5964 ipftq_t *oifq, *nifq;
5968 * If the queue hasn't changed and we last touched this entry at the
5969 * same ipf time, then we're not going to achieve anything by either
5970 * changing the ttl or moving it on the queue.
5972 if (oifq == nifq && tqe->tqe_touched == ticks)
5976 * For any of this to be outside the lock, there is a risk that two
5977 * packets entering simultaneously, with one changing to a different
5978 * queue and one not, could end up with things in a bizarre state.
5980 MUTEX_ENTER(&oifq->ifq_lock);
5982 tqe->tqe_touched = ticks;
5983 tqe->tqe_die = ticks + nifq->ifq_ttl;
5985 * Is the operation here going to be a no-op ?
5988 if ((tqe->tqe_next == NULL) ||
5989 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5990 MUTEX_EXIT(&oifq->ifq_lock);
5996 * Remove from the old queue
5998 *tqe->tqe_pnext = tqe->tqe_next;
6000 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6002 oifq->ifq_tail = tqe->tqe_pnext;
6003 tqe->tqe_next = NULL;
6006 * If we're moving from one queue to another, release the
6007 * lock on the old queue and get a lock on the new queue.
6008 * For user defined queues, if we're moving off it, call
6009 * delete in case it can now be freed.
6012 tqe->tqe_ifq = NULL;
6014 (void) ipf_deletetimeoutqueue(oifq);
6016 MUTEX_EXIT(&oifq->ifq_lock);
6018 MUTEX_ENTER(&nifq->ifq_lock);
6020 tqe->tqe_ifq = nifq;
6025 * Add to the bottom of the new queue
6027 tqe->tqe_pnext = nifq->ifq_tail;
6028 *nifq->ifq_tail = tqe;
6029 nifq->ifq_tail = &tqe->tqe_next;
6030 MUTEX_EXIT(&nifq->ifq_lock);
6034 /* ------------------------------------------------------------------------ */
6035 /* Function: ipf_updateipid */
6036 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6037 /* Parameters: fin(I) - pointer to packet information */
6039 /* When we are doing NAT, change the IP of every packet to represent a */
6040 /* single sequence of packets coming from the host, hiding any host */
6041 /* specific sequencing that might otherwise be revealed. If the packet is */
6042 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
6043 /* the fragment cache for non-leading fragments. If a non-leading fragment */
6044 /* has no match in the cache, return an error. */
6045 /* ------------------------------------------------------------------------ */
6050 u_short id, ido, sums;
6054 if (fin->fin_off != 0) {
6055 sum = ipf_frag_ipidknown(fin);
6056 if (sum == 0xffffffff)
6061 id = ipf_nextipid(fin);
6062 if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
6063 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6067 ido = ntohs(ip->ip_id);
6070 ip->ip_id = htons(id);
6071 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6072 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6074 sum = (sum >> 16) + (sum & 0xffff);
6075 sum = (sum >> 16) + (sum & 0xffff);
6076 sums = ~(u_short)sum;
6077 ip->ip_sum = htons(sums);
6082 #ifdef NEED_FRGETIFNAME
6083 /* ------------------------------------------------------------------------ */
6084 /* Function: ipf_getifname */
6085 /* Returns: char * - pointer to interface name */
6086 /* Parameters: ifp(I) - pointer to network interface */
6087 /* buffer(O) - pointer to where to store interface name */
6089 /* Constructs an interface name in the buffer passed. The buffer passed is */
6090 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6091 /* as a NULL pointer then return a pointer to a static array. */
6092 /* ------------------------------------------------------------------------ */
6094 ipf_getifname(ifp, buffer)
6098 static char namebuf[LIFNAMSIZ];
6099 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6100 defined(__sgi) || defined(linux) || defined(_AIX51) || \
6101 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6109 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6110 buffer[LIFNAMSIZ - 1] = '\0';
6111 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6112 defined(__sgi) || defined(_AIX51) || \
6113 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6114 for (s = buffer; *s; s++)
6116 unit = ifp->if_unit;
6117 space = LIFNAMSIZ - (s - buffer);
6118 if ((space > 0) && (unit >= 0)) {
6119 # if defined(SNPRINTF) && defined(_KERNEL)
6120 SNPRINTF(temp, sizeof(temp), "%d", unit);
6122 (void) sprintf(temp, "%d", unit);
6124 (void) strncpy(s, temp, space);
6132 /* ------------------------------------------------------------------------ */
6133 /* Function: ipf_ioctlswitch */
6134 /* Returns: int - -1 continue processing, else ioctl return value */
6135 /* Parameters: unit(I) - device unit opened */
6136 /* data(I) - pointer to ioctl data */
6137 /* cmd(I) - ioctl command */
6138 /* mode(I) - mode value */
6139 /* uid(I) - uid making the ioctl call */
6140 /* ctx(I) - pointer to context data */
6142 /* Based on the value of unit, call the appropriate ioctl handler or return */
6143 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6144 /* for the device in order to execute the ioctl. A special case is made */
6145 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6146 /* The context data pointer is passed through as this is used as the key */
6147 /* for locating a matching token for continued access for walking lists, */
6149 /* ------------------------------------------------------------------------ */
6151 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6152 ipf_main_softc_t *softc;
6153 int unit, mode, uid;
6161 case SIOCIPFINTERROR :
6162 error = BCOPYOUT(&softc->ipf_interror, data,
6163 sizeof(softc->ipf_interror));
6176 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6179 if (softc->ipf_running > 0) {
6180 error = ipf_nat_ioctl(softc, data, cmd, mode,
6188 if (softc->ipf_running > 0) {
6189 error = ipf_state_ioctl(softc, data, cmd, mode,
6197 if (softc->ipf_running > 0) {
6198 error = ipf_auth_ioctl(softc, data, cmd, mode,
6206 if (softc->ipf_running > 0) {
6207 error = ipf_sync_ioctl(softc, data, cmd, mode,
6215 #ifdef IPFILTER_SCAN
6216 if (softc->ipf_running > 0)
6217 error = ipf_scan_ioctl(softc, data, cmd, mode,
6226 case IPL_LOGLOOKUP :
6227 if (softc->ipf_running > 0) {
6228 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6246 * This array defines the expected size of objects coming into the kernel
6247 * for the various recognised object types. The first column is flags (see
6248 * below), 2nd column is current size, 3rd column is the version number of
6249 * when the current size became current.
6251 * 1 = minimum size, not absolute size
6253 static int ipf_objbytes[IPFOBJ_COUNT][3] = {
6254 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6255 { 1, sizeof(struct friostat), 5010000 },
6256 { 0, sizeof(struct fr_info), 5010000 },
6257 { 0, sizeof(struct ipf_authstat), 4010100 },
6258 { 0, sizeof(struct ipfrstat), 5010000 },
6259 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6260 { 0, sizeof(struct natstat), 5010000 },
6261 { 0, sizeof(struct ipstate_save), 5010000 },
6262 { 1, sizeof(struct nat_save), 5010000 },
6263 { 0, sizeof(struct natlookup), 5010000 },
6264 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6265 { 0, sizeof(struct ips_stat), 5010000 },
6266 { 0, sizeof(struct frauth), 5010000 },
6267 { 0, sizeof(struct ipftune), 4010100 },
6268 { 0, sizeof(struct nat), 5010000 },
6269 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6270 { 0, sizeof(struct ipfgeniter), 4011400 },
6271 { 0, sizeof(struct ipftable), 4011400 },
6272 { 0, sizeof(struct ipflookupiter), 4011400 },
6273 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6274 { 1, 0, 0 }, /* IPFEXPR */
6275 { 0, 0, 0 }, /* PROXYCTL */
6276 { 0, sizeof (struct fripf), 5010000 }
6280 /* ------------------------------------------------------------------------ */
6281 /* Function: ipf_inobj */
6282 /* Returns: int - 0 = success, else failure */
6283 /* Parameters: softc(I) - soft context pointerto work with */
6284 /* data(I) - pointer to ioctl data */
6285 /* objp(O) - where to store ipfobj structure */
6286 /* ptr(I) - pointer to data to copy out */
6287 /* type(I) - type of structure being moved */
6289 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6290 /* add things to check for version numbers, sizes, etc, to make it backward */
6291 /* compatible at the ABI for user land. */
6292 /* If objp is not NULL then we assume that the caller wants to see what is */
6293 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6294 /* the caller what version of ipfilter the ioctl program was written to. */
6295 /* ------------------------------------------------------------------------ */
6297 ipf_inobj(softc, data, objp, ptr, type)
6298 ipf_main_softc_t *softc;
6308 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6315 error = BCOPYIN(data, objp, sizeof(*objp));
6321 if (objp->ipfo_type != type) {
6326 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6327 if ((ipf_objbytes[type][0] & 1) != 0) {
6328 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6332 size = ipf_objbytes[type][1];
6333 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6334 size = objp->ipfo_size;
6339 error = COPYIN(objp->ipfo_ptr, ptr, size);
6345 #ifdef IPFILTER_COMPAT
6346 error = ipf_in_compat(softc, objp, ptr, 0);
6356 /* ------------------------------------------------------------------------ */
6357 /* Function: ipf_inobjsz */
6358 /* Returns: int - 0 = success, else failure */
6359 /* Parameters: softc(I) - soft context pointerto work with */
6360 /* data(I) - pointer to ioctl data */
6361 /* ptr(I) - pointer to store real data in */
6362 /* type(I) - type of structure being moved */
6363 /* sz(I) - size of data to copy */
6365 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6366 /* but it must not be smaller than the size defined for the type and the */
6367 /* type must allow for varied sized objects. The extra requirement here is */
6368 /* that sz must match the size of the object being passed in - this is not */
6369 /* not possible nor required in ipf_inobj(). */
6370 /* ------------------------------------------------------------------------ */
6372 ipf_inobjsz(softc, data, ptr, type, sz)
6373 ipf_main_softc_t *softc;
6381 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6386 error = BCOPYIN(data, &obj, sizeof(obj));
6392 if (obj.ipfo_type != type) {
6397 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6398 if (((ipf_objbytes[type][0] & 1) == 0) ||
6399 (sz < ipf_objbytes[type][1])) {
6403 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6409 #ifdef IPFILTER_COMPAT
6410 error = ipf_in_compat(softc, &obj, ptr, sz);
6420 /* ------------------------------------------------------------------------ */
6421 /* Function: ipf_outobjsz */
6422 /* Returns: int - 0 = success, else failure */
6423 /* Parameters: data(I) - pointer to ioctl data */
6424 /* ptr(I) - pointer to store real data in */
6425 /* type(I) - type of structure being moved */
6426 /* sz(I) - size of data to copy */
6428 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6429 /* but it must not be smaller than the size defined for the type and the */
6430 /* type must allow for varied sized objects. The extra requirement here is */
6431 /* that sz must match the size of the object being passed in - this is not */
6432 /* not possible nor required in ipf_outobj(). */
6433 /* ------------------------------------------------------------------------ */
6435 ipf_outobjsz(softc, data, ptr, type, sz)
6436 ipf_main_softc_t *softc;
6444 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6449 error = BCOPYIN(data, &obj, sizeof(obj));
6455 if (obj.ipfo_type != type) {
6460 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6461 if (((ipf_objbytes[type][0] & 1) == 0) ||
6462 (sz < ipf_objbytes[type][1])) {
6466 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6472 #ifdef IPFILTER_COMPAT
6473 error = ipf_out_compat(softc, &obj, ptr);
6483 /* ------------------------------------------------------------------------ */
6484 /* Function: ipf_outobj */
6485 /* Returns: int - 0 = success, else failure */
6486 /* Parameters: data(I) - pointer to ioctl data */
6487 /* ptr(I) - pointer to store real data in */
6488 /* type(I) - type of structure being moved */
6490 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6491 /* future, we add things to check for version numbers, sizes, etc, to make */
6492 /* it backward compatible at the ABI for user land. */
6493 /* ------------------------------------------------------------------------ */
6495 ipf_outobj(softc, data, ptr, type)
6496 ipf_main_softc_t *softc;
6504 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6509 error = BCOPYIN(data, &obj, sizeof(obj));
6515 if (obj.ipfo_type != type) {
6520 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6521 if ((ipf_objbytes[type][0] & 1) != 0) {
6522 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6526 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6531 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6537 #ifdef IPFILTER_COMPAT
6538 error = ipf_out_compat(softc, &obj, ptr);
6548 /* ------------------------------------------------------------------------ */
6549 /* Function: ipf_outobjk */
6550 /* Returns: int - 0 = success, else failure */
6551 /* Parameters: obj(I) - pointer to data description structure */
6552 /* ptr(I) - pointer to kernel data to copy out */
6554 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6555 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6556 /* already populated with information and now we just need to use it. */
6557 /* There is no need for this function to have a "type" parameter as there */
6558 /* is no point in validating information that comes from the kernel with */
6560 /* ------------------------------------------------------------------------ */
6562 ipf_outobjk(softc, obj, ptr)
6563 ipf_main_softc_t *softc;
6567 int type = obj->ipfo_type;
6570 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6575 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6576 if ((ipf_objbytes[type][0] & 1) != 0) {
6577 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6582 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6587 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6593 #ifdef IPFILTER_COMPAT
6594 error = ipf_out_compat(softc, obj, ptr);
6604 /* ------------------------------------------------------------------------ */
6605 /* Function: ipf_checkl4sum */
6606 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6607 /* Parameters: fin(I) - pointer to packet information */
6609 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6610 /* not possible, return without indicating a failure or success but in a */
6611 /* way that is ditinguishable. This function should only be called by the */
6612 /* ipf_checkv6sum() for each platform. */
6613 /* ------------------------------------------------------------------------ */
6618 u_short sum, hdrsum, *csump;
6623 * If the TCP packet isn't a fragment, isn't too short and otherwise
6624 * isn't already considered "bad", then validate the checksum. If
6625 * this check fails then considered the packet to be "bad".
6627 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6638 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6644 if (udp->uh_sum != 0) {
6645 csump = &udp->uh_sum;
6651 case IPPROTO_ICMPV6 :
6652 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6658 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6671 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6673 #if !defined(_KERNEL)
6674 if (sum == hdrsum) {
6675 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6677 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6680 DT2(l4sums, u_short, hdrsum, u_short, sum);
6681 if (hdrsum == sum) {
6682 fin->fin_cksum = FI_CK_SUMOK;
6685 fin->fin_cksum = FI_CK_BAD;
6690 /* ------------------------------------------------------------------------ */
6691 /* Function: ipf_ifpfillv4addr */
6692 /* Returns: int - 0 = address update, -1 = address not updated */
6693 /* Parameters: atype(I) - type of network address update to perform */
6694 /* sin(I) - pointer to source of address information */
6695 /* mask(I) - pointer to source of netmask information */
6696 /* inp(I) - pointer to destination address store */
6697 /* inpmask(I) - pointer to destination netmask store */
6699 /* Given a type of network address update (atype) to perform, copy */
6700 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6701 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6702 /* which case the operation fails. For all values of atype other than */
6703 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6705 /* ------------------------------------------------------------------------ */
6707 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6709 struct sockaddr_in *sin, *mask;
6710 struct in_addr *inp, *inpmask;
6712 if (inpmask != NULL && atype != FRI_NETMASKED)
6713 inpmask->s_addr = 0xffffffff;
6715 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6716 if (atype == FRI_NETMASKED) {
6717 if (inpmask == NULL)
6719 inpmask->s_addr = mask->sin_addr.s_addr;
6721 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6723 inp->s_addr = sin->sin_addr.s_addr;
6730 /* ------------------------------------------------------------------------ */
6731 /* Function: ipf_ifpfillv6addr */
6732 /* Returns: int - 0 = address update, -1 = address not updated */
6733 /* Parameters: atype(I) - type of network address update to perform */
6734 /* sin(I) - pointer to source of address information */
6735 /* mask(I) - pointer to source of netmask information */
6736 /* inp(I) - pointer to destination address store */
6737 /* inpmask(I) - pointer to destination netmask store */
6739 /* Given a type of network address update (atype) to perform, copy */
6740 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6741 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6742 /* which case the operation fails. For all values of atype other than */
6743 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6745 /* ------------------------------------------------------------------------ */
6747 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6749 struct sockaddr_in6 *sin, *mask;
6750 i6addr_t *inp, *inpmask;
6752 i6addr_t *src, *and;
6754 src = (i6addr_t *)&sin->sin6_addr;
6755 and = (i6addr_t *)&mask->sin6_addr;
6757 if (inpmask != NULL && atype != FRI_NETMASKED) {
6758 inpmask->i6[0] = 0xffffffff;
6759 inpmask->i6[1] = 0xffffffff;
6760 inpmask->i6[2] = 0xffffffff;
6761 inpmask->i6[3] = 0xffffffff;
6764 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6765 if (atype == FRI_NETMASKED) {
6766 if (inpmask == NULL)
6768 inpmask->i6[0] = and->i6[0];
6769 inpmask->i6[1] = and->i6[1];
6770 inpmask->i6[2] = and->i6[2];
6771 inpmask->i6[3] = and->i6[3];
6774 inp->i6[0] = src->i6[0] & and->i6[0];
6775 inp->i6[1] = src->i6[1] & and->i6[1];
6776 inp->i6[2] = src->i6[2] & and->i6[2];
6777 inp->i6[3] = src->i6[3] & and->i6[3];
6779 inp->i6[0] = src->i6[0];
6780 inp->i6[1] = src->i6[1];
6781 inp->i6[2] = src->i6[2];
6782 inp->i6[3] = src->i6[3];
6789 /* ------------------------------------------------------------------------ */
6790 /* Function: ipf_matchtag */
6791 /* Returns: 0 == mismatch, 1 == match. */
6792 /* Parameters: tag1(I) - pointer to first tag to compare */
6793 /* tag2(I) - pointer to second tag to compare */
6795 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6796 /* considered to be a match or not match, respectively. The tag is 16 */
6797 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6798 /* compare the ints instead, for speed. tag1 is the master of the */
6799 /* comparison. This function should only be called with both tag1 and tag2 */
6800 /* as non-NULL pointers. */
6801 /* ------------------------------------------------------------------------ */
6803 ipf_matchtag(tag1, tag2)
6804 ipftag_t *tag1, *tag2;
6809 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6812 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6813 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6814 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6815 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6821 /* ------------------------------------------------------------------------ */
6822 /* Function: ipf_coalesce */
6823 /* Returns: 1 == success, -1 == failure, 0 == no change */
6824 /* Parameters: fin(I) - pointer to packet information */
6826 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6827 /* If this call returns a failure then the buffers have also been freed. */
6828 /* ------------------------------------------------------------------------ */
6834 if ((fin->fin_flx & FI_COALESCE) != 0)
6838 * If the mbuf pointers indicate that there is no mbuf to work with,
6839 * return but do not indicate success or failure.
6841 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6844 #if defined(_KERNEL)
6845 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6846 ipf_main_softc_t *softc = fin->fin_main_soft;
6848 DT1(frb_coalesce, fr_info_t *, fin);
6849 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6851 FREE_MB_T(*fin->fin_mp);
6853 fin->fin_reason = FRB_COALESCE;
6854 *fin->fin_mp = NULL;
6859 fin = fin; /* LINT */
6866 * The following table lists all of the tunable variables that can be
6867 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6868 * in the table below is as follows:
6870 * pointer to value, name of value, minimum, maximum, size of the value's
6871 * container, value attribute flags
6873 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6874 * means the value can only be written to when IPFilter is loaded but disabled.
6875 * The obvious implication is if neither of these are set then the value can be
6876 * changed at any time without harm.
6880 /* ------------------------------------------------------------------------ */
6881 /* Function: ipf_tune_findbycookie */
6882 /* Returns: NULL = search failed, else pointer to tune struct */
6883 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6884 /* next(O) - pointer to place to store the cookie for the */
6885 /* "next" tuneable, if it is desired. */
6887 /* This function is used to walk through all of the existing tunables with */
6888 /* successive calls. It searches the known tunables for the one which has */
6889 /* a matching value for "cookie" - ie its address. When returning a match, */
6890 /* the next one to be found may be returned inside next. */
6891 /* ------------------------------------------------------------------------ */
6892 static ipftuneable_t *
6893 ipf_tune_findbycookie(ptop, cookie, next)
6894 ipftuneable_t **ptop;
6895 void *cookie, **next;
6897 ipftuneable_t *ta, **tap;
6899 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6903 * If the next entry in the array has a name
6904 * present, then return a pointer to it for
6905 * where to go next, else return a pointer to
6906 * the dynaminc list as a key to search there
6907 * next. This facilitates a weak linking of
6908 * the two "lists" together.
6910 if ((ta + 1)->ipft_name != NULL)
6918 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6919 if (tap == cookie) {
6921 *next = &ta->ipft_next;
6931 /* ------------------------------------------------------------------------ */
6932 /* Function: ipf_tune_findbyname */
6933 /* Returns: NULL = search failed, else pointer to tune struct */
6934 /* Parameters: name(I) - name of the tuneable entry to find. */
6936 /* Search the static array of tuneables and the list of dynamic tuneables */
6937 /* for an entry with a matching name. If we can find one, return a pointer */
6938 /* to the matching structure. */
6939 /* ------------------------------------------------------------------------ */
6940 static ipftuneable_t *
6941 ipf_tune_findbyname(top, name)
6947 for (ta = top; ta != NULL; ta = ta->ipft_next)
6948 if (!strcmp(ta->ipft_name, name)) {
6956 /* ------------------------------------------------------------------------ */
6957 /* Function: ipf_tune_add_array */
6958 /* Returns: int - 0 == success, else failure */
6959 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6961 /* Appends tune structures from the array passed in (newtune) to the end of */
6962 /* the current list of "dynamic" tuneable parameters. */
6963 /* If any entry to be added is already present (by name) then the operation */
6964 /* is aborted - entries that have been added are removed before returning. */
6965 /* An entry with no name (NULL) is used as the indication that the end of */
6966 /* the array has been reached. */
6967 /* ------------------------------------------------------------------------ */
6969 ipf_tune_add_array(softc, newtune)
6970 ipf_main_softc_t *softc;
6971 ipftuneable_t *newtune;
6973 ipftuneable_t *nt, *dt;
6976 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6977 error = ipf_tune_add(softc, nt);
6979 for (dt = newtune; dt != nt; dt++) {
6980 (void) ipf_tune_del(softc, dt);
6989 /* ------------------------------------------------------------------------ */
6990 /* Function: ipf_tune_array_link */
6991 /* Returns: 0 == success, -1 == failure */
6992 /* Parameters: softc(I) - soft context pointerto work with */
6993 /* array(I) - pointer to an array of tuneables */
6995 /* Given an array of tunables (array), append them to the current list of */
6996 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
6997 /* the array for being appended to the list, initialise all of the next */
6998 /* pointers so we don't need to walk parts of it with ++ and others with */
6999 /* next. The array is expected to have an entry with a NULL name as the */
7000 /* terminator. Trying to add an array with no non-NULL names will return as */
7002 /* ------------------------------------------------------------------------ */
7004 ipf_tune_array_link(softc, array)
7005 ipf_main_softc_t *softc;
7006 ipftuneable_t *array;
7008 ipftuneable_t *t, **p;
7011 if (t->ipft_name == NULL)
7014 for (; t[1].ipft_name != NULL; t++)
7015 t[0].ipft_next = &t[1];
7016 t->ipft_next = NULL;
7019 * Since a pointer to the last entry isn't kept, we need to find it
7020 * each time we want to add new variables to the list.
7022 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7023 if (t->ipft_name == NULL)
7031 /* ------------------------------------------------------------------------ */
7032 /* Function: ipf_tune_array_unlink */
7033 /* Returns: 0 == success, -1 == failure */
7034 /* Parameters: softc(I) - soft context pointerto work with */
7035 /* array(I) - pointer to an array of tuneables */
7037 /* ------------------------------------------------------------------------ */
7039 ipf_tune_array_unlink(softc, array)
7040 ipf_main_softc_t *softc;
7041 ipftuneable_t *array;
7043 ipftuneable_t *t, **p;
7045 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7051 for (; t[1].ipft_name != NULL; t++)
7060 /* ------------------------------------------------------------------------ */
7061 /* Function: ipf_tune_array_copy */
7062 /* Returns: NULL = failure, else pointer to new array */
7063 /* Parameters: base(I) - pointer to structure base */
7064 /* size(I) - size of the array at template */
7065 /* template(I) - original array to copy */
7067 /* Allocate memory for a new set of tuneable values and copy everything */
7068 /* from template into the new region of memory. The new region is full of */
7069 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7071 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7072 /* In the array template, ipftp_offset is the offset (in bytes) of the */
7073 /* location of the tuneable value inside the structure pointed to by base. */
7074 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
7075 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7076 /* ipftp_void that points to the stored value. */
7077 /* ------------------------------------------------------------------------ */
7079 ipf_tune_array_copy(base, size, template)
7082 ipftuneable_t *template;
7084 ipftuneable_t *copy;
7088 KMALLOCS(copy, ipftuneable_t *, size);
7092 bcopy(template, copy, size);
7094 for (i = 0; copy[i].ipft_name; i++) {
7095 copy[i].ipft_una.ipftp_offset += (u_long)base;
7096 copy[i].ipft_next = copy + i + 1;
7103 /* ------------------------------------------------------------------------ */
7104 /* Function: ipf_tune_add */
7105 /* Returns: int - 0 == success, else failure */
7106 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7108 /* Appends tune structures from the array passed in (newtune) to the end of */
7109 /* the current list of "dynamic" tuneable parameters. Once added, the */
7110 /* owner of the object is not expected to ever change "ipft_next". */
7111 /* ------------------------------------------------------------------------ */
7113 ipf_tune_add(softc, newtune)
7114 ipf_main_softc_t *softc;
7115 ipftuneable_t *newtune;
7117 ipftuneable_t *ta, **tap;
7119 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7125 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7128 newtune->ipft_next = NULL;
7134 /* ------------------------------------------------------------------------ */
7135 /* Function: ipf_tune_del */
7136 /* Returns: int - 0 == success, else failure */
7137 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7138 /* current dynamic tuneables */
7140 /* Search for the tune structure, by pointer, in the list of those that are */
7141 /* dynamically added at run time. If found, adjust the list so that this */
7142 /* structure is no longer part of it. */
7143 /* ------------------------------------------------------------------------ */
7145 ipf_tune_del(softc, oldtune)
7146 ipf_main_softc_t *softc;
7147 ipftuneable_t *oldtune;
7149 ipftuneable_t *ta, **tap;
7152 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7153 tap = &ta->ipft_next) {
7154 if (ta == oldtune) {
7155 *tap = oldtune->ipft_next;
7156 oldtune->ipft_next = NULL;
7169 /* ------------------------------------------------------------------------ */
7170 /* Function: ipf_tune_del_array */
7171 /* Returns: int - 0 == success, else failure */
7172 /* Parameters: oldtune - pointer to tuneables array */
7174 /* Remove each tuneable entry in the array from the list of "dynamic" */
7175 /* tunables. If one entry should fail to be found, an error will be */
7176 /* returned and no further ones removed. */
7177 /* An entry with a NULL name is used as the indicator of the last entry in */
7179 /* ------------------------------------------------------------------------ */
7181 ipf_tune_del_array(softc, oldtune)
7182 ipf_main_softc_t *softc;
7183 ipftuneable_t *oldtune;
7188 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7189 error = ipf_tune_del(softc, ot);
7199 /* ------------------------------------------------------------------------ */
7200 /* Function: ipf_tune */
7201 /* Returns: int - 0 == success, else failure */
7202 /* Parameters: cmd(I) - ioctl command number */
7203 /* data(I) - pointer to ioctl data structure */
7205 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7206 /* three ioctls provide the means to access and control global variables */
7207 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7208 /* changed without rebooting, reloading or recompiling. The initialisation */
7209 /* and 'destruction' routines of the various components of ipfilter are all */
7210 /* each responsible for handling their own values being too big. */
7211 /* ------------------------------------------------------------------------ */
7213 ipf_ipftune(softc, cmd, data)
7214 ipf_main_softc_t *softc;
7223 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7227 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7228 cookie = tu.ipft_cookie;
7233 case SIOCIPFGETNEXT :
7235 * If cookie is non-NULL, assume it to be a pointer to the last
7236 * entry we looked at, so find it (if possible) and return a
7237 * pointer to the next one after it. The last entry in the
7238 * the table is a NULL entry, so when we get to it, set cookie
7239 * to NULL and return that, indicating end of list, erstwhile
7240 * if we come in with cookie set to NULL, we are starting anew
7241 * at the front of the list.
7243 if (cookie != NULL) {
7244 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7245 cookie, &tu.ipft_cookie);
7247 ta = softc->ipf_tuners;
7248 tu.ipft_cookie = ta + 1;
7252 * Entry found, but does the data pointed to by that
7253 * row fit in what we can return?
7255 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7261 if (ta->ipft_sz == sizeof(u_long))
7262 tu.ipft_vlong = *ta->ipft_plong;
7263 else if (ta->ipft_sz == sizeof(u_int))
7264 tu.ipft_vint = *ta->ipft_pint;
7265 else if (ta->ipft_sz == sizeof(u_short))
7266 tu.ipft_vshort = *ta->ipft_pshort;
7267 else if (ta->ipft_sz == sizeof(u_char))
7268 tu.ipft_vchar = *ta->ipft_pchar;
7270 tu.ipft_sz = ta->ipft_sz;
7271 tu.ipft_min = ta->ipft_min;
7272 tu.ipft_max = ta->ipft_max;
7273 tu.ipft_flags = ta->ipft_flags;
7274 bcopy(ta->ipft_name, tu.ipft_name,
7275 MIN(sizeof(tu.ipft_name),
7276 strlen(ta->ipft_name) + 1));
7278 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7284 * Search by name or by cookie value for a particular entry
7285 * in the tuning paramter table.
7289 if (cookie != NULL) {
7290 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7294 } else if (tu.ipft_name[0] != '\0') {
7295 ta = ipf_tune_findbyname(softc->ipf_tuners,
7303 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7305 * Fetch the tuning parameters for a particular value
7308 if (ta->ipft_sz == sizeof(u_long))
7309 tu.ipft_vlong = *ta->ipft_plong;
7310 else if (ta->ipft_sz == sizeof(u_int))
7311 tu.ipft_vint = *ta->ipft_pint;
7312 else if (ta->ipft_sz == sizeof(u_short))
7313 tu.ipft_vshort = *ta->ipft_pshort;
7314 else if (ta->ipft_sz == sizeof(u_char))
7315 tu.ipft_vchar = *ta->ipft_pchar;
7316 tu.ipft_cookie = ta;
7317 tu.ipft_sz = ta->ipft_sz;
7318 tu.ipft_min = ta->ipft_min;
7319 tu.ipft_max = ta->ipft_max;
7320 tu.ipft_flags = ta->ipft_flags;
7321 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7323 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7325 * Set an internal parameter. The hard part here is
7326 * getting the new value safely and correctly out of
7327 * the kernel (given we only know its size, not type.)
7331 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7332 (softc->ipf_running > 0)) {
7339 if (in < ta->ipft_min || in > ta->ipft_max) {
7345 if (ta->ipft_func != NULL) {
7349 error = (*ta->ipft_func)(softc, ta,
7353 } else if (ta->ipft_sz == sizeof(u_long)) {
7354 tu.ipft_vlong = *ta->ipft_plong;
7355 *ta->ipft_plong = in;
7357 } else if (ta->ipft_sz == sizeof(u_int)) {
7358 tu.ipft_vint = *ta->ipft_pint;
7359 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7361 } else if (ta->ipft_sz == sizeof(u_short)) {
7362 tu.ipft_vshort = *ta->ipft_pshort;
7363 *ta->ipft_pshort = (u_short)(in & 0xffff);
7365 } else if (ta->ipft_sz == sizeof(u_char)) {
7366 tu.ipft_vchar = *ta->ipft_pchar;
7367 *ta->ipft_pchar = (u_char)(in & 0xff);
7369 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7383 /* ------------------------------------------------------------------------ */
7384 /* Function: ipf_zerostats */
7385 /* Returns: int - 0 = success, else failure */
7386 /* Parameters: data(O) - pointer to pointer for copying data back to */
7388 /* Copies the current statistics out to userspace and then zero's the */
7389 /* current ones in the kernel. The lock is only held across the bzero() as */
7390 /* the copyout may result in paging (ie network activity.) */
7391 /* ------------------------------------------------------------------------ */
7393 ipf_zerostats(softc, data)
7394 ipf_main_softc_t *softc;
7401 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7404 ipf_getstat(softc, &fio, obj.ipfo_rev);
7405 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7409 WRITE_ENTER(&softc->ipf_mutex);
7410 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7411 RWLOCK_EXIT(&softc->ipf_mutex);
7417 /* ------------------------------------------------------------------------ */
7418 /* Function: ipf_resolvedest */
7420 /* Parameters: softc(I) - pointer to soft context main structure */
7421 /* base(I) - where strings are stored */
7422 /* fdp(IO) - pointer to destination information to resolve */
7423 /* v(I) - IP protocol version to match */
7425 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7426 /* if a matching name can be found for the particular IP protocol version */
7427 /* then store the interface pointer in the frdest struct. If no match is */
7428 /* found, then set the interface pointer to be -1 as NULL is considered to */
7429 /* indicate there is no information at all in the structure. */
7430 /* ------------------------------------------------------------------------ */
7432 ipf_resolvedest(softc, base, fdp, v)
7433 ipf_main_softc_t *softc;
7443 if (fdp->fd_name != -1) {
7444 if (fdp->fd_type == FRD_DSTLIST) {
7445 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7447 base + fdp->fd_name,
7454 ifp = GETIFP(base + fdp->fd_name, v);
7461 if ((ifp != NULL) && (ifp != (void *)-1)) {
7462 fdp->fd_local = ipf_deliverlocal(softc, v, ifp, &fdp->fd_ip6);
7469 /* ------------------------------------------------------------------------ */
7470 /* Function: ipf_resolvenic */
7471 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7472 /* pointer to interface structure for NIC */
7473 /* Parameters: softc(I)- pointer to soft context main structure */
7474 /* name(I) - complete interface name */
7475 /* v(I) - IP protocol version */
7477 /* Look for a network interface structure that firstly has a matching name */
7478 /* to that passed in and that is also being used for that IP protocol */
7479 /* version (necessary on some platforms where there are separate listings */
7480 /* for both IPv4 and IPv6 on the same physical NIC. */
7481 /* ------------------------------------------------------------------------ */
7483 ipf_resolvenic(softc, name, v)
7484 ipf_main_softc_t *softc;
7490 softc = softc; /* gcc -Wextra */
7491 if (name[0] == '\0')
7494 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7498 nic = GETIFP(name, v);
7505 /* ------------------------------------------------------------------------ */
7506 /* Function: ipf_token_expire */
7507 /* Returns: None. */
7508 /* Parameters: softc(I) - pointer to soft context main structure */
7510 /* This function is run every ipf tick to see if there are any tokens that */
7511 /* have been held for too long and need to be freed up. */
7512 /* ------------------------------------------------------------------------ */
7514 ipf_token_expire(softc)
7515 ipf_main_softc_t *softc;
7519 WRITE_ENTER(&softc->ipf_tokens);
7520 while ((it = softc->ipf_token_head) != NULL) {
7521 if (it->ipt_die > softc->ipf_ticks)
7524 ipf_token_deref(softc, it);
7526 RWLOCK_EXIT(&softc->ipf_tokens);
7530 /* ------------------------------------------------------------------------ */
7531 /* Function: ipf_token_flush */
7532 /* Returns: None. */
7533 /* Parameters: softc(I) - pointer to soft context main structure */
7535 /* Loop through all of the existing tokens and call deref to see if they */
7536 /* can be freed. Normally a function like this might just loop on */
7537 /* ipf_token_head but there is a chance that a token might have a ref count */
7538 /* of greater than one and in that case the the reference would drop twice */
7539 /* by code that is only entitled to drop it once. */
7540 /* ------------------------------------------------------------------------ */
7542 ipf_token_flush(softc)
7543 ipf_main_softc_t *softc;
7545 ipftoken_t *it, *next;
7547 WRITE_ENTER(&softc->ipf_tokens);
7548 for (it = softc->ipf_token_head; it != NULL; it = next) {
7549 next = it->ipt_next;
7550 (void) ipf_token_deref(softc, it);
7552 RWLOCK_EXIT(&softc->ipf_tokens);
7556 /* ------------------------------------------------------------------------ */
7557 /* Function: ipf_token_del */
7558 /* Returns: int - 0 = success, else error */
7559 /* Parameters: softc(I)- pointer to soft context main structure */
7560 /* type(I) - the token type to match */
7561 /* uid(I) - uid owning the token */
7562 /* ptr(I) - context pointer for the token */
7564 /* This function looks for a a token in the current list that matches up */
7565 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7566 /* call ipf_token_dewref() to remove it from the list. In the event that */
7567 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7568 /* enables debugging to distinguish between the two paths that ultimately */
7569 /* lead to a token to be deleted. */
7570 /* ------------------------------------------------------------------------ */
7572 ipf_token_del(softc, type, uid, ptr)
7573 ipf_main_softc_t *softc;
7583 WRITE_ENTER(&softc->ipf_tokens);
7584 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7585 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7586 uid == it->ipt_uid) {
7587 it->ipt_complete = 2;
7588 ipf_token_deref(softc, it);
7593 RWLOCK_EXIT(&softc->ipf_tokens);
7599 /* ------------------------------------------------------------------------ */
7600 /* Function: ipf_token_mark_complete */
7601 /* Returns: None. */
7602 /* Parameters: token(I) - pointer to token structure */
7604 /* Mark a token as being ineligable for being found with ipf_token_find. */
7605 /* ------------------------------------------------------------------------ */
7607 ipf_token_mark_complete(token)
7610 if (token->ipt_complete == 0)
7611 token->ipt_complete = 1;
7615 /* ------------------------------------------------------------------------ */
7616 /* Function: ipf_token_find */
7617 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7618 /* Parameters: softc(I)- pointer to soft context main structure */
7619 /* type(I) - the token type to match */
7620 /* uid(I) - uid owning the token */
7621 /* ptr(I) - context pointer for the token */
7623 /* This function looks for a live token in the list of current tokens that */
7624 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7625 /* allocated. If one is found then it is moved to the top of the list of */
7626 /* currently active tokens. */
7627 /* ------------------------------------------------------------------------ */
7629 ipf_token_find(softc, type, uid, ptr)
7630 ipf_main_softc_t *softc;
7634 ipftoken_t *it, *new;
7636 KMALLOC(new, ipftoken_t *);
7638 bzero((char *)new, sizeof(*new));
7640 WRITE_ENTER(&softc->ipf_tokens);
7641 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7642 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7643 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7651 RWLOCK_EXIT(&softc->ipf_tokens);
7656 it->ipt_type = type;
7664 if (it->ipt_complete > 0)
7667 ipf_token_unlink(softc, it);
7671 it->ipt_pnext = softc->ipf_token_tail;
7672 *softc->ipf_token_tail = it;
7673 softc->ipf_token_tail = &it->ipt_next;
7674 it->ipt_next = NULL;
7677 it->ipt_die = softc->ipf_ticks + 20;
7680 RWLOCK_EXIT(&softc->ipf_tokens);
7686 /* ------------------------------------------------------------------------ */
7687 /* Function: ipf_token_unlink */
7688 /* Returns: None. */
7689 /* Parameters: softc(I) - pointer to soft context main structure */
7690 /* token(I) - pointer to token structure */
7691 /* Write Locks: ipf_tokens */
7693 /* This function unlinks a token structure from the linked list of tokens */
7694 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7695 /* but the tail does due to the linked list implementation. */
7696 /* ------------------------------------------------------------------------ */
7698 ipf_token_unlink(softc, token)
7699 ipf_main_softc_t *softc;
7703 if (softc->ipf_token_tail == &token->ipt_next)
7704 softc->ipf_token_tail = token->ipt_pnext;
7706 *token->ipt_pnext = token->ipt_next;
7707 if (token->ipt_next != NULL)
7708 token->ipt_next->ipt_pnext = token->ipt_pnext;
7709 token->ipt_next = NULL;
7710 token->ipt_pnext = NULL;
7714 /* ------------------------------------------------------------------------ */
7715 /* Function: ipf_token_deref */
7716 /* Returns: int - 0 == token freed, else reference count */
7717 /* Parameters: softc(I) - pointer to soft context main structure */
7718 /* token(I) - pointer to token structure */
7719 /* Write Locks: ipf_tokens */
7721 /* Drop the reference count on the token structure and if it drops to zero, */
7722 /* call the dereference function for the token type because it is then */
7723 /* possible to free the token data structure. */
7724 /* ------------------------------------------------------------------------ */
7726 ipf_token_deref(softc, token)
7727 ipf_main_softc_t *softc;
7730 void *data, **datap;
7732 ASSERT(token->ipt_ref > 0);
7734 if (token->ipt_ref > 0)
7735 return token->ipt_ref;
7737 data = token->ipt_data;
7740 if ((data != NULL) && (data != (void *)-1)) {
7741 switch (token->ipt_type)
7743 case IPFGENITER_IPF :
7744 (void) ipf_derefrule(softc, (frentry_t **)datap);
7746 case IPFGENITER_IPNAT :
7747 WRITE_ENTER(&softc->ipf_nat);
7748 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7749 RWLOCK_EXIT(&softc->ipf_nat);
7751 case IPFGENITER_NAT :
7752 ipf_nat_deref(softc, (nat_t **)datap);
7754 case IPFGENITER_STATE :
7755 ipf_state_deref(softc, (ipstate_t **)datap);
7757 case IPFGENITER_FRAG :
7758 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7760 case IPFGENITER_NATFRAG :
7761 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7763 case IPFGENITER_HOSTMAP :
7764 WRITE_ENTER(&softc->ipf_nat);
7765 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7766 RWLOCK_EXIT(&softc->ipf_nat);
7769 ipf_lookup_iterderef(softc, token->ipt_type, data);
7774 ipf_token_unlink(softc, token);
7780 /* ------------------------------------------------------------------------ */
7781 /* Function: ipf_nextrule */
7782 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7783 /* Parameters: softc(I) - pointer to soft context main structure */
7784 /* fr(I) - pointer to filter rule */
7785 /* out(I) - 1 == out rules, 0 == input rules */
7787 /* Starting with "fr", find the next rule to visit. This includes visiting */
7788 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7789 /* last rule in the list. When walking rule lists, it is either input or */
7790 /* output rules that are returned, never both. */
7791 /* ------------------------------------------------------------------------ */
7793 ipf_nextrule(softc, active, unit, fr, out)
7794 ipf_main_softc_t *softc;
7802 if (fr != NULL && fr->fr_group != -1) {
7803 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7804 unit, active, NULL);
7808 fg = softc->ipf_groups[unit][active];
7811 while (fg != NULL) {
7812 next = fg->fg_start;
7813 while (next != NULL) {
7815 if (next->fr_flags & FR_OUTQUE)
7817 } else if (next->fr_flags & FR_INQUE) {
7820 next = next->fr_next;
7829 /* ------------------------------------------------------------------------ */
7830 /* Function: ipf_getnextrule */
7831 /* Returns: int - 0 = success, else error */
7832 /* Parameters: softc(I)- pointer to soft context main structure */
7833 /* t(I) - pointer to destination information to resolve */
7834 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7836 /* This function's first job is to bring in the ipfruleiter_t structure via */
7837 /* the ipfobj_t structure to determine what should be the next rule to */
7838 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7839 /* find the 'next rule'. This may include searching rule group lists or */
7840 /* just be as simple as looking at the 'next' field in the rule structure. */
7841 /* When we have found the rule to return, increase its reference count and */
7842 /* if we used an existing rule to get here, decrease its reference count. */
7843 /* ------------------------------------------------------------------------ */
7845 ipf_getnextrule(softc, t, ptr)
7846 ipf_main_softc_t *softc;
7850 frentry_t *fr, *next, zero;
7859 if (t == NULL || ptr == NULL) {
7864 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7868 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7872 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7876 if (it.iri_nrules == 0) {
7880 if (it.iri_rule == NULL) {
7887 if ((it.iri_inout & F_OUT) != 0)
7891 if ((it.iri_inout & F_ACIN) != 0)
7892 unit = IPL_LOGCOUNT;
7896 READ_ENTER(&softc->ipf_mutex);
7898 if (*it.iri_group == '\0') {
7899 if (unit == IPL_LOGCOUNT) {
7900 next = softc->ipf_acct[out][it.iri_active];
7902 next = softc->ipf_rules[out][it.iri_active];
7905 next = ipf_nextrule(softc, it.iri_active,
7908 fg = ipf_findgroup(softc, it.iri_group, unit,
7909 it.iri_active, NULL);
7911 next = fg->fg_start;
7918 next = ipf_nextrule(softc, it.iri_active, unit,
7922 if (next != NULL && next->fr_next != NULL)
7924 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7930 (void) ipf_derefrule(softc, &fr);
7932 obj.ipfo_type = IPFOBJ_FRENTRY;
7933 dst = (char *)it.iri_rule;
7936 obj.ipfo_size = next->fr_size;
7937 MUTEX_ENTER(&next->fr_lock);
7939 MUTEX_EXIT(&next->fr_lock);
7942 obj.ipfo_size = sizeof(frentry_t);
7943 bzero(&zero, sizeof(zero));
7947 it.iri_rule = predict ? next : NULL;
7949 ipf_token_mark_complete(t);
7951 RWLOCK_EXIT(&softc->ipf_mutex);
7954 error = ipf_outobjk(softc, &obj, next);
7955 if (error == 0 && t->ipt_data != NULL) {
7956 dst += obj.ipfo_size;
7957 if (next->fr_data != NULL) {
7960 if (next->fr_type == FR_T_IPFEXPR)
7961 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7963 dobj.ipfo_type = IPFOBJ_FRIPF;
7964 dobj.ipfo_size = next->fr_dsize;
7965 dobj.ipfo_rev = obj.ipfo_rev;
7966 dobj.ipfo_ptr = dst;
7967 error = ipf_outobjk(softc, &dobj, next->fr_data);
7971 if ((fr != NULL) && (next == &zero))
7972 (void) ipf_derefrule(softc, &fr);
7978 /* ------------------------------------------------------------------------ */
7979 /* Function: ipf_frruleiter */
7980 /* Returns: int - 0 = success, else error */
7981 /* Parameters: softc(I)- pointer to soft context main structure */
7982 /* data(I) - the token type to match */
7983 /* uid(I) - uid owning the token */
7984 /* ptr(I) - context pointer for the token */
7986 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
7987 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
7988 /* the process doing the ioctl and use that to ask for the next rule. */
7989 /* ------------------------------------------------------------------------ */
7991 ipf_frruleiter(softc, data, uid, ctx)
7992 ipf_main_softc_t *softc;
8001 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8002 if (token != NULL) {
8003 error = ipf_getnextrule(softc, token, data);
8004 WRITE_ENTER(&softc->ipf_tokens);
8005 ipf_token_deref(softc, token);
8006 RWLOCK_EXIT(&softc->ipf_tokens);
8008 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8012 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8019 /* ------------------------------------------------------------------------ */
8020 /* Function: ipf_geniter */
8021 /* Returns: int - 0 = success, else error */
8022 /* Parameters: softc(I) - pointer to soft context main structure */
8023 /* token(I) - pointer to ipftoken_t structure */
8024 /* itp(I) - pointer to iterator data */
8026 /* Decide which iterator function to call using information passed through */
8027 /* the ipfgeniter_t structure at itp. */
8028 /* ------------------------------------------------------------------------ */
8030 ipf_geniter(softc, token, itp)
8031 ipf_main_softc_t *softc;
8037 switch (itp->igi_type)
8039 case IPFGENITER_FRAG :
8040 error = ipf_frag_pkt_next(softc, token, itp);
8052 /* ------------------------------------------------------------------------ */
8053 /* Function: ipf_genericiter */
8054 /* Returns: int - 0 = success, else error */
8055 /* Parameters: softc(I)- pointer to soft context main structure */
8056 /* data(I) - the token type to match */
8057 /* uid(I) - uid owning the token */
8058 /* ptr(I) - context pointer for the token */
8060 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8061 /* ------------------------------------------------------------------------ */
8063 ipf_genericiter(softc, data, uid, ctx)
8064 ipf_main_softc_t *softc;
8072 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8076 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8077 if (token != NULL) {
8078 token->ipt_subtype = iter.igi_type;
8079 error = ipf_geniter(softc, token, &iter);
8080 WRITE_ENTER(&softc->ipf_tokens);
8081 ipf_token_deref(softc, token);
8082 RWLOCK_EXIT(&softc->ipf_tokens);
8092 /* ------------------------------------------------------------------------ */
8093 /* Function: ipf_ipf_ioctl */
8094 /* Returns: int - 0 = success, else error */
8095 /* Parameters: softc(I)- pointer to soft context main structure */
8096 /* data(I) - the token type to match */
8097 /* cmd(I) - the ioctl command number */
8098 /* mode(I) - mode flags for the ioctl */
8099 /* uid(I) - uid owning the token */
8100 /* ptr(I) - context pointer for the token */
8102 /* This function handles all of the ioctl command that are actually isssued */
8103 /* to the /dev/ipl device. */
8104 /* ------------------------------------------------------------------------ */
8106 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8107 ipf_main_softc_t *softc;
8121 if (!(mode & FWRITE)) {
8125 error = BCOPYIN(data, &tmp, sizeof(tmp));
8132 WRITE_ENTER(&softc->ipf_global);
8134 if (softc->ipf_running > 0)
8137 error = ipfattach(softc);
8139 softc->ipf_running = 1;
8141 (void) ipfdetach(softc);
8143 if (softc->ipf_running == 1)
8144 error = ipfdetach(softc);
8148 softc->ipf_running = -1;
8150 RWLOCK_EXIT(&softc->ipf_global);
8155 if (!(mode & FWRITE)) {
8161 case SIOCIPFGETNEXT :
8163 error = ipf_ipftune(softc, cmd, (void *)data);
8167 if (!(mode & FWRITE)) {
8171 error = BCOPYIN(data, &softc->ipf_flags,
8172 sizeof(softc->ipf_flags));
8181 error = BCOPYOUT(&softc->ipf_flags, data,
8182 sizeof(softc->ipf_flags));
8190 error = ipf_resolvefunc(softc, (void *)data);
8197 if (!(mode & FWRITE)) {
8201 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8202 softc->ipf_active, 1);
8209 if (!(mode & FWRITE)) {
8213 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8214 1 - softc->ipf_active, 1);
8219 if (!(mode & FWRITE)) {
8223 WRITE_ENTER(&softc->ipf_mutex);
8224 error = BCOPYOUT(&softc->ipf_active, data,
8225 sizeof(softc->ipf_active));
8230 softc->ipf_active = 1 - softc->ipf_active;
8232 RWLOCK_EXIT(&softc->ipf_mutex);
8237 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8241 ipf_getstat(softc, &fio, obj.ipfo_rev);
8242 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8246 if (!(mode & FWRITE)) {
8250 error = ipf_zerostats(softc, (caddr_t)data);
8254 if (!(mode & FWRITE)) {
8258 error = BCOPYIN(data, &tmp, sizeof(tmp));
8260 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8261 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8275 if (!(mode & FWRITE)) {
8279 error = BCOPYIN(data, &tmp, sizeof(tmp));
8281 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8282 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8296 if (!(mode & FWRITE)) {
8300 error = BCOPYIN(data, &tmp, sizeof(tmp));
8302 ipf_state_setlock(softc->ipf_state_soft, tmp);
8303 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8304 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8305 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8315 if (!(mode & FWRITE)) {
8319 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8320 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8327 #endif /* IPFILTER_LOG */
8330 if (!(mode & FWRITE)) {
8334 WRITE_ENTER(&softc->ipf_global);
8335 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8338 ipf_sync(softc, NULL);
8341 RWLOCK_EXIT(&softc->ipf_global);
8347 error = ipf_outobj(softc, (void *)data,
8348 ipf_frag_stats(softc->ipf_frag_soft),
8354 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8355 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8361 error = ipf_frruleiter(softc, data, uid, ctx);
8367 error = ipf_genericiter(softc, data, uid, ctx);
8371 case SIOCIPFDELTOK :
8372 error = BCOPYIN(data, &tmp, sizeof(tmp));
8375 error = ipf_token_del(softc, tmp, uid, ctx);
8390 /* ------------------------------------------------------------------------ */
8391 /* Function: ipf_decaps */
8392 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8393 /* flags indicating packet filtering decision. */
8394 /* Parameters: fin(I) - pointer to packet information */
8395 /* pass(I) - IP protocol version to match */
8396 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8398 /* This function is called for packets that are wrapt up in other packets, */
8399 /* for example, an IP packet that is the entire data segment for another IP */
8400 /* packet. If the basic constraints for this are satisfied, change the */
8401 /* buffer to point to the start of the inner packet and start processing */
8402 /* rules belonging to the head group this rule specifies. */
8403 /* ------------------------------------------------------------------------ */
8405 ipf_decaps(fin, pass, l5proto)
8410 fr_info_t fin2, *fino = NULL;
8416 if ((fin->fin_flx & FI_COALESCE) == 0)
8417 if (ipf_coalesce(fin) == -1)
8421 hlen = fin->fin_hlen;
8427 * In this case, the specific protocol being decapsulated
8428 * inside UDP frames comes from the rule.
8430 nh = fin->fin_fr->fr_icode;
8433 case IPPROTO_GRE : /* 47 */
8434 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8435 hlen += sizeof(grehdr_t);
8436 if (gre.gr_R|gre.gr_s)
8448 * If the routing options flag is set, validate that it is
8449 * there and bounce over it.
8452 /* This is really heavy weight and lots of room for error, */
8453 /* so for now, put it off and get the simple stuff right. */
8455 u_char off, len, *s;
8462 aplen = fin->fin_plen - hlen;
8464 af = (s[0] << 8) | s[1];
8469 if (af == 0 && len == 0) {
8480 hlen = s - (u_char *)fin->fin_dp;
8486 case IPPROTO_IPIP : /* 4 */
8491 default : /* Includes ESP, AH is special for IPv4 */
8504 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8508 #if defined(MENTAT) && defined(_KERNEL)
8514 fin->fin_plen -= elen;
8516 ip = (ip_t *)((char *)fin->fin_ip + elen);
8519 * Make sure we have at least enough data for the network layer
8523 hlen = IP_HL(ip) << 2;
8525 else if (IP_V(ip) == 6)
8526 hlen = sizeof(ip6_t);
8531 if (fin->fin_plen < hlen)
8534 fin->fin_dp = (char *)ip + hlen;
8536 if (IP_V(ip) == 4) {
8538 * Perform IPv4 header checksum validation.
8540 if (ipf_cksum((u_short *)ip, hlen))
8544 if (ipf_makefrip(hlen, ip, fin) == -1) {
8547 #if defined(MENTAT) && defined(_KERNEL)
8555 DT1(frb_decapfrip, fr_info_t *, fin);
8556 pass &= ~FR_CMDMASK;
8557 pass |= FR_BLOCK|FR_QUICK;
8558 fin->fin_reason = FRB_DECAPFRIP;
8562 pass = ipf_scanlist(fin, pass);
8565 * Copy the packet filter "result" fields out of the fr_info_t struct
8566 * that is local to the decapsulation processing and back into the
8567 * one we were called with.
8569 fino->fin_flx = fin->fin_flx;
8570 fino->fin_rev = fin->fin_rev;
8571 fino->fin_icode = fin->fin_icode;
8572 fino->fin_rule = fin->fin_rule;
8573 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8574 fino->fin_fr = fin->fin_fr;
8575 fino->fin_error = fin->fin_error;
8576 fino->fin_mp = fin->fin_mp;
8577 fino->fin_m = fin->fin_m;
8580 #if defined(MENTAT) && defined(_KERNEL)
8591 /* ------------------------------------------------------------------------ */
8592 /* Function: ipf_matcharray_load */
8593 /* Returns: int - 0 = success, else error */
8594 /* Parameters: softc(I) - pointer to soft context main structure */
8595 /* data(I) - pointer to ioctl data */
8596 /* objp(I) - ipfobj_t structure to load data into */
8597 /* arrayptr(I) - pointer to location to store array pointer */
8599 /* This function loads in a mathing array through the ipfobj_t struct that */
8600 /* describes it. Sanity checking and array size limitations are enforced */
8601 /* in this function to prevent userspace from trying to load in something */
8602 /* that is insanely big. Once the size of the array is known, the memory */
8603 /* required is malloc'd and returned through changing *arrayptr. The */
8604 /* contents of the array are verified before returning. Only in the event */
8605 /* of a successful call is the caller required to free up the malloc area. */
8606 /* ------------------------------------------------------------------------ */
8608 ipf_matcharray_load(softc, data, objp, arrayptr)
8609 ipf_main_softc_t *softc;
8614 int arraysize, *array, error;
8618 error = BCOPYIN(data, objp, sizeof(*objp));
8624 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8629 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8630 (objp->ipfo_size > 1024)) {
8635 arraysize = objp->ipfo_size * sizeof(*array);
8636 KMALLOCS(array, int *, arraysize);
8637 if (array == NULL) {
8642 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8644 KFREES(array, arraysize);
8649 if (ipf_matcharray_verify(array, arraysize) != 0) {
8650 KFREES(array, arraysize);
8660 /* ------------------------------------------------------------------------ */
8661 /* Function: ipf_matcharray_verify */
8663 /* Parameters: array(I) - pointer to matching array */
8664 /* arraysize(I) - number of elements in the array */
8666 /* Verify the contents of a matching array by stepping through each element */
8667 /* in it. The actual commands in the array are not verified for */
8668 /* correctness, only that all of the sizes are correctly within limits. */
8669 /* ------------------------------------------------------------------------ */
8671 ipf_matcharray_verify(array, arraysize)
8672 int *array, arraysize;
8674 int i, nelem, maxidx;
8677 nelem = arraysize / sizeof(*array);
8680 * Currently, it makes no sense to have an array less than 6
8681 * elements long - the initial size at the from, a single operation
8682 * (minimum 4 in length) and a trailer, for a total of 6.
8684 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8689 * Verify the size of data pointed to by array with how long
8690 * the array claims to be itself.
8692 if (array[0] * sizeof(*array) != arraysize) {
8698 * The last opcode in this array should be an IPF_EXP_END.
8700 if (array[maxidx] != IPF_EXP_END) {
8704 for (i = 1; i < maxidx; ) {
8705 e = (ipfexp_t *)(array + i);
8708 * The length of the bits to check must be at least 1
8709 * (or else there is nothing to comapre with!) and it
8710 * cannot exceed the length of the data present.
8712 if ((e->ipfe_size < 1 ) ||
8713 (e->ipfe_size + i > maxidx)) {
8722 /* ------------------------------------------------------------------------ */
8723 /* Function: ipf_fr_matcharray */
8724 /* Returns: int - 0 = match failed, else positive match */
8725 /* Parameters: fin(I) - pointer to packet information */
8726 /* array(I) - pointer to matching array */
8728 /* This function is used to apply a matching array against a packet and */
8729 /* return an indication of whether or not the packet successfully matches */
8730 /* all of the commands in it. */
8731 /* ------------------------------------------------------------------------ */
8733 ipf_fr_matcharray(fin, array)
8737 int i, n, *x, rv, p;
8744 for (; n > 0; x += 3 + x[3], rv = 0) {
8746 if (e->ipfe_cmd == IPF_EXP_END)
8751 * The upper 16 bits currently store the protocol value.
8752 * This is currently used with TCP and UDP port compares and
8753 * allows "tcp.port = 80" without requiring an explicit
8754 " "ip.pr = tcp" first.
8756 p = e->ipfe_cmd >> 16;
8757 if ((p != 0) && (p != fin->fin_p))
8760 switch (e->ipfe_cmd)
8762 case IPF_EXP_IP_PR :
8763 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8764 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8768 case IPF_EXP_IP_SRCADDR :
8769 if (fin->fin_v != 4)
8771 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8772 rv |= ((fin->fin_saddr &
8773 e->ipfe_arg0[i * 2 + 1]) ==
8774 e->ipfe_arg0[i * 2]);
8778 case IPF_EXP_IP_DSTADDR :
8779 if (fin->fin_v != 4)
8781 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8782 rv |= ((fin->fin_daddr &
8783 e->ipfe_arg0[i * 2 + 1]) ==
8784 e->ipfe_arg0[i * 2]);
8788 case IPF_EXP_IP_ADDR :
8789 if (fin->fin_v != 4)
8791 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8792 rv |= ((fin->fin_saddr &
8793 e->ipfe_arg0[i * 2 + 1]) ==
8794 e->ipfe_arg0[i * 2]) ||
8796 e->ipfe_arg0[i * 2 + 1]) ==
8797 e->ipfe_arg0[i * 2]);
8802 case IPF_EXP_IP6_SRCADDR :
8803 if (fin->fin_v != 6)
8805 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8806 rv |= IP6_MASKEQ(&fin->fin_src6,
8807 &e->ipfe_arg0[i * 8 + 4],
8808 &e->ipfe_arg0[i * 8]);
8812 case IPF_EXP_IP6_DSTADDR :
8813 if (fin->fin_v != 6)
8815 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8816 rv |= IP6_MASKEQ(&fin->fin_dst6,
8817 &e->ipfe_arg0[i * 8 + 4],
8818 &e->ipfe_arg0[i * 8]);
8822 case IPF_EXP_IP6_ADDR :
8823 if (fin->fin_v != 6)
8825 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8826 rv |= IP6_MASKEQ(&fin->fin_src6,
8827 &e->ipfe_arg0[i * 8 + 4],
8828 &e->ipfe_arg0[i * 8]) ||
8829 IP6_MASKEQ(&fin->fin_dst6,
8830 &e->ipfe_arg0[i * 8 + 4],
8831 &e->ipfe_arg0[i * 8]);
8836 case IPF_EXP_UDP_PORT :
8837 case IPF_EXP_TCP_PORT :
8838 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8839 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8840 (fin->fin_dport == e->ipfe_arg0[i]);
8844 case IPF_EXP_UDP_SPORT :
8845 case IPF_EXP_TCP_SPORT :
8846 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8847 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8851 case IPF_EXP_UDP_DPORT :
8852 case IPF_EXP_TCP_DPORT :
8853 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8854 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8858 case IPF_EXP_TCP_FLAGS :
8859 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8860 rv |= ((fin->fin_tcpf &
8861 e->ipfe_arg0[i * 2 + 1]) ==
8862 e->ipfe_arg0[i * 2]);
8876 /* ------------------------------------------------------------------------ */
8877 /* Function: ipf_queueflush */
8878 /* Returns: int - number of entries flushed (0 = none) */
8879 /* Parameters: softc(I) - pointer to soft context main structure */
8880 /* deletefn(I) - function to call to delete entry */
8881 /* ipfqs(I) - top of the list of ipf internal queues */
8882 /* userqs(I) - top of the list of user defined timeouts */
8884 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8885 /* need to try a bit harder to free up some space. The algorithm used here */
8886 /* split into two parts but both halves have the same goal: to reduce the */
8887 /* number of connections considered to be "active" to the low watermark. */
8888 /* There are two steps in doing this: */
8889 /* 1) Remove any TCP connections that are already considered to be "closed" */
8890 /* but have not yet been removed from the state table. The two states */
8891 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8892 /* candidates for this style of removal. If freeing up entries in */
8893 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8894 /* we do not go on to step 2. */
8896 /* 2) Look for the oldest entries on each timeout queue and free them if */
8897 /* they are within the given window we are considering. Where the */
8898 /* window starts and the steps taken to increase its size depend upon */
8899 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8900 /* last 30 seconds is not touched. */
8902 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8904 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8905 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8907 /* Points to note: */
8908 /* - tqe_die is the time, in the future, when entries die. */
8909 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8911 /* - tqe_touched is when the entry was last used by NAT/state */
8912 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8913 /* ipf_ticks any given timeout queue and vice versa. */
8914 /* - both tqe_die and tqe_touched increase over time */
8915 /* - timeout queues are sorted with the highest value of tqe_die at the */
8916 /* bottom and therefore the smallest values of each are at the top */
8917 /* - the pointer passed in as ipfqs should point to an array of timeout */
8918 /* queues representing each of the TCP states */
8920 /* We start by setting up a maximum range to scan for things to move of */
8921 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8922 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8923 /* we start again with a new value for "iend" and "istart". This is */
8924 /* continued until we either finish the scan of 30 second intervals or the */
8925 /* low water mark is reached. */
8926 /* ------------------------------------------------------------------------ */
8928 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8929 ipf_main_softc_t *softc;
8930 ipftq_delete_fn_t deletefn;
8931 ipftq_t *ipfqs, *userqs;
8935 u_long interval, istart, iend;
8936 ipftq_t *ifq, *ifqnext;
8937 ipftqent_t *tqe, *tqn;
8940 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8941 tqn = tqe->tqe_next;
8942 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8945 if ((*activep * 100 / size) > low) {
8946 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8947 ((tqe = tqn) != NULL); ) {
8948 tqn = tqe->tqe_next;
8949 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8954 if ((*activep * 100 / size) <= low) {
8959 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8960 * used then the operations are upgraded to floating point
8961 * and kernels don't like floating point...
8963 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8964 istart = IPF_TTLVAL(86400 * 4);
8965 interval = IPF_TTLVAL(43200);
8966 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8967 istart = IPF_TTLVAL(43200);
8968 interval = IPF_TTLVAL(1800);
8969 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8970 istart = IPF_TTLVAL(1800);
8971 interval = IPF_TTLVAL(30);
8975 if (istart > softc->ipf_ticks) {
8976 if (softc->ipf_ticks - interval < interval)
8979 istart = (softc->ipf_ticks / interval) * interval;
8982 iend = softc->ipf_ticks - interval;
8984 while ((*activep * 100 / size) > low) {
8987 try = softc->ipf_ticks - istart;
8989 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8990 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8991 if (try < tqe->tqe_touched)
8993 tqn = tqe->tqe_next;
8994 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8999 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9000 ifqnext = ifq->ifq_next;
9002 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9003 if (try < tqe->tqe_touched)
9005 tqn = tqe->tqe_next;
9006 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9012 if (interval == IPF_TTLVAL(43200)) {
9013 interval = IPF_TTLVAL(1800);
9014 } else if (interval == IPF_TTLVAL(1800)) {
9015 interval = IPF_TTLVAL(30);
9019 if (interval >= softc->ipf_ticks)
9022 iend = softc->ipf_ticks - interval;
9031 /* ------------------------------------------------------------------------ */
9032 /* Function: ipf_deliverlocal */
9033 /* Returns: int - 1 = local address, 0 = non-local address */
9034 /* Parameters: softc(I) - pointer to soft context main structure */
9035 /* ipversion(I) - IP protocol version (4 or 6) */
9036 /* ifp(I) - network interface pointer */
9037 /* ipaddr(I) - IPv4/6 destination address */
9039 /* This fucntion is used to determine in the address "ipaddr" belongs to */
9040 /* the network interface represented by ifp. */
9041 /* ------------------------------------------------------------------------ */
9043 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9044 ipf_main_softc_t *softc;
9052 if (ipversion == 4) {
9053 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9054 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9059 } else if (ipversion == 6) {
9060 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9061 if (IP6_EQ(&addr, ipaddr))
9071 /* ------------------------------------------------------------------------ */
9072 /* Function: ipf_settimeout */
9073 /* Returns: int - 0 = success, -1 = failure */
9074 /* Parameters: softc(I) - pointer to soft context main structure */
9075 /* t(I) - pointer to tuneable array entry */
9076 /* p(I) - pointer to values passed in to apply */
9078 /* This function is called to set the timeout values for each distinct */
9079 /* queue timeout that is available. When called, it calls into both the */
9080 /* state and NAT code, telling them to update their timeout queues. */
9081 /* ------------------------------------------------------------------------ */
9083 ipf_settimeout(softc, t, p)
9084 struct ipf_main_softc_s *softc;
9090 * ipf_interror should be set by the functions called here, not
9091 * by this function - it's just a middle man.
9093 if (ipf_state_settimeout(softc, t, p) == -1)
9095 if (ipf_nat_settimeout(softc, t, p) == -1)
9101 /* ------------------------------------------------------------------------ */
9102 /* Function: ipf_apply_timeout */
9103 /* Returns: int - 0 = success, -1 = failure */
9104 /* Parameters: head(I) - pointer to tuneable array entry */
9105 /* seconds(I) - pointer to values passed in to apply */
9107 /* This function applies a timeout of "seconds" to the timeout queue that */
9108 /* is pointed to by "head". All entries on this list have an expiration */
9109 /* set to be the current tick value of ipf plus the ttl. Given that this */
9110 /* function should only be called when the delta is non-zero, the task is */
9111 /* to walk the entire list and apply the change. The sort order will not */
9112 /* change. The only catch is that this is O(n) across the list, so if the */
9113 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
9114 /* could take a relatively long time to work through them all. */
9115 /* ------------------------------------------------------------------------ */
9117 ipf_apply_timeout(head, seconds)
9121 u_int oldtimeout, newtimeout;
9125 MUTEX_ENTER(&head->ifq_lock);
9126 oldtimeout = head->ifq_ttl;
9127 newtimeout = IPF_TTLVAL(seconds);
9128 delta = oldtimeout - newtimeout;
9130 head->ifq_ttl = newtimeout;
9132 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9133 tqe->tqe_die += delta;
9135 MUTEX_EXIT(&head->ifq_lock);
9139 /* ------------------------------------------------------------------------ */
9140 /* Function: ipf_settimeout_tcp */
9141 /* Returns: int - 0 = successfully applied, -1 = failed */
9142 /* Parameters: t(I) - pointer to tuneable to change */
9143 /* p(I) - pointer to new timeout information */
9144 /* tab(I) - pointer to table of TCP queues */
9146 /* This function applies the new timeout (p) to the TCP tunable (t) and */
9147 /* updates all of the entries on the relevant timeout queue by calling */
9148 /* ipf_apply_timeout(). */
9149 /* ------------------------------------------------------------------------ */
9151 ipf_settimeout_tcp(t, p, tab)
9156 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9157 !strcmp(t->ipft_name, "tcp_established")) {
9158 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9159 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9160 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9161 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9162 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9163 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9164 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9165 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9166 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9167 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9168 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9169 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9170 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9171 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9172 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9173 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9174 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9175 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9176 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9177 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9178 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9179 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9180 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9181 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9182 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9185 * ipf_interror isn't set here because it should be set
9186 * by whatever called this function.
9194 /* ------------------------------------------------------------------------ */
9195 /* Function: ipf_main_soft_create */
9196 /* Returns: NULL = failure, else success */
9197 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9199 /* Create the foundation soft context structure. In circumstances where it */
9200 /* is not required to dynamically allocate the context, a pointer can be */
9201 /* passed in (rather than NULL) to a structure to be initialised. */
9202 /* The main thing of interest is that a number of locks are initialised */
9203 /* here instead of in the where might be expected - in the relevant create */
9204 /* function elsewhere. This is done because the current locking design has */
9205 /* some areas where these locks are used outside of their module. */
9206 /* Possibly the most important exercise that is done here is setting of all */
9207 /* the timeout values, allowing them to be changed before init(). */
9208 /* ------------------------------------------------------------------------ */
9210 ipf_main_soft_create(arg)
9213 ipf_main_softc_t *softc;
9216 KMALLOC(softc, ipf_main_softc_t *);
9223 bzero((char *)softc, sizeof(*softc));
9226 * This serves as a flag as to whether or not the softc should be
9227 * free'd when _destroy is called.
9229 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9231 softc->ipf_tuners = ipf_tune_array_copy(softc,
9232 sizeof(ipf_main_tuneables),
9233 ipf_main_tuneables);
9234 if (softc->ipf_tuners == NULL) {
9235 ipf_main_soft_destroy(softc);
9239 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9240 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9241 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9242 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9243 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9244 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9245 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9246 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9247 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9249 softc->ipf_token_head = NULL;
9250 softc->ipf_token_tail = &softc->ipf_token_head;
9252 softc->ipf_tcpidletimeout = FIVE_DAYS;
9253 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9254 softc->ipf_tcplastack = IPF_TTLVAL(30);
9255 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9256 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9257 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9258 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9259 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9260 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9261 softc->ipf_udptimeout = IPF_TTLVAL(120);
9262 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9263 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9264 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9265 softc->ipf_iptimeout = IPF_TTLVAL(60);
9267 #if defined(IPFILTER_DEFAULT_BLOCK)
9268 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9270 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9272 softc->ipf_minttl = 4;
9273 softc->ipf_icmpminfragmtu = 68;
9274 softc->ipf_flags = IPF_LOGGING;
9279 /* ------------------------------------------------------------------------ */
9280 /* Function: ipf_main_soft_init */
9281 /* Returns: 0 = success, -1 = failure */
9282 /* Parameters: softc(I) - pointer to soft context main structure */
9284 /* A null-op function that exists as a placeholder so that the flow in */
9285 /* other functions is obvious. */
9286 /* ------------------------------------------------------------------------ */
9289 ipf_main_soft_init(softc)
9290 ipf_main_softc_t *softc;
9296 /* ------------------------------------------------------------------------ */
9297 /* Function: ipf_main_soft_destroy */
9299 /* Parameters: softc(I) - pointer to soft context main structure */
9301 /* Undo everything that we did in ipf_main_soft_create. */
9303 /* The most important check that needs to be made here is whether or not */
9304 /* the structure was allocated by ipf_main_soft_create() by checking what */
9305 /* value is stored in ipf_dynamic_main. */
9306 /* ------------------------------------------------------------------------ */
9309 ipf_main_soft_destroy(softc)
9310 ipf_main_softc_t *softc;
9313 RW_DESTROY(&softc->ipf_frag);
9314 RW_DESTROY(&softc->ipf_poolrw);
9315 RW_DESTROY(&softc->ipf_nat);
9316 RW_DESTROY(&softc->ipf_state);
9317 RW_DESTROY(&softc->ipf_tokens);
9318 RW_DESTROY(&softc->ipf_mutex);
9319 RW_DESTROY(&softc->ipf_global);
9320 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9321 MUTEX_DESTROY(&softc->ipf_rw);
9323 if (softc->ipf_tuners != NULL) {
9324 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9326 if (softc->ipf_dynamic_softc == 1) {
9332 /* ------------------------------------------------------------------------ */
9333 /* Function: ipf_main_soft_fini */
9334 /* Returns: 0 = success, -1 = failure */
9335 /* Parameters: softc(I) - pointer to soft context main structure */
9337 /* Clean out the rules which have been added since _init was last called, */
9338 /* the only dynamic part of the mainline. */
9339 /* ------------------------------------------------------------------------ */
9341 ipf_main_soft_fini(softc)
9342 ipf_main_softc_t *softc;
9344 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9345 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9346 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9347 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9353 /* ------------------------------------------------------------------------ */
9354 /* Function: ipf_main_load */
9355 /* Returns: 0 = success, -1 = failure */
9356 /* Parameters: none */
9358 /* Handle global initialisation that needs to be done for the base part of */
9359 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9360 /* arrays that get used by the state/NAT code. */
9361 /* ------------------------------------------------------------------------ */
9367 /* fill icmp reply type table */
9368 for (i = 0; i <= ICMP_MAXTYPE; i++)
9369 icmpreplytype4[i] = -1;
9370 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9371 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9372 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9373 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9376 /* fill icmp reply type table */
9377 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9378 icmpreplytype6[i] = -1;
9379 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9380 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9381 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9382 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9383 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9390 /* ------------------------------------------------------------------------ */
9391 /* Function: ipf_main_unload */
9392 /* Returns: 0 = success, -1 = failure */
9393 /* Parameters: none */
9395 /* A null-op function that exists as a placeholder so that the flow in */
9396 /* other functions is obvious. */
9397 /* ------------------------------------------------------------------------ */
9405 /* ------------------------------------------------------------------------ */
9406 /* Function: ipf_load_all */
9407 /* Returns: 0 = success, -1 = failure */
9408 /* Parameters: none */
9410 /* Work through all of the subsystems inside IPFilter and call the load */
9411 /* function for each in an order that won't lead to a crash :) */
9412 /* ------------------------------------------------------------------------ */
9416 if (ipf_main_load() == -1)
9419 if (ipf_state_main_load() == -1)
9422 if (ipf_nat_main_load() == -1)
9425 if (ipf_frag_main_load() == -1)
9428 if (ipf_auth_main_load() == -1)
9431 if (ipf_proxy_main_load() == -1)
9438 /* ------------------------------------------------------------------------ */
9439 /* Function: ipf_unload_all */
9440 /* Returns: 0 = success, -1 = failure */
9441 /* Parameters: none */
9443 /* Work through all of the subsystems inside IPFilter and call the unload */
9444 /* function for each in an order that won't lead to a crash :) */
9445 /* ------------------------------------------------------------------------ */
9449 if (ipf_proxy_main_unload() == -1)
9452 if (ipf_auth_main_unload() == -1)
9455 if (ipf_frag_main_unload() == -1)
9458 if (ipf_nat_main_unload() == -1)
9461 if (ipf_state_main_unload() == -1)
9464 if (ipf_main_unload() == -1)
9471 /* ------------------------------------------------------------------------ */
9472 /* Function: ipf_create_all */
9473 /* Returns: NULL = failure, else success */
9474 /* Parameters: arg(I) - pointer to soft context main structure */
9476 /* Work through all of the subsystems inside IPFilter and call the create */
9477 /* function for each in an order that won't lead to a crash :) */
9478 /* ------------------------------------------------------------------------ */
9483 ipf_main_softc_t *softc;
9485 softc = ipf_main_soft_create(arg);
9490 softc->ipf_log_soft = ipf_log_soft_create(softc);
9491 if (softc->ipf_log_soft == NULL) {
9492 ipf_destroy_all(softc);
9497 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9498 if (softc->ipf_lookup_soft == NULL) {
9499 ipf_destroy_all(softc);
9503 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9504 if (softc->ipf_sync_soft == NULL) {
9505 ipf_destroy_all(softc);
9509 softc->ipf_state_soft = ipf_state_soft_create(softc);
9510 if (softc->ipf_state_soft == NULL) {
9511 ipf_destroy_all(softc);
9515 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9516 if (softc->ipf_nat_soft == NULL) {
9517 ipf_destroy_all(softc);
9521 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9522 if (softc->ipf_frag_soft == NULL) {
9523 ipf_destroy_all(softc);
9527 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9528 if (softc->ipf_auth_soft == NULL) {
9529 ipf_destroy_all(softc);
9533 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9534 if (softc->ipf_proxy_soft == NULL) {
9535 ipf_destroy_all(softc);
9543 /* ------------------------------------------------------------------------ */
9544 /* Function: ipf_destroy_all */
9546 /* Parameters: softc(I) - pointer to soft context main structure */
9548 /* Work through all of the subsystems inside IPFilter and call the destroy */
9549 /* function for each in an order that won't lead to a crash :) */
9551 /* Every one of these functions is expected to succeed, so there is no */
9552 /* checking of return values. */
9553 /* ------------------------------------------------------------------------ */
9555 ipf_destroy_all(softc)
9556 ipf_main_softc_t *softc;
9559 if (softc->ipf_state_soft != NULL) {
9560 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9561 softc->ipf_state_soft = NULL;
9564 if (softc->ipf_nat_soft != NULL) {
9565 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9566 softc->ipf_nat_soft = NULL;
9569 if (softc->ipf_frag_soft != NULL) {
9570 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9571 softc->ipf_frag_soft = NULL;
9574 if (softc->ipf_auth_soft != NULL) {
9575 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9576 softc->ipf_auth_soft = NULL;
9579 if (softc->ipf_proxy_soft != NULL) {
9580 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9581 softc->ipf_proxy_soft = NULL;
9584 if (softc->ipf_sync_soft != NULL) {
9585 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9586 softc->ipf_sync_soft = NULL;
9589 if (softc->ipf_lookup_soft != NULL) {
9590 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9591 softc->ipf_lookup_soft = NULL;
9595 if (softc->ipf_log_soft != NULL) {
9596 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9597 softc->ipf_log_soft = NULL;
9601 ipf_main_soft_destroy(softc);
9605 /* ------------------------------------------------------------------------ */
9606 /* Function: ipf_init_all */
9607 /* Returns: 0 = success, -1 = failure */
9608 /* Parameters: softc(I) - pointer to soft context main structure */
9610 /* Work through all of the subsystems inside IPFilter and call the init */
9611 /* function for each in an order that won't lead to a crash :) */
9612 /* ------------------------------------------------------------------------ */
9615 ipf_main_softc_t *softc;
9618 if (ipf_main_soft_init(softc) == -1)
9622 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9626 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9629 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9632 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9635 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9638 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9641 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9644 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9651 /* ------------------------------------------------------------------------ */
9652 /* Function: ipf_fini_all */
9653 /* Returns: 0 = success, -1 = failure */
9654 /* Parameters: softc(I) - pointer to soft context main structure */
9656 /* Work through all of the subsystems inside IPFilter and call the fini */
9657 /* function for each in an order that won't lead to a crash :) */
9658 /* ------------------------------------------------------------------------ */
9661 ipf_main_softc_t *softc;
9664 ipf_token_flush(softc);
9666 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9669 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9672 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9675 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9678 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9681 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9684 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9688 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9692 if (ipf_main_soft_fini(softc) == -1)
9699 /* ------------------------------------------------------------------------ */
9700 /* Function: ipf_rule_expire */
9702 /* Parameters: softc(I) - pointer to soft context main structure */
9704 /* At present this function exists just to support temporary addition of */
9705 /* firewall rules. Both inactive and active lists are scanned for items to */
9706 /* purge, as by rights, the expiration is computed as soon as the rule is */
9708 /* ------------------------------------------------------------------------ */
9710 ipf_rule_expire(softc)
9711 ipf_main_softc_t *softc;
9715 if ((softc->ipf_rule_explist[0] == NULL) &&
9716 (softc->ipf_rule_explist[1] == NULL))
9719 WRITE_ENTER(&softc->ipf_mutex);
9721 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9723 * Because the list is kept sorted on insertion, the fist
9724 * one that dies in the future means no more work to do.
9726 if (fr->fr_die > softc->ipf_ticks)
9728 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9731 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9733 * Because the list is kept sorted on insertion, the fist
9734 * one that dies in the future means no more work to do.
9736 if (fr->fr_die > softc->ipf_ticks)
9738 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9741 RWLOCK_EXIT(&softc->ipf_mutex);
9745 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9746 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9749 host_node_t RBI_ZERO(ipf_rb);
9750 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9753 /* ------------------------------------------------------------------------ */
9754 /* Function: ipf_ht_node_cmp */
9755 /* Returns: int - 0 == nodes are the same, .. */
9756 /* Parameters: k1(I) - pointer to first key to compare */
9757 /* k2(I) - pointer to second key to compare */
9759 /* The "key" for the node is a combination of two fields: the address */
9760 /* family and the address itself. */
9762 /* Because we're not actually interpreting the address data, it isn't */
9763 /* necessary to convert them to/from network/host byte order. The mask is */
9764 /* just used to remove bits that aren't significant - it doesn't matter */
9765 /* where they are, as long as they're always in the same place. */
9767 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9768 /* this is where individual ones will differ the most - but not true for */
9769 /* for /48's, etc. */
9770 /* ------------------------------------------------------------------------ */
9772 ipf_ht_node_cmp(k1, k2)
9773 struct host_node_s *k1, *k2;
9777 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9781 if (k1->hn_addr.adf_family == AF_INET)
9782 return (k2->hn_addr.adf_addr.in4.s_addr -
9783 k1->hn_addr.adf_addr.in4.s_addr);
9785 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9788 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9791 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9794 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9799 /* ------------------------------------------------------------------------ */
9800 /* Function: ipf_ht_node_make_key */
9802 /* parameters: htp(I) - pointer to address tracking structure */
9803 /* key(I) - where to store masked address for lookup */
9804 /* family(I) - protocol family of address */
9805 /* addr(I) - pointer to network address */
9807 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9808 /* copy the address passed in into the key structure whilst masking out the */
9809 /* bits that we don't want. */
9811 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9812 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9813 /* have to be wary of that and not allow 32-128 to happen. */
9814 /* ------------------------------------------------------------------------ */
9816 ipf_ht_node_make_key(htp, key, family, addr)
9822 key->hn_addr.adf_family = family;
9823 if (family == AF_INET) {
9827 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9828 bits = htp->ht_netmask;
9832 mask = htonl(0xffffffff << (32 - bits));
9834 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9837 int bits = htp->ht_netmask;
9839 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9841 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9842 htonl(0xffffffff << (128 - bits));
9843 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9844 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9845 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9846 } else if (bits > 64) {
9847 key->hn_addr.adf_addr.i6[3] = 0;
9848 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9849 htonl(0xffffffff << (96 - bits));
9850 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9851 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9852 } else if (bits > 32) {
9853 key->hn_addr.adf_addr.i6[3] = 0;
9854 key->hn_addr.adf_addr.i6[2] = 0;
9855 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9856 htonl(0xffffffff << (64 - bits));
9857 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9859 key->hn_addr.adf_addr.i6[3] = 0;
9860 key->hn_addr.adf_addr.i6[2] = 0;
9861 key->hn_addr.adf_addr.i6[1] = 0;
9862 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9863 htonl(0xffffffff << (32 - bits));
9870 /* ------------------------------------------------------------------------ */
9871 /* Function: ipf_ht_node_add */
9872 /* Returns: int - 0 == success, -1 == failure */
9873 /* Parameters: softc(I) - pointer to soft context main structure */
9874 /* htp(I) - pointer to address tracking structure */
9875 /* family(I) - protocol family of address */
9876 /* addr(I) - pointer to network address */
9878 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9879 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9881 /* After preparing the key with the address information to find, look in */
9882 /* the red-black tree to see if the address is known. A successful call to */
9883 /* this function can mean one of two things: a new node was added to the */
9884 /* tree or a matching node exists and we're able to bump up its activity. */
9885 /* ------------------------------------------------------------------------ */
9887 ipf_ht_node_add(softc, htp, family, addr)
9888 ipf_main_softc_t *softc;
9896 ipf_ht_node_make_key(htp, &k, family, addr);
9898 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9900 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9902 KMALLOC(h, host_node_t *);
9905 LBUMP(ipf_rb_no_mem);
9910 * If there was a macro to initialise the RB node then that
9911 * would get used here, but there isn't...
9913 bzero((char *)h, sizeof(*h));
9914 h->hn_addr = k.hn_addr;
9915 h->hn_addr.adf_family = k.hn_addr.adf_family;
9916 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9917 htp->ht_cur_nodes++;
9919 if ((htp->ht_max_per_node != 0) &&
9920 (h->hn_active >= htp->ht_max_per_node)) {
9921 DT(ipf_rb_node_max);
9922 LBUMP(ipf_rb_node_max);
9933 /* ------------------------------------------------------------------------ */
9934 /* Function: ipf_ht_node_del */
9935 /* Returns: int - 0 == success, -1 == failure */
9936 /* parameters: htp(I) - pointer to address tracking structure */
9937 /* family(I) - protocol family of address */
9938 /* addr(I) - pointer to network address */
9940 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9941 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9943 /* Try and find the address passed in amongst the leavese on this tree to */
9944 /* be friend. If found then drop the active account for that node drops by */
9945 /* one. If that count reaches 0, it is time to free it all up. */
9946 /* ------------------------------------------------------------------------ */
9948 ipf_ht_node_del(htp, family, addr)
9956 ipf_ht_node_make_key(htp, &k, family, addr);
9958 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9963 if (h->hn_active == 0) {
9964 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9965 htp->ht_cur_nodes--;
9974 /* ------------------------------------------------------------------------ */
9975 /* Function: ipf_rb_ht_init */
9977 /* Parameters: head(I) - pointer to host tracking structure */
9979 /* Initialise the host tracking structure to be ready for use above. */
9980 /* ------------------------------------------------------------------------ */
9982 ipf_rb_ht_init(head)
9985 RBI_INIT(ipf_rb, &head->ht_root);
9989 /* ------------------------------------------------------------------------ */
9990 /* Function: ipf_rb_ht_freenode */
9992 /* Parameters: head(I) - pointer to host tracking structure */
9993 /* arg(I) - additional argument from walk caller */
9995 /* Free an actual host_node_t structure. */
9996 /* ------------------------------------------------------------------------ */
9998 ipf_rb_ht_freenode(node, arg)
10006 /* ------------------------------------------------------------------------ */
10007 /* Function: ipf_rb_ht_flush */
10009 /* Parameters: head(I) - pointer to host tracking structure */
10011 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
10012 /* and free'ing each one. */
10013 /* ------------------------------------------------------------------------ */
10015 ipf_rb_ht_flush(head)
10016 host_track_t *head;
10018 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10022 /* ------------------------------------------------------------------------ */
10023 /* Function: ipf_slowtimer */
10025 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
10027 /* Slowly expire held state for fragments. Timeouts are set * in */
10028 /* expectation of this being called twice per second. */
10029 /* ------------------------------------------------------------------------ */
10031 ipf_slowtimer(softc)
10032 ipf_main_softc_t *softc;
10035 ipf_token_expire(softc);
10036 ipf_frag_expire(softc);
10037 ipf_state_expire(softc);
10038 ipf_nat_expire(softc);
10039 ipf_auth_expire(softc);
10040 ipf_lookup_expire(softc);
10041 ipf_rule_expire(softc);
10042 ipf_sync_expire(softc);
10043 softc->ipf_ticks++;
10044 # if defined(__OpenBSD__)
10045 timeout_add(&ipf_slowtimer_ch, hz/2);
10050 /* ------------------------------------------------------------------------ */
10051 /* Function: ipf_inet_mask_add */
10053 /* Parameters: bits(I) - pointer to nat context information */
10054 /* mtab(I) - pointer to mask hash table structure */
10056 /* When called, bits represents the mask of a new NAT rule that has just */
10057 /* been added. This function inserts a bitmask into the array of masks to */
10058 /* search when searching for a matching NAT rule for a packet. */
10059 /* Prevention of duplicate masks is achieved by checking the use count for */
10060 /* a given netmask. */
10061 /* ------------------------------------------------------------------------ */
10063 ipf_inet_mask_add(bits, mtab)
10065 ipf_v4_masktab_t *mtab;
10070 mtab->imt4_masks[bits]++;
10071 if (mtab->imt4_masks[bits] > 1)
10077 mask = 0xffffffff << (32 - bits);
10079 for (i = 0; i < 33; i++) {
10080 if (ntohl(mtab->imt4_active[i]) < mask) {
10081 for (j = 32; j > i; j--)
10082 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10083 mtab->imt4_active[i] = htonl(mask);
10091 /* ------------------------------------------------------------------------ */
10092 /* Function: ipf_inet_mask_del */
10094 /* Parameters: bits(I) - number of bits set in the netmask */
10095 /* mtab(I) - pointer to mask hash table structure */
10097 /* Remove the 32bit bitmask represented by "bits" from the collection of */
10098 /* netmasks stored inside of mtab. */
10099 /* ------------------------------------------------------------------------ */
10101 ipf_inet_mask_del(bits, mtab)
10103 ipf_v4_masktab_t *mtab;
10108 mtab->imt4_masks[bits]--;
10109 if (mtab->imt4_masks[bits] > 0)
10112 mask = htonl(0xffffffff << (32 - bits));
10113 for (i = 0; i < 33; i++) {
10114 if (mtab->imt4_active[i] == mask) {
10115 for (j = i + 1; j < 33; j++)
10116 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10121 ASSERT(mtab->imt4_max >= 0);
10126 /* ------------------------------------------------------------------------ */
10127 /* Function: ipf_inet6_mask_add */
10129 /* Parameters: bits(I) - number of bits set in mask */
10130 /* mask(I) - pointer to mask to add */
10131 /* mtab(I) - pointer to mask hash table structure */
10133 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10134 /* has just been added. This function inserts a bitmask into the array of */
10135 /* masks to search when searching for a matching NAT rule for a packet. */
10136 /* Prevention of duplicate masks is achieved by checking the use count for */
10137 /* a given netmask. */
10138 /* ------------------------------------------------------------------------ */
10140 ipf_inet6_mask_add(bits, mask, mtab)
10143 ipf_v6_masktab_t *mtab;
10148 mtab->imt6_masks[bits]++;
10149 if (mtab->imt6_masks[bits] > 1)
10160 for (i = 0; i < 129; i++) {
10161 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10162 for (j = 128; j > i; j--)
10163 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10164 mtab->imt6_active[i] = *mask;
10172 /* ------------------------------------------------------------------------ */
10173 /* Function: ipf_inet6_mask_del */
10175 /* Parameters: bits(I) - number of bits set in mask */
10176 /* mask(I) - pointer to mask to remove */
10177 /* mtab(I) - pointer to mask hash table structure */
10179 /* Remove the 128bit bitmask represented by "bits" from the collection of */
10180 /* netmasks stored inside of mtab. */
10181 /* ------------------------------------------------------------------------ */
10183 ipf_inet6_mask_del(bits, mask, mtab)
10186 ipf_v6_masktab_t *mtab;
10191 mtab->imt6_masks[bits]--;
10192 if (mtab->imt6_masks[bits] > 0)
10202 for (i = 0; i < 129; i++) {
10203 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10204 for (j = i + 1; j < 129; j++) {
10205 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10206 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10213 ASSERT(mtab->imt6_max >= 0);