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 *,
218 static u_int ipf_pcksum6 __P((fr_info_t *, ip6_t *,
219 u_int32_t, u_int32_t));
221 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
222 !defined(__FreeBSD__)) || \
223 FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
224 OPENBSD_LT_REV(200006)
225 static int ppsratecheck(struct timeval *, int *, int);
230 * bit values for identifying presence of individual IP options
231 * All of these tables should be ordered by increasing key value on the left
232 * hand side to allow for binary searching of the array and include a trailer
233 * with a 0 for the bitmask for linear searches to easily find the end with.
235 static const struct optlist ipopts[] = {
236 { IPOPT_NOP, 0x000001 },
237 { IPOPT_RR, 0x000002 },
238 { IPOPT_ZSU, 0x000004 },
239 { IPOPT_MTUP, 0x000008 },
240 { IPOPT_MTUR, 0x000010 },
241 { IPOPT_ENCODE, 0x000020 },
242 { IPOPT_TS, 0x000040 },
243 { IPOPT_TR, 0x000080 },
244 { IPOPT_SECURITY, 0x000100 },
245 { IPOPT_LSRR, 0x000200 },
246 { IPOPT_E_SEC, 0x000400 },
247 { IPOPT_CIPSO, 0x000800 },
248 { IPOPT_SATID, 0x001000 },
249 { IPOPT_SSRR, 0x002000 },
250 { IPOPT_ADDEXT, 0x004000 },
251 { IPOPT_VISA, 0x008000 },
252 { IPOPT_IMITD, 0x010000 },
253 { IPOPT_EIP, 0x020000 },
254 { IPOPT_FINN, 0x040000 },
259 static const struct optlist ip6exthdr[] = {
260 { IPPROTO_HOPOPTS, 0x000001 },
261 { IPPROTO_IPV6, 0x000002 },
262 { IPPROTO_ROUTING, 0x000004 },
263 { IPPROTO_FRAGMENT, 0x000008 },
264 { IPPROTO_ESP, 0x000010 },
265 { IPPROTO_AH, 0x000020 },
266 { IPPROTO_NONE, 0x000040 },
267 { IPPROTO_DSTOPTS, 0x000080 },
268 { IPPROTO_MOBILITY, 0x000100 },
274 * bit values for identifying presence of individual IP security options
276 static const struct optlist secopt[] = {
277 { IPSO_CLASS_RES4, 0x01 },
278 { IPSO_CLASS_TOPS, 0x02 },
279 { IPSO_CLASS_SECR, 0x04 },
280 { IPSO_CLASS_RES3, 0x08 },
281 { IPSO_CLASS_CONF, 0x10 },
282 { IPSO_CLASS_UNCL, 0x20 },
283 { IPSO_CLASS_RES2, 0x40 },
284 { IPSO_CLASS_RES1, 0x80 }
287 char ipfilter_version[] = IPL_VERSION;
300 #ifdef IPFILTER_COMPILED
303 #ifdef IPFILTER_CKSUM
317 * Table of functions available for use with call rules.
319 static ipfunc_resolve_t ipf_availfuncs[] = {
320 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
321 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
322 { "", NULL, NULL, NULL }
325 static ipftuneable_t ipf_main_tuneables[] = {
326 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
327 "ipf_flags", 0, 0xffffffff,
328 stsizeof(ipf_main_softc_t, ipf_flags),
330 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
332 stsizeof(ipf_main_softc_t, ipf_active),
333 IPFT_RDONLY, NULL, NULL },
334 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
335 "control_forwarding", 0, 1,
336 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
338 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
340 stsizeof(ipf_main_softc_t, ipf_update_ipid),
342 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
344 stsizeof(ipf_main_softc_t, ipf_chksrc),
346 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
348 stsizeof(ipf_main_softc_t, ipf_minttl),
350 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
351 "icmp_minfragmtu", 0, 1,
352 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
354 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
355 "default_pass", 0, 0xffffffff,
356 stsizeof(ipf_main_softc_t, ipf_pass),
358 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
359 "tcp_idle_timeout", 1, 0x7fffffff,
360 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
361 0, NULL, ipf_settimeout },
362 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
363 "tcp_close_wait", 1, 0x7fffffff,
364 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
365 0, NULL, ipf_settimeout },
366 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
367 "tcp_last_ack", 1, 0x7fffffff,
368 stsizeof(ipf_main_softc_t, ipf_tcplastack),
369 0, NULL, ipf_settimeout },
370 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
371 "tcp_timeout", 1, 0x7fffffff,
372 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
373 0, NULL, ipf_settimeout },
374 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
375 "tcp_syn_sent", 1, 0x7fffffff,
376 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
377 0, NULL, ipf_settimeout },
378 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
379 "tcp_syn_received", 1, 0x7fffffff,
380 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
381 0, NULL, ipf_settimeout },
382 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
383 "tcp_closed", 1, 0x7fffffff,
384 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
385 0, NULL, ipf_settimeout },
386 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
387 "tcp_half_closed", 1, 0x7fffffff,
388 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
389 0, NULL, ipf_settimeout },
390 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
391 "tcp_time_wait", 1, 0x7fffffff,
392 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
393 0, NULL, ipf_settimeout },
394 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
395 "udp_timeout", 1, 0x7fffffff,
396 stsizeof(ipf_main_softc_t, ipf_udptimeout),
397 0, NULL, ipf_settimeout },
398 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
399 "udp_ack_timeout", 1, 0x7fffffff,
400 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
401 0, NULL, ipf_settimeout },
402 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
403 "icmp_timeout", 1, 0x7fffffff,
404 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
405 0, NULL, ipf_settimeout },
406 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
407 "icmp_ack_timeout", 1, 0x7fffffff,
408 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
409 0, NULL, ipf_settimeout },
410 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
411 "ip_timeout", 1, 0x7fffffff,
412 stsizeof(ipf_main_softc_t, ipf_iptimeout),
413 0, NULL, ipf_settimeout },
414 #if defined(INSTANCES) && defined(_KERNEL)
415 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
416 "intercept_loopback", 0, 1,
417 stsizeof(ipf_main_softc_t, ipf_get_loopback),
418 0, NULL, ipf_set_loopback },
428 * The next section of code is a a collection of small routines that set
429 * fields in the fr_info_t structure passed based on properties of the
430 * current packet. There are different routines for the same protocol
431 * for each of IPv4 and IPv6. Adding a new protocol, for which there
432 * will "special" inspection for setup, is now more easily done by adding
433 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
434 * adding more code to a growing switch statement.
437 static INLINE int ipf_pr_ah6 __P((fr_info_t *));
438 static INLINE void ipf_pr_esp6 __P((fr_info_t *));
439 static INLINE void ipf_pr_gre6 __P((fr_info_t *));
440 static INLINE void ipf_pr_udp6 __P((fr_info_t *));
441 static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
442 static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
443 static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
444 static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
445 static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
446 static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
447 static INLINE int ipf_pr_routing6 __P((fr_info_t *));
448 static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
449 static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
450 static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
453 /* ------------------------------------------------------------------------ */
454 /* Function: ipf_pr_short6 */
456 /* Parameters: fin(I) - pointer to packet information */
457 /* xmin(I) - minimum header size */
460 /* This is function enforces the 'is a packet too short to be legit' rule */
461 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
462 /* for ipf_pr_short() for more details. */
463 /* ------------------------------------------------------------------------ */
465 ipf_pr_short6(fin, xmin)
470 if (fin->fin_dlen < xmin)
471 fin->fin_flx |= FI_SHORT;
475 /* ------------------------------------------------------------------------ */
476 /* Function: ipf_pr_ipv6hdr */
478 /* Parameters: fin(I) - pointer to packet information */
481 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
482 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
483 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
484 /* of that possibility arising. */
485 /* ------------------------------------------------------------------------ */
490 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
491 int p, go = 1, i, hdrcount;
492 fr_ip_t *fi = &fin->fin_fi;
503 fi->fi_ttl = ip6->ip6_hlim;
504 fi->fi_src.in6 = ip6->ip6_src;
505 fin->fin_crc += fi->fi_src.i6[0];
506 fin->fin_crc += fi->fi_src.i6[1];
507 fin->fin_crc += fi->fi_src.i6[2];
508 fin->fin_crc += fi->fi_src.i6[3];
509 fi->fi_dst.in6 = ip6->ip6_dst;
510 fin->fin_crc += fi->fi_dst.i6[0];
511 fin->fin_crc += fi->fi_dst.i6[1];
512 fin->fin_crc += fi->fi_dst.i6[2];
513 fin->fin_crc += fi->fi_dst.i6[3];
515 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
516 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
519 while (go && !(fin->fin_flx & FI_SHORT)) {
532 case IPPROTO_ICMPV6 :
542 case IPPROTO_HOPOPTS :
543 p = ipf_pr_hopopts6(fin);
546 case IPPROTO_MOBILITY :
547 p = ipf_pr_mobility6(fin);
550 case IPPROTO_DSTOPTS :
551 p = ipf_pr_dstopts6(fin);
554 case IPPROTO_ROUTING :
555 p = ipf_pr_routing6(fin);
568 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
569 if (ip6exthdr[i].ol_val == p) {
570 fin->fin_flx |= ip6exthdr[i].ol_bit;
580 case IPPROTO_FRAGMENT :
581 p = ipf_pr_fragment6(fin);
583 * Given that the only fragments we want to let through
584 * (where fin_off != 0) are those where the non-first
585 * fragments only have data, we can safely stop looking
586 * at headers if this is a non-leading fragment.
588 if (fin->fin_off != 0)
599 * It is important to note that at this point, for the
600 * extension headers (go != 0), the entire header may not have
601 * been pulled up when the code gets to this point. This is
602 * only done for "go != 0" because the other header handlers
603 * will all pullup their complete header. The other indicator
604 * of an incomplete packet is that this was just an extension
607 if ((go != 0) && (p != IPPROTO_NONE) &&
608 (ipf_pr_pullup(fin, 0) == -1)) {
615 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
616 * and destroy whatever packet was here. The caller of this function
617 * expects us to return if there is a problem with ipf_pullup.
619 if (fin->fin_m == NULL) {
620 ipf_main_softc_t *softc = fin->fin_main_soft;
622 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
629 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
630 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
632 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
633 ipf_main_softc_t *softc = fin->fin_main_soft;
635 fin->fin_flx |= FI_BAD;
636 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
637 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
642 /* ------------------------------------------------------------------------ */
643 /* Function: ipf_pr_ipv6exthdr */
644 /* Returns: struct ip6_ext * - pointer to the start of the next header */
645 /* or NULL if there is a prolblem. */
646 /* Parameters: fin(I) - pointer to packet information */
647 /* multiple(I) - flag indicating yes/no if multiple occurances */
648 /* of this extension header are allowed. */
649 /* proto(I) - protocol number for this extension header */
652 /* This function embodies a number of common checks that all IPv6 extension */
653 /* headers must be subjected to. For example, making sure the packet is */
654 /* big enough for it to be in, checking if it is repeated and setting a */
655 /* flag to indicate its presence. */
656 /* ------------------------------------------------------------------------ */
657 static INLINE struct ip6_ext *
658 ipf_pr_ipv6exthdr(fin, multiple, proto)
662 ipf_main_softc_t *softc = fin->fin_main_soft;
667 fin->fin_flx |= FI_V6EXTHDR;
669 /* 8 is default length of extension hdr */
670 if ((fin->fin_dlen - 8) < 0) {
671 fin->fin_flx |= FI_SHORT;
672 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
676 if (ipf_pr_pullup(fin, 8) == -1) {
677 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
684 case IPPROTO_FRAGMENT :
688 shift = 8 + (hdr->ip6e_len << 3);
692 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
693 fin->fin_flx |= FI_BAD;
694 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
698 fin->fin_dp = (char *)fin->fin_dp + shift;
699 fin->fin_dlen -= shift;
702 * If we have seen a fragment header, do not set any flags to indicate
703 * the presence of this extension header as it has no impact on the
704 * end result until after it has been defragmented.
706 if (fin->fin_flx & FI_FRAG)
709 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
710 if (ip6exthdr[i].ol_val == proto) {
712 * Most IPv6 extension headers are only allowed once.
714 if ((multiple == 0) &&
715 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
716 fin->fin_flx |= FI_BAD;
718 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
726 /* ------------------------------------------------------------------------ */
727 /* Function: ipf_pr_hopopts6 */
728 /* Returns: int - value of the next header or IPPROTO_NONE if error */
729 /* Parameters: fin(I) - pointer to packet information */
732 /* This is function checks pending hop by hop options extension header */
733 /* ------------------------------------------------------------------------ */
740 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
743 return hdr->ip6e_nxt;
747 /* ------------------------------------------------------------------------ */
748 /* Function: ipf_pr_mobility6 */
749 /* Returns: int - value of the next header or IPPROTO_NONE if error */
750 /* Parameters: fin(I) - pointer to packet information */
753 /* This is function checks the IPv6 mobility extension header */
754 /* ------------------------------------------------------------------------ */
756 ipf_pr_mobility6(fin)
761 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
764 return hdr->ip6e_nxt;
768 /* ------------------------------------------------------------------------ */
769 /* Function: ipf_pr_routing6 */
770 /* Returns: int - value of the next header or IPPROTO_NONE if error */
771 /* Parameters: fin(I) - pointer to packet information */
774 /* This is function checks pending routing extension header */
775 /* ------------------------------------------------------------------------ */
780 struct ip6_routing *hdr;
782 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
786 switch (hdr->ip6r_type)
790 * Nasty extension header length?
792 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
793 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
794 ipf_main_softc_t *softc = fin->fin_main_soft;
796 fin->fin_flx |= FI_BAD;
797 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
806 return hdr->ip6r_nxt;
810 /* ------------------------------------------------------------------------ */
811 /* Function: ipf_pr_fragment6 */
812 /* Returns: int - value of the next header or IPPROTO_NONE if error */
813 /* Parameters: fin(I) - pointer to packet information */
816 /* Examine the IPv6 fragment header and extract fragment offset information.*/
818 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
819 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
820 /* packets with a fragment header can fit into. They are as follows: */
822 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
823 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
824 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
825 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
826 /* 5. [IPV6][0-n EH][FH][data] */
828 /* IPV6 = IPv6 header, FH = Fragment Header, */
829 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
831 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
832 /* scenario in which they happen is in extreme circumstances that are most */
833 /* likely to be an indication of an attack rather than normal traffic. */
834 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
835 /* are two rules that can be used to guard against type 3 packets: L4 */
836 /* headers must always be in a packet that has the offset field set to 0 */
837 /* and no packet is allowed to overlay that where offset = 0. */
838 /* ------------------------------------------------------------------------ */
840 ipf_pr_fragment6(fin)
843 ipf_main_softc_t *softc = fin->fin_main_soft;
844 struct ip6_frag *frag;
846 fin->fin_flx |= FI_FRAG;
848 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
850 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
854 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
856 * Any fragment that isn't the last fragment must have its
857 * length as a multiple of 8.
859 if ((fin->fin_plen & 7) != 0)
860 fin->fin_flx |= FI_BAD;
863 fin->fin_fraghdr = frag;
864 fin->fin_id = frag->ip6f_ident;
865 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
866 if (fin->fin_off != 0)
867 fin->fin_flx |= FI_FRAGBODY;
870 * Jumbograms aren't handled, so the max. length is 64k
872 if ((fin->fin_off << 3) + fin->fin_dlen > 65535)
873 fin->fin_flx |= FI_BAD;
876 * We don't know where the transport layer header (or whatever is next
877 * is), as it could be behind destination options (amongst others) so
878 * return the fragment header as the type of packet this is. Note that
879 * this effectively disables the fragment cache for > 1 protocol at a
882 return frag->ip6f_nxt;
886 /* ------------------------------------------------------------------------ */
887 /* Function: ipf_pr_dstopts6 */
888 /* Returns: int - value of the next header or IPPROTO_NONE if error */
889 /* Parameters: fin(I) - pointer to packet information */
892 /* This is function checks pending destination options extension header */
893 /* ------------------------------------------------------------------------ */
898 ipf_main_softc_t *softc = fin->fin_main_soft;
901 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
903 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
906 return hdr->ip6e_nxt;
910 /* ------------------------------------------------------------------------ */
911 /* Function: ipf_pr_icmp6 */
913 /* Parameters: fin(I) - pointer to packet information */
916 /* This routine is mainly concerned with determining the minimum valid size */
917 /* for an ICMPv6 packet. */
918 /* ------------------------------------------------------------------------ */
923 int minicmpsz = sizeof(struct icmp6_hdr);
924 struct icmp6_hdr *icmp6;
926 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
927 ipf_main_softc_t *softc = fin->fin_main_soft;
929 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
933 if (fin->fin_dlen > 1) {
938 fin->fin_data[0] = *(u_short *)icmp6;
940 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
941 fin->fin_flx |= FI_ICMPQUERY;
943 switch (icmp6->icmp6_type)
945 case ICMP6_ECHO_REPLY :
946 case ICMP6_ECHO_REQUEST :
947 if (fin->fin_dlen >= 6)
948 fin->fin_data[1] = icmp6->icmp6_id;
949 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
952 case ICMP6_DST_UNREACH :
953 case ICMP6_PACKET_TOO_BIG :
954 case ICMP6_TIME_EXCEEDED :
955 case ICMP6_PARAM_PROB :
956 fin->fin_flx |= FI_ICMPERR;
957 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
958 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
961 if (M_LEN(fin->fin_m) < fin->fin_plen) {
962 if (ipf_coalesce(fin) != 1)
966 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
970 * If the destination of this packet doesn't match the
971 * source of the original packet then this packet is
975 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
976 if (IP6_NEQ(&fin->fin_fi.fi_dst,
977 (i6addr_t *)&ip6->ip6_src))
978 fin->fin_flx |= FI_BAD;
985 ipf_pr_short6(fin, minicmpsz);
986 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
987 u_char p = fin->fin_p;
989 fin->fin_p = IPPROTO_ICMPV6;
996 /* ------------------------------------------------------------------------ */
997 /* Function: ipf_pr_udp6 */
999 /* Parameters: fin(I) - pointer to packet information */
1002 /* Analyse the packet for IPv6/UDP properties. */
1003 /* Is not expected to be called for fragmented packets. */
1004 /* ------------------------------------------------------------------------ */
1010 if (ipf_pr_udpcommon(fin) == 0) {
1011 u_char p = fin->fin_p;
1013 fin->fin_p = IPPROTO_UDP;
1014 ipf_checkv6sum(fin);
1020 /* ------------------------------------------------------------------------ */
1021 /* Function: ipf_pr_tcp6 */
1023 /* Parameters: fin(I) - pointer to packet information */
1026 /* Analyse the packet for IPv6/TCP properties. */
1027 /* Is not expected to be called for fragmented packets. */
1028 /* ------------------------------------------------------------------------ */
1034 if (ipf_pr_tcpcommon(fin) == 0) {
1035 u_char p = fin->fin_p;
1037 fin->fin_p = IPPROTO_TCP;
1038 ipf_checkv6sum(fin);
1044 /* ------------------------------------------------------------------------ */
1045 /* Function: ipf_pr_esp6 */
1047 /* Parameters: fin(I) - pointer to packet information */
1050 /* Analyse the packet for ESP properties. */
1051 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1052 /* even though the newer ESP packets must also have a sequence number that */
1053 /* is 32bits as well, it is not possible(?) to determine the version from a */
1054 /* simple packet header. */
1055 /* ------------------------------------------------------------------------ */
1061 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1062 ipf_main_softc_t *softc = fin->fin_main_soft;
1064 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1070 /* ------------------------------------------------------------------------ */
1071 /* Function: ipf_pr_ah6 */
1072 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1073 /* Parameters: fin(I) - pointer to packet information */
1076 /* Analyse the packet for AH properties. */
1077 /* The minimum length is taken to be the combination of all fields in the */
1078 /* header being present and no authentication data (null algorithm used.) */
1079 /* ------------------------------------------------------------------------ */
1086 fin->fin_flx |= FI_AH;
1088 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1090 ipf_main_softc_t *softc = fin->fin_main_soft;
1092 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1093 return IPPROTO_NONE;
1096 ipf_pr_short6(fin, sizeof(*ah));
1099 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1100 * enough data to satisfy ah_next (the very first one.)
1106 /* ------------------------------------------------------------------------ */
1107 /* Function: ipf_pr_gre6 */
1109 /* Parameters: fin(I) - pointer to packet information */
1111 /* Analyse the packet for GRE properties. */
1112 /* ------------------------------------------------------------------------ */
1119 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1120 ipf_main_softc_t *softc = fin->fin_main_soft;
1122 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1127 if (GRE_REV(gre->gr_flags) == 1)
1128 fin->fin_data[0] = gre->gr_call;
1130 #endif /* USE_INET6 */
1133 /* ------------------------------------------------------------------------ */
1134 /* Function: ipf_pr_pullup */
1135 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1136 /* Parameters: fin(I) - pointer to packet information */
1137 /* plen(I) - length (excluding L3 header) to pullup */
1139 /* Short inline function to cut down on code duplication to perform a call */
1140 /* to ipf_pullup to ensure there is the required amount of data, */
1141 /* consecutively in the packet buffer. */
1143 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1144 /* points to the first byte after the complete layer 3 header, which will */
1145 /* include all of the known extension headers for IPv6 or options for IPv4. */
1147 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1148 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1149 /* - fin_ip) to what is passed through. */
1150 /* ------------------------------------------------------------------------ */
1152 ipf_pr_pullup(fin, plen)
1156 ipf_main_softc_t *softc = fin->fin_main_soft;
1158 if (fin->fin_m != NULL) {
1159 if (fin->fin_dp != NULL)
1160 plen += (char *)fin->fin_dp -
1161 ((char *)fin->fin_ip + fin->fin_hlen);
1162 plen += fin->fin_hlen;
1163 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1164 #if defined(_KERNEL)
1165 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1166 DT(ipf_pullup_fail);
1167 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1170 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1172 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1174 * Fake ipf_pullup failing
1176 fin->fin_reason = FRB_PULLUP;
1177 *fin->fin_mp = NULL;
1188 /* ------------------------------------------------------------------------ */
1189 /* Function: ipf_pr_short */
1191 /* Parameters: fin(I) - pointer to packet information */
1192 /* xmin(I) - minimum header size */
1194 /* Check if a packet is "short" as defined by xmin. The rule we are */
1195 /* applying here is that the packet must not be fragmented within the layer */
1196 /* 4 header. That is, it must not be a fragment that has its offset set to */
1197 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1198 /* entire layer 4 header must be present (min). */
1199 /* ------------------------------------------------------------------------ */
1201 ipf_pr_short(fin, xmin)
1206 if (fin->fin_off == 0) {
1207 if (fin->fin_dlen < xmin)
1208 fin->fin_flx |= FI_SHORT;
1209 } else if (fin->fin_off < xmin) {
1210 fin->fin_flx |= FI_SHORT;
1215 /* ------------------------------------------------------------------------ */
1216 /* Function: ipf_pr_icmp */
1218 /* Parameters: fin(I) - pointer to packet information */
1221 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1222 /* except extrememly bad packets, both type and code will be present. */
1223 /* The expected minimum size of an ICMP packet is very much dependent on */
1224 /* the type of it. */
1226 /* XXX - other ICMP sanity checks? */
1227 /* ------------------------------------------------------------------------ */
1232 ipf_main_softc_t *softc = fin->fin_main_soft;
1233 int minicmpsz = sizeof(struct icmp);
1237 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1239 if (fin->fin_off != 0) {
1240 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1244 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1245 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1251 fin->fin_data[0] = *(u_short *)icmp;
1252 fin->fin_data[1] = icmp->icmp_id;
1254 switch (icmp->icmp_type)
1256 case ICMP_ECHOREPLY :
1258 /* Router discovery messaes - RFC 1256 */
1259 case ICMP_ROUTERADVERT :
1260 case ICMP_ROUTERSOLICIT :
1261 fin->fin_flx |= FI_ICMPQUERY;
1262 minicmpsz = ICMP_MINLEN;
1265 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1266 * 3 * timestamp(3 * 4)
1269 case ICMP_TSTAMPREPLY :
1270 fin->fin_flx |= FI_ICMPQUERY;
1274 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1278 case ICMP_IREQREPLY :
1280 case ICMP_MASKREPLY :
1281 fin->fin_flx |= FI_ICMPQUERY;
1285 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1289 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1290 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu)
1291 fin->fin_flx |= FI_BAD;
1295 case ICMP_SOURCEQUENCH :
1296 case ICMP_REDIRECT :
1297 case ICMP_TIMXCEED :
1298 case ICMP_PARAMPROB :
1299 fin->fin_flx |= FI_ICMPERR;
1300 if (ipf_coalesce(fin) != 1) {
1301 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1306 * ICMP error packets should not be generated for IP
1307 * packets that are a fragment that isn't the first
1310 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1311 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1312 fin->fin_flx |= FI_BAD;
1315 * If the destination of this packet doesn't match the
1316 * source of the original packet then this packet is
1319 if (oip->ip_src.s_addr != fin->fin_daddr)
1320 fin->fin_flx |= FI_BAD;
1326 ipf_pr_short(fin, minicmpsz);
1328 ipf_checkv4sum(fin);
1332 /* ------------------------------------------------------------------------ */
1333 /* Function: ipf_pr_tcpcommon */
1334 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1335 /* Parameters: fin(I) - pointer to packet information */
1337 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1338 /* and make some checks with how they interact with other fields. */
1339 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1340 /* valid and mark the packet as bad if not. */
1341 /* ------------------------------------------------------------------------ */
1343 ipf_pr_tcpcommon(fin)
1346 ipf_main_softc_t *softc = fin->fin_main_soft;
1350 fin->fin_flx |= FI_TCPUDP;
1351 if (fin->fin_off != 0) {
1352 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1356 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1357 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1362 if (fin->fin_dlen > 3) {
1363 fin->fin_sport = ntohs(tcp->th_sport);
1364 fin->fin_dport = ntohs(tcp->th_dport);
1367 if ((fin->fin_flx & FI_SHORT) != 0) {
1368 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1373 * Use of the TCP data offset *must* result in a value that is at
1374 * least the same size as the TCP header.
1376 tlen = TCP_OFF(tcp) << 2;
1377 if (tlen < sizeof(tcphdr_t)) {
1378 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1379 fin->fin_flx |= FI_BAD;
1383 flags = tcp->th_flags;
1384 fin->fin_tcpf = tcp->th_flags;
1387 * If the urgent flag is set, then the urgent pointer must
1388 * also be set and vice versa. Good TCP packets do not have
1389 * just one of these set.
1391 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1392 fin->fin_flx |= FI_BAD;
1394 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1396 * Ignore this case (#if 0) as it shows up in "real"
1397 * traffic with bogus values in the urgent pointer field.
1399 fin->fin_flx |= FI_BAD;
1401 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1402 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1403 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1404 fin->fin_flx |= FI_BAD;
1406 } else if (((flags & TH_SYN) != 0) &&
1407 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1409 * SYN with URG and PUSH set is not for normal TCP but it is
1410 * possible(?) with T/TCP...but who uses T/TCP?
1412 fin->fin_flx |= FI_BAD;
1414 } else if (!(flags & TH_ACK)) {
1416 * If the ack bit isn't set, then either the SYN or
1417 * RST bit must be set. If the SYN bit is set, then
1418 * we expect the ACK field to be 0. If the ACK is
1419 * not set and if URG, PSH or FIN are set, consdier
1420 * that to indicate a bad TCP packet.
1422 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1424 * Cisco PIX sets the ACK field to a random value.
1425 * In light of this, do not set FI_BAD until a patch
1426 * is available from Cisco to ensure that
1427 * interoperability between existing systems is
1430 /*fin->fin_flx |= FI_BAD*/;
1431 } else if (!(flags & (TH_RST|TH_SYN))) {
1432 fin->fin_flx |= FI_BAD;
1433 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1434 fin->fin_flx |= FI_BAD;
1437 if (fin->fin_flx & FI_BAD) {
1438 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1443 * At this point, it's not exactly clear what is to be gained by
1444 * marking up which TCP options are and are not present. The one we
1445 * are most interested in is the TCP window scale. This is only in
1446 * a SYN packet [RFC1323] so we don't need this here...?
1447 * Now if we were to analyse the header for passive fingerprinting,
1448 * then that might add some weight to adding this...
1450 if (tlen == sizeof(tcphdr_t)) {
1454 if (ipf_pr_pullup(fin, tlen) == -1) {
1455 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1462 s = (u_char *)(tcp + 1);
1463 off = IP_HL(ip) << 2;
1465 if (fin->fin_mp != NULL) {
1466 mb_t *m = *fin->fin_mp;
1468 if (off + tlen > M_LEN(m))
1472 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1476 else if (opt == TCPOPT_NOP)
1482 if (ol < 2 || ol > tlen)
1486 for (i = 9, mv = 4; mv >= 0; ) {
1488 if (opt == (u_char)op->ol_val) {
1489 optmsk |= op->ol_bit;
1503 /* ------------------------------------------------------------------------ */
1504 /* Function: ipf_pr_udpcommon */
1505 /* Returns: int - 0 = header ok, 1 = bad packet */
1506 /* Parameters: fin(I) - pointer to packet information */
1508 /* Extract the UDP source and destination ports, if present. If compiled */
1509 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1510 /* ------------------------------------------------------------------------ */
1512 ipf_pr_udpcommon(fin)
1517 fin->fin_flx |= FI_TCPUDP;
1519 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1520 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1521 ipf_main_softc_t *softc = fin->fin_main_soft;
1523 fin->fin_flx |= FI_SHORT;
1524 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1530 fin->fin_sport = ntohs(udp->uh_sport);
1531 fin->fin_dport = ntohs(udp->uh_dport);
1538 /* ------------------------------------------------------------------------ */
1539 /* Function: ipf_pr_tcp */
1541 /* Parameters: fin(I) - pointer to packet information */
1544 /* Analyse the packet for IPv4/TCP properties. */
1545 /* ------------------------------------------------------------------------ */
1551 ipf_pr_short(fin, sizeof(tcphdr_t));
1553 if (ipf_pr_tcpcommon(fin) == 0)
1554 ipf_checkv4sum(fin);
1558 /* ------------------------------------------------------------------------ */
1559 /* Function: ipf_pr_udp */
1561 /* Parameters: fin(I) - pointer to packet information */
1564 /* Analyse the packet for IPv4/UDP properties. */
1565 /* ------------------------------------------------------------------------ */
1571 ipf_pr_short(fin, sizeof(udphdr_t));
1573 if (ipf_pr_udpcommon(fin) == 0)
1574 ipf_checkv4sum(fin);
1578 /* ------------------------------------------------------------------------ */
1579 /* Function: ipf_pr_esp */
1581 /* Parameters: fin(I) - pointer to packet information */
1583 /* Analyse the packet for ESP properties. */
1584 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1585 /* even though the newer ESP packets must also have a sequence number that */
1586 /* is 32bits as well, it is not possible(?) to determine the version from a */
1587 /* simple packet header. */
1588 /* ------------------------------------------------------------------------ */
1594 if (fin->fin_off == 0) {
1595 ipf_pr_short(fin, 8);
1596 if (ipf_pr_pullup(fin, 8) == -1) {
1597 ipf_main_softc_t *softc = fin->fin_main_soft;
1599 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1605 /* ------------------------------------------------------------------------ */
1606 /* Function: ipf_pr_ah */
1607 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1608 /* Parameters: fin(I) - pointer to packet information */
1610 /* Analyse the packet for AH properties. */
1611 /* The minimum length is taken to be the combination of all fields in the */
1612 /* header being present and no authentication data (null algorithm used.) */
1613 /* ------------------------------------------------------------------------ */
1618 ipf_main_softc_t *softc = fin->fin_main_soft;
1622 fin->fin_flx |= FI_AH;
1623 ipf_pr_short(fin, sizeof(*ah));
1625 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1626 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1627 return IPPROTO_NONE;
1630 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1631 DT(fr_v4_ah_pullup_1);
1632 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1633 return IPPROTO_NONE;
1636 ah = (authhdr_t *)fin->fin_dp;
1638 len = (ah->ah_plen + 2) << 2;
1639 ipf_pr_short(fin, len);
1640 if (ipf_pr_pullup(fin, len) == -1) {
1641 DT(fr_v4_ah_pullup_2);
1642 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1643 return IPPROTO_NONE;
1647 * Adjust fin_dp and fin_dlen for skipping over the authentication
1650 fin->fin_dp = (char *)fin->fin_dp + len;
1651 fin->fin_dlen -= len;
1656 /* ------------------------------------------------------------------------ */
1657 /* Function: ipf_pr_gre */
1659 /* Parameters: fin(I) - pointer to packet information */
1661 /* Analyse the packet for GRE properties. */
1662 /* ------------------------------------------------------------------------ */
1667 ipf_main_softc_t *softc = fin->fin_main_soft;
1670 ipf_pr_short(fin, sizeof(grehdr_t));
1672 if (fin->fin_off != 0) {
1673 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1677 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1678 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1683 if (GRE_REV(gre->gr_flags) == 1)
1684 fin->fin_data[0] = gre->gr_call;
1688 /* ------------------------------------------------------------------------ */
1689 /* Function: ipf_pr_ipv4hdr */
1691 /* Parameters: fin(I) - pointer to packet information */
1694 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1695 /* Check all options present and flag their presence if any exist. */
1696 /* ------------------------------------------------------------------------ */
1701 u_short optmsk = 0, secmsk = 0, auth = 0;
1702 int hlen, ol, mv, p, i;
1703 const struct optlist *op;
1710 hlen = fin->fin_hlen;
1716 fi->fi_tos = ip->ip_tos;
1717 fin->fin_id = ip->ip_id;
1718 off = ntohs(ip->ip_off);
1720 /* Get both TTL and protocol */
1721 fi->fi_p = ip->ip_p;
1722 fi->fi_ttl = ip->ip_ttl;
1724 /* Zero out bits not used in IPv6 address */
1725 fi->fi_src.i6[1] = 0;
1726 fi->fi_src.i6[2] = 0;
1727 fi->fi_src.i6[3] = 0;
1728 fi->fi_dst.i6[1] = 0;
1729 fi->fi_dst.i6[2] = 0;
1730 fi->fi_dst.i6[3] = 0;
1732 fi->fi_saddr = ip->ip_src.s_addr;
1733 fin->fin_crc += fi->fi_saddr;
1734 fi->fi_daddr = ip->ip_dst.s_addr;
1735 fin->fin_crc += fi->fi_daddr;
1736 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1737 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1740 * set packet attribute flags based on the offset and
1741 * calculate the byte offset that it represents.
1743 off &= IP_MF|IP_OFFMASK;
1745 int morefrag = off & IP_MF;
1747 fi->fi_flx |= FI_FRAG;
1750 fin->fin_flx |= FI_FRAGBODY;
1752 if ((off + fin->fin_dlen > 65535) ||
1753 (fin->fin_dlen == 0) ||
1754 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1756 * The length of the packet, starting at its
1757 * offset cannot exceed 65535 (0xffff) as the
1758 * length of an IP packet is only 16 bits.
1760 * Any fragment that isn't the last fragment
1761 * must have a length greater than 0 and it
1762 * must be an even multiple of 8.
1764 fi->fi_flx |= FI_BAD;
1771 * Call per-protocol setup and checking
1773 if (p == IPPROTO_AH) {
1775 * Treat AH differently because we expect there to be another
1776 * layer 4 header after it.
1805 * If it is a standard IP header (no options), set the flag fields
1806 * which relate to options to 0.
1808 if (hlen == sizeof(*ip)) {
1816 * So the IP header has some IP options attached. Walk the entire
1817 * list of options present with this packet and set flags to indicate
1818 * which ones are here and which ones are not. For the somewhat out
1819 * of date and obscure security classification options, set a flag to
1820 * represent which classification is present.
1822 fi->fi_flx |= FI_OPTIONS;
1824 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1828 else if (opt == IPOPT_NOP)
1834 if (ol < 2 || ol > hlen)
1837 for (i = 9, mv = 4; mv >= 0; ) {
1840 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1845 case IPOPT_SECURITY :
1846 if (optmsk & op->ol_bit) {
1847 fin->fin_flx |= FI_BAD;
1849 doi = ipf_checkripso(s);
1851 auth = doi & 0xffff;
1857 if (optmsk & op->ol_bit) {
1858 fin->fin_flx |= FI_BAD;
1860 doi = ipf_checkcipso(fin,
1863 auth = doi & 0xffff;
1867 optmsk |= op->ol_bit;
1870 if (opt < op->ol_val)
1883 if (auth && !(auth & 0x0100))
1885 fi->fi_optmsk = optmsk;
1886 fi->fi_secmsk = secmsk;
1891 /* ------------------------------------------------------------------------ */
1892 /* Function: ipf_checkripso */
1894 /* Parameters: s(I) - pointer to start of RIPSO option */
1896 /* ------------------------------------------------------------------------ */
1901 const struct optlist *sp;
1902 u_short secmsk = 0, auth = 0;
1906 sec = *(s + 2); /* classification */
1907 for (j = 3, m = 2; m >= 0; ) {
1909 if (sec == sp->ol_val) {
1910 secmsk |= sp->ol_bit;
1916 if (sec < sp->ol_val)
1923 return (secmsk << 16) | auth;
1927 /* ------------------------------------------------------------------------ */
1928 /* Function: ipf_checkcipso */
1929 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1930 /* Parameters: fin(IO) - pointer to packet information */
1931 /* s(I) - pointer to start of CIPSO option */
1932 /* ol(I) - length of CIPSO option field */
1934 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1935 /* header and returns that whilst also storing the highest sensitivity */
1936 /* value found in the fr_info_t structure. */
1938 /* No attempt is made to extract the category bitmaps as these are defined */
1939 /* by the user (rather than the protocol) and can be rather numerous on the */
1941 /* ------------------------------------------------------------------------ */
1943 ipf_checkcipso(fin, s, ol)
1948 ipf_main_softc_t *softc = fin->fin_main_soft;
1951 u_char *t, tag, tlen, sensitivity;
1954 if (ol < 6 || ol > 40) {
1955 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1956 fin->fin_flx |= FI_BAD;
1961 fi->fi_sensitivity = 0;
1963 * The DOI field MUST be there.
1965 bcopy(s + 2, &doi, sizeof(doi));
1967 t = (u_char *)s + 6;
1968 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1971 if (tlen > len || tlen < 4 || tlen > 34) {
1972 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1973 fin->fin_flx |= FI_BAD;
1979 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1980 * draft (16 July 1992) that has expired.
1983 fin->fin_flx |= FI_BAD;
1985 } else if (tag == 1) {
1986 if (*(t + 2) != 0) {
1987 fin->fin_flx |= FI_BAD;
1990 sensitivity = *(t + 3);
1991 /* Category bitmap for categories 0-239 */
1993 } else if (tag == 4) {
1994 if (*(t + 2) != 0) {
1995 fin->fin_flx |= FI_BAD;
1998 sensitivity = *(t + 3);
1999 /* Enumerated categories, 16bits each, upto 15 */
2001 } else if (tag == 5) {
2002 if (*(t + 2) != 0) {
2003 fin->fin_flx |= FI_BAD;
2006 sensitivity = *(t + 3);
2007 /* Range of categories (2*16bits), up to 7 pairs */
2009 } else if (tag > 127) {
2010 /* Custom defined DOI */
2013 fin->fin_flx |= FI_BAD;
2017 if (sensitivity > fi->fi_sensitivity)
2018 fi->fi_sensitivity = sensitivity;
2025 /* ------------------------------------------------------------------------ */
2026 /* Function: ipf_makefrip */
2027 /* Returns: int - 0 == packet ok, -1 == packet freed */
2028 /* Parameters: hlen(I) - length of IP packet header */
2029 /* ip(I) - pointer to the IP header */
2030 /* fin(IO) - pointer to packet information */
2032 /* Compact the IP header into a structure which contains just the info. */
2033 /* which is useful for comparing IP headers with and store this information */
2034 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2035 /* this function will be called with either an IPv4 or IPv6 packet. */
2036 /* ------------------------------------------------------------------------ */
2038 ipf_makefrip(hlen, ip, fin)
2043 ipf_main_softc_t *softc = fin->fin_main_soft;
2047 fin->fin_hlen = (u_short)hlen;
2049 fin->fin_rule = 0xffffffff;
2050 fin->fin_group[0] = -1;
2051 fin->fin_group[1] = '\0';
2052 fin->fin_dp = (char *)ip + hlen;
2056 fin->fin_plen = ntohs(ip->ip_len);
2057 fin->fin_dlen = fin->fin_plen - hlen;
2058 ipf_pr_ipv4hdr(fin);
2060 } else if (v == 6) {
2061 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2062 fin->fin_dlen = fin->fin_plen;
2063 fin->fin_plen += hlen;
2065 ipf_pr_ipv6hdr(fin);
2068 if (fin->fin_ip == NULL) {
2069 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2076 /* ------------------------------------------------------------------------ */
2077 /* Function: ipf_portcheck */
2078 /* Returns: int - 1 == port matched, 0 == port match failed */
2079 /* Parameters: frp(I) - pointer to port check `expression' */
2080 /* pop(I) - port number to evaluate */
2082 /* Perform a comparison of a port number against some other(s), using a */
2083 /* structure with compare information stored in it. */
2084 /* ------------------------------------------------------------------------ */
2086 ipf_portcheck(frp, pop)
2096 * Do opposite test to that required and continue if that succeeds.
2098 switch (frp->frp_cmp)
2101 if (pop != po) /* EQUAL */
2105 if (pop == po) /* NOTEQUAL */
2109 if (pop >= po) /* LESSTHAN */
2113 if (pop <= po) /* GREATERTHAN */
2117 if (pop > po) /* LT or EQ */
2121 if (pop < po) /* GT or EQ */
2125 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2129 if (pop <= po || pop >= frp->frp_top) /* In range */
2133 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2143 /* ------------------------------------------------------------------------ */
2144 /* Function: ipf_tcpudpchk */
2145 /* Returns: int - 1 == protocol matched, 0 == check failed */
2146 /* Parameters: fda(I) - pointer to packet information */
2147 /* ft(I) - pointer to structure with comparison data */
2149 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2150 /* structure containing information that we want to match against. */
2151 /* ------------------------------------------------------------------------ */
2153 ipf_tcpudpchk(fi, ft)
2160 * Both ports should *always* be in the first fragment.
2161 * So far, I cannot find any cases where they can not be.
2163 * compare destination ports
2166 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2169 * compare source ports
2171 if (err && ft->ftu_scmp)
2172 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2175 * If we don't have all the TCP/UDP header, then how can we
2176 * expect to do any sort of match on it ? If we were looking for
2177 * TCP flags, then NO match. If not, then match (which should
2178 * satisfy the "short" class too).
2180 if (err && (fi->fi_p == IPPROTO_TCP)) {
2181 if (fi->fi_flx & FI_SHORT)
2182 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2184 * Match the flags ? If not, abort this match.
2186 if (ft->ftu_tcpfm &&
2187 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2188 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2189 ft->ftu_tcpfm, ft->ftu_tcpf));
2197 /* ------------------------------------------------------------------------ */
2198 /* Function: ipf_check_ipf */
2199 /* Returns: int - 0 == match, else no match */
2200 /* Parameters: fin(I) - pointer to packet information */
2201 /* fr(I) - pointer to filter rule */
2202 /* portcmp(I) - flag indicating whether to attempt matching on */
2203 /* TCP/UDP port data. */
2205 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2206 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2207 /* this function. */
2208 /* ------------------------------------------------------------------------ */
2210 ipf_check_ipf(fin, fr, portcmp)
2215 u_32_t *ld, *lm, *lip;
2223 lm = (u_32_t *)&fri->fri_mip;
2224 ld = (u_32_t *)&fri->fri_ip;
2227 * first 32 bits to check coversion:
2228 * IP version, TOS, TTL, protocol
2230 i = ((*lip & *lm) != *ld);
2231 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2232 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2237 * Next 32 bits is a constructed bitmask indicating which IP options
2238 * are present (if any) in this packet.
2241 i = ((*lip & *lm) != *ld);
2242 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2243 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2249 * Unrolled loops (4 each, for 32 bits) for address checks.
2252 * Check the source address.
2254 if (fr->fr_satype == FRI_LOOKUP) {
2255 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2256 fi->fi_v, lip, fin->fin_plen);
2263 i = ((*lip & *lm) != *ld);
2264 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2265 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2266 if (fi->fi_v == 6) {
2268 i |= ((*lip & *lm) != *ld);
2269 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2270 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2272 i |= ((*lip & *lm) != *ld);
2273 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2274 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2276 i |= ((*lip & *lm) != *ld);
2277 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2278 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2285 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2290 * Check the destination address.
2293 if (fr->fr_datype == FRI_LOOKUP) {
2294 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2295 fi->fi_v, lip, fin->fin_plen);
2302 i = ((*lip & *lm) != *ld);
2303 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2304 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2305 if (fi->fi_v == 6) {
2307 i |= ((*lip & *lm) != *ld);
2308 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2309 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2311 i |= ((*lip & *lm) != *ld);
2312 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2313 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2315 i |= ((*lip & *lm) != *ld);
2316 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2317 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2324 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2328 * IP addresses matched. The next 32bits contains:
2329 * mast of old IP header security & authentication bits.
2332 i = (*ld - (*lip & *lm));
2333 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2336 * Next we have 32 bits of packet flags.
2339 i |= (*ld - (*lip & *lm));
2340 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2344 * If a fragment, then only the first has what we're
2345 * looking for here...
2348 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2351 if (fr->fr_dcmp || fr->fr_scmp ||
2352 fr->fr_tcpf || fr->fr_tcpfm)
2354 if (fr->fr_icmpm || fr->fr_icmp) {
2355 if (((fi->fi_p != IPPROTO_ICMP) &&
2356 (fi->fi_p != IPPROTO_ICMPV6)) ||
2357 fin->fin_off || (fin->fin_dlen < 2))
2359 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2361 FR_DEBUG(("i. %#x & %#x != %#x\n",
2363 fr->fr_icmpm, fr->fr_icmp));
2373 /* ------------------------------------------------------------------------ */
2374 /* Function: ipf_scanlist */
2375 /* Returns: int - result flags of scanning filter list */
2376 /* Parameters: fin(I) - pointer to packet information */
2377 /* pass(I) - default result to return for filtering */
2379 /* Check the input/output list of rules for a match to the current packet. */
2380 /* If a match is found, the value of fr_flags from the rule becomes the */
2381 /* return value and fin->fin_fr points to the matched rule. */
2383 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2384 /* When unwinding, it should finish up with fin_depth as 0. */
2386 /* Could be per interface, but this gets real nasty when you don't have, */
2387 /* or can't easily change, the kernel source code to . */
2388 /* ------------------------------------------------------------------------ */
2390 ipf_scanlist(fin, pass)
2394 ipf_main_softc_t *softc = fin->fin_main_soft;
2395 int rulen, portcmp, off, skip;
2396 struct frentry *fr, *fnext;
2397 u_32_t passt, passo;
2400 * Do not allow nesting deeper than 16 levels.
2402 if (fin->fin_depth >= 16)
2408 * If there are no rules in this list, return now.
2419 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2422 for (rulen = 0; fr; fr = fnext, rulen++) {
2423 fnext = fr->fr_next;
2425 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2431 * In all checks below, a null (zero) value in the
2432 * filter struture is taken to mean a wildcard.
2434 * check that we are working for the right interface
2437 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2440 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2442 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2443 FR_ISPASS(pass) ? 'p' :
2444 FR_ISACCOUNT(pass) ? 'A' :
2445 FR_ISAUTH(pass) ? 'a' :
2446 (pass & FR_NOMATCH) ? 'n' :'b'));
2447 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2452 switch (fr->fr_type)
2455 case FR_T_IPF_BUILTIN :
2456 if (ipf_check_ipf(fin, fr, portcmp))
2459 #if defined(IPFILTER_BPF)
2461 case FR_T_BPFOPC_BUILTIN :
2466 if (*fin->fin_mp == NULL)
2468 if (fin->fin_family != fr->fr_family)
2470 mc = (u_char *)fin->fin_m;
2471 wlen = fin->fin_dlen + fin->fin_hlen;
2472 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2477 case FR_T_CALLFUNC_BUILTIN :
2481 f = (*fr->fr_func)(fin, &pass);
2490 case FR_T_IPFEXPR_BUILTIN :
2491 if (fin->fin_family != fr->fr_family)
2493 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2501 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2502 if (fin->fin_nattag == NULL)
2504 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2507 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2509 passt = fr->fr_flags;
2512 * If the rule is a "call now" rule, then call the function
2513 * in the rule, if it exists and use the results from that.
2514 * If the function pointer is bad, just make like we ignore
2515 * it, except for increasing the hit counter.
2517 if ((passt & FR_CALLNOW) != 0) {
2520 ATOMIC_INC64(fr->fr_hits);
2521 if ((fr->fr_func == NULL) ||
2522 (fr->fr_func == (ipfunc_t)-1))
2527 fr = (*fr->fr_func)(fin, &passt);
2532 passt = fr->fr_flags;
2538 * Just log this packet...
2540 if ((passt & FR_LOGMASK) == FR_LOG) {
2541 if (ipf_log_pkt(fin, passt) == -1) {
2542 if (passt & FR_LOGORBLOCK) {
2544 passt &= ~FR_CMDMASK;
2545 passt |= FR_BLOCK|FR_QUICK;
2546 fin->fin_reason = FRB_LOGFAIL;
2550 #endif /* IPFILTER_LOG */
2552 MUTEX_ENTER(&fr->fr_lock);
2553 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2555 MUTEX_EXIT(&fr->fr_lock);
2556 fin->fin_rule = rulen;
2559 if (FR_ISSKIP(passt)) {
2562 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2563 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2567 if (passt & (FR_RETICMP|FR_FAKEICMP))
2568 fin->fin_icode = fr->fr_icode;
2570 if (fr->fr_group != -1) {
2571 (void) strncpy(fin->fin_group,
2572 FR_NAME(fr, fr_group),
2573 strlen(FR_NAME(fr, fr_group)));
2575 fin->fin_group[0] = '\0';
2578 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2580 if (fr->fr_grphead != NULL) {
2581 fin->fin_fr = fr->fr_grphead->fg_start;
2582 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2584 if (FR_ISDECAPS(passt))
2585 passt = ipf_decaps(fin, pass, fr->fr_icode);
2587 passt = ipf_scanlist(fin, pass);
2589 if (fin->fin_fr == NULL) {
2590 fin->fin_rule = rulen;
2591 if (fr->fr_group != -1)
2592 (void) strncpy(fin->fin_group,
2595 strlen(fr->fr_names +
2603 if (pass & FR_QUICK) {
2605 * Finally, if we've asked to track state for this
2606 * packet, set it up. Add state for "quick" rules
2607 * here so that if the action fails we can consider
2608 * the rule to "not match" and keep on processing
2611 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2612 !(fin->fin_flx & FI_STATE)) {
2613 int out = fin->fin_out;
2616 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2617 LBUMPD(ipf_stats[out], fr_ads);
2619 LBUMPD(ipf_stats[out], fr_bads);
2632 /* ------------------------------------------------------------------------ */
2633 /* Function: ipf_acctpkt */
2634 /* Returns: frentry_t* - always returns NULL */
2635 /* Parameters: fin(I) - pointer to packet information */
2636 /* passp(IO) - pointer to current/new filter decision (unused) */
2638 /* Checks a packet against accounting rules, if there are any for the given */
2639 /* IP protocol version. */
2641 /* N.B.: this function returns NULL to match the prototype used by other */
2642 /* functions called from the IPFilter "mainline" in ipf_check(). */
2643 /* ------------------------------------------------------------------------ */
2645 ipf_acctpkt(fin, passp)
2649 ipf_main_softc_t *softc = fin->fin_main_soft;
2650 char group[FR_GROUPLEN];
2651 frentry_t *fr, *frsave;
2655 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2658 frsave = fin->fin_fr;
2659 bcopy(fin->fin_group, group, FR_GROUPLEN);
2660 rulen = fin->fin_rule;
2662 pass = ipf_scanlist(fin, FR_NOMATCH);
2663 if (FR_ISACCOUNT(pass)) {
2664 LBUMPD(ipf_stats[0], fr_acct);
2666 fin->fin_fr = frsave;
2667 bcopy(group, fin->fin_group, FR_GROUPLEN);
2668 fin->fin_rule = rulen;
2674 /* ------------------------------------------------------------------------ */
2675 /* Function: ipf_firewall */
2676 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2677 /* were found, returns NULL. */
2678 /* Parameters: fin(I) - pointer to packet information */
2679 /* passp(IO) - pointer to current/new filter decision (unused) */
2681 /* Applies an appropriate set of firewall rules to the packet, to see if */
2682 /* there are any matches. The first check is to see if a match can be seen */
2683 /* in the cache. If not, then search an appropriate list of rules. Once a */
2684 /* matching rule is found, take any appropriate actions as defined by the */
2685 /* rule - except logging. */
2686 /* ------------------------------------------------------------------------ */
2688 ipf_firewall(fin, passp)
2692 ipf_main_softc_t *softc = fin->fin_main_soft;
2701 * This rule cache will only affect packets that are not being
2702 * statefully filtered.
2704 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2705 if (fin->fin_fr != NULL)
2706 pass = ipf_scanlist(fin, softc->ipf_pass);
2708 if ((pass & FR_NOMATCH)) {
2709 LBUMPD(ipf_stats[out], fr_nom);
2714 * Apply packets per second rate-limiting to a rule as required.
2716 if ((fr != NULL) && (fr->fr_pps != 0) &&
2717 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2718 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2719 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2721 LBUMPD(ipf_stats[out], fr_ppshit);
2722 fin->fin_reason = FRB_PPSRATE;
2726 * If we fail to add a packet to the authorization queue, then we
2727 * drop the packet later. However, if it was added then pretend
2728 * we've dropped it already.
2730 if (FR_ISAUTH(pass)) {
2731 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2732 DT1(frb_authnew, fr_info_t *, fin);
2733 fin->fin_m = *fin->fin_mp = NULL;
2734 fin->fin_reason = FRB_AUTHNEW;
2738 fin->fin_error = ENOSPC;
2742 if ((fr != NULL) && (fr->fr_func != NULL) &&
2743 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2744 (void) (*fr->fr_func)(fin, &pass);
2747 * If a rule is a pre-auth rule, check again in the list of rules
2748 * loaded for authenticated use. It does not particulary matter
2749 * if this search fails because a "preauth" result, from a rule,
2750 * is treated as "not a pass", hence the packet is blocked.
2752 if (FR_ISPREAUTH(pass)) {
2753 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2757 * If the rule has "keep frag" and the packet is actually a fragment,
2758 * then create a fragment state entry.
2760 if (pass & FR_KEEPFRAG) {
2761 if (fin->fin_flx & FI_FRAG) {
2762 if (ipf_frag_new(softc, fin, pass) == -1) {
2763 LBUMP(ipf_stats[out].fr_bnfr);
2765 LBUMP(ipf_stats[out].fr_nfr);
2768 LBUMP(ipf_stats[out].fr_cfr);
2779 /* ------------------------------------------------------------------------ */
2780 /* Function: ipf_check */
2781 /* Returns: int - 0 == packet allowed through, */
2783 /* -1 == packet blocked */
2784 /* 1 == packet not matched */
2785 /* -2 == requires authentication */
2787 /* > 0 == filter error # for packet */
2788 /* Parameters: ctx(I) - pointer to the instance context */
2789 /* ip(I) - pointer to start of IPv4/6 packet */
2790 /* hlen(I) - length of header */
2791 /* ifp(I) - pointer to interface this packet is on */
2792 /* out(I) - 0 == packet going in, 1 == packet going out */
2793 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2795 /* Solaris & HP-UX ONLY : */
2796 /* qpi(I) - pointer to STREAMS queue information for this */
2797 /* interface & direction. */
2799 /* ipf_check() is the master function for all IPFilter packet processing. */
2800 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2801 /* authorisation (or pre-authorisation), presence of related state info., */
2802 /* generating log entries, IP packet accounting, routing of packets as */
2803 /* directed by firewall rules and of course whether or not to allow the */
2804 /* packet to be further processed by the kernel. */
2806 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2807 /* freed. Packets passed may be returned with the pointer pointed to by */
2808 /* by "mp" changed to a new buffer. */
2809 /* ------------------------------------------------------------------------ */
2811 ipf_check(ctx, ip, hlen, ifp, out
2812 #if defined(_KERNEL) && defined(MENTAT)
2826 * The above really sucks, but short of writing a diff
2828 ipf_main_softc_t *softc = ctx;
2830 fr_info_t *fin = &frinfo;
2831 u_32_t pass = softc->ipf_pass;
2832 frentry_t *fr = NULL;
2837 * The first part of ipf_check() deals with making sure that what goes
2838 * into the filtering engine makes some sense. Information about the
2839 * the packet is distilled, collected into a fr_info_t structure and
2840 * the an attempt to ensure the buffer the packet is in is big enough
2841 * to hold all the required packet headers.
2845 qpktinfo_t *qpi = qif;
2848 if ((u_int)ip & 0x3)
2855 if (softc->ipf_running <= 0) {
2859 bzero((char *)fin, sizeof(*fin));
2862 if (qpi->qpi_flags & QF_BROADCAST)
2863 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2864 if (qpi->qpi_flags & QF_MULTICAST)
2865 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2873 # if defined(M_MCAST)
2874 if ((m->m_flags & M_MCAST) != 0)
2875 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2877 # if defined(M_MLOOP)
2878 if ((m->m_flags & M_MLOOP) != 0)
2879 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2881 # if defined(M_BCAST)
2882 if ((m->m_flags & M_BCAST) != 0)
2883 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2885 # ifdef M_CANFASTFWD
2887 * XXX For now, IP Filter and fast-forwarding of cached flows
2888 * XXX are mutually exclusive. Eventually, IP Filter should
2889 * XXX get a "can-fast-forward" filter rule.
2891 m->m_flags &= ~M_CANFASTFWD;
2892 # endif /* M_CANFASTFWD */
2893 # if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2894 (__FreeBSD_version < 501108))
2896 * disable delayed checksums.
2898 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2899 in_delayed_cksum(m);
2900 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2902 # endif /* CSUM_DELAY_DATA */
2903 # endif /* MENTAT */
2905 bzero((char *)fin, sizeof(*fin));
2907 # if defined(M_MCAST)
2908 if ((m->m_flags & M_MCAST) != 0)
2909 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2911 # if defined(M_MLOOP)
2912 if ((m->m_flags & M_MLOOP) != 0)
2913 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2915 # if defined(M_BCAST)
2916 if ((m->m_flags & M_BCAST) != 0)
2917 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2919 #endif /* _KERNEL */
2927 fin->fin_error = ENETUNREACH;
2928 fin->fin_hlen = (u_short)hlen;
2929 fin->fin_dp = (char *)ip + hlen;
2930 fin->fin_main_soft = softc;
2932 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2938 LBUMP(ipf_stats[out].fr_ipv6);
2940 * Jumbo grams are quite likely too big for internal buffer
2941 * structures to handle comfortably, for now, so just drop
2944 if (((ip6_t *)ip)->ip6_plen == 0) {
2945 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2946 pass = FR_BLOCK|FR_NOMATCH;
2947 fin->fin_reason = FRB_JUMBO;
2950 fin->fin_family = AF_INET6;
2954 fin->fin_family = AF_INET;
2957 if (ipf_makefrip(hlen, ip, fin) == -1) {
2958 DT1(frb_makefrip, fr_info_t *, fin);
2959 pass = FR_BLOCK|FR_NOMATCH;
2960 fin->fin_reason = FRB_MAKEFRIP;
2965 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2966 * becomes NULL and so we have no packet to free.
2968 if (*fin->fin_mp == NULL)
2973 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2974 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2975 fin->fin_flx |= FI_BADSRC;
2977 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2978 LBUMPD(ipf_stats[0], fr_v4_badttl);
2979 fin->fin_flx |= FI_LOWTTL;
2984 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2985 LBUMPD(ipf_stats[0], fr_v6_badttl);
2986 fin->fin_flx |= FI_LOWTTL;
2992 if (fin->fin_flx & FI_SHORT) {
2993 LBUMPD(ipf_stats[out], fr_short);
2996 READ_ENTER(&softc->ipf_mutex);
3002 if (ipf_nat_checkin(fin, &pass) == -1) {
3008 if (ipf_nat6_checkin(fin, &pass) == -1) {
3019 * If a packet is found in the auth table, then skip checking
3020 * the access lists for permission but we do need to consider
3021 * the result as if it were from the ACL's. In addition, being
3022 * found in the auth table means it has been seen before, so do
3023 * not pass it through accounting (again), lest it be counted twice.
3025 fr = ipf_auth_check(fin, &pass);
3026 if (!out && (fr == NULL))
3027 (void) ipf_acctpkt(fin, NULL);
3030 if ((fin->fin_flx & FI_FRAG) != 0)
3031 fr = ipf_frag_known(fin, &pass);
3034 fr = ipf_state_check(fin, &pass);
3037 if ((pass & FR_NOMATCH) || (fr == NULL))
3038 fr = ipf_firewall(fin, &pass);
3041 * If we've asked to track state for this packet, set it up.
3042 * Here rather than ipf_firewall because ipf_checkauth may decide
3043 * to return a packet for "keep state"
3045 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3046 !(fin->fin_flx & FI_STATE)) {
3047 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3048 LBUMP(ipf_stats[out].fr_ads);
3050 LBUMP(ipf_stats[out].fr_bads);
3051 if (FR_ISPASS(pass)) {
3053 pass &= ~FR_CMDMASK;
3055 fin->fin_reason = FRB_STATEADD;
3061 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3062 fin->fin_dif = &fr->fr_dif;
3063 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3067 * Only count/translate packets which will be passed on, out the
3070 if (out && FR_ISPASS(pass)) {
3071 (void) ipf_acctpkt(fin, NULL);
3076 if (ipf_nat_checkout(fin, &pass) == -1) {
3078 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3079 if (ipf_updateipid(fin) == -1) {
3081 LBUMP(ipf_stats[1].fr_ipud);
3082 pass &= ~FR_CMDMASK;
3084 fin->fin_reason = FRB_UPDATEIPID;
3086 LBUMP(ipf_stats[0].fr_ipud);
3092 (void) ipf_nat6_checkout(fin, &pass);
3102 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3103 (void) ipf_dolog(fin, &pass);
3108 * The FI_STATE flag is cleared here so that calling ipf_state_check
3109 * will work when called from inside of fr_fastroute. Although
3110 * there is a similar flag, FI_NATED, for NAT, it does have the same
3111 * impact on code execution.
3113 fin->fin_flx &= ~FI_STATE;
3115 #if defined(FASTROUTE_RECURSION)
3117 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3118 * a packet below can sometimes cause a recursive call into IPFilter.
3119 * On those platforms where that does happen, we need to hang onto
3120 * the filter rule just in case someone decides to remove or flush it
3124 MUTEX_ENTER(&fr->fr_lock);
3126 MUTEX_EXIT(&fr->fr_lock);
3129 RWLOCK_EXIT(&softc->ipf_mutex);
3132 if ((pass & FR_RETMASK) != 0) {
3134 * Should we return an ICMP packet to indicate error
3135 * status passing through the packet filter ?
3136 * WARNING: ICMP error packets AND TCP RST packets should
3137 * ONLY be sent in repsonse to incoming packets. Sending
3138 * them in response to outbound packets can result in a
3139 * panic on some operating systems.
3142 if (pass & FR_RETICMP) {
3145 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3149 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3151 LBUMP(ipf_stats[0].fr_ret);
3152 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3153 !(fin->fin_flx & FI_SHORT)) {
3154 if (((fin->fin_flx & FI_OOW) != 0) ||
3155 (ipf_send_reset(fin) == 0)) {
3156 LBUMP(ipf_stats[1].fr_ret);
3161 * When using return-* with auth rules, the auth code
3162 * takes over disposing of this packet.
3164 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3165 DT1(frb_authcapture, fr_info_t *, fin);
3166 fin->fin_m = *fin->fin_mp = NULL;
3167 fin->fin_reason = FRB_AUTHCAPTURE;
3171 if (pass & FR_RETRST) {
3172 fin->fin_error = ECONNRESET;
3178 * After the above so that ICMP unreachables and TCP RSTs get
3181 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3182 ipf_nat_uncreate(fin);
3185 * If we didn't drop off the bottom of the list of rules (and thus
3186 * the 'current' rule fr is not NULL), then we may have some extra
3187 * instructions about what to do with a packet.
3188 * Once we're finished return to our caller, freeing the packet if
3189 * we are dropping it.
3195 * Generate a duplicated packet first because ipf_fastroute
3196 * can lead to fin_m being free'd... not good.
3199 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3200 (fdp->fd_ptr != (void *)-1)) {
3201 mc = M_COPY(fin->fin_m);
3203 ipf_fastroute(mc, &mc, fin, fdp);
3207 if (!out && (pass & FR_FASTROUTE)) {
3209 * For fastroute rule, no destination interface defined
3210 * so pass NULL as the frdest_t parameter
3212 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3214 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3215 (fdp->fd_ptr != (struct ifnet *)-1)) {
3216 /* this is for to rules: */
3217 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3221 #if defined(FASTROUTE_RECURSION)
3222 (void) ipf_derefrule(softc, &fr);
3225 #if !defined(FASTROUTE_RECURSION)
3226 RWLOCK_EXIT(&softc->ipf_mutex);
3230 if (!FR_ISPASS(pass)) {
3231 LBUMP(ipf_stats[out].fr_block);
3239 LBUMP(ipf_stats[out].fr_pass);
3240 #if defined(_KERNEL) && defined(__sgi)
3241 if ((fin->fin_hbuf != NULL) &&
3242 (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3243 COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3251 if (FR_ISPASS(pass))
3253 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3254 return fin->fin_error;
3257 (*mp)->mb_ifp = fin->fin_ifp;
3258 blockreason = fin->fin_reason;
3259 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3260 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3261 if ((pass & FR_NOMATCH) != 0)
3264 if ((pass & FR_RETMASK) != 0)
3265 switch (pass & FR_RETMASK)
3275 switch (pass & FR_CMDMASK)
3289 #endif /* _KERNEL */
3294 /* ------------------------------------------------------------------------ */
3295 /* Function: ipf_dolog */
3296 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3297 /* Parameters: fin(I) - pointer to packet information */
3298 /* passp(IO) - pointer to current/new filter decision (unused) */
3300 /* Checks flags set to see how a packet should be logged, if it is to be */
3301 /* logged. Adjust statistics based on its success or not. */
3302 /* ------------------------------------------------------------------------ */
3304 ipf_dolog(fin, passp)
3308 ipf_main_softc_t *softc = fin->fin_main_soft;
3315 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3316 pass |= FF_LOGNOMATCH;
3317 LBUMPD(ipf_stats[out], fr_npkl);
3320 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3321 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3322 if ((pass & FR_LOGMASK) != FR_LOGP)
3324 LBUMPD(ipf_stats[out], fr_ppkl);
3327 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3328 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3329 if ((pass & FR_LOGMASK) != FR_LOGB)
3330 pass |= FF_LOGBLOCK;
3331 LBUMPD(ipf_stats[out], fr_bpkl);
3334 if (ipf_log_pkt(fin, pass) == -1) {
3336 * If the "or-block" option has been used then
3337 * block the packet if we failed to log it.
3339 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3340 DT1(frb_logfail2, u_int, pass);
3341 pass &= ~FR_CMDMASK;
3343 fin->fin_reason = FRB_LOGFAIL2;
3351 #endif /* IPFILTER_LOG */
3354 /* ------------------------------------------------------------------------ */
3355 /* Function: ipf_cksum */
3356 /* Returns: u_short - IP header checksum */
3357 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3358 /* len(I) - length of buffer in bytes */
3360 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3362 /* N.B.: addr should be 16bit aligned. */
3363 /* ------------------------------------------------------------------------ */
3365 ipf_cksum(addr, len)
3371 for (sum = 0; len > 1; len -= 2)
3374 /* mop up an odd byte, if necessary */
3376 sum += *(u_char *)addr;
3379 * add back carry outs from top 16 bits to low 16 bits
3381 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3382 sum += (sum >> 16); /* add carry */
3383 return (u_short)(~sum);
3387 /* ------------------------------------------------------------------------ */
3388 /* Function: fr_cksum */
3389 /* Returns: u_short - layer 4 checksum */
3390 /* Parameters: fin(I) - pointer to packet information */
3391 /* ip(I) - pointer to IP header */
3392 /* l4proto(I) - protocol to caclulate checksum for */
3393 /* l4hdr(I) - pointer to layer 4 header */
3395 /* Calculates the TCP checksum for the packet held in "m", using the data */
3396 /* in the IP header "ip" to seed it. */
3398 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3399 /* and the TCP header. We also assume that data blocks aren't allocated in */
3402 /* Expects ip_len and ip_off to be in network byte order when called. */
3403 /* ------------------------------------------------------------------------ */
3405 fr_cksum(fin, ip, l4proto, l4hdr)
3411 u_short *sp, slen, sumsave, *csump;
3426 sum = htons((u_short)l4proto);
3428 * Add up IP Header portion
3431 if (IP_V(ip) == 4) {
3433 hlen = IP_HL(ip) << 2;
3435 sp = (u_short *)&ip->ip_src;
3436 sum += *sp++; /* ip_src */
3438 sum += *sp++; /* ip_dst */
3440 slen = fin->fin_plen - off;
3443 } else if (IP_V(ip) == 6) {
3448 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3449 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3450 return(ipf_pcksum6(fin, ip6, off, len));
3459 csump = &((udphdr_t *)l4hdr)->uh_sum;
3463 csump = &((tcphdr_t *)l4hdr)->th_sum;
3466 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3467 sum = 0; /* Pseudo-checksum is not included */
3470 case IPPROTO_ICMPV6 :
3471 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3478 if (csump != NULL) {
3483 sum2 = ipf_pcksum(fin, off, sum);
3490 /* ------------------------------------------------------------------------ */
3491 /* Function: ipf_findgroup */
3492 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3493 /* Parameters: softc(I) - pointer to soft context main structure */
3494 /* group(I) - group name to search for */
3495 /* unit(I) - device to which this group belongs */
3496 /* set(I) - which set of rules (inactive/inactive) this is */
3497 /* fgpp(O) - pointer to place to store pointer to the pointer */
3498 /* to where to add the next (last) group or where */
3499 /* to delete group from. */
3501 /* Search amongst the defined groups for a particular group number. */
3502 /* ------------------------------------------------------------------------ */
3504 ipf_findgroup(softc, group, unit, set, fgpp)
3505 ipf_main_softc_t *softc;
3511 frgroup_t *fg, **fgp;
3514 * Which list of groups to search in is dependent on which list of
3515 * rules are being operated on.
3517 fgp = &softc->ipf_groups[unit][set];
3519 while ((fg = *fgp) != NULL) {
3520 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3531 /* ------------------------------------------------------------------------ */
3532 /* Function: ipf_group_add */
3533 /* Returns: frgroup_t * - NULL == did not create group, */
3534 /* != NULL == pointer to the group */
3535 /* Parameters: softc(I) - pointer to soft context main structure */
3536 /* num(I) - group number to add */
3537 /* head(I) - rule pointer that is using this as the head */
3538 /* flags(I) - rule flags which describe the type of rule it is */
3539 /* unit(I) - device to which this group will belong to */
3540 /* set(I) - which set of rules (inactive/inactive) this is */
3541 /* Write Locks: ipf_mutex */
3543 /* Add a new group head, or if it already exists, increase the reference */
3545 /* ------------------------------------------------------------------------ */
3547 ipf_group_add(softc, group, head, flags, unit, set)
3548 ipf_main_softc_t *softc;
3555 frgroup_t *fg, **fgp;
3561 if (unit == IPL_LOGIPF && *group == '\0')
3565 gflags = flags & FR_INOUT;
3567 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3569 if (fg->fg_head == NULL && head != NULL)
3571 if (fg->fg_flags == 0)
3572 fg->fg_flags = gflags;
3573 else if (gflags != fg->fg_flags)
3579 KMALLOC(fg, frgroup_t *);
3582 fg->fg_start = NULL;
3584 bcopy(group, fg->fg_name, strlen(group) + 1);
3585 fg->fg_flags = gflags;
3587 fg->fg_set = &softc->ipf_groups[unit][set];
3594 /* ------------------------------------------------------------------------ */
3595 /* Function: ipf_group_del */
3596 /* Returns: int - number of rules deleted */
3597 /* Parameters: softc(I) - pointer to soft context main structure */
3598 /* group(I) - group name to delete */
3599 /* fr(I) - filter rule from which group is referenced */
3600 /* Write Locks: ipf_mutex */
3602 /* This function is called whenever a reference to a group is to be dropped */
3603 /* and thus its reference count needs to be lowered and the group free'd if */
3604 /* the reference count reaches zero. Passing in fr is really for the sole */
3605 /* purpose of knowing when the head rule is being deleted. */
3606 /* ------------------------------------------------------------------------ */
3608 ipf_group_del(softc, group, fr)
3609 ipf_main_softc_t *softc;
3614 if (group->fg_head == fr)
3615 group->fg_head = NULL;
3618 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3619 ipf_group_free(group);
3623 /* ------------------------------------------------------------------------ */
3624 /* Function: ipf_group_free */
3626 /* Parameters: group(I) - pointer to filter rule group */
3628 /* Remove the group from the list of groups and free it. */
3629 /* ------------------------------------------------------------------------ */
3631 ipf_group_free(group)
3636 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3638 *gp = group->fg_next;
3646 /* ------------------------------------------------------------------------ */
3647 /* Function: ipf_group_flush */
3648 /* Returns: int - number of rules flush from group */
3649 /* Parameters: softc(I) - pointer to soft context main structure */
3650 /* Parameters: group(I) - pointer to filter rule group */
3652 /* Remove all of the rules that currently are listed under the given group. */
3653 /* ------------------------------------------------------------------------ */
3655 ipf_group_flush(softc, group)
3656 ipf_main_softc_t *softc;
3661 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3667 /* ------------------------------------------------------------------------ */
3668 /* Function: ipf_getrulen */
3669 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3670 /* Parameters: softc(I) - pointer to soft context main structure */
3671 /* Parameters: unit(I) - device for which to count the rule's number */
3672 /* flags(I) - which set of rules to find the rule in */
3673 /* group(I) - group name */
3674 /* n(I) - rule number to find */
3676 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3677 /* group # g doesn't exist or there are less than n rules in the group. */
3678 /* ------------------------------------------------------------------------ */
3680 ipf_getrulen(softc, unit, group, n)
3681 ipf_main_softc_t *softc;
3689 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3692 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3700 /* ------------------------------------------------------------------------ */
3701 /* Function: ipf_flushlist */
3702 /* Returns: int - >= 0 - number of flushed rules */
3703 /* Parameters: softc(I) - pointer to soft context main structure */
3704 /* nfreedp(O) - pointer to int where flush count is stored */
3705 /* listp(I) - pointer to list to flush pointer */
3706 /* Write Locks: ipf_mutex */
3708 /* Recursively flush rules from the list, descending groups as they are */
3709 /* encountered. if a rule is the head of a group and it has lost all its */
3710 /* group members, then also delete the group reference. nfreedp is needed */
3711 /* to store the accumulating count of rules removed, whereas the returned */
3712 /* value is just the number removed from the current list. The latter is */
3713 /* needed to correctly adjust reference counts on rules that define groups. */
3715 /* NOTE: Rules not loaded from user space cannot be flushed. */
3716 /* ------------------------------------------------------------------------ */
3718 ipf_flushlist(softc, nfreedp, listp)
3719 ipf_main_softc_t *softc;
3726 while ((fp = *listp) != NULL) {
3727 if ((fp->fr_type & FR_T_BUILTIN) ||
3728 !(fp->fr_flags & FR_COPIED)) {
3729 listp = &fp->fr_next;
3732 *listp = fp->fr_next;
3733 if (fp->fr_next != NULL)
3734 fp->fr_next->fr_pnext = fp->fr_pnext;
3735 fp->fr_pnext = NULL;
3737 if (fp->fr_grphead != NULL) {
3738 freed += ipf_group_flush(softc, fp->fr_grphead);
3739 fp->fr_names[fp->fr_grhead] = '\0';
3742 if (fp->fr_icmpgrp != NULL) {
3743 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3744 fp->fr_names[fp->fr_icmphead] = '\0';
3747 if (fp->fr_srctrack.ht_max_nodes)
3748 ipf_rb_ht_flush(&fp->fr_srctrack);
3752 ASSERT(fp->fr_ref > 0);
3753 if (ipf_derefrule(softc, &fp) == 0)
3761 /* ------------------------------------------------------------------------ */
3762 /* Function: ipf_flush */
3763 /* Returns: int - >= 0 - number of flushed rules */
3764 /* Parameters: softc(I) - pointer to soft context main structure */
3765 /* unit(I) - device for which to flush rules */
3766 /* flags(I) - which set of rules to flush */
3768 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3769 /* and IPv6) as defined by the value of flags. */
3770 /* ------------------------------------------------------------------------ */
3772 ipf_flush(softc, unit, flags)
3773 ipf_main_softc_t *softc;
3777 int flushed = 0, set;
3779 WRITE_ENTER(&softc->ipf_mutex);
3781 set = softc->ipf_active;
3782 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3785 if (flags & FR_OUTQUE) {
3786 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3787 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3789 if (flags & FR_INQUE) {
3790 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3791 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3794 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3795 flags & (FR_INQUE|FR_OUTQUE));
3797 RWLOCK_EXIT(&softc->ipf_mutex);
3799 if (unit == IPL_LOGIPF) {
3802 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3810 /* ------------------------------------------------------------------------ */
3811 /* Function: ipf_flush_groups */
3812 /* Returns: int - >= 0 - number of flushed rules */
3813 /* Parameters: softc(I) - soft context pointerto work with */
3814 /* grhead(I) - pointer to the start of the group list to flush */
3815 /* flags(I) - which set of rules to flush */
3817 /* Walk through all of the groups under the given group head and remove all */
3818 /* of those that match the flags passed in. The for loop here is bit more */
3819 /* complicated than usual because the removal of a rule with ipf_derefrule */
3820 /* may end up removing not only the structure pointed to by "fg" but also */
3821 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3822 /* removed from the group then it is necessary to start again. */
3823 /* ------------------------------------------------------------------------ */
3825 ipf_flush_groups(softc, grhead, flags)
3826 ipf_main_softc_t *softc;
3830 frentry_t *fr, **frp;
3831 frgroup_t *fg, **fgp;
3835 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3836 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3841 frp = &fg->fg_start;
3842 while ((removed == 0) && ((fr = *frp) != NULL)) {
3843 if ((fr->fr_flags & flags) == 0) {
3846 if (fr->fr_next != NULL)
3847 fr->fr_next->fr_pnext = fr->fr_pnext;
3849 fr->fr_pnext = NULL;
3851 (void) ipf_derefrule(softc, &fr);
3863 /* ------------------------------------------------------------------------ */
3864 /* Function: memstr */
3865 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3866 /* Parameters: src(I) - pointer to byte sequence to match */
3867 /* dst(I) - pointer to byte sequence to search */
3868 /* slen(I) - match length */
3869 /* dlen(I) - length available to search in */
3871 /* Search dst for a sequence of bytes matching those at src and extend for */
3873 /* ------------------------------------------------------------------------ */
3875 memstr(src, dst, slen, dlen)
3882 while (dlen >= slen) {
3883 if (bcmp(src, dst, slen) == 0) {
3892 /* ------------------------------------------------------------------------ */
3893 /* Function: ipf_fixskip */
3895 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3896 /* rp(I) - rule added/removed with skip in it. */
3897 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3898 /* depending on whether a rule was just added */
3901 /* Adjust all the rules in a list which would have skip'd past the position */
3902 /* where we are inserting to skip to the right place given the change. */
3903 /* ------------------------------------------------------------------------ */
3905 ipf_fixskip(listp, rp, addremove)
3906 frentry_t **listp, *rp;
3913 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3919 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3920 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3921 fp->fr_arg += addremove;
3926 /* ------------------------------------------------------------------------ */
3927 /* Function: count4bits */
3928 /* Returns: int - >= 0 - number of consecutive bits in input */
3929 /* Parameters: ip(I) - 32bit IP address */
3932 /* count consecutive 1's in bit mask. If the mask generated by counting */
3933 /* consecutive 1's is different to that passed, return -1, else return # */
3935 /* ------------------------------------------------------------------------ */
3943 ip = ipn = ntohl(ip);
3944 for (i = 32; i; i--, ipn *= 2)
3945 if (ipn & 0x80000000)
3950 for (i = 32, j = cnt; i; i--, j--) {
3961 /* ------------------------------------------------------------------------ */
3962 /* Function: count6bits */
3963 /* Returns: int - >= 0 - number of consecutive bits in input */
3964 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3967 /* count consecutive 1's in bit mask. */
3968 /* ------------------------------------------------------------------------ */
3977 for (k = 3; k >= 0; k--)
3978 if (msk[k] == 0xffffffff)
3981 for (j = msk[k]; j; j <<= 1)
3988 #endif /* _KERNEL */
3991 /* ------------------------------------------------------------------------ */
3992 /* Function: ipf_synclist */
3993 /* Returns: int - 0 = no failures, else indication of first failure */
3994 /* Parameters: fr(I) - start of filter list to sync interface names for */
3995 /* ifp(I) - interface pointer for limiting sync lookups */
3996 /* Write Locks: ipf_mutex */
3998 /* Walk through a list of filter rules and resolve any interface names into */
3999 /* pointers. Where dynamic addresses are used, also update the IP address */
4000 /* used in the rule. The interface pointer is used to limit the lookups to */
4001 /* a specific set of matching names if it is non-NULL. */
4002 /* Errors can occur when resolving the destination name of to/dup-to fields */
4003 /* when the name points to a pool and that pool doest not exist. If this */
4004 /* does happen then it is necessary to check if there are any lookup refs */
4005 /* that need to be dropped before returning with an error. */
4006 /* ------------------------------------------------------------------------ */
4008 ipf_synclist(softc, fr, ifp)
4009 ipf_main_softc_t *softc;
4013 frentry_t *frt, *start = fr;
4022 for (; fr; fr = fr->fr_next) {
4023 if (fr->fr_family == AF_INET)
4025 else if (fr->fr_family == AF_INET6)
4031 * Lookup all the interface names that are part of the rule.
4033 for (i = 0; i < 4; i++) {
4034 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4036 if (fr->fr_ifnames[i] == -1)
4038 name = FR_NAME(fr, fr_ifnames[i]);
4039 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4042 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4043 if (fr->fr_satype != FRI_NORMAL &&
4044 fr->fr_satype != FRI_LOOKUP) {
4045 ifa = ipf_resolvenic(softc, fr->fr_names +
4047 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4048 &fr->fr_src6, &fr->fr_smsk6);
4050 if (fr->fr_datype != FRI_NORMAL &&
4051 fr->fr_datype != FRI_LOOKUP) {
4052 ifa = ipf_resolvenic(softc, fr->fr_names +
4054 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4055 &fr->fr_dst6, &fr->fr_dmsk6);
4059 fdp = &fr->fr_tifs[0];
4060 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4061 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4066 fdp = &fr->fr_tifs[1];
4067 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4068 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4074 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4075 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4080 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4081 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4082 fr->fr_srcptr = ipf_lookup_res_num(softc,
4088 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4089 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4090 fr->fr_dstptr = ipf_lookup_res_num(softc,
4100 for (frt = start; frt != fr; fr = fr->fr_next) {
4101 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4102 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4103 ipf_lookup_deref(softc, frt->fr_srctype,
4105 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4106 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4107 ipf_lookup_deref(softc, frt->fr_dsttype,
4114 /* ------------------------------------------------------------------------ */
4115 /* Function: ipf_sync */
4117 /* Parameters: Nil */
4119 /* ipf_sync() is called when we suspect that the interface list or */
4120 /* information about interfaces (like IP#) has changed. Go through all */
4121 /* filter rules, NAT entries and the state table and check if anything */
4122 /* needs to be changed/updated. */
4123 /* ------------------------------------------------------------------------ */
4125 ipf_sync(softc, ifp)
4126 ipf_main_softc_t *softc;
4132 ipf_nat_sync(softc, ifp);
4133 ipf_state_sync(softc, ifp);
4134 ipf_lookup_sync(softc, ifp);
4137 WRITE_ENTER(&softc->ipf_mutex);
4138 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4139 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4140 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4141 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4143 for (i = 0; i < IPL_LOGSIZE; i++) {
4146 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4147 (void) ipf_synclist(softc, g->fg_start, ifp);
4148 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4149 (void) ipf_synclist(softc, g->fg_start, ifp);
4151 RWLOCK_EXIT(&softc->ipf_mutex);
4158 * In the functions below, bcopy() is called because the pointer being
4159 * copied _from_ in this instance is a pointer to a char buf (which could
4160 * end up being unaligned) and on the kernel's local stack.
4162 /* ------------------------------------------------------------------------ */
4163 /* Function: copyinptr */
4164 /* Returns: int - 0 = success, else failure */
4165 /* Parameters: src(I) - pointer to the source address */
4166 /* dst(I) - destination address */
4167 /* size(I) - number of bytes to copy */
4169 /* Copy a block of data in from user space, given a pointer to the pointer */
4170 /* to start copying from (src) and a pointer to where to store it (dst). */
4171 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4172 /* ------------------------------------------------------------------------ */
4174 copyinptr(softc, src, dst, size)
4175 ipf_main_softc_t *softc;
4183 error = COPYIN(src, &ca, sizeof(ca));
4187 bcopy(src, (caddr_t)&ca, sizeof(ca));
4189 error = COPYIN(ca, dst, size);
4198 /* ------------------------------------------------------------------------ */
4199 /* Function: copyoutptr */
4200 /* Returns: int - 0 = success, else failure */
4201 /* Parameters: src(I) - pointer to the source address */
4202 /* dst(I) - destination address */
4203 /* size(I) - number of bytes to copy */
4205 /* Copy a block of data out to user space, given a pointer to the pointer */
4206 /* to start copying from (src) and a pointer to where to store it (dst). */
4207 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4208 /* ------------------------------------------------------------------------ */
4210 copyoutptr(softc, src, dst, size)
4211 ipf_main_softc_t *softc;
4218 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4219 error = COPYOUT(src, ca, size);
4228 /* ------------------------------------------------------------------------ */
4229 /* Function: ipf_lock */
4230 /* Returns: int - 0 = success, else error */
4231 /* Parameters: data(I) - pointer to lock value to set */
4232 /* lockp(O) - pointer to location to store old lock value */
4234 /* Get the new value for the lock integer, set it and return the old value */
4236 /* ------------------------------------------------------------------------ */
4238 ipf_lock(data, lockp)
4244 err = BCOPYIN(data, &arg, sizeof(arg));
4247 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4255 /* ------------------------------------------------------------------------ */
4256 /* Function: ipf_getstat */
4258 /* Parameters: softc(I) - pointer to soft context main structure */
4259 /* fiop(I) - pointer to ipfilter stats structure */
4260 /* rev(I) - version claim by program doing ioctl */
4262 /* Stores a copy of current pointers, counters, etc, in the friostat */
4264 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4265 /* program is looking for. This ensure that validation of the version it */
4266 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4267 /* allow older binaries to work but kernels without it will not. */
4268 /* ------------------------------------------------------------------------ */
4271 ipf_getstat(softc, fiop, rev)
4272 ipf_main_softc_t *softc;
4278 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4279 sizeof(ipf_statistics_t) * 2);
4280 fiop->f_locks[IPL_LOGSTATE] = -1;
4281 fiop->f_locks[IPL_LOGNAT] = -1;
4282 fiop->f_locks[IPL_LOGIPF] = -1;
4283 fiop->f_locks[IPL_LOGAUTH] = -1;
4285 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4286 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4287 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4288 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4289 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4290 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4291 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4292 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4294 fiop->f_ticks = softc->ipf_ticks;
4295 fiop->f_active = softc->ipf_active;
4296 fiop->f_froute[0] = softc->ipf_frouteok[0];
4297 fiop->f_froute[1] = softc->ipf_frouteok[1];
4298 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4299 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4301 fiop->f_running = softc->ipf_running;
4302 for (i = 0; i < IPL_LOGSIZE; i++) {
4303 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4304 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4307 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4308 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4309 fiop->f_logging = 1;
4312 fiop->f_log_fail = 0;
4313 fiop->f_logging = 0;
4315 fiop->f_defpass = softc->ipf_pass;
4316 fiop->f_features = ipf_features;
4318 #ifdef IPFILTER_COMPAT
4319 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4320 (rev / 1000000) % 100,
4321 (rev / 10000) % 100,
4325 (void) strncpy(fiop->f_version, ipfilter_version,
4326 sizeof(fiop->f_version));
4332 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4333 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4336 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4337 -1, /* 4: ICMP_SOURCEQUENCH */
4338 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4341 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4343 -1, /* 10: UNUSED */
4344 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4345 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4346 -1, /* 13: ICMP_TSTAMP */
4347 -1, /* 14: ICMP_TSTAMPREPLY */
4348 -1, /* 15: ICMP_IREQ */
4349 -1, /* 16: ICMP_IREQREPLY */
4350 -1, /* 17: ICMP_MASKREQ */
4351 -1, /* 18: ICMP_MASKREPLY */
4355 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4356 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4357 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4358 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4359 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4360 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4361 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4362 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4363 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4364 -1, /* 8: ICMP_UNREACH_ISOLATED */
4365 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4366 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4367 -1, /* 11: ICMP_UNREACH_TOSNET */
4368 -1, /* 12: ICMP_UNREACH_TOSHOST */
4369 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4371 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4374 int icmpreplytype4[ICMP_MAXTYPE + 1];
4377 /* ------------------------------------------------------------------------ */
4378 /* Function: ipf_matchicmpqueryreply */
4379 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4380 /* Parameters: v(I) - IP protocol version (4 or 6) */
4381 /* ic(I) - ICMP information */
4382 /* icmp(I) - ICMP packet header */
4383 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4385 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4386 /* reply to one as described by what's in ic. If it is a match, return 1, */
4387 /* else return 0 for no match. */
4388 /* ------------------------------------------------------------------------ */
4390 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4398 ictype = ic->ici_type;
4402 * If we matched its type on the way in, then when going out
4403 * it will still be the same type.
4405 if ((!rev && (icmp->icmp_type == ictype)) ||
4406 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4407 if (icmp->icmp_type != ICMP_ECHOREPLY)
4409 if (icmp->icmp_id == ic->ici_id)
4415 if ((!rev && (icmp->icmp_type == ictype)) ||
4416 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4417 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4419 if (icmp->icmp_id == ic->ici_id)
4428 /* ------------------------------------------------------------------------ */
4429 /* Function: ipf_rule_compare */
4430 /* Parameters: fr1(I) - first rule structure to compare */
4431 /* fr2(I) - second rule structure to compare */
4432 /* Returns: int - 0 == rules are the same, else mismatch */
4434 /* Compare two rules and return 0 if they match or a number indicating */
4435 /* which of the individual checks failed. */
4436 /* ------------------------------------------------------------------------ */
4438 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4440 if (fr1->fr_cksum != fr2->fr_cksum)
4442 if (fr1->fr_size != fr2->fr_size)
4444 if (fr1->fr_dsize != fr2->fr_dsize)
4446 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4447 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4449 if (fr1->fr_data && !fr2->fr_data)
4451 if (!fr1->fr_data && fr2->fr_data)
4454 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4461 /* ------------------------------------------------------------------------ */
4462 /* Function: frrequest */
4463 /* Returns: int - 0 == success, > 0 == errno value */
4464 /* Parameters: unit(I) - device for which this is for */
4465 /* req(I) - ioctl command (SIOC*) */
4466 /* data(I) - pointr to ioctl data */
4467 /* set(I) - 1 or 0 (filter set) */
4468 /* makecopy(I) - flag indicating whether data points to a rule */
4469 /* in kernel space & hence doesn't need copying. */
4471 /* This function handles all the requests which operate on the list of */
4472 /* filter rules. This includes adding, deleting, insertion. It is also */
4473 /* responsible for creating groups when a "head" rule is loaded. Interface */
4474 /* names are resolved here and other sanity checks are made on the content */
4475 /* of the rule structure being loaded. If a rule has user defined timeouts */
4476 /* then make sure they are created and initialised before exiting. */
4477 /* ------------------------------------------------------------------------ */
4479 frrequest(softc, unit, req, data, set, makecopy)
4480 ipf_main_softc_t *softc;
4486 int error = 0, in, family, addrem, need_free = 0;
4487 frentry_t frd, *fp, *f, **fprev, **ftail;
4488 void *ptr, *uptr, *cptr;
4497 if (makecopy != 0) {
4498 bzero(fp, sizeof(frd));
4499 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4503 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4507 KMALLOCS(f, frentry_t *, fp->fr_size);
4512 bzero(f, fp->fr_size);
4513 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4516 KFREES(f, fp->fr_size);
4523 fp->fr_dnext = NULL;
4524 fp->fr_pnext = NULL;
4525 fp->fr_pdnext = NULL;
4527 fp->fr_grphead = NULL;
4528 fp->fr_icmpgrp = NULL;
4529 fp->fr_isc = (void *)-1;
4532 fp->fr_flags |= FR_COPIED;
4534 fp = (frentry_t *)data;
4535 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4539 fp->fr_flags &= ~FR_COPIED;
4542 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4543 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4549 family = fp->fr_family;
4552 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4553 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4555 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4557 else if (req == (ioctlcmd_t)SIOCZRLST)
4566 * Only filter rules for IPv4 or IPv6 are accepted.
4568 if (family == AF_INET) {
4571 } else if (family == AF_INET6) {
4574 } else if (family != 0) {
4581 * If the rule is being loaded from user space, i.e. we had to copy it
4582 * into kernel space, then do not trust the function pointer in the
4585 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4586 if (ipf_findfunc(fp->fr_func) == NULL) {
4593 error = ipf_funcinit(softc, fp);
4598 if ((fp->fr_flags & FR_CALLNOW) &&
4599 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4604 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4605 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4614 if (FR_ISACCOUNT(fp->fr_flags))
4615 unit = IPL_LOGCOUNT;
4618 * Check that each group name in the rule has a start index that
4621 if (fp->fr_icmphead != -1) {
4622 if ((fp->fr_icmphead < 0) ||
4623 (fp->fr_icmphead >= fp->fr_namelen)) {
4628 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4629 fp->fr_names[fp->fr_icmphead] = '\0';
4632 if (fp->fr_grhead != -1) {
4633 if ((fp->fr_grhead < 0) ||
4634 (fp->fr_grhead >= fp->fr_namelen)) {
4639 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4640 fp->fr_names[fp->fr_grhead] = '\0';
4643 if (fp->fr_group != -1) {
4644 if ((fp->fr_group < 0) ||
4645 (fp->fr_group >= fp->fr_namelen)) {
4650 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4652 * Allow loading rules that are in groups to cause
4653 * them to be created if they don't already exit.
4655 group = FR_NAME(fp, fr_group);
4657 fg = ipf_group_add(softc, group, NULL,
4658 fp->fr_flags, unit, set);
4661 fg = ipf_findgroup(softc, group, unit,
4670 if (fg->fg_flags == 0) {
4671 fg->fg_flags = fp->fr_flags & FR_INOUT;
4672 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4680 * If a rule is going to be part of a group then it does
4681 * not matter whether it is an in or out rule, but if it
4682 * isn't in a group, then it does...
4684 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4690 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4693 * Work out which rule list this change is being applied to.
4697 if (unit == IPL_LOGAUTH) {
4698 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4699 (fp->fr_tifs[1].fd_ptr != NULL) ||
4700 (fp->fr_dif.fd_ptr != NULL) ||
4701 (fp->fr_flags & FR_FASTROUTE)) {
4702 softc->ipf_interror = 145;
4706 fprev = ipf_auth_rulehead(softc);
4708 if (FR_ISACCOUNT(fp->fr_flags))
4709 fprev = &softc->ipf_acct[in][set];
4710 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4711 fprev = &softc->ipf_rules[in][set];
4713 if (fprev == NULL) {
4720 fprev = &fg->fg_start;
4723 * Copy in extra data for the rule.
4725 if (fp->fr_dsize != 0) {
4726 if (makecopy != 0) {
4727 KMALLOCS(ptr, void *, fp->fr_dsize);
4735 * The bcopy case is for when the data is appended
4736 * to the rule by ipf_in_compat().
4738 if (uptr >= (void *)fp &&
4739 uptr < (void *)((char *)fp + fp->fr_size)) {
4740 bcopy(uptr, ptr, fp->fr_dsize);
4743 error = COPYIN(uptr, ptr, fp->fr_dsize);
4759 * Perform per-rule type sanity checks of their members.
4760 * All code after this needs to be aware that allocated memory
4761 * may need to be free'd before exiting.
4763 switch (fp->fr_type & ~FR_T_BUILTIN)
4765 #if defined(IPFILTER_BPF)
4767 if (fp->fr_dsize == 0) {
4772 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4781 * Preparation for error case at the bottom of this function.
4783 if (fp->fr_datype == FRI_LOOKUP)
4784 fp->fr_dstptr = NULL;
4785 if (fp->fr_satype == FRI_LOOKUP)
4786 fp->fr_srcptr = NULL;
4788 if (fp->fr_dsize != sizeof(fripf_t)) {
4795 * Allowing a rule with both "keep state" and "with oow" is
4796 * pointless because adding a state entry to the table will
4797 * fail with the out of window (oow) flag set.
4799 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4805 switch (fp->fr_satype)
4807 case FRI_BROADCAST :
4810 case FRI_NETMASKED :
4812 if (fp->fr_sifpidx < 0) {
4818 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4821 if (fp->fr_srcfunc == NULL) {
4837 switch (fp->fr_datype)
4839 case FRI_BROADCAST :
4842 case FRI_NETMASKED :
4844 if (fp->fr_difpidx < 0) {
4850 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4853 if (fp->fr_dstfunc == NULL) {
4867 case FR_T_CALLFUNC :
4872 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4886 if (fp->fr_tif.fd_name != -1) {
4887 if ((fp->fr_tif.fd_name < 0) ||
4888 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4895 if (fp->fr_dif.fd_name != -1) {
4896 if ((fp->fr_dif.fd_name < 0) ||
4897 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4904 if (fp->fr_rif.fd_name != -1) {
4905 if ((fp->fr_rif.fd_name < 0) ||
4906 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4914 * Lookup all the interface names that are part of the rule.
4916 error = ipf_synclist(softc, fp, NULL);
4919 fp->fr_statecnt = 0;
4920 if (fp->fr_srctrack.ht_max_nodes != 0)
4921 ipf_rb_ht_init(&fp->fr_srctrack);
4924 * Look for an existing matching filter rule, but don't include the
4925 * next or interface pointer in the comparison (fr_next, fr_ifa).
4926 * This elminates rules which are indentical being loaded. Checksum
4927 * the constant part of the filter rule to make comparisons quicker
4928 * (this meaning no pointers are included).
4930 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4933 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4934 for (p = (u_int *)fp->fr_data; p < pp; p++)
4937 WRITE_ENTER(&softc->ipf_mutex);
4940 * Now that the filter rule lists are locked, we can walk the
4941 * chain of them without fear.
4944 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4945 if (fp->fr_collect <= f->fr_collect) {
4953 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4954 if (ipf_rule_compare(fp, f) == 0)
4959 * If zero'ing statistics, copy current to caller and zero.
4967 * Copy and reduce lock because of impending copyout.
4968 * Well we should, but if we do then the atomicity of
4969 * this call and the correctness of fr_hits and
4970 * fr_bytes cannot be guaranteed. As it is, this code
4971 * only resets them to 0 if they are successfully
4972 * copied out into user space.
4974 bcopy((char *)f, (char *)fp, f->fr_size);
4975 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4978 * When we copy this rule back out, set the data
4979 * pointer to be what it was in user space.
4982 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4985 if ((f->fr_dsize != 0) && (uptr != NULL))
4986 error = COPYOUT(f->fr_data, uptr,
4999 if (makecopy != 0) {
5001 KFREES(ptr, fp->fr_dsize);
5003 KFREES(fp, fp->fr_size);
5005 RWLOCK_EXIT(&softc->ipf_mutex);
5011 * At the end of this, ftail must point to the place where the
5012 * new rule is to be saved/inserted/added.
5013 * For SIOCAD*FR, this should be the last rule in the group of
5014 * rules that have equal fr_collect fields.
5015 * For SIOCIN*FR, ...
5017 if (req == (ioctlcmd_t)SIOCADAFR ||
5018 req == (ioctlcmd_t)SIOCADIFR) {
5020 for (ftail = fprev; (f = *ftail) != NULL; ) {
5021 if (f->fr_collect > fp->fr_collect)
5023 ftail = &f->fr_next;
5029 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5030 req == (ioctlcmd_t)SIOCINIFR) {
5031 while ((f = *fprev) != NULL) {
5032 if (f->fr_collect >= fp->fr_collect)
5034 fprev = &f->fr_next;
5037 if (fp->fr_hits != 0) {
5038 while (fp->fr_hits && (f = *ftail)) {
5039 if (f->fr_collect != fp->fr_collect)
5042 ftail = &f->fr_next;
5052 * Request to remove a rule.
5060 * Do not allow activity from user space to interfere
5061 * with rules not loaded that way.
5063 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5070 * Return EBUSY if the rule is being reference by
5071 * something else (eg state information.)
5073 if (f->fr_ref > 1) {
5078 #ifdef IPFILTER_SCAN
5079 if (f->fr_isctag != -1 &&
5080 (f->fr_isc != (struct ipscan *)-1))
5081 ipf_scan_detachfr(f);
5084 if (unit == IPL_LOGAUTH) {
5085 error = ipf_auth_precmd(softc, req, f, ftail);
5089 ipf_rule_delete(softc, f, unit, set);
5091 need_free = makecopy;
5095 * Not removing, so we must be adding/inserting a rule.
5102 if (unit == IPL_LOGAUTH) {
5103 error = ipf_auth_precmd(softc, req, fp, ftail);
5107 MUTEX_NUKE(&fp->fr_lock);
5108 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5109 if (fp->fr_die != 0)
5110 ipf_rule_expire_insert(softc, fp, set);
5115 fp->fr_pnext = ftail;
5116 fp->fr_next = *ftail;
5117 if (fp->fr_next != NULL)
5118 fp->fr_next->fr_pnext = &fp->fr_next;
5121 ipf_fixskip(ftail, fp, 1);
5123 fp->fr_icmpgrp = NULL;
5124 if (fp->fr_icmphead != -1) {
5125 group = FR_NAME(fp, fr_icmphead);
5126 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5127 fp->fr_icmpgrp = fg;
5130 fp->fr_grphead = NULL;
5131 if (fp->fr_grhead != -1) {
5132 group = FR_NAME(fp, fr_grhead);
5133 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5135 fp->fr_grphead = fg;
5139 RWLOCK_EXIT(&softc->ipf_mutex);
5141 if (need_free || (error != 0)) {
5142 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5143 if ((fp->fr_satype == FRI_LOOKUP) &&
5144 (fp->fr_srcptr != NULL))
5145 ipf_lookup_deref(softc, fp->fr_srctype,
5147 if ((fp->fr_datype == FRI_LOOKUP) &&
5148 (fp->fr_dstptr != NULL))
5149 ipf_lookup_deref(softc, fp->fr_dsttype,
5152 if (fp->fr_grp != NULL) {
5153 WRITE_ENTER(&softc->ipf_mutex);
5154 ipf_group_del(softc, fp->fr_grp, fp);
5155 RWLOCK_EXIT(&softc->ipf_mutex);
5157 if ((ptr != NULL) && (makecopy != 0)) {
5158 KFREES(ptr, fp->fr_dsize);
5160 KFREES(fp, fp->fr_size);
5166 /* ------------------------------------------------------------------------ */
5167 /* Function: ipf_rule_delete */
5169 /* Parameters: softc(I) - pointer to soft context main structure */
5170 /* f(I) - pointer to the rule being deleted */
5171 /* ftail(I) - pointer to the pointer to f */
5172 /* unit(I) - device for which this is for */
5173 /* set(I) - 1 or 0 (filter set) */
5175 /* This function attempts to do what it can to delete a filter rule: remove */
5176 /* it from any linked lists and remove any groups it is responsible for. */
5177 /* But in the end, removing a rule can only drop the reference count - we */
5178 /* must use that as the guide for whether or not it can be freed. */
5179 /* ------------------------------------------------------------------------ */
5181 ipf_rule_delete(softc, f, unit, set)
5182 ipf_main_softc_t *softc;
5188 * If fr_pdnext is set, then the rule is on the expire list, so
5189 * remove it from there.
5191 if (f->fr_pdnext != NULL) {
5192 *f->fr_pdnext = f->fr_dnext;
5193 if (f->fr_dnext != NULL)
5194 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5195 f->fr_pdnext = NULL;
5199 ipf_fixskip(f->fr_pnext, f, -1);
5200 if (f->fr_pnext != NULL)
5201 *f->fr_pnext = f->fr_next;
5202 if (f->fr_next != NULL)
5203 f->fr_next->fr_pnext = f->fr_pnext;
5207 (void) ipf_derefrule(softc, &f);
5210 /* ------------------------------------------------------------------------ */
5211 /* Function: ipf_rule_expire_insert */
5213 /* Parameters: softc(I) - pointer to soft context main structure */
5214 /* f(I) - pointer to rule to be added to expire list */
5215 /* set(I) - 1 or 0 (filter set) */
5217 /* If the new rule has a given expiration time, insert it into the list of */
5218 /* expiring rules with the ones to be removed first added to the front of */
5219 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5220 /* expiration interval checks. */
5221 /* ------------------------------------------------------------------------ */
5223 ipf_rule_expire_insert(softc, f, set)
5224 ipf_main_softc_t *softc;
5233 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5234 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5235 fr = fr->fr_dnext) {
5236 if (f->fr_die < fr->fr_die)
5238 if (fr->fr_dnext == NULL) {
5240 * We've got to the last rule and everything
5241 * wanted to be expired before this new node,
5242 * so we have to tack it on the end...
5245 f->fr_pdnext = &fr->fr_dnext;
5251 if (softc->ipf_rule_explist[set] == NULL) {
5252 softc->ipf_rule_explist[set] = f;
5253 f->fr_pdnext = &softc->ipf_rule_explist[set];
5254 } else if (fr != NULL) {
5256 f->fr_pdnext = fr->fr_pdnext;
5257 fr->fr_pdnext = &f->fr_dnext;
5262 /* ------------------------------------------------------------------------ */
5263 /* Function: ipf_findlookup */
5264 /* Returns: NULL = failure, else success */
5265 /* Parameters: softc(I) - pointer to soft context main structure */
5266 /* unit(I) - ipf device we want to find match for */
5267 /* fp(I) - rule for which lookup is for */
5268 /* addrp(I) - pointer to lookup information in address struct */
5269 /* maskp(O) - pointer to lookup information for storage */
5271 /* When using pools and hash tables to store addresses for matching in */
5272 /* rules, it is necessary to resolve both the object referred to by the */
5273 /* name or address (and return that pointer) and also provide the means by */
5274 /* which to determine if an address belongs to that object to make the */
5275 /* packet matching quicker. */
5276 /* ------------------------------------------------------------------------ */
5278 ipf_findlookup(softc, unit, fr, addrp, maskp)
5279 ipf_main_softc_t *softc;
5282 i6addr_t *addrp, *maskp;
5286 switch (addrp->iplookupsubtype)
5289 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5291 &maskp->iplookupfunc);
5294 if (addrp->iplookupname < 0)
5296 if (addrp->iplookupname >= fr->fr_namelen)
5298 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5299 fr->fr_names + addrp->iplookupname,
5300 &maskp->iplookupfunc);
5310 /* ------------------------------------------------------------------------ */
5311 /* Function: ipf_funcinit */
5312 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5313 /* Parameters: softc(I) - pointer to soft context main structure */
5314 /* fr(I) - pointer to filter rule */
5316 /* If a rule is a call rule, then check if the function it points to needs */
5317 /* an init function to be called now the rule has been loaded. */
5318 /* ------------------------------------------------------------------------ */
5320 ipf_funcinit(softc, fr)
5321 ipf_main_softc_t *softc;
5324 ipfunc_resolve_t *ft;
5330 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5331 if (ft->ipfu_addr == fr->fr_func) {
5333 if (ft->ipfu_init != NULL)
5334 err = (*ft->ipfu_init)(softc, fr);
5341 /* ------------------------------------------------------------------------ */
5342 /* Function: ipf_funcfini */
5344 /* Parameters: softc(I) - pointer to soft context main structure */
5345 /* fr(I) - pointer to filter rule */
5347 /* For a given filter rule, call the matching "fini" function if the rule */
5348 /* is using a known function that would have resulted in the "init" being */
5349 /* called for ealier. */
5350 /* ------------------------------------------------------------------------ */
5352 ipf_funcfini(softc, fr)
5353 ipf_main_softc_t *softc;
5356 ipfunc_resolve_t *ft;
5358 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5359 if (ft->ipfu_addr == fr->fr_func) {
5360 if (ft->ipfu_fini != NULL)
5361 (void) (*ft->ipfu_fini)(softc, fr);
5367 /* ------------------------------------------------------------------------ */
5368 /* Function: ipf_findfunc */
5369 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5370 /* Parameters: funcptr(I) - function pointer to lookup */
5372 /* Look for a function in the table of known functions. */
5373 /* ------------------------------------------------------------------------ */
5375 ipf_findfunc(funcptr)
5378 ipfunc_resolve_t *ft;
5380 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5381 if (ft->ipfu_addr == funcptr)
5387 /* ------------------------------------------------------------------------ */
5388 /* Function: ipf_resolvefunc */
5389 /* Returns: int - 0 == success, else error */
5390 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5392 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5393 /* This will either be the function name (if the pointer is set) or the */
5394 /* function pointer if the name is set. When found, fill in the other one */
5395 /* so that the entire, complete, structure can be copied back to user space.*/
5396 /* ------------------------------------------------------------------------ */
5398 ipf_resolvefunc(softc, data)
5399 ipf_main_softc_t *softc;
5402 ipfunc_resolve_t res, *ft;
5405 error = BCOPYIN(data, &res, sizeof(res));
5411 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5412 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5413 if (strncmp(res.ipfu_name, ft->ipfu_name,
5414 sizeof(res.ipfu_name)) == 0) {
5415 res.ipfu_addr = ft->ipfu_addr;
5416 res.ipfu_init = ft->ipfu_init;
5417 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5424 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5425 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5426 if (ft->ipfu_addr == res.ipfu_addr) {
5427 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5428 sizeof(res.ipfu_name));
5429 res.ipfu_init = ft->ipfu_init;
5430 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5442 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5443 !defined(__FreeBSD__)) || \
5444 FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5445 OPENBSD_LT_REV(200006)
5448 * ppsratecheck(): packets (or events) per second limitation.
5451 ppsratecheck(lasttime, curpps, maxpps)
5452 struct timeval *lasttime;
5454 int maxpps; /* maximum pps allowed */
5456 struct timeval tv, delta;
5461 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5462 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5463 if (delta.tv_usec < 0) {
5465 delta.tv_usec += 1000000;
5469 * check for 0,0 is so that the message will be seen at least once.
5470 * if more than one second have passed since the last update of
5471 * lasttime, reset the counter.
5473 * we do increment *curpps even in *curpps < maxpps case, as some may
5474 * try to use *curpps for stat purposes as well.
5476 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5477 delta.tv_sec >= 1) {
5481 } else if (maxpps < 0)
5483 else if (*curpps < maxpps)
5487 *curpps = *curpps + 1;
5494 /* ------------------------------------------------------------------------ */
5495 /* Function: ipf_derefrule */
5496 /* Returns: int - 0 == rule freed up, else rule not freed */
5497 /* Parameters: fr(I) - pointer to filter rule */
5499 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5500 /* free it and any associated storage space being used by it. */
5501 /* ------------------------------------------------------------------------ */
5503 ipf_derefrule(softc, frp)
5504 ipf_main_softc_t *softc;
5513 MUTEX_ENTER(&fr->fr_lock);
5515 if (fr->fr_ref == 0) {
5516 MUTEX_EXIT(&fr->fr_lock);
5517 MUTEX_DESTROY(&fr->fr_lock);
5519 ipf_funcfini(softc, fr);
5522 if (fdp->fd_type == FRD_DSTLIST)
5523 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5526 if (fdp->fd_type == FRD_DSTLIST)
5527 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5530 if (fdp->fd_type == FRD_DSTLIST)
5531 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5533 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5534 fr->fr_satype == FRI_LOOKUP)
5535 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5536 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5537 fr->fr_datype == FRI_LOOKUP)
5538 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5540 if (fr->fr_grp != NULL)
5541 ipf_group_del(softc, fr->fr_grp, fr);
5543 if (fr->fr_grphead != NULL)
5544 ipf_group_del(softc, fr->fr_grphead, fr);
5546 if (fr->fr_icmpgrp != NULL)
5547 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5549 if ((fr->fr_flags & FR_COPIED) != 0) {
5551 KFREES(fr->fr_data, fr->fr_dsize);
5553 KFREES(fr, fr->fr_size);
5558 MUTEX_EXIT(&fr->fr_lock);
5564 /* ------------------------------------------------------------------------ */
5565 /* Function: ipf_grpmapinit */
5566 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5567 /* Parameters: fr(I) - pointer to rule to find hash table for */
5569 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5570 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5571 /* ------------------------------------------------------------------------ */
5573 ipf_grpmapinit(softc, fr)
5574 ipf_main_softc_t *softc;
5577 char name[FR_GROUPLEN];
5580 #if defined(SNPRINTF) && defined(_KERNEL)
5581 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5583 (void) sprintf(name, "%d", fr->fr_arg);
5585 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5590 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5600 /* ------------------------------------------------------------------------ */
5601 /* Function: ipf_grpmapfini */
5602 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5603 /* Parameters: softc(I) - pointer to soft context main structure */
5604 /* fr(I) - pointer to rule to release hash table for */
5606 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5607 /* be called to undo what ipf_grpmapinit caused to be done. */
5608 /* ------------------------------------------------------------------------ */
5610 ipf_grpmapfini(softc, fr)
5611 ipf_main_softc_t *softc;
5617 ipf_lookup_deref(softc, IPLT_HASH, iph);
5622 /* ------------------------------------------------------------------------ */
5623 /* Function: ipf_srcgrpmap */
5624 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5625 /* Parameters: fin(I) - pointer to packet information */
5626 /* passp(IO) - pointer to current/new filter decision (unused) */
5628 /* Look for a rule group head in a hash table, using the source address as */
5629 /* the key, and descend into that group and continue matching rules against */
5631 /* ------------------------------------------------------------------------ */
5633 ipf_srcgrpmap(fin, passp)
5640 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5646 fin->fin_fr = fg->fg_start;
5647 (void) ipf_scanlist(fin, *passp);
5652 /* ------------------------------------------------------------------------ */
5653 /* Function: ipf_dstgrpmap */
5654 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5655 /* Parameters: fin(I) - pointer to packet information */
5656 /* passp(IO) - pointer to current/new filter decision (unused) */
5658 /* Look for a rule group head in a hash table, using the destination */
5659 /* address as the key, and descend into that group and continue matching */
5660 /* rules against the packet. */
5661 /* ------------------------------------------------------------------------ */
5663 ipf_dstgrpmap(fin, passp)
5670 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5676 fin->fin_fr = fg->fg_start;
5677 (void) ipf_scanlist(fin, *passp);
5684 * These functions manage objects on queues for efficient timeouts. There
5685 * are a number of system defined queues as well as user defined timeouts.
5686 * It is expected that a lock is held in the domain in which the queue
5687 * belongs (i.e. either state or NAT) when calling any of these functions
5688 * that prevents ipf_freetimeoutqueue() from being called at the same time
5693 /* ------------------------------------------------------------------------ */
5694 /* Function: ipf_addtimeoutqueue */
5695 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5696 /* timeout queue with given interval. */
5697 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5698 /* of interface queues. */
5699 /* seconds(I) - timeout value in seconds for this queue. */
5701 /* This routine first looks for a timeout queue that matches the interval */
5702 /* being requested. If it finds one, increments the reference counter and */
5703 /* returns a pointer to it. If none are found, it allocates a new one and */
5704 /* inserts it at the top of the list. */
5707 /* It is assumed that the caller of this function has an appropriate lock */
5708 /* held (exclusively) in the domain that encompases 'parent'. */
5709 /* ------------------------------------------------------------------------ */
5711 ipf_addtimeoutqueue(softc, parent, seconds)
5712 ipf_main_softc_t *softc;
5719 period = seconds * IPF_HZ_DIVIDE;
5721 MUTEX_ENTER(&softc->ipf_timeoutlock);
5722 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5723 if (ifq->ifq_ttl == period) {
5725 * Reset the delete flag, if set, so the structure
5726 * gets reused rather than freed and reallocated.
5728 MUTEX_ENTER(&ifq->ifq_lock);
5729 ifq->ifq_flags &= ~IFQF_DELETE;
5731 MUTEX_EXIT(&ifq->ifq_lock);
5732 MUTEX_EXIT(&softc->ipf_timeoutlock);
5738 KMALLOC(ifq, ipftq_t *);
5740 MUTEX_NUKE(&ifq->ifq_lock);
5741 IPFTQ_INIT(ifq, period, "ipftq mutex");
5742 ifq->ifq_next = *parent;
5743 ifq->ifq_pnext = parent;
5744 ifq->ifq_flags = IFQF_USER;
5747 softc->ipf_userifqs++;
5749 MUTEX_EXIT(&softc->ipf_timeoutlock);
5754 /* ------------------------------------------------------------------------ */
5755 /* Function: ipf_deletetimeoutqueue */
5756 /* Returns: int - new reference count value of the timeout queue */
5757 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5758 /* Locks: ifq->ifq_lock */
5760 /* This routine must be called when we're discarding a pointer to a timeout */
5761 /* queue object, taking care of the reference counter. */
5763 /* Now that this just sets a DELETE flag, it requires the expire code to */
5764 /* check the list of user defined timeout queues and call the free function */
5765 /* below (currently commented out) to stop memory leaking. It is done this */
5766 /* way because the locking may not be sufficient to safely do a free when */
5767 /* this function is called. */
5768 /* ------------------------------------------------------------------------ */
5770 ipf_deletetimeoutqueue(ifq)
5775 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5776 ifq->ifq_flags |= IFQF_DELETE;
5779 return ifq->ifq_ref;
5783 /* ------------------------------------------------------------------------ */
5784 /* Function: ipf_freetimeoutqueue */
5785 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5789 /* It is assumed that the caller of this function has an appropriate lock */
5790 /* held (exclusively) in the domain that encompases the callers "domain". */
5791 /* The ifq_lock for this structure should not be held. */
5793 /* Remove a user defined timeout queue from the list of queues it is in and */
5794 /* tidy up after this is done. */
5795 /* ------------------------------------------------------------------------ */
5797 ipf_freetimeoutqueue(softc, ifq)
5798 ipf_main_softc_t *softc;
5802 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5803 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5804 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5805 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5811 * Remove from its position in the list.
5813 *ifq->ifq_pnext = ifq->ifq_next;
5814 if (ifq->ifq_next != NULL)
5815 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5816 ifq->ifq_next = NULL;
5817 ifq->ifq_pnext = NULL;
5819 MUTEX_DESTROY(&ifq->ifq_lock);
5820 ATOMIC_DEC(softc->ipf_userifqs);
5825 /* ------------------------------------------------------------------------ */
5826 /* Function: ipf_deletequeueentry */
5828 /* Parameters: tqe(I) - timeout queue entry to delete */
5830 /* Remove a tail queue entry from its queue and make it an orphan. */
5831 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5832 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5833 /* the correct lock(s) may not be held that would make it safe to do so. */
5834 /* ------------------------------------------------------------------------ */
5836 ipf_deletequeueentry(tqe)
5843 MUTEX_ENTER(&ifq->ifq_lock);
5845 if (tqe->tqe_pnext != NULL) {
5846 *tqe->tqe_pnext = tqe->tqe_next;
5847 if (tqe->tqe_next != NULL)
5848 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5849 else /* we must be the tail anyway */
5850 ifq->ifq_tail = tqe->tqe_pnext;
5852 tqe->tqe_pnext = NULL;
5853 tqe->tqe_ifq = NULL;
5856 (void) ipf_deletetimeoutqueue(ifq);
5857 ASSERT(ifq->ifq_ref > 0);
5859 MUTEX_EXIT(&ifq->ifq_lock);
5863 /* ------------------------------------------------------------------------ */
5864 /* Function: ipf_queuefront */
5866 /* Parameters: tqe(I) - pointer to timeout queue entry */
5868 /* Move a queue entry to the front of the queue, if it isn't already there. */
5869 /* ------------------------------------------------------------------------ */
5880 MUTEX_ENTER(&ifq->ifq_lock);
5881 if (ifq->ifq_head != tqe) {
5882 *tqe->tqe_pnext = tqe->tqe_next;
5884 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5886 ifq->ifq_tail = tqe->tqe_pnext;
5888 tqe->tqe_next = ifq->ifq_head;
5889 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5890 ifq->ifq_head = tqe;
5891 tqe->tqe_pnext = &ifq->ifq_head;
5893 MUTEX_EXIT(&ifq->ifq_lock);
5897 /* ------------------------------------------------------------------------ */
5898 /* Function: ipf_queueback */
5900 /* Parameters: ticks(I) - ipf tick time to use with this call */
5901 /* tqe(I) - pointer to timeout queue entry */
5903 /* Move a queue entry to the back of the queue, if it isn't already there. */
5904 /* We use use ticks to calculate the expiration and mark for when we last */
5905 /* touched the structure. */
5906 /* ------------------------------------------------------------------------ */
5908 ipf_queueback(ticks, tqe)
5917 tqe->tqe_die = ticks + ifq->ifq_ttl;
5918 tqe->tqe_touched = ticks;
5920 MUTEX_ENTER(&ifq->ifq_lock);
5921 if (tqe->tqe_next != NULL) { /* at the end already ? */
5925 *tqe->tqe_pnext = tqe->tqe_next;
5926 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5929 * Make it the last entry.
5931 tqe->tqe_next = NULL;
5932 tqe->tqe_pnext = ifq->ifq_tail;
5933 *ifq->ifq_tail = tqe;
5934 ifq->ifq_tail = &tqe->tqe_next;
5936 MUTEX_EXIT(&ifq->ifq_lock);
5940 /* ------------------------------------------------------------------------ */
5941 /* Function: ipf_queueappend */
5943 /* Parameters: ticks(I) - ipf tick time to use with this call */
5944 /* tqe(I) - pointer to timeout queue entry */
5945 /* ifq(I) - pointer to timeout queue */
5946 /* parent(I) - owing object pointer */
5948 /* Add a new item to this queue and put it on the very end. */
5949 /* We use use ticks to calculate the expiration and mark for when we last */
5950 /* touched the structure. */
5951 /* ------------------------------------------------------------------------ */
5953 ipf_queueappend(ticks, tqe, ifq, parent)
5960 MUTEX_ENTER(&ifq->ifq_lock);
5961 tqe->tqe_parent = parent;
5962 tqe->tqe_pnext = ifq->ifq_tail;
5963 *ifq->ifq_tail = tqe;
5964 ifq->ifq_tail = &tqe->tqe_next;
5965 tqe->tqe_next = NULL;
5967 tqe->tqe_die = ticks + ifq->ifq_ttl;
5968 tqe->tqe_touched = ticks;
5970 MUTEX_EXIT(&ifq->ifq_lock);
5974 /* ------------------------------------------------------------------------ */
5975 /* Function: ipf_movequeue */
5977 /* Parameters: tq(I) - pointer to timeout queue information */
5978 /* oifp(I) - old timeout queue entry was on */
5979 /* nifp(I) - new timeout queue to put entry on */
5981 /* Move a queue entry from one timeout queue to another timeout queue. */
5982 /* If it notices that the current entry is already last and does not need */
5983 /* to move queue, the return. */
5984 /* ------------------------------------------------------------------------ */
5986 ipf_movequeue(ticks, tqe, oifq, nifq)
5989 ipftq_t *oifq, *nifq;
5993 * If the queue hasn't changed and we last touched this entry at the
5994 * same ipf time, then we're not going to achieve anything by either
5995 * changing the ttl or moving it on the queue.
5997 if (oifq == nifq && tqe->tqe_touched == ticks)
6001 * For any of this to be outside the lock, there is a risk that two
6002 * packets entering simultaneously, with one changing to a different
6003 * queue and one not, could end up with things in a bizarre state.
6005 MUTEX_ENTER(&oifq->ifq_lock);
6007 tqe->tqe_touched = ticks;
6008 tqe->tqe_die = ticks + nifq->ifq_ttl;
6010 * Is the operation here going to be a no-op ?
6013 if ((tqe->tqe_next == NULL) ||
6014 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6015 MUTEX_EXIT(&oifq->ifq_lock);
6021 * Remove from the old queue
6023 *tqe->tqe_pnext = tqe->tqe_next;
6025 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6027 oifq->ifq_tail = tqe->tqe_pnext;
6028 tqe->tqe_next = NULL;
6031 * If we're moving from one queue to another, release the
6032 * lock on the old queue and get a lock on the new queue.
6033 * For user defined queues, if we're moving off it, call
6034 * delete in case it can now be freed.
6037 tqe->tqe_ifq = NULL;
6039 (void) ipf_deletetimeoutqueue(oifq);
6041 MUTEX_EXIT(&oifq->ifq_lock);
6043 MUTEX_ENTER(&nifq->ifq_lock);
6045 tqe->tqe_ifq = nifq;
6050 * Add to the bottom of the new queue
6052 tqe->tqe_pnext = nifq->ifq_tail;
6053 *nifq->ifq_tail = tqe;
6054 nifq->ifq_tail = &tqe->tqe_next;
6055 MUTEX_EXIT(&nifq->ifq_lock);
6059 /* ------------------------------------------------------------------------ */
6060 /* Function: ipf_updateipid */
6061 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6062 /* Parameters: fin(I) - pointer to packet information */
6064 /* When we are doing NAT, change the IP of every packet to represent a */
6065 /* single sequence of packets coming from the host, hiding any host */
6066 /* specific sequencing that might otherwise be revealed. If the packet is */
6067 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
6068 /* the fragment cache for non-leading fragments. If a non-leading fragment */
6069 /* has no match in the cache, return an error. */
6070 /* ------------------------------------------------------------------------ */
6075 u_short id, ido, sums;
6079 if (fin->fin_off != 0) {
6080 sum = ipf_frag_ipidknown(fin);
6081 if (sum == 0xffffffff)
6086 id = ipf_nextipid(fin);
6087 if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
6088 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6092 ido = ntohs(ip->ip_id);
6095 ip->ip_id = htons(id);
6096 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6097 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6099 sum = (sum >> 16) + (sum & 0xffff);
6100 sum = (sum >> 16) + (sum & 0xffff);
6101 sums = ~(u_short)sum;
6102 ip->ip_sum = htons(sums);
6107 #ifdef NEED_FRGETIFNAME
6108 /* ------------------------------------------------------------------------ */
6109 /* Function: ipf_getifname */
6110 /* Returns: char * - pointer to interface name */
6111 /* Parameters: ifp(I) - pointer to network interface */
6112 /* buffer(O) - pointer to where to store interface name */
6114 /* Constructs an interface name in the buffer passed. The buffer passed is */
6115 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6116 /* as a NULL pointer then return a pointer to a static array. */
6117 /* ------------------------------------------------------------------------ */
6119 ipf_getifname(ifp, buffer)
6123 static char namebuf[LIFNAMSIZ];
6124 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6125 defined(__sgi) || defined(linux) || defined(_AIX51) || \
6126 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6134 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6135 buffer[LIFNAMSIZ - 1] = '\0';
6136 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6137 defined(__sgi) || defined(_AIX51) || \
6138 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6139 for (s = buffer; *s; s++)
6141 unit = ifp->if_unit;
6142 space = LIFNAMSIZ - (s - buffer);
6143 if ((space > 0) && (unit >= 0)) {
6144 # if defined(SNPRINTF) && defined(_KERNEL)
6145 SNPRINTF(temp, sizeof(temp), "%d", unit);
6147 (void) sprintf(temp, "%d", unit);
6149 (void) strncpy(s, temp, space);
6157 /* ------------------------------------------------------------------------ */
6158 /* Function: ipf_ioctlswitch */
6159 /* Returns: int - -1 continue processing, else ioctl return value */
6160 /* Parameters: unit(I) - device unit opened */
6161 /* data(I) - pointer to ioctl data */
6162 /* cmd(I) - ioctl command */
6163 /* mode(I) - mode value */
6164 /* uid(I) - uid making the ioctl call */
6165 /* ctx(I) - pointer to context data */
6167 /* Based on the value of unit, call the appropriate ioctl handler or return */
6168 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6169 /* for the device in order to execute the ioctl. A special case is made */
6170 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6171 /* The context data pointer is passed through as this is used as the key */
6172 /* for locating a matching token for continued access for walking lists, */
6174 /* ------------------------------------------------------------------------ */
6176 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6177 ipf_main_softc_t *softc;
6178 int unit, mode, uid;
6186 case SIOCIPFINTERROR :
6187 error = BCOPYOUT(&softc->ipf_interror, data,
6188 sizeof(softc->ipf_interror));
6201 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6204 if (softc->ipf_running > 0) {
6205 error = ipf_nat_ioctl(softc, data, cmd, mode,
6213 if (softc->ipf_running > 0) {
6214 error = ipf_state_ioctl(softc, data, cmd, mode,
6222 if (softc->ipf_running > 0) {
6223 error = ipf_auth_ioctl(softc, data, cmd, mode,
6231 if (softc->ipf_running > 0) {
6232 error = ipf_sync_ioctl(softc, data, cmd, mode,
6240 #ifdef IPFILTER_SCAN
6241 if (softc->ipf_running > 0)
6242 error = ipf_scan_ioctl(softc, data, cmd, mode,
6251 case IPL_LOGLOOKUP :
6252 if (softc->ipf_running > 0) {
6253 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6271 * This array defines the expected size of objects coming into the kernel
6272 * for the various recognised object types. The first column is flags (see
6273 * below), 2nd column is current size, 3rd column is the version number of
6274 * when the current size became current.
6276 * 1 = minimum size, not absolute size
6278 static int ipf_objbytes[IPFOBJ_COUNT][3] = {
6279 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6280 { 1, sizeof(struct friostat), 5010000 },
6281 { 0, sizeof(struct fr_info), 5010000 },
6282 { 0, sizeof(struct ipf_authstat), 4010100 },
6283 { 0, sizeof(struct ipfrstat), 5010000 },
6284 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6285 { 0, sizeof(struct natstat), 5010000 },
6286 { 0, sizeof(struct ipstate_save), 5010000 },
6287 { 1, sizeof(struct nat_save), 5010000 },
6288 { 0, sizeof(struct natlookup), 5010000 },
6289 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6290 { 0, sizeof(struct ips_stat), 5010000 },
6291 { 0, sizeof(struct frauth), 5010000 },
6292 { 0, sizeof(struct ipftune), 4010100 },
6293 { 0, sizeof(struct nat), 5010000 },
6294 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6295 { 0, sizeof(struct ipfgeniter), 4011400 },
6296 { 0, sizeof(struct ipftable), 4011400 },
6297 { 0, sizeof(struct ipflookupiter), 4011400 },
6298 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6299 { 1, 0, 0 }, /* IPFEXPR */
6300 { 0, 0, 0 }, /* PROXYCTL */
6301 { 0, sizeof (struct fripf), 5010000 }
6305 /* ------------------------------------------------------------------------ */
6306 /* Function: ipf_inobj */
6307 /* Returns: int - 0 = success, else failure */
6308 /* Parameters: softc(I) - soft context pointerto work with */
6309 /* data(I) - pointer to ioctl data */
6310 /* objp(O) - where to store ipfobj structure */
6311 /* ptr(I) - pointer to data to copy out */
6312 /* type(I) - type of structure being moved */
6314 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6315 /* add things to check for version numbers, sizes, etc, to make it backward */
6316 /* compatible at the ABI for user land. */
6317 /* If objp is not NULL then we assume that the caller wants to see what is */
6318 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6319 /* the caller what version of ipfilter the ioctl program was written to. */
6320 /* ------------------------------------------------------------------------ */
6322 ipf_inobj(softc, data, objp, ptr, type)
6323 ipf_main_softc_t *softc;
6333 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6340 error = BCOPYIN(data, objp, sizeof(*objp));
6346 if (objp->ipfo_type != type) {
6351 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6352 if ((ipf_objbytes[type][0] & 1) != 0) {
6353 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6357 size = ipf_objbytes[type][1];
6358 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6359 size = objp->ipfo_size;
6364 error = COPYIN(objp->ipfo_ptr, ptr, size);
6370 #ifdef IPFILTER_COMPAT
6371 error = ipf_in_compat(softc, objp, ptr, 0);
6381 /* ------------------------------------------------------------------------ */
6382 /* Function: ipf_inobjsz */
6383 /* Returns: int - 0 = success, else failure */
6384 /* Parameters: softc(I) - soft context pointerto work with */
6385 /* data(I) - pointer to ioctl data */
6386 /* ptr(I) - pointer to store real data in */
6387 /* type(I) - type of structure being moved */
6388 /* sz(I) - size of data to copy */
6390 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6391 /* but it must not be smaller than the size defined for the type and the */
6392 /* type must allow for varied sized objects. The extra requirement here is */
6393 /* that sz must match the size of the object being passed in - this is not */
6394 /* not possible nor required in ipf_inobj(). */
6395 /* ------------------------------------------------------------------------ */
6397 ipf_inobjsz(softc, data, ptr, type, sz)
6398 ipf_main_softc_t *softc;
6406 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6411 error = BCOPYIN(data, &obj, sizeof(obj));
6417 if (obj.ipfo_type != type) {
6422 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6423 if (((ipf_objbytes[type][0] & 1) == 0) ||
6424 (sz < ipf_objbytes[type][1])) {
6428 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6434 #ifdef IPFILTER_COMPAT
6435 error = ipf_in_compat(softc, &obj, ptr, sz);
6445 /* ------------------------------------------------------------------------ */
6446 /* Function: ipf_outobjsz */
6447 /* Returns: int - 0 = success, else failure */
6448 /* Parameters: data(I) - pointer to ioctl data */
6449 /* ptr(I) - pointer to store real data in */
6450 /* type(I) - type of structure being moved */
6451 /* sz(I) - size of data to copy */
6453 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6454 /* but it must not be smaller than the size defined for the type and the */
6455 /* type must allow for varied sized objects. The extra requirement here is */
6456 /* that sz must match the size of the object being passed in - this is not */
6457 /* not possible nor required in ipf_outobj(). */
6458 /* ------------------------------------------------------------------------ */
6460 ipf_outobjsz(softc, data, ptr, type, sz)
6461 ipf_main_softc_t *softc;
6469 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6474 error = BCOPYIN(data, &obj, sizeof(obj));
6480 if (obj.ipfo_type != type) {
6485 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6486 if (((ipf_objbytes[type][0] & 1) == 0) ||
6487 (sz < ipf_objbytes[type][1])) {
6491 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6497 #ifdef IPFILTER_COMPAT
6498 error = ipf_out_compat(softc, &obj, ptr);
6508 /* ------------------------------------------------------------------------ */
6509 /* Function: ipf_outobj */
6510 /* Returns: int - 0 = success, else failure */
6511 /* Parameters: data(I) - pointer to ioctl data */
6512 /* ptr(I) - pointer to store real data in */
6513 /* type(I) - type of structure being moved */
6515 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6516 /* future, we add things to check for version numbers, sizes, etc, to make */
6517 /* it backward compatible at the ABI for user land. */
6518 /* ------------------------------------------------------------------------ */
6520 ipf_outobj(softc, data, ptr, type)
6521 ipf_main_softc_t *softc;
6529 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6534 error = BCOPYIN(data, &obj, sizeof(obj));
6540 if (obj.ipfo_type != type) {
6545 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6546 if ((ipf_objbytes[type][0] & 1) != 0) {
6547 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6551 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6556 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6562 #ifdef IPFILTER_COMPAT
6563 error = ipf_out_compat(softc, &obj, ptr);
6573 /* ------------------------------------------------------------------------ */
6574 /* Function: ipf_outobjk */
6575 /* Returns: int - 0 = success, else failure */
6576 /* Parameters: obj(I) - pointer to data description structure */
6577 /* ptr(I) - pointer to kernel data to copy out */
6579 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6580 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6581 /* already populated with information and now we just need to use it. */
6582 /* There is no need for this function to have a "type" parameter as there */
6583 /* is no point in validating information that comes from the kernel with */
6585 /* ------------------------------------------------------------------------ */
6587 ipf_outobjk(softc, obj, ptr)
6588 ipf_main_softc_t *softc;
6592 int type = obj->ipfo_type;
6595 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6600 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6601 if ((ipf_objbytes[type][0] & 1) != 0) {
6602 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6607 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6612 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6618 #ifdef IPFILTER_COMPAT
6619 error = ipf_out_compat(softc, obj, ptr);
6629 /* ------------------------------------------------------------------------ */
6630 /* Function: ipf_checkl4sum */
6631 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6632 /* Parameters: fin(I) - pointer to packet information */
6634 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6635 /* not possible, return without indicating a failure or success but in a */
6636 /* way that is ditinguishable. This function should only be called by the */
6637 /* ipf_checkv6sum() for each platform. */
6638 /* ------------------------------------------------------------------------ */
6643 u_short sum, hdrsum, *csump;
6648 * If the TCP packet isn't a fragment, isn't too short and otherwise
6649 * isn't already considered "bad", then validate the checksum. If
6650 * this check fails then considered the packet to be "bad".
6652 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6655 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6656 if (fin->fin_out == 1) {
6657 fin->fin_cksum = FI_CK_SUMOK;
6669 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6675 if (udp->uh_sum != 0) {
6676 csump = &udp->uh_sum;
6682 case IPPROTO_ICMPV6 :
6683 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6689 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6702 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6704 #if !defined(_KERNEL)
6705 if (sum == hdrsum) {
6706 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6708 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6711 DT2(l4sums, u_short, hdrsum, u_short, sum);
6713 if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6715 if (hdrsum == sum) {
6717 fin->fin_cksum = FI_CK_SUMOK;
6720 fin->fin_cksum = FI_CK_BAD;
6725 /* ------------------------------------------------------------------------ */
6726 /* Function: ipf_ifpfillv4addr */
6727 /* Returns: int - 0 = address update, -1 = address not updated */
6728 /* Parameters: atype(I) - type of network address update to perform */
6729 /* sin(I) - pointer to source of address information */
6730 /* mask(I) - pointer to source of netmask information */
6731 /* inp(I) - pointer to destination address store */
6732 /* inpmask(I) - pointer to destination netmask store */
6734 /* Given a type of network address update (atype) to perform, copy */
6735 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6736 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6737 /* which case the operation fails. For all values of atype other than */
6738 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6740 /* ------------------------------------------------------------------------ */
6742 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6744 struct sockaddr_in *sin, *mask;
6745 struct in_addr *inp, *inpmask;
6747 if (inpmask != NULL && atype != FRI_NETMASKED)
6748 inpmask->s_addr = 0xffffffff;
6750 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6751 if (atype == FRI_NETMASKED) {
6752 if (inpmask == NULL)
6754 inpmask->s_addr = mask->sin_addr.s_addr;
6756 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6758 inp->s_addr = sin->sin_addr.s_addr;
6765 /* ------------------------------------------------------------------------ */
6766 /* Function: ipf_ifpfillv6addr */
6767 /* Returns: int - 0 = address update, -1 = address not updated */
6768 /* Parameters: atype(I) - type of network address update to perform */
6769 /* sin(I) - pointer to source of address information */
6770 /* mask(I) - pointer to source of netmask information */
6771 /* inp(I) - pointer to destination address store */
6772 /* inpmask(I) - pointer to destination netmask store */
6774 /* Given a type of network address update (atype) to perform, copy */
6775 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6776 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6777 /* which case the operation fails. For all values of atype other than */
6778 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6780 /* ------------------------------------------------------------------------ */
6782 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6784 struct sockaddr_in6 *sin, *mask;
6785 i6addr_t *inp, *inpmask;
6787 i6addr_t *src, *and;
6789 src = (i6addr_t *)&sin->sin6_addr;
6790 and = (i6addr_t *)&mask->sin6_addr;
6792 if (inpmask != NULL && atype != FRI_NETMASKED) {
6793 inpmask->i6[0] = 0xffffffff;
6794 inpmask->i6[1] = 0xffffffff;
6795 inpmask->i6[2] = 0xffffffff;
6796 inpmask->i6[3] = 0xffffffff;
6799 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6800 if (atype == FRI_NETMASKED) {
6801 if (inpmask == NULL)
6803 inpmask->i6[0] = and->i6[0];
6804 inpmask->i6[1] = and->i6[1];
6805 inpmask->i6[2] = and->i6[2];
6806 inpmask->i6[3] = and->i6[3];
6809 inp->i6[0] = src->i6[0] & and->i6[0];
6810 inp->i6[1] = src->i6[1] & and->i6[1];
6811 inp->i6[2] = src->i6[2] & and->i6[2];
6812 inp->i6[3] = src->i6[3] & and->i6[3];
6814 inp->i6[0] = src->i6[0];
6815 inp->i6[1] = src->i6[1];
6816 inp->i6[2] = src->i6[2];
6817 inp->i6[3] = src->i6[3];
6824 /* ------------------------------------------------------------------------ */
6825 /* Function: ipf_matchtag */
6826 /* Returns: 0 == mismatch, 1 == match. */
6827 /* Parameters: tag1(I) - pointer to first tag to compare */
6828 /* tag2(I) - pointer to second tag to compare */
6830 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6831 /* considered to be a match or not match, respectively. The tag is 16 */
6832 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6833 /* compare the ints instead, for speed. tag1 is the master of the */
6834 /* comparison. This function should only be called with both tag1 and tag2 */
6835 /* as non-NULL pointers. */
6836 /* ------------------------------------------------------------------------ */
6838 ipf_matchtag(tag1, tag2)
6839 ipftag_t *tag1, *tag2;
6844 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6847 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6848 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6849 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6850 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6856 /* ------------------------------------------------------------------------ */
6857 /* Function: ipf_coalesce */
6858 /* Returns: 1 == success, -1 == failure, 0 == no change */
6859 /* Parameters: fin(I) - pointer to packet information */
6861 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6862 /* If this call returns a failure then the buffers have also been freed. */
6863 /* ------------------------------------------------------------------------ */
6869 if ((fin->fin_flx & FI_COALESCE) != 0)
6873 * If the mbuf pointers indicate that there is no mbuf to work with,
6874 * return but do not indicate success or failure.
6876 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6879 #if defined(_KERNEL)
6880 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6881 ipf_main_softc_t *softc = fin->fin_main_soft;
6883 DT1(frb_coalesce, fr_info_t *, fin);
6884 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6886 FREE_MB_T(*fin->fin_mp);
6888 fin->fin_reason = FRB_COALESCE;
6889 *fin->fin_mp = NULL;
6894 fin = fin; /* LINT */
6901 * The following table lists all of the tunable variables that can be
6902 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6903 * in the table below is as follows:
6905 * pointer to value, name of value, minimum, maximum, size of the value's
6906 * container, value attribute flags
6908 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6909 * means the value can only be written to when IPFilter is loaded but disabled.
6910 * The obvious implication is if neither of these are set then the value can be
6911 * changed at any time without harm.
6915 /* ------------------------------------------------------------------------ */
6916 /* Function: ipf_tune_findbycookie */
6917 /* Returns: NULL = search failed, else pointer to tune struct */
6918 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6919 /* next(O) - pointer to place to store the cookie for the */
6920 /* "next" tuneable, if it is desired. */
6922 /* This function is used to walk through all of the existing tunables with */
6923 /* successive calls. It searches the known tunables for the one which has */
6924 /* a matching value for "cookie" - ie its address. When returning a match, */
6925 /* the next one to be found may be returned inside next. */
6926 /* ------------------------------------------------------------------------ */
6927 static ipftuneable_t *
6928 ipf_tune_findbycookie(ptop, cookie, next)
6929 ipftuneable_t **ptop;
6930 void *cookie, **next;
6932 ipftuneable_t *ta, **tap;
6934 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6938 * If the next entry in the array has a name
6939 * present, then return a pointer to it for
6940 * where to go next, else return a pointer to
6941 * the dynaminc list as a key to search there
6942 * next. This facilitates a weak linking of
6943 * the two "lists" together.
6945 if ((ta + 1)->ipft_name != NULL)
6953 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6954 if (tap == cookie) {
6956 *next = &ta->ipft_next;
6966 /* ------------------------------------------------------------------------ */
6967 /* Function: ipf_tune_findbyname */
6968 /* Returns: NULL = search failed, else pointer to tune struct */
6969 /* Parameters: name(I) - name of the tuneable entry to find. */
6971 /* Search the static array of tuneables and the list of dynamic tuneables */
6972 /* for an entry with a matching name. If we can find one, return a pointer */
6973 /* to the matching structure. */
6974 /* ------------------------------------------------------------------------ */
6975 static ipftuneable_t *
6976 ipf_tune_findbyname(top, name)
6982 for (ta = top; ta != NULL; ta = ta->ipft_next)
6983 if (!strcmp(ta->ipft_name, name)) {
6991 /* ------------------------------------------------------------------------ */
6992 /* Function: ipf_tune_add_array */
6993 /* Returns: int - 0 == success, else failure */
6994 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6996 /* Appends tune structures from the array passed in (newtune) to the end of */
6997 /* the current list of "dynamic" tuneable parameters. */
6998 /* If any entry to be added is already present (by name) then the operation */
6999 /* is aborted - entries that have been added are removed before returning. */
7000 /* An entry with no name (NULL) is used as the indication that the end of */
7001 /* the array has been reached. */
7002 /* ------------------------------------------------------------------------ */
7004 ipf_tune_add_array(softc, newtune)
7005 ipf_main_softc_t *softc;
7006 ipftuneable_t *newtune;
7008 ipftuneable_t *nt, *dt;
7011 for (nt = newtune; nt->ipft_name != NULL; nt++) {
7012 error = ipf_tune_add(softc, nt);
7014 for (dt = newtune; dt != nt; dt++) {
7015 (void) ipf_tune_del(softc, dt);
7024 /* ------------------------------------------------------------------------ */
7025 /* Function: ipf_tune_array_link */
7026 /* Returns: 0 == success, -1 == failure */
7027 /* Parameters: softc(I) - soft context pointerto work with */
7028 /* array(I) - pointer to an array of tuneables */
7030 /* Given an array of tunables (array), append them to the current list of */
7031 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7032 /* the array for being appended to the list, initialise all of the next */
7033 /* pointers so we don't need to walk parts of it with ++ and others with */
7034 /* next. The array is expected to have an entry with a NULL name as the */
7035 /* terminator. Trying to add an array with no non-NULL names will return as */
7037 /* ------------------------------------------------------------------------ */
7039 ipf_tune_array_link(softc, array)
7040 ipf_main_softc_t *softc;
7041 ipftuneable_t *array;
7043 ipftuneable_t *t, **p;
7046 if (t->ipft_name == NULL)
7049 for (; t[1].ipft_name != NULL; t++)
7050 t[0].ipft_next = &t[1];
7051 t->ipft_next = NULL;
7054 * Since a pointer to the last entry isn't kept, we need to find it
7055 * each time we want to add new variables to the list.
7057 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7058 if (t->ipft_name == NULL)
7066 /* ------------------------------------------------------------------------ */
7067 /* Function: ipf_tune_array_unlink */
7068 /* Returns: 0 == success, -1 == failure */
7069 /* Parameters: softc(I) - soft context pointerto work with */
7070 /* array(I) - pointer to an array of tuneables */
7072 /* ------------------------------------------------------------------------ */
7074 ipf_tune_array_unlink(softc, array)
7075 ipf_main_softc_t *softc;
7076 ipftuneable_t *array;
7078 ipftuneable_t *t, **p;
7080 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7086 for (; t[1].ipft_name != NULL; t++)
7095 /* ------------------------------------------------------------------------ */
7096 /* Function: ipf_tune_array_copy */
7097 /* Returns: NULL = failure, else pointer to new array */
7098 /* Parameters: base(I) - pointer to structure base */
7099 /* size(I) - size of the array at template */
7100 /* template(I) - original array to copy */
7102 /* Allocate memory for a new set of tuneable values and copy everything */
7103 /* from template into the new region of memory. The new region is full of */
7104 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7106 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7107 /* In the array template, ipftp_offset is the offset (in bytes) of the */
7108 /* location of the tuneable value inside the structure pointed to by base. */
7109 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
7110 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7111 /* ipftp_void that points to the stored value. */
7112 /* ------------------------------------------------------------------------ */
7114 ipf_tune_array_copy(base, size, template)
7117 ipftuneable_t *template;
7119 ipftuneable_t *copy;
7123 KMALLOCS(copy, ipftuneable_t *, size);
7127 bcopy(template, copy, size);
7129 for (i = 0; copy[i].ipft_name; i++) {
7130 copy[i].ipft_una.ipftp_offset += (u_long)base;
7131 copy[i].ipft_next = copy + i + 1;
7138 /* ------------------------------------------------------------------------ */
7139 /* Function: ipf_tune_add */
7140 /* Returns: int - 0 == success, else failure */
7141 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7143 /* Appends tune structures from the array passed in (newtune) to the end of */
7144 /* the current list of "dynamic" tuneable parameters. Once added, the */
7145 /* owner of the object is not expected to ever change "ipft_next". */
7146 /* ------------------------------------------------------------------------ */
7148 ipf_tune_add(softc, newtune)
7149 ipf_main_softc_t *softc;
7150 ipftuneable_t *newtune;
7152 ipftuneable_t *ta, **tap;
7154 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7160 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7163 newtune->ipft_next = NULL;
7169 /* ------------------------------------------------------------------------ */
7170 /* Function: ipf_tune_del */
7171 /* Returns: int - 0 == success, else failure */
7172 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7173 /* current dynamic tuneables */
7175 /* Search for the tune structure, by pointer, in the list of those that are */
7176 /* dynamically added at run time. If found, adjust the list so that this */
7177 /* structure is no longer part of it. */
7178 /* ------------------------------------------------------------------------ */
7180 ipf_tune_del(softc, oldtune)
7181 ipf_main_softc_t *softc;
7182 ipftuneable_t *oldtune;
7184 ipftuneable_t *ta, **tap;
7187 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7188 tap = &ta->ipft_next) {
7189 if (ta == oldtune) {
7190 *tap = oldtune->ipft_next;
7191 oldtune->ipft_next = NULL;
7204 /* ------------------------------------------------------------------------ */
7205 /* Function: ipf_tune_del_array */
7206 /* Returns: int - 0 == success, else failure */
7207 /* Parameters: oldtune - pointer to tuneables array */
7209 /* Remove each tuneable entry in the array from the list of "dynamic" */
7210 /* tunables. If one entry should fail to be found, an error will be */
7211 /* returned and no further ones removed. */
7212 /* An entry with a NULL name is used as the indicator of the last entry in */
7214 /* ------------------------------------------------------------------------ */
7216 ipf_tune_del_array(softc, oldtune)
7217 ipf_main_softc_t *softc;
7218 ipftuneable_t *oldtune;
7223 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7224 error = ipf_tune_del(softc, ot);
7234 /* ------------------------------------------------------------------------ */
7235 /* Function: ipf_tune */
7236 /* Returns: int - 0 == success, else failure */
7237 /* Parameters: cmd(I) - ioctl command number */
7238 /* data(I) - pointer to ioctl data structure */
7240 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7241 /* three ioctls provide the means to access and control global variables */
7242 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7243 /* changed without rebooting, reloading or recompiling. The initialisation */
7244 /* and 'destruction' routines of the various components of ipfilter are all */
7245 /* each responsible for handling their own values being too big. */
7246 /* ------------------------------------------------------------------------ */
7248 ipf_ipftune(softc, cmd, data)
7249 ipf_main_softc_t *softc;
7258 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7262 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7263 cookie = tu.ipft_cookie;
7268 case SIOCIPFGETNEXT :
7270 * If cookie is non-NULL, assume it to be a pointer to the last
7271 * entry we looked at, so find it (if possible) and return a
7272 * pointer to the next one after it. The last entry in the
7273 * the table is a NULL entry, so when we get to it, set cookie
7274 * to NULL and return that, indicating end of list, erstwhile
7275 * if we come in with cookie set to NULL, we are starting anew
7276 * at the front of the list.
7278 if (cookie != NULL) {
7279 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7280 cookie, &tu.ipft_cookie);
7282 ta = softc->ipf_tuners;
7283 tu.ipft_cookie = ta + 1;
7287 * Entry found, but does the data pointed to by that
7288 * row fit in what we can return?
7290 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7296 if (ta->ipft_sz == sizeof(u_long))
7297 tu.ipft_vlong = *ta->ipft_plong;
7298 else if (ta->ipft_sz == sizeof(u_int))
7299 tu.ipft_vint = *ta->ipft_pint;
7300 else if (ta->ipft_sz == sizeof(u_short))
7301 tu.ipft_vshort = *ta->ipft_pshort;
7302 else if (ta->ipft_sz == sizeof(u_char))
7303 tu.ipft_vchar = *ta->ipft_pchar;
7305 tu.ipft_sz = ta->ipft_sz;
7306 tu.ipft_min = ta->ipft_min;
7307 tu.ipft_max = ta->ipft_max;
7308 tu.ipft_flags = ta->ipft_flags;
7309 bcopy(ta->ipft_name, tu.ipft_name,
7310 MIN(sizeof(tu.ipft_name),
7311 strlen(ta->ipft_name) + 1));
7313 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7319 * Search by name or by cookie value for a particular entry
7320 * in the tuning paramter table.
7324 if (cookie != NULL) {
7325 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7329 } else if (tu.ipft_name[0] != '\0') {
7330 ta = ipf_tune_findbyname(softc->ipf_tuners,
7338 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7340 * Fetch the tuning parameters for a particular value
7343 if (ta->ipft_sz == sizeof(u_long))
7344 tu.ipft_vlong = *ta->ipft_plong;
7345 else if (ta->ipft_sz == sizeof(u_int))
7346 tu.ipft_vint = *ta->ipft_pint;
7347 else if (ta->ipft_sz == sizeof(u_short))
7348 tu.ipft_vshort = *ta->ipft_pshort;
7349 else if (ta->ipft_sz == sizeof(u_char))
7350 tu.ipft_vchar = *ta->ipft_pchar;
7351 tu.ipft_cookie = ta;
7352 tu.ipft_sz = ta->ipft_sz;
7353 tu.ipft_min = ta->ipft_min;
7354 tu.ipft_max = ta->ipft_max;
7355 tu.ipft_flags = ta->ipft_flags;
7356 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7358 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7360 * Set an internal parameter. The hard part here is
7361 * getting the new value safely and correctly out of
7362 * the kernel (given we only know its size, not type.)
7366 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7367 (softc->ipf_running > 0)) {
7374 if (in < ta->ipft_min || in > ta->ipft_max) {
7380 if (ta->ipft_func != NULL) {
7384 error = (*ta->ipft_func)(softc, ta,
7388 } else if (ta->ipft_sz == sizeof(u_long)) {
7389 tu.ipft_vlong = *ta->ipft_plong;
7390 *ta->ipft_plong = in;
7392 } else if (ta->ipft_sz == sizeof(u_int)) {
7393 tu.ipft_vint = *ta->ipft_pint;
7394 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7396 } else if (ta->ipft_sz == sizeof(u_short)) {
7397 tu.ipft_vshort = *ta->ipft_pshort;
7398 *ta->ipft_pshort = (u_short)(in & 0xffff);
7400 } else if (ta->ipft_sz == sizeof(u_char)) {
7401 tu.ipft_vchar = *ta->ipft_pchar;
7402 *ta->ipft_pchar = (u_char)(in & 0xff);
7404 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7418 /* ------------------------------------------------------------------------ */
7419 /* Function: ipf_zerostats */
7420 /* Returns: int - 0 = success, else failure */
7421 /* Parameters: data(O) - pointer to pointer for copying data back to */
7423 /* Copies the current statistics out to userspace and then zero's the */
7424 /* current ones in the kernel. The lock is only held across the bzero() as */
7425 /* the copyout may result in paging (ie network activity.) */
7426 /* ------------------------------------------------------------------------ */
7428 ipf_zerostats(softc, data)
7429 ipf_main_softc_t *softc;
7436 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7439 ipf_getstat(softc, &fio, obj.ipfo_rev);
7440 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7444 WRITE_ENTER(&softc->ipf_mutex);
7445 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7446 RWLOCK_EXIT(&softc->ipf_mutex);
7452 /* ------------------------------------------------------------------------ */
7453 /* Function: ipf_resolvedest */
7455 /* Parameters: softc(I) - pointer to soft context main structure */
7456 /* base(I) - where strings are stored */
7457 /* fdp(IO) - pointer to destination information to resolve */
7458 /* v(I) - IP protocol version to match */
7460 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7461 /* if a matching name can be found for the particular IP protocol version */
7462 /* then store the interface pointer in the frdest struct. If no match is */
7463 /* found, then set the interface pointer to be -1 as NULL is considered to */
7464 /* indicate there is no information at all in the structure. */
7465 /* ------------------------------------------------------------------------ */
7467 ipf_resolvedest(softc, base, fdp, v)
7468 ipf_main_softc_t *softc;
7478 if (fdp->fd_name != -1) {
7479 if (fdp->fd_type == FRD_DSTLIST) {
7480 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7482 base + fdp->fd_name,
7489 ifp = GETIFP(base + fdp->fd_name, v);
7496 if ((ifp != NULL) && (ifp != (void *)-1)) {
7497 fdp->fd_local = ipf_deliverlocal(softc, v, ifp, &fdp->fd_ip6);
7504 /* ------------------------------------------------------------------------ */
7505 /* Function: ipf_resolvenic */
7506 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7507 /* pointer to interface structure for NIC */
7508 /* Parameters: softc(I)- pointer to soft context main structure */
7509 /* name(I) - complete interface name */
7510 /* v(I) - IP protocol version */
7512 /* Look for a network interface structure that firstly has a matching name */
7513 /* to that passed in and that is also being used for that IP protocol */
7514 /* version (necessary on some platforms where there are separate listings */
7515 /* for both IPv4 and IPv6 on the same physical NIC. */
7516 /* ------------------------------------------------------------------------ */
7518 ipf_resolvenic(softc, name, v)
7519 ipf_main_softc_t *softc;
7525 softc = softc; /* gcc -Wextra */
7526 if (name[0] == '\0')
7529 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7533 nic = GETIFP(name, v);
7540 /* ------------------------------------------------------------------------ */
7541 /* Function: ipf_token_expire */
7542 /* Returns: None. */
7543 /* Parameters: softc(I) - pointer to soft context main structure */
7545 /* This function is run every ipf tick to see if there are any tokens that */
7546 /* have been held for too long and need to be freed up. */
7547 /* ------------------------------------------------------------------------ */
7549 ipf_token_expire(softc)
7550 ipf_main_softc_t *softc;
7554 WRITE_ENTER(&softc->ipf_tokens);
7555 while ((it = softc->ipf_token_head) != NULL) {
7556 if (it->ipt_die > softc->ipf_ticks)
7559 ipf_token_deref(softc, it);
7561 RWLOCK_EXIT(&softc->ipf_tokens);
7565 /* ------------------------------------------------------------------------ */
7566 /* Function: ipf_token_flush */
7567 /* Returns: None. */
7568 /* Parameters: softc(I) - pointer to soft context main structure */
7570 /* Loop through all of the existing tokens and call deref to see if they */
7571 /* can be freed. Normally a function like this might just loop on */
7572 /* ipf_token_head but there is a chance that a token might have a ref count */
7573 /* of greater than one and in that case the the reference would drop twice */
7574 /* by code that is only entitled to drop it once. */
7575 /* ------------------------------------------------------------------------ */
7577 ipf_token_flush(softc)
7578 ipf_main_softc_t *softc;
7580 ipftoken_t *it, *next;
7582 WRITE_ENTER(&softc->ipf_tokens);
7583 for (it = softc->ipf_token_head; it != NULL; it = next) {
7584 next = it->ipt_next;
7585 (void) ipf_token_deref(softc, it);
7587 RWLOCK_EXIT(&softc->ipf_tokens);
7591 /* ------------------------------------------------------------------------ */
7592 /* Function: ipf_token_del */
7593 /* Returns: int - 0 = success, else error */
7594 /* Parameters: softc(I)- pointer to soft context main structure */
7595 /* type(I) - the token type to match */
7596 /* uid(I) - uid owning the token */
7597 /* ptr(I) - context pointer for the token */
7599 /* This function looks for a a token in the current list that matches up */
7600 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7601 /* call ipf_token_dewref() to remove it from the list. In the event that */
7602 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7603 /* enables debugging to distinguish between the two paths that ultimately */
7604 /* lead to a token to be deleted. */
7605 /* ------------------------------------------------------------------------ */
7607 ipf_token_del(softc, type, uid, ptr)
7608 ipf_main_softc_t *softc;
7618 WRITE_ENTER(&softc->ipf_tokens);
7619 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7620 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7621 uid == it->ipt_uid) {
7622 it->ipt_complete = 2;
7623 ipf_token_deref(softc, it);
7628 RWLOCK_EXIT(&softc->ipf_tokens);
7634 /* ------------------------------------------------------------------------ */
7635 /* Function: ipf_token_mark_complete */
7636 /* Returns: None. */
7637 /* Parameters: token(I) - pointer to token structure */
7639 /* Mark a token as being ineligable for being found with ipf_token_find. */
7640 /* ------------------------------------------------------------------------ */
7642 ipf_token_mark_complete(token)
7645 if (token->ipt_complete == 0)
7646 token->ipt_complete = 1;
7650 /* ------------------------------------------------------------------------ */
7651 /* Function: ipf_token_find */
7652 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7653 /* Parameters: softc(I)- pointer to soft context main structure */
7654 /* type(I) - the token type to match */
7655 /* uid(I) - uid owning the token */
7656 /* ptr(I) - context pointer for the token */
7658 /* This function looks for a live token in the list of current tokens that */
7659 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7660 /* allocated. If one is found then it is moved to the top of the list of */
7661 /* currently active tokens. */
7662 /* ------------------------------------------------------------------------ */
7664 ipf_token_find(softc, type, uid, ptr)
7665 ipf_main_softc_t *softc;
7669 ipftoken_t *it, *new;
7671 KMALLOC(new, ipftoken_t *);
7673 bzero((char *)new, sizeof(*new));
7675 WRITE_ENTER(&softc->ipf_tokens);
7676 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7677 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7678 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7686 RWLOCK_EXIT(&softc->ipf_tokens);
7691 it->ipt_type = type;
7699 if (it->ipt_complete > 0)
7702 ipf_token_unlink(softc, it);
7706 it->ipt_pnext = softc->ipf_token_tail;
7707 *softc->ipf_token_tail = it;
7708 softc->ipf_token_tail = &it->ipt_next;
7709 it->ipt_next = NULL;
7712 it->ipt_die = softc->ipf_ticks + 20;
7715 RWLOCK_EXIT(&softc->ipf_tokens);
7721 /* ------------------------------------------------------------------------ */
7722 /* Function: ipf_token_unlink */
7723 /* Returns: None. */
7724 /* Parameters: softc(I) - pointer to soft context main structure */
7725 /* token(I) - pointer to token structure */
7726 /* Write Locks: ipf_tokens */
7728 /* This function unlinks a token structure from the linked list of tokens */
7729 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7730 /* but the tail does due to the linked list implementation. */
7731 /* ------------------------------------------------------------------------ */
7733 ipf_token_unlink(softc, token)
7734 ipf_main_softc_t *softc;
7738 if (softc->ipf_token_tail == &token->ipt_next)
7739 softc->ipf_token_tail = token->ipt_pnext;
7741 *token->ipt_pnext = token->ipt_next;
7742 if (token->ipt_next != NULL)
7743 token->ipt_next->ipt_pnext = token->ipt_pnext;
7744 token->ipt_next = NULL;
7745 token->ipt_pnext = NULL;
7749 /* ------------------------------------------------------------------------ */
7750 /* Function: ipf_token_deref */
7751 /* Returns: int - 0 == token freed, else reference count */
7752 /* Parameters: softc(I) - pointer to soft context main structure */
7753 /* token(I) - pointer to token structure */
7754 /* Write Locks: ipf_tokens */
7756 /* Drop the reference count on the token structure and if it drops to zero, */
7757 /* call the dereference function for the token type because it is then */
7758 /* possible to free the token data structure. */
7759 /* ------------------------------------------------------------------------ */
7761 ipf_token_deref(softc, token)
7762 ipf_main_softc_t *softc;
7765 void *data, **datap;
7767 ASSERT(token->ipt_ref > 0);
7769 if (token->ipt_ref > 0)
7770 return token->ipt_ref;
7772 data = token->ipt_data;
7775 if ((data != NULL) && (data != (void *)-1)) {
7776 switch (token->ipt_type)
7778 case IPFGENITER_IPF :
7779 (void) ipf_derefrule(softc, (frentry_t **)datap);
7781 case IPFGENITER_IPNAT :
7782 WRITE_ENTER(&softc->ipf_nat);
7783 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7784 RWLOCK_EXIT(&softc->ipf_nat);
7786 case IPFGENITER_NAT :
7787 ipf_nat_deref(softc, (nat_t **)datap);
7789 case IPFGENITER_STATE :
7790 ipf_state_deref(softc, (ipstate_t **)datap);
7792 case IPFGENITER_FRAG :
7793 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7795 case IPFGENITER_NATFRAG :
7796 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7798 case IPFGENITER_HOSTMAP :
7799 WRITE_ENTER(&softc->ipf_nat);
7800 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7801 RWLOCK_EXIT(&softc->ipf_nat);
7804 ipf_lookup_iterderef(softc, token->ipt_type, data);
7809 ipf_token_unlink(softc, token);
7815 /* ------------------------------------------------------------------------ */
7816 /* Function: ipf_nextrule */
7817 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7818 /* Parameters: softc(I) - pointer to soft context main structure */
7819 /* fr(I) - pointer to filter rule */
7820 /* out(I) - 1 == out rules, 0 == input rules */
7822 /* Starting with "fr", find the next rule to visit. This includes visiting */
7823 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7824 /* last rule in the list. When walking rule lists, it is either input or */
7825 /* output rules that are returned, never both. */
7826 /* ------------------------------------------------------------------------ */
7828 ipf_nextrule(softc, active, unit, fr, out)
7829 ipf_main_softc_t *softc;
7837 if (fr != NULL && fr->fr_group != -1) {
7838 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7839 unit, active, NULL);
7843 fg = softc->ipf_groups[unit][active];
7846 while (fg != NULL) {
7847 next = fg->fg_start;
7848 while (next != NULL) {
7850 if (next->fr_flags & FR_OUTQUE)
7852 } else if (next->fr_flags & FR_INQUE) {
7855 next = next->fr_next;
7864 /* ------------------------------------------------------------------------ */
7865 /* Function: ipf_getnextrule */
7866 /* Returns: int - 0 = success, else error */
7867 /* Parameters: softc(I)- pointer to soft context main structure */
7868 /* t(I) - pointer to destination information to resolve */
7869 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7871 /* This function's first job is to bring in the ipfruleiter_t structure via */
7872 /* the ipfobj_t structure to determine what should be the next rule to */
7873 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7874 /* find the 'next rule'. This may include searching rule group lists or */
7875 /* just be as simple as looking at the 'next' field in the rule structure. */
7876 /* When we have found the rule to return, increase its reference count and */
7877 /* if we used an existing rule to get here, decrease its reference count. */
7878 /* ------------------------------------------------------------------------ */
7880 ipf_getnextrule(softc, t, ptr)
7881 ipf_main_softc_t *softc;
7885 frentry_t *fr, *next, zero;
7894 if (t == NULL || ptr == NULL) {
7899 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7903 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7907 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7911 if (it.iri_nrules == 0) {
7915 if (it.iri_rule == NULL) {
7922 if ((it.iri_inout & F_OUT) != 0)
7926 if ((it.iri_inout & F_ACIN) != 0)
7927 unit = IPL_LOGCOUNT;
7931 READ_ENTER(&softc->ipf_mutex);
7933 if (*it.iri_group == '\0') {
7934 if (unit == IPL_LOGCOUNT) {
7935 next = softc->ipf_acct[out][it.iri_active];
7937 next = softc->ipf_rules[out][it.iri_active];
7940 next = ipf_nextrule(softc, it.iri_active,
7943 fg = ipf_findgroup(softc, it.iri_group, unit,
7944 it.iri_active, NULL);
7946 next = fg->fg_start;
7953 next = ipf_nextrule(softc, it.iri_active, unit,
7957 if (next != NULL && next->fr_next != NULL)
7959 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7965 (void) ipf_derefrule(softc, &fr);
7967 obj.ipfo_type = IPFOBJ_FRENTRY;
7968 dst = (char *)it.iri_rule;
7971 obj.ipfo_size = next->fr_size;
7972 MUTEX_ENTER(&next->fr_lock);
7974 MUTEX_EXIT(&next->fr_lock);
7977 obj.ipfo_size = sizeof(frentry_t);
7978 bzero(&zero, sizeof(zero));
7982 it.iri_rule = predict ? next : NULL;
7984 ipf_token_mark_complete(t);
7986 RWLOCK_EXIT(&softc->ipf_mutex);
7989 error = ipf_outobjk(softc, &obj, next);
7990 if (error == 0 && t->ipt_data != NULL) {
7991 dst += obj.ipfo_size;
7992 if (next->fr_data != NULL) {
7995 if (next->fr_type == FR_T_IPFEXPR)
7996 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7998 dobj.ipfo_type = IPFOBJ_FRIPF;
7999 dobj.ipfo_size = next->fr_dsize;
8000 dobj.ipfo_rev = obj.ipfo_rev;
8001 dobj.ipfo_ptr = dst;
8002 error = ipf_outobjk(softc, &dobj, next->fr_data);
8006 if ((fr != NULL) && (next == &zero))
8007 (void) ipf_derefrule(softc, &fr);
8013 /* ------------------------------------------------------------------------ */
8014 /* Function: ipf_frruleiter */
8015 /* Returns: int - 0 = success, else error */
8016 /* Parameters: softc(I)- pointer to soft context main structure */
8017 /* data(I) - the token type to match */
8018 /* uid(I) - uid owning the token */
8019 /* ptr(I) - context pointer for the token */
8021 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
8022 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
8023 /* the process doing the ioctl and use that to ask for the next rule. */
8024 /* ------------------------------------------------------------------------ */
8026 ipf_frruleiter(softc, data, uid, ctx)
8027 ipf_main_softc_t *softc;
8036 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8037 if (token != NULL) {
8038 error = ipf_getnextrule(softc, token, data);
8039 WRITE_ENTER(&softc->ipf_tokens);
8040 ipf_token_deref(softc, token);
8041 RWLOCK_EXIT(&softc->ipf_tokens);
8043 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8047 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8054 /* ------------------------------------------------------------------------ */
8055 /* Function: ipf_geniter */
8056 /* Returns: int - 0 = success, else error */
8057 /* Parameters: softc(I) - pointer to soft context main structure */
8058 /* token(I) - pointer to ipftoken_t structure */
8059 /* itp(I) - pointer to iterator data */
8061 /* Decide which iterator function to call using information passed through */
8062 /* the ipfgeniter_t structure at itp. */
8063 /* ------------------------------------------------------------------------ */
8065 ipf_geniter(softc, token, itp)
8066 ipf_main_softc_t *softc;
8072 switch (itp->igi_type)
8074 case IPFGENITER_FRAG :
8075 error = ipf_frag_pkt_next(softc, token, itp);
8087 /* ------------------------------------------------------------------------ */
8088 /* Function: ipf_genericiter */
8089 /* Returns: int - 0 = success, else error */
8090 /* Parameters: softc(I)- pointer to soft context main structure */
8091 /* data(I) - the token type to match */
8092 /* uid(I) - uid owning the token */
8093 /* ptr(I) - context pointer for the token */
8095 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8096 /* ------------------------------------------------------------------------ */
8098 ipf_genericiter(softc, data, uid, ctx)
8099 ipf_main_softc_t *softc;
8107 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8111 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8112 if (token != NULL) {
8113 token->ipt_subtype = iter.igi_type;
8114 error = ipf_geniter(softc, token, &iter);
8115 WRITE_ENTER(&softc->ipf_tokens);
8116 ipf_token_deref(softc, token);
8117 RWLOCK_EXIT(&softc->ipf_tokens);
8127 /* ------------------------------------------------------------------------ */
8128 /* Function: ipf_ipf_ioctl */
8129 /* Returns: int - 0 = success, else error */
8130 /* Parameters: softc(I)- pointer to soft context main structure */
8131 /* data(I) - the token type to match */
8132 /* cmd(I) - the ioctl command number */
8133 /* mode(I) - mode flags for the ioctl */
8134 /* uid(I) - uid owning the token */
8135 /* ptr(I) - context pointer for the token */
8137 /* This function handles all of the ioctl command that are actually isssued */
8138 /* to the /dev/ipl device. */
8139 /* ------------------------------------------------------------------------ */
8141 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8142 ipf_main_softc_t *softc;
8156 if (!(mode & FWRITE)) {
8160 error = BCOPYIN(data, &tmp, sizeof(tmp));
8167 WRITE_ENTER(&softc->ipf_global);
8169 if (softc->ipf_running > 0)
8172 error = ipfattach(softc);
8174 softc->ipf_running = 1;
8176 (void) ipfdetach(softc);
8178 if (softc->ipf_running == 1)
8179 error = ipfdetach(softc);
8183 softc->ipf_running = -1;
8185 RWLOCK_EXIT(&softc->ipf_global);
8190 if (!(mode & FWRITE)) {
8196 case SIOCIPFGETNEXT :
8198 error = ipf_ipftune(softc, cmd, (void *)data);
8202 if (!(mode & FWRITE)) {
8206 error = BCOPYIN(data, &softc->ipf_flags,
8207 sizeof(softc->ipf_flags));
8216 error = BCOPYOUT(&softc->ipf_flags, data,
8217 sizeof(softc->ipf_flags));
8225 error = ipf_resolvefunc(softc, (void *)data);
8232 if (!(mode & FWRITE)) {
8236 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8237 softc->ipf_active, 1);
8244 if (!(mode & FWRITE)) {
8248 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8249 1 - softc->ipf_active, 1);
8254 if (!(mode & FWRITE)) {
8258 WRITE_ENTER(&softc->ipf_mutex);
8259 error = BCOPYOUT(&softc->ipf_active, data,
8260 sizeof(softc->ipf_active));
8265 softc->ipf_active = 1 - softc->ipf_active;
8267 RWLOCK_EXIT(&softc->ipf_mutex);
8272 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8276 ipf_getstat(softc, &fio, obj.ipfo_rev);
8277 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8281 if (!(mode & FWRITE)) {
8285 error = ipf_zerostats(softc, (caddr_t)data);
8289 if (!(mode & FWRITE)) {
8293 error = BCOPYIN(data, &tmp, sizeof(tmp));
8295 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8296 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8310 if (!(mode & FWRITE)) {
8314 error = BCOPYIN(data, &tmp, sizeof(tmp));
8316 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8317 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8331 if (!(mode & FWRITE)) {
8335 error = BCOPYIN(data, &tmp, sizeof(tmp));
8337 ipf_state_setlock(softc->ipf_state_soft, tmp);
8338 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8339 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8340 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8350 if (!(mode & FWRITE)) {
8354 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8355 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8362 #endif /* IPFILTER_LOG */
8365 if (!(mode & FWRITE)) {
8369 WRITE_ENTER(&softc->ipf_global);
8370 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8373 ipf_sync(softc, NULL);
8376 RWLOCK_EXIT(&softc->ipf_global);
8382 error = ipf_outobj(softc, (void *)data,
8383 ipf_frag_stats(softc->ipf_frag_soft),
8389 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8390 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8396 error = ipf_frruleiter(softc, data, uid, ctx);
8402 error = ipf_genericiter(softc, data, uid, ctx);
8406 case SIOCIPFDELTOK :
8407 error = BCOPYIN(data, &tmp, sizeof(tmp));
8410 error = ipf_token_del(softc, tmp, uid, ctx);
8425 /* ------------------------------------------------------------------------ */
8426 /* Function: ipf_decaps */
8427 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8428 /* flags indicating packet filtering decision. */
8429 /* Parameters: fin(I) - pointer to packet information */
8430 /* pass(I) - IP protocol version to match */
8431 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8433 /* This function is called for packets that are wrapt up in other packets, */
8434 /* for example, an IP packet that is the entire data segment for another IP */
8435 /* packet. If the basic constraints for this are satisfied, change the */
8436 /* buffer to point to the start of the inner packet and start processing */
8437 /* rules belonging to the head group this rule specifies. */
8438 /* ------------------------------------------------------------------------ */
8440 ipf_decaps(fin, pass, l5proto)
8445 fr_info_t fin2, *fino = NULL;
8451 if ((fin->fin_flx & FI_COALESCE) == 0)
8452 if (ipf_coalesce(fin) == -1)
8456 hlen = fin->fin_hlen;
8462 * In this case, the specific protocol being decapsulated
8463 * inside UDP frames comes from the rule.
8465 nh = fin->fin_fr->fr_icode;
8468 case IPPROTO_GRE : /* 47 */
8469 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8470 hlen += sizeof(grehdr_t);
8471 if (gre.gr_R|gre.gr_s)
8483 * If the routing options flag is set, validate that it is
8484 * there and bounce over it.
8487 /* This is really heavy weight and lots of room for error, */
8488 /* so for now, put it off and get the simple stuff right. */
8490 u_char off, len, *s;
8497 aplen = fin->fin_plen - hlen;
8499 af = (s[0] << 8) | s[1];
8504 if (af == 0 && len == 0) {
8515 hlen = s - (u_char *)fin->fin_dp;
8521 case IPPROTO_IPIP : /* 4 */
8526 default : /* Includes ESP, AH is special for IPv4 */
8539 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8543 #if defined(MENTAT) && defined(_KERNEL)
8549 fin->fin_plen -= elen;
8551 ip = (ip_t *)((char *)fin->fin_ip + elen);
8554 * Make sure we have at least enough data for the network layer
8558 hlen = IP_HL(ip) << 2;
8560 else if (IP_V(ip) == 6)
8561 hlen = sizeof(ip6_t);
8566 if (fin->fin_plen < hlen)
8569 fin->fin_dp = (char *)ip + hlen;
8571 if (IP_V(ip) == 4) {
8573 * Perform IPv4 header checksum validation.
8575 if (ipf_cksum((u_short *)ip, hlen))
8579 if (ipf_makefrip(hlen, ip, fin) == -1) {
8582 #if defined(MENTAT) && defined(_KERNEL)
8590 DT1(frb_decapfrip, fr_info_t *, fin);
8591 pass &= ~FR_CMDMASK;
8592 pass |= FR_BLOCK|FR_QUICK;
8593 fin->fin_reason = FRB_DECAPFRIP;
8597 pass = ipf_scanlist(fin, pass);
8600 * Copy the packet filter "result" fields out of the fr_info_t struct
8601 * that is local to the decapsulation processing and back into the
8602 * one we were called with.
8604 fino->fin_flx = fin->fin_flx;
8605 fino->fin_rev = fin->fin_rev;
8606 fino->fin_icode = fin->fin_icode;
8607 fino->fin_rule = fin->fin_rule;
8608 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8609 fino->fin_fr = fin->fin_fr;
8610 fino->fin_error = fin->fin_error;
8611 fino->fin_mp = fin->fin_mp;
8612 fino->fin_m = fin->fin_m;
8615 #if defined(MENTAT) && defined(_KERNEL)
8626 /* ------------------------------------------------------------------------ */
8627 /* Function: ipf_matcharray_load */
8628 /* Returns: int - 0 = success, else error */
8629 /* Parameters: softc(I) - pointer to soft context main structure */
8630 /* data(I) - pointer to ioctl data */
8631 /* objp(I) - ipfobj_t structure to load data into */
8632 /* arrayptr(I) - pointer to location to store array pointer */
8634 /* This function loads in a mathing array through the ipfobj_t struct that */
8635 /* describes it. Sanity checking and array size limitations are enforced */
8636 /* in this function to prevent userspace from trying to load in something */
8637 /* that is insanely big. Once the size of the array is known, the memory */
8638 /* required is malloc'd and returned through changing *arrayptr. The */
8639 /* contents of the array are verified before returning. Only in the event */
8640 /* of a successful call is the caller required to free up the malloc area. */
8641 /* ------------------------------------------------------------------------ */
8643 ipf_matcharray_load(softc, data, objp, arrayptr)
8644 ipf_main_softc_t *softc;
8649 int arraysize, *array, error;
8653 error = BCOPYIN(data, objp, sizeof(*objp));
8659 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8664 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8665 (objp->ipfo_size > 1024)) {
8670 arraysize = objp->ipfo_size * sizeof(*array);
8671 KMALLOCS(array, int *, arraysize);
8672 if (array == NULL) {
8677 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8679 KFREES(array, arraysize);
8684 if (ipf_matcharray_verify(array, arraysize) != 0) {
8685 KFREES(array, arraysize);
8695 /* ------------------------------------------------------------------------ */
8696 /* Function: ipf_matcharray_verify */
8698 /* Parameters: array(I) - pointer to matching array */
8699 /* arraysize(I) - number of elements in the array */
8701 /* Verify the contents of a matching array by stepping through each element */
8702 /* in it. The actual commands in the array are not verified for */
8703 /* correctness, only that all of the sizes are correctly within limits. */
8704 /* ------------------------------------------------------------------------ */
8706 ipf_matcharray_verify(array, arraysize)
8707 int *array, arraysize;
8709 int i, nelem, maxidx;
8712 nelem = arraysize / sizeof(*array);
8715 * Currently, it makes no sense to have an array less than 6
8716 * elements long - the initial size at the from, a single operation
8717 * (minimum 4 in length) and a trailer, for a total of 6.
8719 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8724 * Verify the size of data pointed to by array with how long
8725 * the array claims to be itself.
8727 if (array[0] * sizeof(*array) != arraysize) {
8733 * The last opcode in this array should be an IPF_EXP_END.
8735 if (array[maxidx] != IPF_EXP_END) {
8739 for (i = 1; i < maxidx; ) {
8740 e = (ipfexp_t *)(array + i);
8743 * The length of the bits to check must be at least 1
8744 * (or else there is nothing to comapre with!) and it
8745 * cannot exceed the length of the data present.
8747 if ((e->ipfe_size < 1 ) ||
8748 (e->ipfe_size + i > maxidx)) {
8757 /* ------------------------------------------------------------------------ */
8758 /* Function: ipf_fr_matcharray */
8759 /* Returns: int - 0 = match failed, else positive match */
8760 /* Parameters: fin(I) - pointer to packet information */
8761 /* array(I) - pointer to matching array */
8763 /* This function is used to apply a matching array against a packet and */
8764 /* return an indication of whether or not the packet successfully matches */
8765 /* all of the commands in it. */
8766 /* ------------------------------------------------------------------------ */
8768 ipf_fr_matcharray(fin, array)
8772 int i, n, *x, rv, p;
8779 for (; n > 0; x += 3 + x[3], rv = 0) {
8781 if (e->ipfe_cmd == IPF_EXP_END)
8786 * The upper 16 bits currently store the protocol value.
8787 * This is currently used with TCP and UDP port compares and
8788 * allows "tcp.port = 80" without requiring an explicit
8789 " "ip.pr = tcp" first.
8791 p = e->ipfe_cmd >> 16;
8792 if ((p != 0) && (p != fin->fin_p))
8795 switch (e->ipfe_cmd)
8797 case IPF_EXP_IP_PR :
8798 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8799 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8803 case IPF_EXP_IP_SRCADDR :
8804 if (fin->fin_v != 4)
8806 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8807 rv |= ((fin->fin_saddr &
8808 e->ipfe_arg0[i * 2 + 1]) ==
8809 e->ipfe_arg0[i * 2]);
8813 case IPF_EXP_IP_DSTADDR :
8814 if (fin->fin_v != 4)
8816 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8817 rv |= ((fin->fin_daddr &
8818 e->ipfe_arg0[i * 2 + 1]) ==
8819 e->ipfe_arg0[i * 2]);
8823 case IPF_EXP_IP_ADDR :
8824 if (fin->fin_v != 4)
8826 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8827 rv |= ((fin->fin_saddr &
8828 e->ipfe_arg0[i * 2 + 1]) ==
8829 e->ipfe_arg0[i * 2]) ||
8831 e->ipfe_arg0[i * 2 + 1]) ==
8832 e->ipfe_arg0[i * 2]);
8837 case IPF_EXP_IP6_SRCADDR :
8838 if (fin->fin_v != 6)
8840 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8841 rv |= IP6_MASKEQ(&fin->fin_src6,
8842 &e->ipfe_arg0[i * 8 + 4],
8843 &e->ipfe_arg0[i * 8]);
8847 case IPF_EXP_IP6_DSTADDR :
8848 if (fin->fin_v != 6)
8850 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8851 rv |= IP6_MASKEQ(&fin->fin_dst6,
8852 &e->ipfe_arg0[i * 8 + 4],
8853 &e->ipfe_arg0[i * 8]);
8857 case IPF_EXP_IP6_ADDR :
8858 if (fin->fin_v != 6)
8860 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8861 rv |= IP6_MASKEQ(&fin->fin_src6,
8862 &e->ipfe_arg0[i * 8 + 4],
8863 &e->ipfe_arg0[i * 8]) ||
8864 IP6_MASKEQ(&fin->fin_dst6,
8865 &e->ipfe_arg0[i * 8 + 4],
8866 &e->ipfe_arg0[i * 8]);
8871 case IPF_EXP_UDP_PORT :
8872 case IPF_EXP_TCP_PORT :
8873 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8874 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8875 (fin->fin_dport == e->ipfe_arg0[i]);
8879 case IPF_EXP_UDP_SPORT :
8880 case IPF_EXP_TCP_SPORT :
8881 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8882 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8886 case IPF_EXP_UDP_DPORT :
8887 case IPF_EXP_TCP_DPORT :
8888 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8889 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8893 case IPF_EXP_TCP_FLAGS :
8894 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8895 rv |= ((fin->fin_tcpf &
8896 e->ipfe_arg0[i * 2 + 1]) ==
8897 e->ipfe_arg0[i * 2]);
8911 /* ------------------------------------------------------------------------ */
8912 /* Function: ipf_queueflush */
8913 /* Returns: int - number of entries flushed (0 = none) */
8914 /* Parameters: softc(I) - pointer to soft context main structure */
8915 /* deletefn(I) - function to call to delete entry */
8916 /* ipfqs(I) - top of the list of ipf internal queues */
8917 /* userqs(I) - top of the list of user defined timeouts */
8919 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8920 /* need to try a bit harder to free up some space. The algorithm used here */
8921 /* split into two parts but both halves have the same goal: to reduce the */
8922 /* number of connections considered to be "active" to the low watermark. */
8923 /* There are two steps in doing this: */
8924 /* 1) Remove any TCP connections that are already considered to be "closed" */
8925 /* but have not yet been removed from the state table. The two states */
8926 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8927 /* candidates for this style of removal. If freeing up entries in */
8928 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8929 /* we do not go on to step 2. */
8931 /* 2) Look for the oldest entries on each timeout queue and free them if */
8932 /* they are within the given window we are considering. Where the */
8933 /* window starts and the steps taken to increase its size depend upon */
8934 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8935 /* last 30 seconds is not touched. */
8937 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8939 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8940 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8942 /* Points to note: */
8943 /* - tqe_die is the time, in the future, when entries die. */
8944 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8946 /* - tqe_touched is when the entry was last used by NAT/state */
8947 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8948 /* ipf_ticks any given timeout queue and vice versa. */
8949 /* - both tqe_die and tqe_touched increase over time */
8950 /* - timeout queues are sorted with the highest value of tqe_die at the */
8951 /* bottom and therefore the smallest values of each are at the top */
8952 /* - the pointer passed in as ipfqs should point to an array of timeout */
8953 /* queues representing each of the TCP states */
8955 /* We start by setting up a maximum range to scan for things to move of */
8956 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8957 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8958 /* we start again with a new value for "iend" and "istart". This is */
8959 /* continued until we either finish the scan of 30 second intervals or the */
8960 /* low water mark is reached. */
8961 /* ------------------------------------------------------------------------ */
8963 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8964 ipf_main_softc_t *softc;
8965 ipftq_delete_fn_t deletefn;
8966 ipftq_t *ipfqs, *userqs;
8970 u_long interval, istart, iend;
8971 ipftq_t *ifq, *ifqnext;
8972 ipftqent_t *tqe, *tqn;
8975 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8976 tqn = tqe->tqe_next;
8977 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8980 if ((*activep * 100 / size) > low) {
8981 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8982 ((tqe = tqn) != NULL); ) {
8983 tqn = tqe->tqe_next;
8984 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8989 if ((*activep * 100 / size) <= low) {
8994 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8995 * used then the operations are upgraded to floating point
8996 * and kernels don't like floating point...
8998 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8999 istart = IPF_TTLVAL(86400 * 4);
9000 interval = IPF_TTLVAL(43200);
9001 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9002 istart = IPF_TTLVAL(43200);
9003 interval = IPF_TTLVAL(1800);
9004 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9005 istart = IPF_TTLVAL(1800);
9006 interval = IPF_TTLVAL(30);
9010 if (istart > softc->ipf_ticks) {
9011 if (softc->ipf_ticks - interval < interval)
9014 istart = (softc->ipf_ticks / interval) * interval;
9017 iend = softc->ipf_ticks - interval;
9019 while ((*activep * 100 / size) > low) {
9022 try = softc->ipf_ticks - istart;
9024 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9025 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9026 if (try < tqe->tqe_touched)
9028 tqn = tqe->tqe_next;
9029 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9034 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9035 ifqnext = ifq->ifq_next;
9037 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9038 if (try < tqe->tqe_touched)
9040 tqn = tqe->tqe_next;
9041 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9047 if (interval == IPF_TTLVAL(43200)) {
9048 interval = IPF_TTLVAL(1800);
9049 } else if (interval == IPF_TTLVAL(1800)) {
9050 interval = IPF_TTLVAL(30);
9054 if (interval >= softc->ipf_ticks)
9057 iend = softc->ipf_ticks - interval;
9066 /* ------------------------------------------------------------------------ */
9067 /* Function: ipf_deliverlocal */
9068 /* Returns: int - 1 = local address, 0 = non-local address */
9069 /* Parameters: softc(I) - pointer to soft context main structure */
9070 /* ipversion(I) - IP protocol version (4 or 6) */
9071 /* ifp(I) - network interface pointer */
9072 /* ipaddr(I) - IPv4/6 destination address */
9074 /* This fucntion is used to determine in the address "ipaddr" belongs to */
9075 /* the network interface represented by ifp. */
9076 /* ------------------------------------------------------------------------ */
9078 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9079 ipf_main_softc_t *softc;
9087 if (ipversion == 4) {
9088 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9089 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9094 } else if (ipversion == 6) {
9095 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9096 if (IP6_EQ(&addr, ipaddr))
9106 /* ------------------------------------------------------------------------ */
9107 /* Function: ipf_settimeout */
9108 /* Returns: int - 0 = success, -1 = failure */
9109 /* Parameters: softc(I) - pointer to soft context main structure */
9110 /* t(I) - pointer to tuneable array entry */
9111 /* p(I) - pointer to values passed in to apply */
9113 /* This function is called to set the timeout values for each distinct */
9114 /* queue timeout that is available. When called, it calls into both the */
9115 /* state and NAT code, telling them to update their timeout queues. */
9116 /* ------------------------------------------------------------------------ */
9118 ipf_settimeout(softc, t, p)
9119 struct ipf_main_softc_s *softc;
9125 * ipf_interror should be set by the functions called here, not
9126 * by this function - it's just a middle man.
9128 if (ipf_state_settimeout(softc, t, p) == -1)
9130 if (ipf_nat_settimeout(softc, t, p) == -1)
9136 /* ------------------------------------------------------------------------ */
9137 /* Function: ipf_apply_timeout */
9138 /* Returns: int - 0 = success, -1 = failure */
9139 /* Parameters: head(I) - pointer to tuneable array entry */
9140 /* seconds(I) - pointer to values passed in to apply */
9142 /* This function applies a timeout of "seconds" to the timeout queue that */
9143 /* is pointed to by "head". All entries on this list have an expiration */
9144 /* set to be the current tick value of ipf plus the ttl. Given that this */
9145 /* function should only be called when the delta is non-zero, the task is */
9146 /* to walk the entire list and apply the change. The sort order will not */
9147 /* change. The only catch is that this is O(n) across the list, so if the */
9148 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
9149 /* could take a relatively long time to work through them all. */
9150 /* ------------------------------------------------------------------------ */
9152 ipf_apply_timeout(head, seconds)
9156 u_int oldtimeout, newtimeout;
9160 MUTEX_ENTER(&head->ifq_lock);
9161 oldtimeout = head->ifq_ttl;
9162 newtimeout = IPF_TTLVAL(seconds);
9163 delta = oldtimeout - newtimeout;
9165 head->ifq_ttl = newtimeout;
9167 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9168 tqe->tqe_die += delta;
9170 MUTEX_EXIT(&head->ifq_lock);
9174 /* ------------------------------------------------------------------------ */
9175 /* Function: ipf_settimeout_tcp */
9176 /* Returns: int - 0 = successfully applied, -1 = failed */
9177 /* Parameters: t(I) - pointer to tuneable to change */
9178 /* p(I) - pointer to new timeout information */
9179 /* tab(I) - pointer to table of TCP queues */
9181 /* This function applies the new timeout (p) to the TCP tunable (t) and */
9182 /* updates all of the entries on the relevant timeout queue by calling */
9183 /* ipf_apply_timeout(). */
9184 /* ------------------------------------------------------------------------ */
9186 ipf_settimeout_tcp(t, p, tab)
9191 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9192 !strcmp(t->ipft_name, "tcp_established")) {
9193 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9194 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9195 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9196 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9197 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9198 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9199 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9200 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9201 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9202 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9203 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9204 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9205 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9206 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9207 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9208 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9209 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9210 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9211 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9212 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9213 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9214 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9215 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9216 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9217 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9220 * ipf_interror isn't set here because it should be set
9221 * by whatever called this function.
9229 /* ------------------------------------------------------------------------ */
9230 /* Function: ipf_main_soft_create */
9231 /* Returns: NULL = failure, else success */
9232 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9234 /* Create the foundation soft context structure. In circumstances where it */
9235 /* is not required to dynamically allocate the context, a pointer can be */
9236 /* passed in (rather than NULL) to a structure to be initialised. */
9237 /* The main thing of interest is that a number of locks are initialised */
9238 /* here instead of in the where might be expected - in the relevant create */
9239 /* function elsewhere. This is done because the current locking design has */
9240 /* some areas where these locks are used outside of their module. */
9241 /* Possibly the most important exercise that is done here is setting of all */
9242 /* the timeout values, allowing them to be changed before init(). */
9243 /* ------------------------------------------------------------------------ */
9245 ipf_main_soft_create(arg)
9248 ipf_main_softc_t *softc;
9251 KMALLOC(softc, ipf_main_softc_t *);
9258 bzero((char *)softc, sizeof(*softc));
9261 * This serves as a flag as to whether or not the softc should be
9262 * free'd when _destroy is called.
9264 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9266 softc->ipf_tuners = ipf_tune_array_copy(softc,
9267 sizeof(ipf_main_tuneables),
9268 ipf_main_tuneables);
9269 if (softc->ipf_tuners == NULL) {
9270 ipf_main_soft_destroy(softc);
9274 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9275 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9276 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9277 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9278 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9279 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9280 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9281 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9282 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9284 softc->ipf_token_head = NULL;
9285 softc->ipf_token_tail = &softc->ipf_token_head;
9287 softc->ipf_tcpidletimeout = FIVE_DAYS;
9288 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9289 softc->ipf_tcplastack = IPF_TTLVAL(30);
9290 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9291 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9292 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9293 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9294 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9295 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9296 softc->ipf_udptimeout = IPF_TTLVAL(120);
9297 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9298 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9299 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9300 softc->ipf_iptimeout = IPF_TTLVAL(60);
9302 #if defined(IPFILTER_DEFAULT_BLOCK)
9303 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9305 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9307 softc->ipf_minttl = 4;
9308 softc->ipf_icmpminfragmtu = 68;
9309 softc->ipf_flags = IPF_LOGGING;
9314 /* ------------------------------------------------------------------------ */
9315 /* Function: ipf_main_soft_init */
9316 /* Returns: 0 = success, -1 = failure */
9317 /* Parameters: softc(I) - pointer to soft context main structure */
9319 /* A null-op function that exists as a placeholder so that the flow in */
9320 /* other functions is obvious. */
9321 /* ------------------------------------------------------------------------ */
9324 ipf_main_soft_init(softc)
9325 ipf_main_softc_t *softc;
9331 /* ------------------------------------------------------------------------ */
9332 /* Function: ipf_main_soft_destroy */
9334 /* Parameters: softc(I) - pointer to soft context main structure */
9336 /* Undo everything that we did in ipf_main_soft_create. */
9338 /* The most important check that needs to be made here is whether or not */
9339 /* the structure was allocated by ipf_main_soft_create() by checking what */
9340 /* value is stored in ipf_dynamic_main. */
9341 /* ------------------------------------------------------------------------ */
9344 ipf_main_soft_destroy(softc)
9345 ipf_main_softc_t *softc;
9348 RW_DESTROY(&softc->ipf_frag);
9349 RW_DESTROY(&softc->ipf_poolrw);
9350 RW_DESTROY(&softc->ipf_nat);
9351 RW_DESTROY(&softc->ipf_state);
9352 RW_DESTROY(&softc->ipf_tokens);
9353 RW_DESTROY(&softc->ipf_mutex);
9354 RW_DESTROY(&softc->ipf_global);
9355 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9356 MUTEX_DESTROY(&softc->ipf_rw);
9358 if (softc->ipf_tuners != NULL) {
9359 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9361 if (softc->ipf_dynamic_softc == 1) {
9367 /* ------------------------------------------------------------------------ */
9368 /* Function: ipf_main_soft_fini */
9369 /* Returns: 0 = success, -1 = failure */
9370 /* Parameters: softc(I) - pointer to soft context main structure */
9372 /* Clean out the rules which have been added since _init was last called, */
9373 /* the only dynamic part of the mainline. */
9374 /* ------------------------------------------------------------------------ */
9376 ipf_main_soft_fini(softc)
9377 ipf_main_softc_t *softc;
9379 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9380 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9381 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9382 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9388 /* ------------------------------------------------------------------------ */
9389 /* Function: ipf_main_load */
9390 /* Returns: 0 = success, -1 = failure */
9391 /* Parameters: none */
9393 /* Handle global initialisation that needs to be done for the base part of */
9394 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9395 /* arrays that get used by the state/NAT code. */
9396 /* ------------------------------------------------------------------------ */
9402 /* fill icmp reply type table */
9403 for (i = 0; i <= ICMP_MAXTYPE; i++)
9404 icmpreplytype4[i] = -1;
9405 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9406 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9407 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9408 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9411 /* fill icmp reply type table */
9412 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9413 icmpreplytype6[i] = -1;
9414 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9415 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9416 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9417 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9418 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9425 /* ------------------------------------------------------------------------ */
9426 /* Function: ipf_main_unload */
9427 /* Returns: 0 = success, -1 = failure */
9428 /* Parameters: none */
9430 /* A null-op function that exists as a placeholder so that the flow in */
9431 /* other functions is obvious. */
9432 /* ------------------------------------------------------------------------ */
9440 /* ------------------------------------------------------------------------ */
9441 /* Function: ipf_load_all */
9442 /* Returns: 0 = success, -1 = failure */
9443 /* Parameters: none */
9445 /* Work through all of the subsystems inside IPFilter and call the load */
9446 /* function for each in an order that won't lead to a crash :) */
9447 /* ------------------------------------------------------------------------ */
9451 if (ipf_main_load() == -1)
9454 if (ipf_state_main_load() == -1)
9457 if (ipf_nat_main_load() == -1)
9460 if (ipf_frag_main_load() == -1)
9463 if (ipf_auth_main_load() == -1)
9466 if (ipf_proxy_main_load() == -1)
9473 /* ------------------------------------------------------------------------ */
9474 /* Function: ipf_unload_all */
9475 /* Returns: 0 = success, -1 = failure */
9476 /* Parameters: none */
9478 /* Work through all of the subsystems inside IPFilter and call the unload */
9479 /* function for each in an order that won't lead to a crash :) */
9480 /* ------------------------------------------------------------------------ */
9484 if (ipf_proxy_main_unload() == -1)
9487 if (ipf_auth_main_unload() == -1)
9490 if (ipf_frag_main_unload() == -1)
9493 if (ipf_nat_main_unload() == -1)
9496 if (ipf_state_main_unload() == -1)
9499 if (ipf_main_unload() == -1)
9506 /* ------------------------------------------------------------------------ */
9507 /* Function: ipf_create_all */
9508 /* Returns: NULL = failure, else success */
9509 /* Parameters: arg(I) - pointer to soft context main structure */
9511 /* Work through all of the subsystems inside IPFilter and call the create */
9512 /* function for each in an order that won't lead to a crash :) */
9513 /* ------------------------------------------------------------------------ */
9518 ipf_main_softc_t *softc;
9520 softc = ipf_main_soft_create(arg);
9525 softc->ipf_log_soft = ipf_log_soft_create(softc);
9526 if (softc->ipf_log_soft == NULL) {
9527 ipf_destroy_all(softc);
9532 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9533 if (softc->ipf_lookup_soft == NULL) {
9534 ipf_destroy_all(softc);
9538 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9539 if (softc->ipf_sync_soft == NULL) {
9540 ipf_destroy_all(softc);
9544 softc->ipf_state_soft = ipf_state_soft_create(softc);
9545 if (softc->ipf_state_soft == NULL) {
9546 ipf_destroy_all(softc);
9550 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9551 if (softc->ipf_nat_soft == NULL) {
9552 ipf_destroy_all(softc);
9556 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9557 if (softc->ipf_frag_soft == NULL) {
9558 ipf_destroy_all(softc);
9562 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9563 if (softc->ipf_auth_soft == NULL) {
9564 ipf_destroy_all(softc);
9568 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9569 if (softc->ipf_proxy_soft == NULL) {
9570 ipf_destroy_all(softc);
9578 /* ------------------------------------------------------------------------ */
9579 /* Function: ipf_destroy_all */
9581 /* Parameters: softc(I) - pointer to soft context main structure */
9583 /* Work through all of the subsystems inside IPFilter and call the destroy */
9584 /* function for each in an order that won't lead to a crash :) */
9586 /* Every one of these functions is expected to succeed, so there is no */
9587 /* checking of return values. */
9588 /* ------------------------------------------------------------------------ */
9590 ipf_destroy_all(softc)
9591 ipf_main_softc_t *softc;
9594 if (softc->ipf_state_soft != NULL) {
9595 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9596 softc->ipf_state_soft = NULL;
9599 if (softc->ipf_nat_soft != NULL) {
9600 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9601 softc->ipf_nat_soft = NULL;
9604 if (softc->ipf_frag_soft != NULL) {
9605 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9606 softc->ipf_frag_soft = NULL;
9609 if (softc->ipf_auth_soft != NULL) {
9610 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9611 softc->ipf_auth_soft = NULL;
9614 if (softc->ipf_proxy_soft != NULL) {
9615 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9616 softc->ipf_proxy_soft = NULL;
9619 if (softc->ipf_sync_soft != NULL) {
9620 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9621 softc->ipf_sync_soft = NULL;
9624 if (softc->ipf_lookup_soft != NULL) {
9625 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9626 softc->ipf_lookup_soft = NULL;
9630 if (softc->ipf_log_soft != NULL) {
9631 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9632 softc->ipf_log_soft = NULL;
9636 ipf_main_soft_destroy(softc);
9640 /* ------------------------------------------------------------------------ */
9641 /* Function: ipf_init_all */
9642 /* Returns: 0 = success, -1 = failure */
9643 /* Parameters: softc(I) - pointer to soft context main structure */
9645 /* Work through all of the subsystems inside IPFilter and call the init */
9646 /* function for each in an order that won't lead to a crash :) */
9647 /* ------------------------------------------------------------------------ */
9650 ipf_main_softc_t *softc;
9653 if (ipf_main_soft_init(softc) == -1)
9657 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9661 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9664 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9667 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9670 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9673 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9676 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9679 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9686 /* ------------------------------------------------------------------------ */
9687 /* Function: ipf_fini_all */
9688 /* Returns: 0 = success, -1 = failure */
9689 /* Parameters: softc(I) - pointer to soft context main structure */
9691 /* Work through all of the subsystems inside IPFilter and call the fini */
9692 /* function for each in an order that won't lead to a crash :) */
9693 /* ------------------------------------------------------------------------ */
9696 ipf_main_softc_t *softc;
9699 ipf_token_flush(softc);
9701 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9704 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9707 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9710 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9713 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9716 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9719 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9723 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9727 if (ipf_main_soft_fini(softc) == -1)
9734 /* ------------------------------------------------------------------------ */
9735 /* Function: ipf_rule_expire */
9737 /* Parameters: softc(I) - pointer to soft context main structure */
9739 /* At present this function exists just to support temporary addition of */
9740 /* firewall rules. Both inactive and active lists are scanned for items to */
9741 /* purge, as by rights, the expiration is computed as soon as the rule is */
9743 /* ------------------------------------------------------------------------ */
9745 ipf_rule_expire(softc)
9746 ipf_main_softc_t *softc;
9750 if ((softc->ipf_rule_explist[0] == NULL) &&
9751 (softc->ipf_rule_explist[1] == NULL))
9754 WRITE_ENTER(&softc->ipf_mutex);
9756 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9758 * Because the list is kept sorted on insertion, the fist
9759 * one that dies in the future means no more work to do.
9761 if (fr->fr_die > softc->ipf_ticks)
9763 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9766 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9768 * Because the list is kept sorted on insertion, the fist
9769 * one that dies in the future means no more work to do.
9771 if (fr->fr_die > softc->ipf_ticks)
9773 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9776 RWLOCK_EXIT(&softc->ipf_mutex);
9780 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9781 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9784 host_node_t RBI_ZERO(ipf_rb);
9785 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9788 /* ------------------------------------------------------------------------ */
9789 /* Function: ipf_ht_node_cmp */
9790 /* Returns: int - 0 == nodes are the same, .. */
9791 /* Parameters: k1(I) - pointer to first key to compare */
9792 /* k2(I) - pointer to second key to compare */
9794 /* The "key" for the node is a combination of two fields: the address */
9795 /* family and the address itself. */
9797 /* Because we're not actually interpreting the address data, it isn't */
9798 /* necessary to convert them to/from network/host byte order. The mask is */
9799 /* just used to remove bits that aren't significant - it doesn't matter */
9800 /* where they are, as long as they're always in the same place. */
9802 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9803 /* this is where individual ones will differ the most - but not true for */
9804 /* for /48's, etc. */
9805 /* ------------------------------------------------------------------------ */
9807 ipf_ht_node_cmp(k1, k2)
9808 struct host_node_s *k1, *k2;
9812 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9816 if (k1->hn_addr.adf_family == AF_INET)
9817 return (k2->hn_addr.adf_addr.in4.s_addr -
9818 k1->hn_addr.adf_addr.in4.s_addr);
9820 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9823 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9826 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9829 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9834 /* ------------------------------------------------------------------------ */
9835 /* Function: ipf_ht_node_make_key */
9837 /* parameters: htp(I) - pointer to address tracking structure */
9838 /* key(I) - where to store masked address for lookup */
9839 /* family(I) - protocol family of address */
9840 /* addr(I) - pointer to network address */
9842 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9843 /* copy the address passed in into the key structure whilst masking out the */
9844 /* bits that we don't want. */
9846 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9847 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9848 /* have to be wary of that and not allow 32-128 to happen. */
9849 /* ------------------------------------------------------------------------ */
9851 ipf_ht_node_make_key(htp, key, family, addr)
9857 key->hn_addr.adf_family = family;
9858 if (family == AF_INET) {
9862 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9863 bits = htp->ht_netmask;
9867 mask = htonl(0xffffffff << (32 - bits));
9869 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9872 int bits = htp->ht_netmask;
9874 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9876 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9877 htonl(0xffffffff << (128 - bits));
9878 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9879 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9880 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9881 } else if (bits > 64) {
9882 key->hn_addr.adf_addr.i6[3] = 0;
9883 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9884 htonl(0xffffffff << (96 - bits));
9885 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9886 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9887 } else if (bits > 32) {
9888 key->hn_addr.adf_addr.i6[3] = 0;
9889 key->hn_addr.adf_addr.i6[2] = 0;
9890 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9891 htonl(0xffffffff << (64 - bits));
9892 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9894 key->hn_addr.adf_addr.i6[3] = 0;
9895 key->hn_addr.adf_addr.i6[2] = 0;
9896 key->hn_addr.adf_addr.i6[1] = 0;
9897 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9898 htonl(0xffffffff << (32 - bits));
9905 /* ------------------------------------------------------------------------ */
9906 /* Function: ipf_ht_node_add */
9907 /* Returns: int - 0 == success, -1 == failure */
9908 /* Parameters: softc(I) - pointer to soft context main structure */
9909 /* htp(I) - pointer to address tracking structure */
9910 /* family(I) - protocol family of address */
9911 /* addr(I) - pointer to network address */
9913 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9914 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9916 /* After preparing the key with the address information to find, look in */
9917 /* the red-black tree to see if the address is known. A successful call to */
9918 /* this function can mean one of two things: a new node was added to the */
9919 /* tree or a matching node exists and we're able to bump up its activity. */
9920 /* ------------------------------------------------------------------------ */
9922 ipf_ht_node_add(softc, htp, family, addr)
9923 ipf_main_softc_t *softc;
9931 ipf_ht_node_make_key(htp, &k, family, addr);
9933 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9935 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9937 KMALLOC(h, host_node_t *);
9940 LBUMP(ipf_rb_no_mem);
9945 * If there was a macro to initialise the RB node then that
9946 * would get used here, but there isn't...
9948 bzero((char *)h, sizeof(*h));
9949 h->hn_addr = k.hn_addr;
9950 h->hn_addr.adf_family = k.hn_addr.adf_family;
9951 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9952 htp->ht_cur_nodes++;
9954 if ((htp->ht_max_per_node != 0) &&
9955 (h->hn_active >= htp->ht_max_per_node)) {
9956 DT(ipf_rb_node_max);
9957 LBUMP(ipf_rb_node_max);
9968 /* ------------------------------------------------------------------------ */
9969 /* Function: ipf_ht_node_del */
9970 /* Returns: int - 0 == success, -1 == failure */
9971 /* parameters: htp(I) - pointer to address tracking structure */
9972 /* family(I) - protocol family of address */
9973 /* addr(I) - pointer to network address */
9975 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9976 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9978 /* Try and find the address passed in amongst the leavese on this tree to */
9979 /* be friend. If found then drop the active account for that node drops by */
9980 /* one. If that count reaches 0, it is time to free it all up. */
9981 /* ------------------------------------------------------------------------ */
9983 ipf_ht_node_del(htp, family, addr)
9991 ipf_ht_node_make_key(htp, &k, family, addr);
9993 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9998 if (h->hn_active == 0) {
9999 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10000 htp->ht_cur_nodes--;
10009 /* ------------------------------------------------------------------------ */
10010 /* Function: ipf_rb_ht_init */
10012 /* Parameters: head(I) - pointer to host tracking structure */
10014 /* Initialise the host tracking structure to be ready for use above. */
10015 /* ------------------------------------------------------------------------ */
10017 ipf_rb_ht_init(head)
10018 host_track_t *head;
10020 RBI_INIT(ipf_rb, &head->ht_root);
10024 /* ------------------------------------------------------------------------ */
10025 /* Function: ipf_rb_ht_freenode */
10027 /* Parameters: head(I) - pointer to host tracking structure */
10028 /* arg(I) - additional argument from walk caller */
10030 /* Free an actual host_node_t structure. */
10031 /* ------------------------------------------------------------------------ */
10033 ipf_rb_ht_freenode(node, arg)
10041 /* ------------------------------------------------------------------------ */
10042 /* Function: ipf_rb_ht_flush */
10044 /* Parameters: head(I) - pointer to host tracking structure */
10046 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
10047 /* and free'ing each one. */
10048 /* ------------------------------------------------------------------------ */
10050 ipf_rb_ht_flush(head)
10051 host_track_t *head;
10053 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10057 /* ------------------------------------------------------------------------ */
10058 /* Function: ipf_slowtimer */
10060 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
10062 /* Slowly expire held state for fragments. Timeouts are set * in */
10063 /* expectation of this being called twice per second. */
10064 /* ------------------------------------------------------------------------ */
10066 ipf_slowtimer(softc)
10067 ipf_main_softc_t *softc;
10070 ipf_token_expire(softc);
10071 ipf_frag_expire(softc);
10072 ipf_state_expire(softc);
10073 ipf_nat_expire(softc);
10074 ipf_auth_expire(softc);
10075 ipf_lookup_expire(softc);
10076 ipf_rule_expire(softc);
10077 ipf_sync_expire(softc);
10078 softc->ipf_ticks++;
10079 # if defined(__OpenBSD__)
10080 timeout_add(&ipf_slowtimer_ch, hz/2);
10085 /* ------------------------------------------------------------------------ */
10086 /* Function: ipf_inet_mask_add */
10088 /* Parameters: bits(I) - pointer to nat context information */
10089 /* mtab(I) - pointer to mask hash table structure */
10091 /* When called, bits represents the mask of a new NAT rule that has just */
10092 /* been added. This function inserts a bitmask into the array of masks to */
10093 /* search when searching for a matching NAT rule for a packet. */
10094 /* Prevention of duplicate masks is achieved by checking the use count for */
10095 /* a given netmask. */
10096 /* ------------------------------------------------------------------------ */
10098 ipf_inet_mask_add(bits, mtab)
10100 ipf_v4_masktab_t *mtab;
10105 mtab->imt4_masks[bits]++;
10106 if (mtab->imt4_masks[bits] > 1)
10112 mask = 0xffffffff << (32 - bits);
10114 for (i = 0; i < 33; i++) {
10115 if (ntohl(mtab->imt4_active[i]) < mask) {
10116 for (j = 32; j > i; j--)
10117 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10118 mtab->imt4_active[i] = htonl(mask);
10126 /* ------------------------------------------------------------------------ */
10127 /* Function: ipf_inet_mask_del */
10129 /* Parameters: bits(I) - number of bits set in the netmask */
10130 /* mtab(I) - pointer to mask hash table structure */
10132 /* Remove the 32bit bitmask represented by "bits" from the collection of */
10133 /* netmasks stored inside of mtab. */
10134 /* ------------------------------------------------------------------------ */
10136 ipf_inet_mask_del(bits, mtab)
10138 ipf_v4_masktab_t *mtab;
10143 mtab->imt4_masks[bits]--;
10144 if (mtab->imt4_masks[bits] > 0)
10147 mask = htonl(0xffffffff << (32 - bits));
10148 for (i = 0; i < 33; i++) {
10149 if (mtab->imt4_active[i] == mask) {
10150 for (j = i + 1; j < 33; j++)
10151 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10156 ASSERT(mtab->imt4_max >= 0);
10161 /* ------------------------------------------------------------------------ */
10162 /* Function: ipf_inet6_mask_add */
10164 /* Parameters: bits(I) - number of bits set in mask */
10165 /* mask(I) - pointer to mask to add */
10166 /* mtab(I) - pointer to mask hash table structure */
10168 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10169 /* has just been added. This function inserts a bitmask into the array of */
10170 /* masks to search when searching for a matching NAT rule for a packet. */
10171 /* Prevention of duplicate masks is achieved by checking the use count for */
10172 /* a given netmask. */
10173 /* ------------------------------------------------------------------------ */
10175 ipf_inet6_mask_add(bits, mask, mtab)
10178 ipf_v6_masktab_t *mtab;
10183 mtab->imt6_masks[bits]++;
10184 if (mtab->imt6_masks[bits] > 1)
10195 for (i = 0; i < 129; i++) {
10196 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10197 for (j = 128; j > i; j--)
10198 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10199 mtab->imt6_active[i] = *mask;
10207 /* ------------------------------------------------------------------------ */
10208 /* Function: ipf_inet6_mask_del */
10210 /* Parameters: bits(I) - number of bits set in mask */
10211 /* mask(I) - pointer to mask to remove */
10212 /* mtab(I) - pointer to mask hash table structure */
10214 /* Remove the 128bit bitmask represented by "bits" from the collection of */
10215 /* netmasks stored inside of mtab. */
10216 /* ------------------------------------------------------------------------ */
10218 ipf_inet6_mask_del(bits, mask, mtab)
10221 ipf_v6_masktab_t *mtab;
10226 mtab->imt6_masks[bits]--;
10227 if (mtab->imt6_masks[bits] > 0)
10237 for (i = 0; i < 129; i++) {
10238 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10239 for (j = i + 1; j < 129; j++) {
10240 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10241 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10248 ASSERT(mtab->imt6_max >= 0);
10253 ipf_pcksum6(fin, ip6, off, len)
10263 if (m->m_len < sizeof(struct ip6_hdr)) {
10267 sum = in6_cksum(m, ip6->ip6_nxt, off, len);
10272 ipf_pcksum6(fin, ip6, off, len)
10281 sp = (u_short *)&ip6->ip6_src;
10282 sum = *sp++; /* ip6_src */
10290 sum += *sp++; /* ip6_dst */
10298 return(ipf_pcksum(fin, off, sum));