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 # if !defined(IPFILTER_LKM)
25 # include "opt_inet6.h"
27 # include <sys/filio.h>
29 # include <sys/ioctl.h>
31 #if defined(__SVR4) || defined(sun) /* SOLARIS */
32 # include <sys/filio.h>
34 # include <sys/fcntl.h>
36 # include <sys/systm.h>
37 # include <sys/file.h>
43 # include <sys/file.h>
49 # include <sys/mbuf.h>
51 # include <sys/byteorder.h>
52 # if (SOLARIS2 < 5) && defined(sun)
53 # include <sys/dditypes.h>
56 # include <sys/protosw.h>
57 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66 # include <netinet/udp.h>
67 # include <netinet/ip_icmp.h>
68 #include "netinet/ip_compat.h"
70 # include <netinet/icmp6.h>
71 # if !SOLARIS && defined(_KERNEL)
72 # include <netinet6/in6_var.h>
75 #include "netinet/ip_fil.h"
76 #include "netinet/ip_nat.h"
77 #include "netinet/ip_frag.h"
78 #include "netinet/ip_state.h"
79 #include "netinet/ip_proxy.h"
80 #include "netinet/ip_auth.h"
82 # include "netinet/ip_scan.h"
84 #include "netinet/ip_sync.h"
85 #include "netinet/ip_lookup.h"
86 #include "netinet/ip_pool.h"
87 #include "netinet/ip_htable.h"
88 #ifdef IPFILTER_COMPILED
89 # include "netinet/ip_rules.h"
91 #if defined(IPFILTER_BPF) && defined(_KERNEL)
94 #if defined(__FreeBSD_version)
95 # include <sys/malloc.h>
97 #include "netinet/ipl.h"
99 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100 # include <sys/callout.h>
101 extern struct callout ipf_slowtimer_ch;
103 /* END OF INCLUDES */
106 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
107 static const char rcsid[] = "@(#)$FreeBSD$";
108 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
115 extern int blockreason;
118 #define LBUMP(x) softc->x++
119 #define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
121 static INLINE int ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122 static u_32_t ipf_checkcipso __P((fr_info_t *, u_char *, int));
123 static u_32_t ipf_checkripso __P((u_char *));
124 static u_32_t ipf_decaps __P((fr_info_t *, u_32_t, int));
126 static frentry_t *ipf_dolog __P((fr_info_t *, u_32_t *));
128 static int ipf_flushlist __P((ipf_main_softc_t *, int *,
130 static int ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
132 static ipfunc_t ipf_findfunc __P((ipfunc_t));
133 static void *ipf_findlookup __P((ipf_main_softc_t *, int,
135 i6addr_t *, i6addr_t *));
136 static frentry_t *ipf_firewall __P((fr_info_t *, u_32_t *));
137 static int ipf_fr_matcharray __P((fr_info_t *, int *));
138 static int ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
140 static void ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141 static int ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142 static int ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
144 static void ipf_getstat __P((ipf_main_softc_t *,
145 struct friostat *, int));
146 static int ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147 static void ipf_group_free __P((frgroup_t *));
148 static int ipf_grpmapfini __P((struct ipf_main_softc_s *,
150 static int ipf_grpmapinit __P((struct ipf_main_softc_s *,
152 static frentry_t *ipf_nextrule __P((ipf_main_softc_t *, int, int,
154 static int ipf_portcheck __P((frpcmp_t *, u_32_t));
155 static INLINE int ipf_pr_ah __P((fr_info_t *));
156 static INLINE void ipf_pr_esp __P((fr_info_t *));
157 static INLINE void ipf_pr_gre __P((fr_info_t *));
158 static INLINE void ipf_pr_udp __P((fr_info_t *));
159 static INLINE void ipf_pr_tcp __P((fr_info_t *));
160 static INLINE void ipf_pr_icmp __P((fr_info_t *));
161 static INLINE void ipf_pr_ipv4hdr __P((fr_info_t *));
162 static INLINE void ipf_pr_short __P((fr_info_t *, int));
163 static INLINE int ipf_pr_tcpcommon __P((fr_info_t *));
164 static INLINE int ipf_pr_udpcommon __P((fr_info_t *));
165 static void ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
167 static void ipf_rule_expire_insert __P((ipf_main_softc_t *,
169 static int ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
171 static void ipf_token_flush __P((ipf_main_softc_t *));
172 static void ipf_token_unlink __P((ipf_main_softc_t *,
174 static ipftuneable_t *ipf_tune_findbyname __P((ipftuneable_t *,
176 static ipftuneable_t *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
178 static int ipf_updateipid __P((fr_info_t *));
179 static int ipf_settimeout __P((struct ipf_main_softc_s *,
180 struct ipftuneable *,
182 #if !defined(_KERNEL) || SOLARIS
183 static int ppsratecheck(struct timeval *, int *, int);
188 * bit values for identifying presence of individual IP options
189 * All of these tables should be ordered by increasing key value on the left
190 * hand side to allow for binary searching of the array and include a trailer
191 * with a 0 for the bitmask for linear searches to easily find the end with.
193 static const struct optlist ipopts[20] = {
194 { IPOPT_NOP, 0x000001 },
195 { IPOPT_RR, 0x000002 },
196 { IPOPT_ZSU, 0x000004 },
197 { IPOPT_MTUP, 0x000008 },
198 { IPOPT_MTUR, 0x000010 },
199 { IPOPT_ENCODE, 0x000020 },
200 { IPOPT_TS, 0x000040 },
201 { IPOPT_TR, 0x000080 },
202 { IPOPT_SECURITY, 0x000100 },
203 { IPOPT_LSRR, 0x000200 },
204 { IPOPT_E_SEC, 0x000400 },
205 { IPOPT_CIPSO, 0x000800 },
206 { IPOPT_SATID, 0x001000 },
207 { IPOPT_SSRR, 0x002000 },
208 { IPOPT_ADDEXT, 0x004000 },
209 { IPOPT_VISA, 0x008000 },
210 { IPOPT_IMITD, 0x010000 },
211 { IPOPT_EIP, 0x020000 },
212 { IPOPT_FINN, 0x040000 },
217 static const struct optlist ip6exthdr[] = {
218 { IPPROTO_HOPOPTS, 0x000001 },
219 { IPPROTO_IPV6, 0x000002 },
220 { IPPROTO_ROUTING, 0x000004 },
221 { IPPROTO_FRAGMENT, 0x000008 },
222 { IPPROTO_ESP, 0x000010 },
223 { IPPROTO_AH, 0x000020 },
224 { IPPROTO_NONE, 0x000040 },
225 { IPPROTO_DSTOPTS, 0x000080 },
226 { IPPROTO_MOBILITY, 0x000100 },
232 * bit values for identifying presence of individual IP security options
234 static const struct optlist secopt[8] = {
235 { IPSO_CLASS_RES4, 0x01 },
236 { IPSO_CLASS_TOPS, 0x02 },
237 { IPSO_CLASS_SECR, 0x04 },
238 { IPSO_CLASS_RES3, 0x08 },
239 { IPSO_CLASS_CONF, 0x10 },
240 { IPSO_CLASS_UNCL, 0x20 },
241 { IPSO_CLASS_RES2, 0x40 },
242 { IPSO_CLASS_RES1, 0x80 }
245 char ipfilter_version[] = IPL_VERSION;
258 #ifdef IPFILTER_COMPILED
261 #ifdef IPFILTER_CKSUM
275 * Table of functions available for use with call rules.
277 static ipfunc_resolve_t ipf_availfuncs[] = {
278 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280 { "", NULL, NULL, NULL }
283 static ipftuneable_t ipf_main_tuneables[] = {
284 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285 "ipf_flags", 0, 0xffffffff,
286 stsizeof(ipf_main_softc_t, ipf_flags),
288 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
290 stsizeof(ipf_main_softc_t, ipf_active),
291 IPFT_RDONLY, NULL, NULL },
292 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293 "control_forwarding", 0, 1,
294 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
296 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
298 stsizeof(ipf_main_softc_t, ipf_update_ipid),
300 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
302 stsizeof(ipf_main_softc_t, ipf_chksrc),
304 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
306 stsizeof(ipf_main_softc_t, ipf_minttl),
308 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309 "icmp_minfragmtu", 0, 1,
310 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
312 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313 "default_pass", 0, 0xffffffff,
314 stsizeof(ipf_main_softc_t, ipf_pass),
316 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317 "tcp_idle_timeout", 1, 0x7fffffff,
318 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319 0, NULL, ipf_settimeout },
320 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321 "tcp_close_wait", 1, 0x7fffffff,
322 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323 0, NULL, ipf_settimeout },
324 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325 "tcp_last_ack", 1, 0x7fffffff,
326 stsizeof(ipf_main_softc_t, ipf_tcplastack),
327 0, NULL, ipf_settimeout },
328 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329 "tcp_timeout", 1, 0x7fffffff,
330 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331 0, NULL, ipf_settimeout },
332 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333 "tcp_syn_sent", 1, 0x7fffffff,
334 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335 0, NULL, ipf_settimeout },
336 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337 "tcp_syn_received", 1, 0x7fffffff,
338 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339 0, NULL, ipf_settimeout },
340 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341 "tcp_closed", 1, 0x7fffffff,
342 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343 0, NULL, ipf_settimeout },
344 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345 "tcp_half_closed", 1, 0x7fffffff,
346 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347 0, NULL, ipf_settimeout },
348 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349 "tcp_time_wait", 1, 0x7fffffff,
350 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351 0, NULL, ipf_settimeout },
352 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353 "udp_timeout", 1, 0x7fffffff,
354 stsizeof(ipf_main_softc_t, ipf_udptimeout),
355 0, NULL, ipf_settimeout },
356 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357 "udp_ack_timeout", 1, 0x7fffffff,
358 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359 0, NULL, ipf_settimeout },
360 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361 "icmp_timeout", 1, 0x7fffffff,
362 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363 0, NULL, ipf_settimeout },
364 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365 "icmp_ack_timeout", 1, 0x7fffffff,
366 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367 0, NULL, ipf_settimeout },
368 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369 "ip_timeout", 1, 0x7fffffff,
370 stsizeof(ipf_main_softc_t, ipf_iptimeout),
371 0, NULL, ipf_settimeout },
372 #if defined(INSTANCES) && defined(_KERNEL)
373 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374 "intercept_loopback", 0, 1,
375 stsizeof(ipf_main_softc_t, ipf_get_loopback),
376 0, NULL, ipf_set_loopback },
386 * The next section of code is a collection of small routines that set
387 * fields in the fr_info_t structure passed based on properties of the
388 * current packet. There are different routines for the same protocol
389 * for each of IPv4 and IPv6. Adding a new protocol, for which there
390 * will "special" inspection for setup, is now more easily done by adding
391 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392 * adding more code to a growing switch statement.
395 static INLINE int ipf_pr_ah6 __P((fr_info_t *));
396 static INLINE void ipf_pr_esp6 __P((fr_info_t *));
397 static INLINE void ipf_pr_gre6 __P((fr_info_t *));
398 static INLINE void ipf_pr_udp6 __P((fr_info_t *));
399 static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
400 static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
401 static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
402 static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
403 static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
404 static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
405 static INLINE int ipf_pr_routing6 __P((fr_info_t *));
406 static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
407 static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
408 static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
411 /* ------------------------------------------------------------------------ */
412 /* Function: ipf_pr_short6 */
414 /* Parameters: fin(I) - pointer to packet information */
415 /* xmin(I) - minimum header size */
418 /* This is function enforces the 'is a packet too short to be legit' rule */
419 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
420 /* for ipf_pr_short() for more details. */
421 /* ------------------------------------------------------------------------ */
423 ipf_pr_short6(fin, xmin)
428 if (fin->fin_dlen < xmin)
429 fin->fin_flx |= FI_SHORT;
433 /* ------------------------------------------------------------------------ */
434 /* Function: ipf_pr_ipv6hdr */
436 /* Parameters: fin(I) - pointer to packet information */
439 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
440 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
441 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
442 /* of that possibility arising. */
443 /* ------------------------------------------------------------------------ */
448 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449 int p, go = 1, i, hdrcount;
450 fr_ip_t *fi = &fin->fin_fi;
461 fi->fi_ttl = ip6->ip6_hlim;
462 fi->fi_src.in6 = ip6->ip6_src;
463 fin->fin_crc += fi->fi_src.i6[0];
464 fin->fin_crc += fi->fi_src.i6[1];
465 fin->fin_crc += fi->fi_src.i6[2];
466 fin->fin_crc += fi->fi_src.i6[3];
467 fi->fi_dst.in6 = ip6->ip6_dst;
468 fin->fin_crc += fi->fi_dst.i6[0];
469 fin->fin_crc += fi->fi_dst.i6[1];
470 fin->fin_crc += fi->fi_dst.i6[2];
471 fin->fin_crc += fi->fi_dst.i6[3];
473 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
477 while (go && !(fin->fin_flx & FI_SHORT)) {
490 case IPPROTO_ICMPV6 :
500 case IPPROTO_HOPOPTS :
501 p = ipf_pr_hopopts6(fin);
504 case IPPROTO_MOBILITY :
505 p = ipf_pr_mobility6(fin);
508 case IPPROTO_DSTOPTS :
509 p = ipf_pr_dstopts6(fin);
512 case IPPROTO_ROUTING :
513 p = ipf_pr_routing6(fin);
526 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527 if (ip6exthdr[i].ol_val == p) {
528 fin->fin_flx |= ip6exthdr[i].ol_bit;
538 case IPPROTO_FRAGMENT :
539 p = ipf_pr_fragment6(fin);
541 * Given that the only fragments we want to let through
542 * (where fin_off != 0) are those where the non-first
543 * fragments only have data, we can safely stop looking
544 * at headers if this is a non-leading fragment.
546 if (fin->fin_off != 0)
557 * It is important to note that at this point, for the
558 * extension headers (go != 0), the entire header may not have
559 * been pulled up when the code gets to this point. This is
560 * only done for "go != 0" because the other header handlers
561 * will all pullup their complete header. The other indicator
562 * of an incomplete packet is that this was just an extension
565 if ((go != 0) && (p != IPPROTO_NONE) &&
566 (ipf_pr_pullup(fin, 0) == -1)) {
573 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574 * and destroy whatever packet was here. The caller of this function
575 * expects us to return if there is a problem with ipf_pullup.
577 if (fin->fin_m == NULL) {
578 ipf_main_softc_t *softc = fin->fin_main_soft;
580 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
587 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
590 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591 ipf_main_softc_t *softc = fin->fin_main_soft;
593 fin->fin_flx |= FI_BAD;
594 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
601 /* ------------------------------------------------------------------------ */
602 /* Function: ipf_pr_ipv6exthdr */
603 /* Returns: struct ip6_ext * - pointer to the start of the next header */
604 /* or NULL if there is a prolblem. */
605 /* Parameters: fin(I) - pointer to packet information */
606 /* multiple(I) - flag indicating yes/no if multiple occurances */
607 /* of this extension header are allowed. */
608 /* proto(I) - protocol number for this extension header */
611 /* This function embodies a number of common checks that all IPv6 extension */
612 /* headers must be subjected to. For example, making sure the packet is */
613 /* big enough for it to be in, checking if it is repeated and setting a */
614 /* flag to indicate its presence. */
615 /* ------------------------------------------------------------------------ */
616 static INLINE struct ip6_ext *
617 ipf_pr_ipv6exthdr(fin, multiple, proto)
621 ipf_main_softc_t *softc = fin->fin_main_soft;
626 fin->fin_flx |= FI_V6EXTHDR;
628 /* 8 is default length of extension hdr */
629 if ((fin->fin_dlen - 8) < 0) {
630 fin->fin_flx |= FI_SHORT;
631 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
635 if (ipf_pr_pullup(fin, 8) == -1) {
636 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
643 case IPPROTO_FRAGMENT :
647 shift = 8 + (hdr->ip6e_len << 3);
651 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
652 fin->fin_flx |= FI_BAD;
653 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
658 fin->fin_dp = (char *)fin->fin_dp + shift;
659 fin->fin_dlen -= shift;
662 * If we have seen a fragment header, do not set any flags to indicate
663 * the presence of this extension header as it has no impact on the
664 * end result until after it has been defragmented.
666 if (fin->fin_flx & FI_FRAG)
669 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670 if (ip6exthdr[i].ol_val == proto) {
672 * Most IPv6 extension headers are only allowed once.
674 if ((multiple == 0) &&
675 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676 fin->fin_flx |= FI_BAD;
677 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
679 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
687 /* ------------------------------------------------------------------------ */
688 /* Function: ipf_pr_hopopts6 */
689 /* Returns: int - value of the next header or IPPROTO_NONE if error */
690 /* Parameters: fin(I) - pointer to packet information */
693 /* This is function checks pending hop by hop options extension header */
694 /* ------------------------------------------------------------------------ */
701 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
704 return hdr->ip6e_nxt;
708 /* ------------------------------------------------------------------------ */
709 /* Function: ipf_pr_mobility6 */
710 /* Returns: int - value of the next header or IPPROTO_NONE if error */
711 /* Parameters: fin(I) - pointer to packet information */
714 /* This is function checks the IPv6 mobility extension header */
715 /* ------------------------------------------------------------------------ */
717 ipf_pr_mobility6(fin)
722 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
725 return hdr->ip6e_nxt;
729 /* ------------------------------------------------------------------------ */
730 /* Function: ipf_pr_routing6 */
731 /* Returns: int - value of the next header or IPPROTO_NONE if error */
732 /* Parameters: fin(I) - pointer to packet information */
735 /* This is function checks pending routing extension header */
736 /* ------------------------------------------------------------------------ */
741 struct ip6_routing *hdr;
743 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
747 switch (hdr->ip6r_type)
751 * Nasty extension header length?
753 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755 ipf_main_softc_t *softc = fin->fin_main_soft;
757 fin->fin_flx |= FI_BAD;
758 DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
768 return hdr->ip6r_nxt;
772 /* ------------------------------------------------------------------------ */
773 /* Function: ipf_pr_fragment6 */
774 /* Returns: int - value of the next header or IPPROTO_NONE if error */
775 /* Parameters: fin(I) - pointer to packet information */
778 /* Examine the IPv6 fragment header and extract fragment offset information.*/
780 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
782 /* packets with a fragment header can fit into. They are as follows: */
784 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
785 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
786 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
787 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
788 /* 5. [IPV6][0-n EH][FH][data] */
790 /* IPV6 = IPv6 header, FH = Fragment Header, */
791 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
793 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
794 /* scenario in which they happen is in extreme circumstances that are most */
795 /* likely to be an indication of an attack rather than normal traffic. */
796 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
797 /* are two rules that can be used to guard against type 3 packets: L4 */
798 /* headers must always be in a packet that has the offset field set to 0 */
799 /* and no packet is allowed to overlay that where offset = 0. */
800 /* ------------------------------------------------------------------------ */
802 ipf_pr_fragment6(fin)
805 ipf_main_softc_t *softc = fin->fin_main_soft;
806 struct ip6_frag *frag;
808 fin->fin_flx |= FI_FRAG;
810 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
812 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
816 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
818 * Any fragment that isn't the last fragment must have its
819 * length as a multiple of 8.
821 if ((fin->fin_plen & 7) != 0) {
822 fin->fin_flx |= FI_BAD;
823 DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
827 fin->fin_fraghdr = frag;
828 fin->fin_id = frag->ip6f_ident;
829 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830 if (fin->fin_off != 0)
831 fin->fin_flx |= FI_FRAGBODY;
834 * Jumbograms aren't handled, so the max. length is 64k
836 if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837 fin->fin_flx |= FI_BAD;
838 DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
842 * We don't know where the transport layer header (or whatever is next
843 * is), as it could be behind destination options (amongst others) so
844 * return the fragment header as the type of packet this is. Note that
845 * this effectively disables the fragment cache for > 1 protocol at a
848 return frag->ip6f_nxt;
852 /* ------------------------------------------------------------------------ */
853 /* Function: ipf_pr_dstopts6 */
854 /* Returns: int - value of the next header or IPPROTO_NONE if error */
855 /* Parameters: fin(I) - pointer to packet information */
858 /* This is function checks pending destination options extension header */
859 /* ------------------------------------------------------------------------ */
864 ipf_main_softc_t *softc = fin->fin_main_soft;
867 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
869 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
872 return hdr->ip6e_nxt;
876 /* ------------------------------------------------------------------------ */
877 /* Function: ipf_pr_icmp6 */
879 /* Parameters: fin(I) - pointer to packet information */
882 /* This routine is mainly concerned with determining the minimum valid size */
883 /* for an ICMPv6 packet. */
884 /* ------------------------------------------------------------------------ */
889 int minicmpsz = sizeof(struct icmp6_hdr);
890 struct icmp6_hdr *icmp6;
892 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893 ipf_main_softc_t *softc = fin->fin_main_soft;
895 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
899 if (fin->fin_dlen > 1) {
904 fin->fin_data[0] = *(u_short *)icmp6;
906 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907 fin->fin_flx |= FI_ICMPQUERY;
909 switch (icmp6->icmp6_type)
911 case ICMP6_ECHO_REPLY :
912 case ICMP6_ECHO_REQUEST :
913 if (fin->fin_dlen >= 6)
914 fin->fin_data[1] = icmp6->icmp6_id;
915 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
918 case ICMP6_DST_UNREACH :
919 case ICMP6_PACKET_TOO_BIG :
920 case ICMP6_TIME_EXCEEDED :
921 case ICMP6_PARAM_PROB :
922 fin->fin_flx |= FI_ICMPERR;
923 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
927 if (M_LEN(fin->fin_m) < fin->fin_plen) {
928 if (ipf_coalesce(fin) != 1)
932 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
936 * If the destination of this packet doesn't match the
937 * source of the original packet then this packet is
941 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942 if (IP6_NEQ(&fin->fin_fi.fi_dst,
943 (i6addr_t *)&ip6->ip6_src)) {
944 fin->fin_flx |= FI_BAD;
945 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
953 ipf_pr_short6(fin, minicmpsz);
954 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955 u_char p = fin->fin_p;
957 fin->fin_p = IPPROTO_ICMPV6;
964 /* ------------------------------------------------------------------------ */
965 /* Function: ipf_pr_udp6 */
967 /* Parameters: fin(I) - pointer to packet information */
970 /* Analyse the packet for IPv6/UDP properties. */
971 /* Is not expected to be called for fragmented packets. */
972 /* ------------------------------------------------------------------------ */
978 if (ipf_pr_udpcommon(fin) == 0) {
979 u_char p = fin->fin_p;
981 fin->fin_p = IPPROTO_UDP;
988 /* ------------------------------------------------------------------------ */
989 /* Function: ipf_pr_tcp6 */
991 /* Parameters: fin(I) - pointer to packet information */
994 /* Analyse the packet for IPv6/TCP properties. */
995 /* Is not expected to be called for fragmented packets. */
996 /* ------------------------------------------------------------------------ */
1002 if (ipf_pr_tcpcommon(fin) == 0) {
1003 u_char p = fin->fin_p;
1005 fin->fin_p = IPPROTO_TCP;
1006 ipf_checkv6sum(fin);
1012 /* ------------------------------------------------------------------------ */
1013 /* Function: ipf_pr_esp6 */
1015 /* Parameters: fin(I) - pointer to packet information */
1018 /* Analyse the packet for ESP properties. */
1019 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1020 /* even though the newer ESP packets must also have a sequence number that */
1021 /* is 32bits as well, it is not possible(?) to determine the version from a */
1022 /* simple packet header. */
1023 /* ------------------------------------------------------------------------ */
1029 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030 ipf_main_softc_t *softc = fin->fin_main_soft;
1032 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1038 /* ------------------------------------------------------------------------ */
1039 /* Function: ipf_pr_ah6 */
1040 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1041 /* Parameters: fin(I) - pointer to packet information */
1044 /* Analyse the packet for AH properties. */
1045 /* The minimum length is taken to be the combination of all fields in the */
1046 /* header being present and no authentication data (null algorithm used.) */
1047 /* ------------------------------------------------------------------------ */
1054 fin->fin_flx |= FI_AH;
1056 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1058 ipf_main_softc_t *softc = fin->fin_main_soft;
1060 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061 return IPPROTO_NONE;
1064 ipf_pr_short6(fin, sizeof(*ah));
1067 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068 * enough data to satisfy ah_next (the very first one.)
1074 /* ------------------------------------------------------------------------ */
1075 /* Function: ipf_pr_gre6 */
1077 /* Parameters: fin(I) - pointer to packet information */
1079 /* Analyse the packet for GRE properties. */
1080 /* ------------------------------------------------------------------------ */
1087 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088 ipf_main_softc_t *softc = fin->fin_main_soft;
1090 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1095 if (GRE_REV(gre->gr_flags) == 1)
1096 fin->fin_data[0] = gre->gr_call;
1098 #endif /* USE_INET6 */
1101 /* ------------------------------------------------------------------------ */
1102 /* Function: ipf_pr_pullup */
1103 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1104 /* Parameters: fin(I) - pointer to packet information */
1105 /* plen(I) - length (excluding L3 header) to pullup */
1107 /* Short inline function to cut down on code duplication to perform a call */
1108 /* to ipf_pullup to ensure there is the required amount of data, */
1109 /* consecutively in the packet buffer. */
1111 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1112 /* points to the first byte after the complete layer 3 header, which will */
1113 /* include all of the known extension headers for IPv6 or options for IPv4. */
1115 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1116 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1117 /* - fin_ip) to what is passed through. */
1118 /* ------------------------------------------------------------------------ */
1120 ipf_pr_pullup(fin, plen)
1124 ipf_main_softc_t *softc = fin->fin_main_soft;
1126 if (fin->fin_m != NULL) {
1127 if (fin->fin_dp != NULL)
1128 plen += (char *)fin->fin_dp -
1129 ((char *)fin->fin_ip + fin->fin_hlen);
1130 plen += fin->fin_hlen;
1131 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132 #if defined(_KERNEL)
1133 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134 DT(ipf_pullup_fail);
1135 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1138 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1140 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1142 * Fake ipf_pullup failing
1144 fin->fin_reason = FRB_PULLUP;
1145 *fin->fin_mp = NULL;
1156 /* ------------------------------------------------------------------------ */
1157 /* Function: ipf_pr_short */
1159 /* Parameters: fin(I) - pointer to packet information */
1160 /* xmin(I) - minimum header size */
1162 /* Check if a packet is "short" as defined by xmin. The rule we are */
1163 /* applying here is that the packet must not be fragmented within the layer */
1164 /* 4 header. That is, it must not be a fragment that has its offset set to */
1165 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1166 /* entire layer 4 header must be present (min). */
1167 /* ------------------------------------------------------------------------ */
1169 ipf_pr_short(fin, xmin)
1174 if (fin->fin_off == 0) {
1175 if (fin->fin_dlen < xmin)
1176 fin->fin_flx |= FI_SHORT;
1177 } else if (fin->fin_off < xmin) {
1178 fin->fin_flx |= FI_SHORT;
1183 /* ------------------------------------------------------------------------ */
1184 /* Function: ipf_pr_icmp */
1186 /* Parameters: fin(I) - pointer to packet information */
1189 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1190 /* except extrememly bad packets, both type and code will be present. */
1191 /* The expected minimum size of an ICMP packet is very much dependent on */
1192 /* the type of it. */
1194 /* XXX - other ICMP sanity checks? */
1195 /* ------------------------------------------------------------------------ */
1200 ipf_main_softc_t *softc = fin->fin_main_soft;
1201 int minicmpsz = sizeof(struct icmp);
1205 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1207 if (fin->fin_off != 0) {
1208 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1212 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1219 fin->fin_data[0] = *(u_short *)icmp;
1220 fin->fin_data[1] = icmp->icmp_id;
1222 switch (icmp->icmp_type)
1224 case ICMP_ECHOREPLY :
1226 /* Router discovery messaes - RFC 1256 */
1227 case ICMP_ROUTERADVERT :
1228 case ICMP_ROUTERSOLICIT :
1229 fin->fin_flx |= FI_ICMPQUERY;
1230 minicmpsz = ICMP_MINLEN;
1233 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234 * 3 * timestamp(3 * 4)
1237 case ICMP_TSTAMPREPLY :
1238 fin->fin_flx |= FI_ICMPQUERY;
1242 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1246 case ICMP_IREQREPLY :
1248 case ICMP_MASKREPLY :
1249 fin->fin_flx |= FI_ICMPQUERY;
1253 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1257 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259 fin->fin_flx |= FI_BAD;
1260 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1265 case ICMP_SOURCEQUENCH :
1266 case ICMP_REDIRECT :
1267 case ICMP_TIMXCEED :
1268 case ICMP_PARAMPROB :
1269 fin->fin_flx |= FI_ICMPERR;
1270 if (ipf_coalesce(fin) != 1) {
1271 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1276 * ICMP error packets should not be generated for IP
1277 * packets that are a fragment that isn't the first
1280 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282 fin->fin_flx |= FI_BAD;
1283 DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1287 * If the destination of this packet doesn't match the
1288 * source of the original packet then this packet is
1291 if (oip->ip_src.s_addr != fin->fin_daddr) {
1292 fin->fin_flx |= FI_BAD;
1293 DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1300 ipf_pr_short(fin, minicmpsz);
1302 ipf_checkv4sum(fin);
1306 /* ------------------------------------------------------------------------ */
1307 /* Function: ipf_pr_tcpcommon */
1308 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1309 /* Parameters: fin(I) - pointer to packet information */
1311 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1312 /* and make some checks with how they interact with other fields. */
1313 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1314 /* valid and mark the packet as bad if not. */
1315 /* ------------------------------------------------------------------------ */
1317 ipf_pr_tcpcommon(fin)
1320 ipf_main_softc_t *softc = fin->fin_main_soft;
1324 fin->fin_flx |= FI_TCPUDP;
1325 if (fin->fin_off != 0) {
1326 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1330 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1336 if (fin->fin_dlen > 3) {
1337 fin->fin_sport = ntohs(tcp->th_sport);
1338 fin->fin_dport = ntohs(tcp->th_dport);
1341 if ((fin->fin_flx & FI_SHORT) != 0) {
1342 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1347 * Use of the TCP data offset *must* result in a value that is at
1348 * least the same size as the TCP header.
1350 tlen = TCP_OFF(tcp) << 2;
1351 if (tlen < sizeof(tcphdr_t)) {
1352 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353 fin->fin_flx |= FI_BAD;
1354 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1358 flags = tcp->th_flags;
1359 fin->fin_tcpf = tcp->th_flags;
1362 * If the urgent flag is set, then the urgent pointer must
1363 * also be set and vice versa. Good TCP packets do not have
1364 * just one of these set.
1366 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367 fin->fin_flx |= FI_BAD;
1368 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1370 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1372 * Ignore this case (#if 0) as it shows up in "real"
1373 * traffic with bogus values in the urgent pointer field.
1375 fin->fin_flx |= FI_BAD;
1376 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1378 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381 fin->fin_flx |= FI_BAD;
1382 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1384 } else if (((flags & TH_SYN) != 0) &&
1385 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1387 * SYN with URG and PUSH set is not for normal TCP but it is
1388 * possible(?) with T/TCP...but who uses T/TCP?
1390 fin->fin_flx |= FI_BAD;
1391 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1393 } else if (!(flags & TH_ACK)) {
1395 * If the ack bit isn't set, then either the SYN or
1396 * RST bit must be set. If the SYN bit is set, then
1397 * we expect the ACK field to be 0. If the ACK is
1398 * not set and if URG, PSH or FIN are set, consdier
1399 * that to indicate a bad TCP packet.
1401 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1403 * Cisco PIX sets the ACK field to a random value.
1404 * In light of this, do not set FI_BAD until a patch
1405 * is available from Cisco to ensure that
1406 * interoperability between existing systems is
1409 /*fin->fin_flx |= FI_BAD*/;
1410 /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411 } else if (!(flags & (TH_RST|TH_SYN))) {
1412 fin->fin_flx |= FI_BAD;
1413 DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415 fin->fin_flx |= FI_BAD;
1416 DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1419 if (fin->fin_flx & FI_BAD) {
1420 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1425 * At this point, it's not exactly clear what is to be gained by
1426 * marking up which TCP options are and are not present. The one we
1427 * are most interested in is the TCP window scale. This is only in
1428 * a SYN packet [RFC1323] so we don't need this here...?
1429 * Now if we were to analyse the header for passive fingerprinting,
1430 * then that might add some weight to adding this...
1432 if (tlen == sizeof(tcphdr_t)) {
1436 if (ipf_pr_pullup(fin, tlen) == -1) {
1437 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1444 s = (u_char *)(tcp + 1);
1445 off = IP_HL(ip) << 2;
1447 if (fin->fin_mp != NULL) {
1448 mb_t *m = *fin->fin_mp;
1450 if (off + tlen > M_LEN(m))
1454 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1458 else if (opt == TCPOPT_NOP)
1464 if (ol < 2 || ol > tlen)
1468 for (i = 9, mv = 4; mv >= 0; ) {
1470 if (opt == (u_char)op->ol_val) {
1471 optmsk |= op->ol_bit;
1485 /* ------------------------------------------------------------------------ */
1486 /* Function: ipf_pr_udpcommon */
1487 /* Returns: int - 0 = header ok, 1 = bad packet */
1488 /* Parameters: fin(I) - pointer to packet information */
1490 /* Extract the UDP source and destination ports, if present. If compiled */
1491 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1492 /* ------------------------------------------------------------------------ */
1494 ipf_pr_udpcommon(fin)
1499 fin->fin_flx |= FI_TCPUDP;
1501 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503 ipf_main_softc_t *softc = fin->fin_main_soft;
1505 fin->fin_flx |= FI_SHORT;
1506 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1512 fin->fin_sport = ntohs(udp->uh_sport);
1513 fin->fin_dport = ntohs(udp->uh_dport);
1520 /* ------------------------------------------------------------------------ */
1521 /* Function: ipf_pr_tcp */
1523 /* Parameters: fin(I) - pointer to packet information */
1526 /* Analyse the packet for IPv4/TCP properties. */
1527 /* ------------------------------------------------------------------------ */
1533 ipf_pr_short(fin, sizeof(tcphdr_t));
1535 if (ipf_pr_tcpcommon(fin) == 0)
1536 ipf_checkv4sum(fin);
1540 /* ------------------------------------------------------------------------ */
1541 /* Function: ipf_pr_udp */
1543 /* Parameters: fin(I) - pointer to packet information */
1546 /* Analyse the packet for IPv4/UDP properties. */
1547 /* ------------------------------------------------------------------------ */
1553 ipf_pr_short(fin, sizeof(udphdr_t));
1555 if (ipf_pr_udpcommon(fin) == 0)
1556 ipf_checkv4sum(fin);
1560 /* ------------------------------------------------------------------------ */
1561 /* Function: ipf_pr_esp */
1563 /* Parameters: fin(I) - pointer to packet information */
1565 /* Analyse the packet for ESP properties. */
1566 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1567 /* even though the newer ESP packets must also have a sequence number that */
1568 /* is 32bits as well, it is not possible(?) to determine the version from a */
1569 /* simple packet header. */
1570 /* ------------------------------------------------------------------------ */
1576 if (fin->fin_off == 0) {
1577 ipf_pr_short(fin, 8);
1578 if (ipf_pr_pullup(fin, 8) == -1) {
1579 ipf_main_softc_t *softc = fin->fin_main_soft;
1581 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1587 /* ------------------------------------------------------------------------ */
1588 /* Function: ipf_pr_ah */
1589 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1590 /* Parameters: fin(I) - pointer to packet information */
1592 /* Analyse the packet for AH properties. */
1593 /* The minimum length is taken to be the combination of all fields in the */
1594 /* header being present and no authentication data (null algorithm used.) */
1595 /* ------------------------------------------------------------------------ */
1600 ipf_main_softc_t *softc = fin->fin_main_soft;
1604 fin->fin_flx |= FI_AH;
1605 ipf_pr_short(fin, sizeof(*ah));
1607 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609 return IPPROTO_NONE;
1612 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613 DT(fr_v4_ah_pullup_1);
1614 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615 return IPPROTO_NONE;
1618 ah = (authhdr_t *)fin->fin_dp;
1620 len = (ah->ah_plen + 2) << 2;
1621 ipf_pr_short(fin, len);
1622 if (ipf_pr_pullup(fin, len) == -1) {
1623 DT(fr_v4_ah_pullup_2);
1624 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625 return IPPROTO_NONE;
1629 * Adjust fin_dp and fin_dlen for skipping over the authentication
1632 fin->fin_dp = (char *)fin->fin_dp + len;
1633 fin->fin_dlen -= len;
1638 /* ------------------------------------------------------------------------ */
1639 /* Function: ipf_pr_gre */
1641 /* Parameters: fin(I) - pointer to packet information */
1643 /* Analyse the packet for GRE properties. */
1644 /* ------------------------------------------------------------------------ */
1649 ipf_main_softc_t *softc = fin->fin_main_soft;
1652 ipf_pr_short(fin, sizeof(grehdr_t));
1654 if (fin->fin_off != 0) {
1655 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1659 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1665 if (GRE_REV(gre->gr_flags) == 1)
1666 fin->fin_data[0] = gre->gr_call;
1670 /* ------------------------------------------------------------------------ */
1671 /* Function: ipf_pr_ipv4hdr */
1673 /* Parameters: fin(I) - pointer to packet information */
1676 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1677 /* Check all options present and flag their presence if any exist. */
1678 /* ------------------------------------------------------------------------ */
1683 u_short optmsk = 0, secmsk = 0, auth = 0;
1684 int hlen, ol, mv, p, i;
1685 const struct optlist *op;
1692 hlen = fin->fin_hlen;
1698 fi->fi_tos = ip->ip_tos;
1699 fin->fin_id = ip->ip_id;
1700 off = ntohs(ip->ip_off);
1702 /* Get both TTL and protocol */
1703 fi->fi_p = ip->ip_p;
1704 fi->fi_ttl = ip->ip_ttl;
1706 /* Zero out bits not used in IPv6 address */
1707 fi->fi_src.i6[1] = 0;
1708 fi->fi_src.i6[2] = 0;
1709 fi->fi_src.i6[3] = 0;
1710 fi->fi_dst.i6[1] = 0;
1711 fi->fi_dst.i6[2] = 0;
1712 fi->fi_dst.i6[3] = 0;
1714 fi->fi_saddr = ip->ip_src.s_addr;
1715 fin->fin_crc += fi->fi_saddr;
1716 fi->fi_daddr = ip->ip_dst.s_addr;
1717 fin->fin_crc += fi->fi_daddr;
1718 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1722 * set packet attribute flags based on the offset and
1723 * calculate the byte offset that it represents.
1725 off &= IP_MF|IP_OFFMASK;
1727 int morefrag = off & IP_MF;
1729 fi->fi_flx |= FI_FRAG;
1732 fin->fin_flx |= FI_FRAGBODY;
1734 if ((off + fin->fin_dlen > 65535) ||
1735 (fin->fin_dlen == 0) ||
1736 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1738 * The length of the packet, starting at its
1739 * offset cannot exceed 65535 (0xffff) as the
1740 * length of an IP packet is only 16 bits.
1742 * Any fragment that isn't the last fragment
1743 * must have a length greater than 0 and it
1744 * must be an even multiple of 8.
1746 fi->fi_flx |= FI_BAD;
1747 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1754 * Call per-protocol setup and checking
1756 if (p == IPPROTO_AH) {
1758 * Treat AH differently because we expect there to be another
1759 * layer 4 header after it.
1788 * If it is a standard IP header (no options), set the flag fields
1789 * which relate to options to 0.
1791 if (hlen == sizeof(*ip)) {
1799 * So the IP header has some IP options attached. Walk the entire
1800 * list of options present with this packet and set flags to indicate
1801 * which ones are here and which ones are not. For the somewhat out
1802 * of date and obscure security classification options, set a flag to
1803 * represent which classification is present.
1805 fi->fi_flx |= FI_OPTIONS;
1807 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1811 else if (opt == IPOPT_NOP)
1817 if (ol < 2 || ol > hlen)
1820 for (i = 9, mv = 4; mv >= 0; ) {
1823 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1828 case IPOPT_SECURITY :
1829 if (optmsk & op->ol_bit) {
1830 fin->fin_flx |= FI_BAD;
1831 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1833 doi = ipf_checkripso(s);
1835 auth = doi & 0xffff;
1841 if (optmsk & op->ol_bit) {
1842 fin->fin_flx |= FI_BAD;
1843 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1845 doi = ipf_checkcipso(fin,
1848 auth = doi & 0xffff;
1852 optmsk |= op->ol_bit;
1855 if (opt < op->ol_val)
1868 if (auth && !(auth & 0x0100))
1870 fi->fi_optmsk = optmsk;
1871 fi->fi_secmsk = secmsk;
1876 /* ------------------------------------------------------------------------ */
1877 /* Function: ipf_checkripso */
1879 /* Parameters: s(I) - pointer to start of RIPSO option */
1881 /* ------------------------------------------------------------------------ */
1886 const struct optlist *sp;
1887 u_short secmsk = 0, auth = 0;
1891 sec = *(s + 2); /* classification */
1892 for (j = 3, m = 2; m >= 0; ) {
1894 if (sec == sp->ol_val) {
1895 secmsk |= sp->ol_bit;
1901 if (sec < sp->ol_val)
1908 return (secmsk << 16) | auth;
1912 /* ------------------------------------------------------------------------ */
1913 /* Function: ipf_checkcipso */
1914 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1915 /* Parameters: fin(IO) - pointer to packet information */
1916 /* s(I) - pointer to start of CIPSO option */
1917 /* ol(I) - length of CIPSO option field */
1919 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1920 /* header and returns that whilst also storing the highest sensitivity */
1921 /* value found in the fr_info_t structure. */
1923 /* No attempt is made to extract the category bitmaps as these are defined */
1924 /* by the user (rather than the protocol) and can be rather numerous on the */
1926 /* ------------------------------------------------------------------------ */
1928 ipf_checkcipso(fin, s, ol)
1933 ipf_main_softc_t *softc = fin->fin_main_soft;
1936 u_char *t, tag, tlen, sensitivity;
1939 if (ol < 6 || ol > 40) {
1940 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1941 fin->fin_flx |= FI_BAD;
1942 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1947 fi->fi_sensitivity = 0;
1949 * The DOI field MUST be there.
1951 bcopy(s + 2, &doi, sizeof(doi));
1953 t = (u_char *)s + 6;
1954 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1957 if (tlen > len || tlen < 4 || tlen > 34) {
1958 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1959 fin->fin_flx |= FI_BAD;
1960 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1966 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1967 * draft (16 July 1992) that has expired.
1970 fin->fin_flx |= FI_BAD;
1971 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1973 } else if (tag == 1) {
1974 if (*(t + 2) != 0) {
1975 fin->fin_flx |= FI_BAD;
1976 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1979 sensitivity = *(t + 3);
1980 /* Category bitmap for categories 0-239 */
1982 } else if (tag == 4) {
1983 if (*(t + 2) != 0) {
1984 fin->fin_flx |= FI_BAD;
1985 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1988 sensitivity = *(t + 3);
1989 /* Enumerated categories, 16bits each, upto 15 */
1991 } else if (tag == 5) {
1992 if (*(t + 2) != 0) {
1993 fin->fin_flx |= FI_BAD;
1994 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1997 sensitivity = *(t + 3);
1998 /* Range of categories (2*16bits), up to 7 pairs */
2000 } else if (tag > 127) {
2001 /* Custom defined DOI */
2004 fin->fin_flx |= FI_BAD;
2005 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2009 if (sensitivity > fi->fi_sensitivity)
2010 fi->fi_sensitivity = sensitivity;
2017 /* ------------------------------------------------------------------------ */
2018 /* Function: ipf_makefrip */
2019 /* Returns: int - 0 == packet ok, -1 == packet freed */
2020 /* Parameters: hlen(I) - length of IP packet header */
2021 /* ip(I) - pointer to the IP header */
2022 /* fin(IO) - pointer to packet information */
2024 /* Compact the IP header into a structure which contains just the info. */
2025 /* which is useful for comparing IP headers with and store this information */
2026 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2027 /* this function will be called with either an IPv4 or IPv6 packet. */
2028 /* ------------------------------------------------------------------------ */
2030 ipf_makefrip(hlen, ip, fin)
2035 ipf_main_softc_t *softc = fin->fin_main_soft;
2039 fin->fin_hlen = (u_short)hlen;
2041 fin->fin_rule = 0xffffffff;
2042 fin->fin_group[0] = -1;
2043 fin->fin_group[1] = '\0';
2044 fin->fin_dp = (char *)ip + hlen;
2048 fin->fin_plen = ntohs(ip->ip_len);
2049 fin->fin_dlen = fin->fin_plen - hlen;
2050 ipf_pr_ipv4hdr(fin);
2052 } else if (v == 6) {
2053 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2054 fin->fin_dlen = fin->fin_plen;
2055 fin->fin_plen += hlen;
2057 ipf_pr_ipv6hdr(fin);
2060 if (fin->fin_ip == NULL) {
2061 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2068 /* ------------------------------------------------------------------------ */
2069 /* Function: ipf_portcheck */
2070 /* Returns: int - 1 == port matched, 0 == port match failed */
2071 /* Parameters: frp(I) - pointer to port check `expression' */
2072 /* pop(I) - port number to evaluate */
2074 /* Perform a comparison of a port number against some other(s), using a */
2075 /* structure with compare information stored in it. */
2076 /* ------------------------------------------------------------------------ */
2078 ipf_portcheck(frp, pop)
2088 * Do opposite test to that required and continue if that succeeds.
2090 switch (frp->frp_cmp)
2093 if (pop != po) /* EQUAL */
2097 if (pop == po) /* NOTEQUAL */
2101 if (pop >= po) /* LESSTHAN */
2105 if (pop <= po) /* GREATERTHAN */
2109 if (pop > po) /* LT or EQ */
2113 if (pop < po) /* GT or EQ */
2117 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2121 if (pop <= po || pop >= frp->frp_top) /* In range */
2125 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2135 /* ------------------------------------------------------------------------ */
2136 /* Function: ipf_tcpudpchk */
2137 /* Returns: int - 1 == protocol matched, 0 == check failed */
2138 /* Parameters: fda(I) - pointer to packet information */
2139 /* ft(I) - pointer to structure with comparison data */
2141 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2142 /* structure containing information that we want to match against. */
2143 /* ------------------------------------------------------------------------ */
2145 ipf_tcpudpchk(fi, ft)
2152 * Both ports should *always* be in the first fragment.
2153 * So far, I cannot find any cases where they can not be.
2155 * compare destination ports
2158 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2161 * compare source ports
2163 if (err && ft->ftu_scmp)
2164 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2167 * If we don't have all the TCP/UDP header, then how can we
2168 * expect to do any sort of match on it ? If we were looking for
2169 * TCP flags, then NO match. If not, then match (which should
2170 * satisfy the "short" class too).
2172 if (err && (fi->fi_p == IPPROTO_TCP)) {
2173 if (fi->fi_flx & FI_SHORT)
2174 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2176 * Match the flags ? If not, abort this match.
2178 if (ft->ftu_tcpfm &&
2179 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2180 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2181 ft->ftu_tcpfm, ft->ftu_tcpf));
2189 /* ------------------------------------------------------------------------ */
2190 /* Function: ipf_check_ipf */
2191 /* Returns: int - 0 == match, else no match */
2192 /* Parameters: fin(I) - pointer to packet information */
2193 /* fr(I) - pointer to filter rule */
2194 /* portcmp(I) - flag indicating whether to attempt matching on */
2195 /* TCP/UDP port data. */
2197 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2198 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2199 /* this function. */
2200 /* ------------------------------------------------------------------------ */
2202 ipf_check_ipf(fin, fr, portcmp)
2207 u_32_t *ld, *lm, *lip;
2215 lm = (u_32_t *)&fri->fri_mip;
2216 ld = (u_32_t *)&fri->fri_ip;
2219 * first 32 bits to check coversion:
2220 * IP version, TOS, TTL, protocol
2222 i = ((*lip & *lm) != *ld);
2223 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2224 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2229 * Next 32 bits is a constructed bitmask indicating which IP options
2230 * are present (if any) in this packet.
2233 i = ((*lip & *lm) != *ld);
2234 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2235 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2241 * Unrolled loops (4 each, for 32 bits) for address checks.
2244 * Check the source address.
2246 if (fr->fr_satype == FRI_LOOKUP) {
2247 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2248 fi->fi_v, lip, fin->fin_plen);
2255 i = ((*lip & *lm) != *ld);
2256 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2257 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2258 if (fi->fi_v == 6) {
2260 i |= ((*lip & *lm) != *ld);
2261 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2262 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2264 i |= ((*lip & *lm) != *ld);
2265 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2266 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2268 i |= ((*lip & *lm) != *ld);
2269 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2270 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2277 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2282 * Check the destination address.
2285 if (fr->fr_datype == FRI_LOOKUP) {
2286 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2287 fi->fi_v, lip, fin->fin_plen);
2294 i = ((*lip & *lm) != *ld);
2295 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2296 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2297 if (fi->fi_v == 6) {
2299 i |= ((*lip & *lm) != *ld);
2300 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2301 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2303 i |= ((*lip & *lm) != *ld);
2304 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2305 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2307 i |= ((*lip & *lm) != *ld);
2308 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2309 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2316 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2320 * IP addresses matched. The next 32bits contains:
2321 * mast of old IP header security & authentication bits.
2324 i = (*ld - (*lip & *lm));
2325 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2328 * Next we have 32 bits of packet flags.
2331 i |= (*ld - (*lip & *lm));
2332 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2336 * If a fragment, then only the first has what we're
2337 * looking for here...
2340 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2343 if (fr->fr_dcmp || fr->fr_scmp ||
2344 fr->fr_tcpf || fr->fr_tcpfm)
2346 if (fr->fr_icmpm || fr->fr_icmp) {
2347 if (((fi->fi_p != IPPROTO_ICMP) &&
2348 (fi->fi_p != IPPROTO_ICMPV6)) ||
2349 fin->fin_off || (fin->fin_dlen < 2))
2351 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2353 FR_DEBUG(("i. %#x & %#x != %#x\n",
2355 fr->fr_icmpm, fr->fr_icmp));
2365 /* ------------------------------------------------------------------------ */
2366 /* Function: ipf_scanlist */
2367 /* Returns: int - result flags of scanning filter list */
2368 /* Parameters: fin(I) - pointer to packet information */
2369 /* pass(I) - default result to return for filtering */
2371 /* Check the input/output list of rules for a match to the current packet. */
2372 /* If a match is found, the value of fr_flags from the rule becomes the */
2373 /* return value and fin->fin_fr points to the matched rule. */
2375 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2376 /* When unwinding, it should finish up with fin_depth as 0. */
2378 /* Could be per interface, but this gets real nasty when you don't have, */
2379 /* or can't easily change, the kernel source code to . */
2380 /* ------------------------------------------------------------------------ */
2382 ipf_scanlist(fin, pass)
2386 ipf_main_softc_t *softc = fin->fin_main_soft;
2387 int rulen, portcmp, off, skip;
2388 struct frentry *fr, *fnext;
2389 u_32_t passt, passo;
2392 * Do not allow nesting deeper than 16 levels.
2394 if (fin->fin_depth >= 16)
2400 * If there are no rules in this list, return now.
2411 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2414 for (rulen = 0; fr; fr = fnext, rulen++) {
2415 fnext = fr->fr_next;
2417 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2423 * In all checks below, a null (zero) value in the
2424 * filter struture is taken to mean a wildcard.
2426 * check that we are working for the right interface
2429 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2432 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2434 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2435 FR_ISPASS(pass) ? 'p' :
2436 FR_ISACCOUNT(pass) ? 'A' :
2437 FR_ISAUTH(pass) ? 'a' :
2438 (pass & FR_NOMATCH) ? 'n' :'b'));
2439 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2444 switch (fr->fr_type)
2447 case FR_T_IPF_BUILTIN :
2448 if (ipf_check_ipf(fin, fr, portcmp))
2451 #if defined(IPFILTER_BPF)
2453 case FR_T_BPFOPC_BUILTIN :
2458 if (*fin->fin_mp == NULL)
2460 if (fin->fin_family != fr->fr_family)
2462 mc = (u_char *)fin->fin_m;
2463 wlen = fin->fin_dlen + fin->fin_hlen;
2464 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2469 case FR_T_CALLFUNC_BUILTIN :
2473 f = (*fr->fr_func)(fin, &pass);
2482 case FR_T_IPFEXPR_BUILTIN :
2483 if (fin->fin_family != fr->fr_family)
2485 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2493 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2494 if (fin->fin_nattag == NULL)
2496 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2499 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2501 passt = fr->fr_flags;
2504 * If the rule is a "call now" rule, then call the function
2505 * in the rule, if it exists and use the results from that.
2506 * If the function pointer is bad, just make like we ignore
2507 * it, except for increasing the hit counter.
2509 if ((passt & FR_CALLNOW) != 0) {
2512 ATOMIC_INC64(fr->fr_hits);
2513 if ((fr->fr_func == NULL) ||
2514 (fr->fr_func == (ipfunc_t)-1))
2519 fr = (*fr->fr_func)(fin, &passt);
2524 passt = fr->fr_flags;
2530 * Just log this packet...
2532 if ((passt & FR_LOGMASK) == FR_LOG) {
2533 if (ipf_log_pkt(fin, passt) == -1) {
2534 if (passt & FR_LOGORBLOCK) {
2536 passt &= ~FR_CMDMASK;
2537 passt |= FR_BLOCK|FR_QUICK;
2538 fin->fin_reason = FRB_LOGFAIL;
2542 #endif /* IPFILTER_LOG */
2544 MUTEX_ENTER(&fr->fr_lock);
2545 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2547 MUTEX_EXIT(&fr->fr_lock);
2548 fin->fin_rule = rulen;
2551 if (FR_ISSKIP(passt)) {
2554 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2555 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2559 if (passt & (FR_RETICMP|FR_FAKEICMP))
2560 fin->fin_icode = fr->fr_icode;
2562 if (fr->fr_group != -1) {
2563 (void) strncpy(fin->fin_group,
2564 FR_NAME(fr, fr_group),
2565 strlen(FR_NAME(fr, fr_group)));
2567 fin->fin_group[0] = '\0';
2570 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2572 if (fr->fr_grphead != NULL) {
2573 fin->fin_fr = fr->fr_grphead->fg_start;
2574 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2576 if (FR_ISDECAPS(passt))
2577 passt = ipf_decaps(fin, pass, fr->fr_icode);
2579 passt = ipf_scanlist(fin, pass);
2581 if (fin->fin_fr == NULL) {
2582 fin->fin_rule = rulen;
2583 if (fr->fr_group != -1)
2584 (void) strncpy(fin->fin_group,
2587 strlen(fr->fr_names +
2595 if (pass & FR_QUICK) {
2597 * Finally, if we've asked to track state for this
2598 * packet, set it up. Add state for "quick" rules
2599 * here so that if the action fails we can consider
2600 * the rule to "not match" and keep on processing
2603 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2604 !(fin->fin_flx & FI_STATE)) {
2605 int out = fin->fin_out;
2608 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2609 LBUMPD(ipf_stats[out], fr_ads);
2611 LBUMPD(ipf_stats[out], fr_bads);
2624 /* ------------------------------------------------------------------------ */
2625 /* Function: ipf_acctpkt */
2626 /* Returns: frentry_t* - always returns NULL */
2627 /* Parameters: fin(I) - pointer to packet information */
2628 /* passp(IO) - pointer to current/new filter decision (unused) */
2630 /* Checks a packet against accounting rules, if there are any for the given */
2631 /* IP protocol version. */
2633 /* N.B.: this function returns NULL to match the prototype used by other */
2634 /* functions called from the IPFilter "mainline" in ipf_check(). */
2635 /* ------------------------------------------------------------------------ */
2637 ipf_acctpkt(fin, passp)
2641 ipf_main_softc_t *softc = fin->fin_main_soft;
2642 char group[FR_GROUPLEN];
2643 frentry_t *fr, *frsave;
2647 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2650 frsave = fin->fin_fr;
2651 bcopy(fin->fin_group, group, FR_GROUPLEN);
2652 rulen = fin->fin_rule;
2654 pass = ipf_scanlist(fin, FR_NOMATCH);
2655 if (FR_ISACCOUNT(pass)) {
2656 LBUMPD(ipf_stats[0], fr_acct);
2658 fin->fin_fr = frsave;
2659 bcopy(group, fin->fin_group, FR_GROUPLEN);
2660 fin->fin_rule = rulen;
2666 /* ------------------------------------------------------------------------ */
2667 /* Function: ipf_firewall */
2668 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2669 /* were found, returns NULL. */
2670 /* Parameters: fin(I) - pointer to packet information */
2671 /* passp(IO) - pointer to current/new filter decision (unused) */
2673 /* Applies an appropriate set of firewall rules to the packet, to see if */
2674 /* there are any matches. The first check is to see if a match can be seen */
2675 /* in the cache. If not, then search an appropriate list of rules. Once a */
2676 /* matching rule is found, take any appropriate actions as defined by the */
2677 /* rule - except logging. */
2678 /* ------------------------------------------------------------------------ */
2680 ipf_firewall(fin, passp)
2684 ipf_main_softc_t *softc = fin->fin_main_soft;
2693 * This rule cache will only affect packets that are not being
2694 * statefully filtered.
2696 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2697 if (fin->fin_fr != NULL)
2698 pass = ipf_scanlist(fin, softc->ipf_pass);
2700 if ((pass & FR_NOMATCH)) {
2701 LBUMPD(ipf_stats[out], fr_nom);
2706 * Apply packets per second rate-limiting to a rule as required.
2708 if ((fr != NULL) && (fr->fr_pps != 0) &&
2709 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2710 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2711 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2713 LBUMPD(ipf_stats[out], fr_ppshit);
2714 fin->fin_reason = FRB_PPSRATE;
2718 * If we fail to add a packet to the authorization queue, then we
2719 * drop the packet later. However, if it was added then pretend
2720 * we've dropped it already.
2722 if (FR_ISAUTH(pass)) {
2723 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2724 DT1(frb_authnew, fr_info_t *, fin);
2725 fin->fin_m = *fin->fin_mp = NULL;
2726 fin->fin_reason = FRB_AUTHNEW;
2730 fin->fin_error = ENOSPC;
2734 if ((fr != NULL) && (fr->fr_func != NULL) &&
2735 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2736 (void) (*fr->fr_func)(fin, &pass);
2739 * If a rule is a pre-auth rule, check again in the list of rules
2740 * loaded for authenticated use. It does not particulary matter
2741 * if this search fails because a "preauth" result, from a rule,
2742 * is treated as "not a pass", hence the packet is blocked.
2744 if (FR_ISPREAUTH(pass)) {
2745 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2749 * If the rule has "keep frag" and the packet is actually a fragment,
2750 * then create a fragment state entry.
2752 if (pass & FR_KEEPFRAG) {
2753 if (fin->fin_flx & FI_FRAG) {
2754 if (ipf_frag_new(softc, fin, pass) == -1) {
2755 LBUMP(ipf_stats[out].fr_bnfr);
2757 LBUMP(ipf_stats[out].fr_nfr);
2760 LBUMP(ipf_stats[out].fr_cfr);
2771 /* ------------------------------------------------------------------------ */
2772 /* Function: ipf_check */
2773 /* Returns: int - 0 == packet allowed through, */
2775 /* -1 == packet blocked */
2776 /* 1 == packet not matched */
2777 /* -2 == requires authentication */
2779 /* > 0 == filter error # for packet */
2780 /* Parameters: ctx(I) - pointer to the instance context */
2781 /* ip(I) - pointer to start of IPv4/6 packet */
2782 /* hlen(I) - length of header */
2783 /* ifp(I) - pointer to interface this packet is on */
2784 /* out(I) - 0 == packet going in, 1 == packet going out */
2785 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2788 /* qpi(I) - pointer to STREAMS queue information for this */
2789 /* interface & direction. */
2791 /* ipf_check() is the master function for all IPFilter packet processing. */
2792 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2793 /* authorisation (or pre-authorisation), presence of related state info., */
2794 /* generating log entries, IP packet accounting, routing of packets as */
2795 /* directed by firewall rules and of course whether or not to allow the */
2796 /* packet to be further processed by the kernel. */
2798 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2799 /* freed. Packets passed may be returned with the pointer pointed to by */
2800 /* by "mp" changed to a new buffer. */
2801 /* ------------------------------------------------------------------------ */
2803 ipf_check(ctx, ip, hlen, ifp, out
2804 #if defined(_KERNEL) && defined(MENTAT)
2818 * The above really sucks, but short of writing a diff
2820 ipf_main_softc_t *softc = ctx;
2822 fr_info_t *fin = &frinfo;
2823 u_32_t pass = softc->ipf_pass;
2824 frentry_t *fr = NULL;
2829 * The first part of ipf_check() deals with making sure that what goes
2830 * into the filtering engine makes some sense. Information about the
2831 * the packet is distilled, collected into a fr_info_t structure and
2832 * the an attempt to ensure the buffer the packet is in is big enough
2833 * to hold all the required packet headers.
2837 qpktinfo_t *qpi = qif;
2840 if ((u_int)ip & 0x3)
2847 if (softc->ipf_running <= 0) {
2851 bzero((char *)fin, sizeof(*fin));
2854 if (qpi->qpi_flags & QF_BROADCAST)
2855 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2856 if (qpi->qpi_flags & QF_MULTICAST)
2857 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2865 # if defined(M_MCAST)
2866 if ((m->m_flags & M_MCAST) != 0)
2867 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2869 # if defined(M_MLOOP)
2870 if ((m->m_flags & M_MLOOP) != 0)
2871 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2873 # if defined(M_BCAST)
2874 if ((m->m_flags & M_BCAST) != 0)
2875 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2877 # ifdef M_CANFASTFWD
2879 * XXX For now, IP Filter and fast-forwarding of cached flows
2880 * XXX are mutually exclusive. Eventually, IP Filter should
2881 * XXX get a "can-fast-forward" filter rule.
2883 m->m_flags &= ~M_CANFASTFWD;
2884 # endif /* M_CANFASTFWD */
2885 # if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2886 (__FreeBSD_version < 501108))
2888 * disable delayed checksums.
2890 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2891 in_delayed_cksum(m);
2892 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2894 # endif /* CSUM_DELAY_DATA */
2895 # endif /* MENTAT */
2897 bzero((char *)fin, sizeof(*fin));
2899 # if defined(M_MCAST)
2900 if ((m->m_flags & M_MCAST) != 0)
2901 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2903 # if defined(M_MLOOP)
2904 if ((m->m_flags & M_MLOOP) != 0)
2905 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2907 # if defined(M_BCAST)
2908 if ((m->m_flags & M_BCAST) != 0)
2909 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2911 #endif /* _KERNEL */
2919 fin->fin_error = ENETUNREACH;
2920 fin->fin_hlen = (u_short)hlen;
2921 fin->fin_dp = (char *)ip + hlen;
2922 fin->fin_main_soft = softc;
2924 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2930 LBUMP(ipf_stats[out].fr_ipv6);
2932 * Jumbo grams are quite likely too big for internal buffer
2933 * structures to handle comfortably, for now, so just drop
2936 if (((ip6_t *)ip)->ip6_plen == 0) {
2937 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2938 pass = FR_BLOCK|FR_NOMATCH;
2939 fin->fin_reason = FRB_JUMBO;
2942 fin->fin_family = AF_INET6;
2946 fin->fin_family = AF_INET;
2949 if (ipf_makefrip(hlen, ip, fin) == -1) {
2950 DT1(frb_makefrip, fr_info_t *, fin);
2951 pass = FR_BLOCK|FR_NOMATCH;
2952 fin->fin_reason = FRB_MAKEFRIP;
2957 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2958 * becomes NULL and so we have no packet to free.
2960 if (*fin->fin_mp == NULL)
2965 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2966 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2967 fin->fin_flx |= FI_BADSRC;
2969 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2970 LBUMPD(ipf_stats[0], fr_v4_badttl);
2971 fin->fin_flx |= FI_LOWTTL;
2976 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2977 LBUMPD(ipf_stats[0], fr_v6_badttl);
2978 fin->fin_flx |= FI_LOWTTL;
2984 if (fin->fin_flx & FI_SHORT) {
2985 LBUMPD(ipf_stats[out], fr_short);
2988 READ_ENTER(&softc->ipf_mutex);
2994 if (ipf_nat_checkin(fin, &pass) == -1) {
3000 if (ipf_nat6_checkin(fin, &pass) == -1) {
3011 * If a packet is found in the auth table, then skip checking
3012 * the access lists for permission but we do need to consider
3013 * the result as if it were from the ACL's. In addition, being
3014 * found in the auth table means it has been seen before, so do
3015 * not pass it through accounting (again), lest it be counted twice.
3017 fr = ipf_auth_check(fin, &pass);
3018 if (!out && (fr == NULL))
3019 (void) ipf_acctpkt(fin, NULL);
3022 if ((fin->fin_flx & FI_FRAG) != 0)
3023 fr = ipf_frag_known(fin, &pass);
3026 fr = ipf_state_check(fin, &pass);
3029 if ((pass & FR_NOMATCH) || (fr == NULL))
3030 fr = ipf_firewall(fin, &pass);
3033 * If we've asked to track state for this packet, set it up.
3034 * Here rather than ipf_firewall because ipf_checkauth may decide
3035 * to return a packet for "keep state"
3037 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3038 !(fin->fin_flx & FI_STATE)) {
3039 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3040 LBUMP(ipf_stats[out].fr_ads);
3042 LBUMP(ipf_stats[out].fr_bads);
3043 if (FR_ISPASS(pass)) {
3045 pass &= ~FR_CMDMASK;
3047 fin->fin_reason = FRB_STATEADD;
3053 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3054 fin->fin_dif = &fr->fr_dif;
3055 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3059 * Only count/translate packets which will be passed on, out the
3062 if (out && FR_ISPASS(pass)) {
3063 (void) ipf_acctpkt(fin, NULL);
3068 if (ipf_nat_checkout(fin, &pass) == -1) {
3070 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3071 if (ipf_updateipid(fin) == -1) {
3073 LBUMP(ipf_stats[1].fr_ipud);
3074 pass &= ~FR_CMDMASK;
3076 fin->fin_reason = FRB_UPDATEIPID;
3078 LBUMP(ipf_stats[0].fr_ipud);
3084 (void) ipf_nat6_checkout(fin, &pass);
3094 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3095 (void) ipf_dolog(fin, &pass);
3100 * The FI_STATE flag is cleared here so that calling ipf_state_check
3101 * will work when called from inside of fr_fastroute. Although
3102 * there is a similar flag, FI_NATED, for NAT, it does have the same
3103 * impact on code execution.
3105 fin->fin_flx &= ~FI_STATE;
3107 #if defined(FASTROUTE_RECURSION)
3109 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3110 * a packet below can sometimes cause a recursive call into IPFilter.
3111 * On those platforms where that does happen, we need to hang onto
3112 * the filter rule just in case someone decides to remove or flush it
3116 MUTEX_ENTER(&fr->fr_lock);
3118 MUTEX_EXIT(&fr->fr_lock);
3121 RWLOCK_EXIT(&softc->ipf_mutex);
3124 if ((pass & FR_RETMASK) != 0) {
3126 * Should we return an ICMP packet to indicate error
3127 * status passing through the packet filter ?
3128 * WARNING: ICMP error packets AND TCP RST packets should
3129 * ONLY be sent in repsonse to incoming packets. Sending
3130 * them in response to outbound packets can result in a
3131 * panic on some operating systems.
3134 if (pass & FR_RETICMP) {
3137 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3141 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3143 LBUMP(ipf_stats[0].fr_ret);
3144 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3145 !(fin->fin_flx & FI_SHORT)) {
3146 if (((fin->fin_flx & FI_OOW) != 0) ||
3147 (ipf_send_reset(fin) == 0)) {
3148 LBUMP(ipf_stats[1].fr_ret);
3153 * When using return-* with auth rules, the auth code
3154 * takes over disposing of this packet.
3156 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3157 DT1(frb_authcapture, fr_info_t *, fin);
3158 fin->fin_m = *fin->fin_mp = NULL;
3159 fin->fin_reason = FRB_AUTHCAPTURE;
3163 if (pass & FR_RETRST) {
3164 fin->fin_error = ECONNRESET;
3170 * After the above so that ICMP unreachables and TCP RSTs get
3173 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3174 ipf_nat_uncreate(fin);
3177 * If we didn't drop off the bottom of the list of rules (and thus
3178 * the 'current' rule fr is not NULL), then we may have some extra
3179 * instructions about what to do with a packet.
3180 * Once we're finished return to our caller, freeing the packet if
3181 * we are dropping it.
3187 * Generate a duplicated packet first because ipf_fastroute
3188 * can lead to fin_m being free'd... not good.
3191 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3192 (fdp->fd_ptr != (void *)-1)) {
3193 mc = M_COPY(fin->fin_m);
3195 ipf_fastroute(mc, &mc, fin, fdp);
3199 if (!out && (pass & FR_FASTROUTE)) {
3201 * For fastroute rule, no destination interface defined
3202 * so pass NULL as the frdest_t parameter
3204 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3206 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3207 (fdp->fd_ptr != (struct ifnet *)-1)) {
3208 /* this is for to rules: */
3209 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3213 #if defined(FASTROUTE_RECURSION)
3214 (void) ipf_derefrule(softc, &fr);
3217 #if !defined(FASTROUTE_RECURSION)
3218 RWLOCK_EXIT(&softc->ipf_mutex);
3222 if (!FR_ISPASS(pass)) {
3223 LBUMP(ipf_stats[out].fr_block);
3231 LBUMP(ipf_stats[out].fr_pass);
3237 if (FR_ISPASS(pass))
3239 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3240 return fin->fin_error;
3243 (*mp)->mb_ifp = fin->fin_ifp;
3244 blockreason = fin->fin_reason;
3245 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3246 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3247 if ((pass & FR_NOMATCH) != 0)
3250 if ((pass & FR_RETMASK) != 0)
3251 switch (pass & FR_RETMASK)
3261 switch (pass & FR_CMDMASK)
3275 #endif /* _KERNEL */
3280 /* ------------------------------------------------------------------------ */
3281 /* Function: ipf_dolog */
3282 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3283 /* Parameters: fin(I) - pointer to packet information */
3284 /* passp(IO) - pointer to current/new filter decision (unused) */
3286 /* Checks flags set to see how a packet should be logged, if it is to be */
3287 /* logged. Adjust statistics based on its success or not. */
3288 /* ------------------------------------------------------------------------ */
3290 ipf_dolog(fin, passp)
3294 ipf_main_softc_t *softc = fin->fin_main_soft;
3301 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3302 pass |= FF_LOGNOMATCH;
3303 LBUMPD(ipf_stats[out], fr_npkl);
3306 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3307 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3308 if ((pass & FR_LOGMASK) != FR_LOGP)
3310 LBUMPD(ipf_stats[out], fr_ppkl);
3313 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3314 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3315 if ((pass & FR_LOGMASK) != FR_LOGB)
3316 pass |= FF_LOGBLOCK;
3317 LBUMPD(ipf_stats[out], fr_bpkl);
3320 if (ipf_log_pkt(fin, pass) == -1) {
3322 * If the "or-block" option has been used then
3323 * block the packet if we failed to log it.
3325 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3326 DT1(frb_logfail2, u_int, pass);
3327 pass &= ~FR_CMDMASK;
3329 fin->fin_reason = FRB_LOGFAIL2;
3337 #endif /* IPFILTER_LOG */
3340 /* ------------------------------------------------------------------------ */
3341 /* Function: ipf_cksum */
3342 /* Returns: u_short - IP header checksum */
3343 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3344 /* len(I) - length of buffer in bytes */
3346 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3348 /* N.B.: addr should be 16bit aligned. */
3349 /* ------------------------------------------------------------------------ */
3351 ipf_cksum(addr, len)
3357 for (sum = 0; len > 1; len -= 2)
3360 /* mop up an odd byte, if necessary */
3362 sum += *(u_char *)addr;
3365 * add back carry outs from top 16 bits to low 16 bits
3367 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3368 sum += (sum >> 16); /* add carry */
3369 return (u_short)(~sum);
3373 /* ------------------------------------------------------------------------ */
3374 /* Function: fr_cksum */
3375 /* Returns: u_short - layer 4 checksum */
3376 /* Parameters: fin(I) - pointer to packet information */
3377 /* ip(I) - pointer to IP header */
3378 /* l4proto(I) - protocol to caclulate checksum for */
3379 /* l4hdr(I) - pointer to layer 4 header */
3381 /* Calculates the TCP checksum for the packet held in "m", using the data */
3382 /* in the IP header "ip" to seed it. */
3384 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3385 /* and the TCP header. We also assume that data blocks aren't allocated in */
3388 /* Expects ip_len and ip_off to be in network byte order when called. */
3389 /* ------------------------------------------------------------------------ */
3391 fr_cksum(fin, ip, l4proto, l4hdr)
3397 u_short *sp, slen, sumsave, *csump;
3412 sum = htons((u_short)l4proto);
3414 * Add up IP Header portion
3417 if (IP_V(ip) == 4) {
3419 hlen = IP_HL(ip) << 2;
3421 sp = (u_short *)&ip->ip_src;
3422 sum += *sp++; /* ip_src */
3424 sum += *sp++; /* ip_dst */
3427 } else if (IP_V(ip) == 6) {
3429 hlen = sizeof(*ip6);
3430 off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3431 sp = (u_short *)&ip6->ip6_src;
3432 sum += *sp++; /* ip6_src */
3440 /* This needs to be routing header aware. */
3441 sum += *sp++; /* ip6_dst */
3453 slen = fin->fin_plen - off;
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) || SOLARIS
5445 * ppsratecheck(): packets (or events) per second limitation.
5448 ppsratecheck(lasttime, curpps, maxpps)
5449 struct timeval *lasttime;
5451 int maxpps; /* maximum pps allowed */
5453 struct timeval tv, delta;
5458 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5459 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5460 if (delta.tv_usec < 0) {
5462 delta.tv_usec += 1000000;
5466 * check for 0,0 is so that the message will be seen at least once.
5467 * if more than one second have passed since the last update of
5468 * lasttime, reset the counter.
5470 * we do increment *curpps even in *curpps < maxpps case, as some may
5471 * try to use *curpps for stat purposes as well.
5473 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5474 delta.tv_sec >= 1) {
5478 } else if (maxpps < 0)
5480 else if (*curpps < maxpps)
5484 *curpps = *curpps + 1;
5491 /* ------------------------------------------------------------------------ */
5492 /* Function: ipf_derefrule */
5493 /* Returns: int - 0 == rule freed up, else rule not freed */
5494 /* Parameters: fr(I) - pointer to filter rule */
5496 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5497 /* free it and any associated storage space being used by it. */
5498 /* ------------------------------------------------------------------------ */
5500 ipf_derefrule(softc, frp)
5501 ipf_main_softc_t *softc;
5510 MUTEX_ENTER(&fr->fr_lock);
5512 if (fr->fr_ref == 0) {
5513 MUTEX_EXIT(&fr->fr_lock);
5514 MUTEX_DESTROY(&fr->fr_lock);
5516 ipf_funcfini(softc, fr);
5519 if (fdp->fd_type == FRD_DSTLIST)
5520 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5523 if (fdp->fd_type == FRD_DSTLIST)
5524 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5527 if (fdp->fd_type == FRD_DSTLIST)
5528 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5530 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5531 fr->fr_satype == FRI_LOOKUP)
5532 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5533 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5534 fr->fr_datype == FRI_LOOKUP)
5535 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5537 if (fr->fr_grp != NULL)
5538 ipf_group_del(softc, fr->fr_grp, fr);
5540 if (fr->fr_grphead != NULL)
5541 ipf_group_del(softc, fr->fr_grphead, fr);
5543 if (fr->fr_icmpgrp != NULL)
5544 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5546 if ((fr->fr_flags & FR_COPIED) != 0) {
5548 KFREES(fr->fr_data, fr->fr_dsize);
5550 KFREES(fr, fr->fr_size);
5555 MUTEX_EXIT(&fr->fr_lock);
5561 /* ------------------------------------------------------------------------ */
5562 /* Function: ipf_grpmapinit */
5563 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5564 /* Parameters: fr(I) - pointer to rule to find hash table for */
5566 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5567 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5568 /* ------------------------------------------------------------------------ */
5570 ipf_grpmapinit(softc, fr)
5571 ipf_main_softc_t *softc;
5574 char name[FR_GROUPLEN];
5577 #if defined(SNPRINTF) && defined(_KERNEL)
5578 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5580 (void) sprintf(name, "%d", fr->fr_arg);
5582 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5587 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5597 /* ------------------------------------------------------------------------ */
5598 /* Function: ipf_grpmapfini */
5599 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5600 /* Parameters: softc(I) - pointer to soft context main structure */
5601 /* fr(I) - pointer to rule to release hash table for */
5603 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5604 /* be called to undo what ipf_grpmapinit caused to be done. */
5605 /* ------------------------------------------------------------------------ */
5607 ipf_grpmapfini(softc, fr)
5608 ipf_main_softc_t *softc;
5614 ipf_lookup_deref(softc, IPLT_HASH, iph);
5619 /* ------------------------------------------------------------------------ */
5620 /* Function: ipf_srcgrpmap */
5621 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5622 /* Parameters: fin(I) - pointer to packet information */
5623 /* passp(IO) - pointer to current/new filter decision (unused) */
5625 /* Look for a rule group head in a hash table, using the source address as */
5626 /* the key, and descend into that group and continue matching rules against */
5628 /* ------------------------------------------------------------------------ */
5630 ipf_srcgrpmap(fin, passp)
5637 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5643 fin->fin_fr = fg->fg_start;
5644 (void) ipf_scanlist(fin, *passp);
5649 /* ------------------------------------------------------------------------ */
5650 /* Function: ipf_dstgrpmap */
5651 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5652 /* Parameters: fin(I) - pointer to packet information */
5653 /* passp(IO) - pointer to current/new filter decision (unused) */
5655 /* Look for a rule group head in a hash table, using the destination */
5656 /* address as the key, and descend into that group and continue matching */
5657 /* rules against the packet. */
5658 /* ------------------------------------------------------------------------ */
5660 ipf_dstgrpmap(fin, passp)
5667 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5673 fin->fin_fr = fg->fg_start;
5674 (void) ipf_scanlist(fin, *passp);
5681 * These functions manage objects on queues for efficient timeouts. There
5682 * are a number of system defined queues as well as user defined timeouts.
5683 * It is expected that a lock is held in the domain in which the queue
5684 * belongs (i.e. either state or NAT) when calling any of these functions
5685 * that prevents ipf_freetimeoutqueue() from being called at the same time
5690 /* ------------------------------------------------------------------------ */
5691 /* Function: ipf_addtimeoutqueue */
5692 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5693 /* timeout queue with given interval. */
5694 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5695 /* of interface queues. */
5696 /* seconds(I) - timeout value in seconds for this queue. */
5698 /* This routine first looks for a timeout queue that matches the interval */
5699 /* being requested. If it finds one, increments the reference counter and */
5700 /* returns a pointer to it. If none are found, it allocates a new one and */
5701 /* inserts it at the top of the list. */
5704 /* It is assumed that the caller of this function has an appropriate lock */
5705 /* held (exclusively) in the domain that encompases 'parent'. */
5706 /* ------------------------------------------------------------------------ */
5708 ipf_addtimeoutqueue(softc, parent, seconds)
5709 ipf_main_softc_t *softc;
5716 period = seconds * IPF_HZ_DIVIDE;
5718 MUTEX_ENTER(&softc->ipf_timeoutlock);
5719 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5720 if (ifq->ifq_ttl == period) {
5722 * Reset the delete flag, if set, so the structure
5723 * gets reused rather than freed and reallocated.
5725 MUTEX_ENTER(&ifq->ifq_lock);
5726 ifq->ifq_flags &= ~IFQF_DELETE;
5728 MUTEX_EXIT(&ifq->ifq_lock);
5729 MUTEX_EXIT(&softc->ipf_timeoutlock);
5735 KMALLOC(ifq, ipftq_t *);
5737 MUTEX_NUKE(&ifq->ifq_lock);
5738 IPFTQ_INIT(ifq, period, "ipftq mutex");
5739 ifq->ifq_next = *parent;
5740 ifq->ifq_pnext = parent;
5741 ifq->ifq_flags = IFQF_USER;
5744 softc->ipf_userifqs++;
5746 MUTEX_EXIT(&softc->ipf_timeoutlock);
5751 /* ------------------------------------------------------------------------ */
5752 /* Function: ipf_deletetimeoutqueue */
5753 /* Returns: int - new reference count value of the timeout queue */
5754 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5755 /* Locks: ifq->ifq_lock */
5757 /* This routine must be called when we're discarding a pointer to a timeout */
5758 /* queue object, taking care of the reference counter. */
5760 /* Now that this just sets a DELETE flag, it requires the expire code to */
5761 /* check the list of user defined timeout queues and call the free function */
5762 /* below (currently commented out) to stop memory leaking. It is done this */
5763 /* way because the locking may not be sufficient to safely do a free when */
5764 /* this function is called. */
5765 /* ------------------------------------------------------------------------ */
5767 ipf_deletetimeoutqueue(ifq)
5772 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5773 ifq->ifq_flags |= IFQF_DELETE;
5776 return ifq->ifq_ref;
5780 /* ------------------------------------------------------------------------ */
5781 /* Function: ipf_freetimeoutqueue */
5782 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5786 /* It is assumed that the caller of this function has an appropriate lock */
5787 /* held (exclusively) in the domain that encompases the callers "domain". */
5788 /* The ifq_lock for this structure should not be held. */
5790 /* Remove a user defined timeout queue from the list of queues it is in and */
5791 /* tidy up after this is done. */
5792 /* ------------------------------------------------------------------------ */
5794 ipf_freetimeoutqueue(softc, ifq)
5795 ipf_main_softc_t *softc;
5799 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5800 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5801 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5802 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5808 * Remove from its position in the list.
5810 *ifq->ifq_pnext = ifq->ifq_next;
5811 if (ifq->ifq_next != NULL)
5812 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5813 ifq->ifq_next = NULL;
5814 ifq->ifq_pnext = NULL;
5816 MUTEX_DESTROY(&ifq->ifq_lock);
5817 ATOMIC_DEC(softc->ipf_userifqs);
5822 /* ------------------------------------------------------------------------ */
5823 /* Function: ipf_deletequeueentry */
5825 /* Parameters: tqe(I) - timeout queue entry to delete */
5827 /* Remove a tail queue entry from its queue and make it an orphan. */
5828 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5829 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5830 /* the correct lock(s) may not be held that would make it safe to do so. */
5831 /* ------------------------------------------------------------------------ */
5833 ipf_deletequeueentry(tqe)
5840 MUTEX_ENTER(&ifq->ifq_lock);
5842 if (tqe->tqe_pnext != NULL) {
5843 *tqe->tqe_pnext = tqe->tqe_next;
5844 if (tqe->tqe_next != NULL)
5845 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5846 else /* we must be the tail anyway */
5847 ifq->ifq_tail = tqe->tqe_pnext;
5849 tqe->tqe_pnext = NULL;
5850 tqe->tqe_ifq = NULL;
5853 (void) ipf_deletetimeoutqueue(ifq);
5854 ASSERT(ifq->ifq_ref > 0);
5856 MUTEX_EXIT(&ifq->ifq_lock);
5860 /* ------------------------------------------------------------------------ */
5861 /* Function: ipf_queuefront */
5863 /* Parameters: tqe(I) - pointer to timeout queue entry */
5865 /* Move a queue entry to the front of the queue, if it isn't already there. */
5866 /* ------------------------------------------------------------------------ */
5877 MUTEX_ENTER(&ifq->ifq_lock);
5878 if (ifq->ifq_head != tqe) {
5879 *tqe->tqe_pnext = tqe->tqe_next;
5881 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5883 ifq->ifq_tail = tqe->tqe_pnext;
5885 tqe->tqe_next = ifq->ifq_head;
5886 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5887 ifq->ifq_head = tqe;
5888 tqe->tqe_pnext = &ifq->ifq_head;
5890 MUTEX_EXIT(&ifq->ifq_lock);
5894 /* ------------------------------------------------------------------------ */
5895 /* Function: ipf_queueback */
5897 /* Parameters: ticks(I) - ipf tick time to use with this call */
5898 /* tqe(I) - pointer to timeout queue entry */
5900 /* Move a queue entry to the back of the queue, if it isn't already there. */
5901 /* We use use ticks to calculate the expiration and mark for when we last */
5902 /* touched the structure. */
5903 /* ------------------------------------------------------------------------ */
5905 ipf_queueback(ticks, tqe)
5914 tqe->tqe_die = ticks + ifq->ifq_ttl;
5915 tqe->tqe_touched = ticks;
5917 MUTEX_ENTER(&ifq->ifq_lock);
5918 if (tqe->tqe_next != NULL) { /* at the end already ? */
5922 *tqe->tqe_pnext = tqe->tqe_next;
5923 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5926 * Make it the last entry.
5928 tqe->tqe_next = NULL;
5929 tqe->tqe_pnext = ifq->ifq_tail;
5930 *ifq->ifq_tail = tqe;
5931 ifq->ifq_tail = &tqe->tqe_next;
5933 MUTEX_EXIT(&ifq->ifq_lock);
5937 /* ------------------------------------------------------------------------ */
5938 /* Function: ipf_queueappend */
5940 /* Parameters: ticks(I) - ipf tick time to use with this call */
5941 /* tqe(I) - pointer to timeout queue entry */
5942 /* ifq(I) - pointer to timeout queue */
5943 /* parent(I) - owing object pointer */
5945 /* Add a new item to this queue and put it on the very end. */
5946 /* We use use ticks to calculate the expiration and mark for when we last */
5947 /* touched the structure. */
5948 /* ------------------------------------------------------------------------ */
5950 ipf_queueappend(ticks, tqe, ifq, parent)
5957 MUTEX_ENTER(&ifq->ifq_lock);
5958 tqe->tqe_parent = parent;
5959 tqe->tqe_pnext = ifq->ifq_tail;
5960 *ifq->ifq_tail = tqe;
5961 ifq->ifq_tail = &tqe->tqe_next;
5962 tqe->tqe_next = NULL;
5964 tqe->tqe_die = ticks + ifq->ifq_ttl;
5965 tqe->tqe_touched = ticks;
5967 MUTEX_EXIT(&ifq->ifq_lock);
5971 /* ------------------------------------------------------------------------ */
5972 /* Function: ipf_movequeue */
5974 /* Parameters: tq(I) - pointer to timeout queue information */
5975 /* oifp(I) - old timeout queue entry was on */
5976 /* nifp(I) - new timeout queue to put entry on */
5978 /* Move a queue entry from one timeout queue to another timeout queue. */
5979 /* If it notices that the current entry is already last and does not need */
5980 /* to move queue, the return. */
5981 /* ------------------------------------------------------------------------ */
5983 ipf_movequeue(ticks, tqe, oifq, nifq)
5986 ipftq_t *oifq, *nifq;
5990 * If the queue hasn't changed and we last touched this entry at the
5991 * same ipf time, then we're not going to achieve anything by either
5992 * changing the ttl or moving it on the queue.
5994 if (oifq == nifq && tqe->tqe_touched == ticks)
5998 * For any of this to be outside the lock, there is a risk that two
5999 * packets entering simultaneously, with one changing to a different
6000 * queue and one not, could end up with things in a bizarre state.
6002 MUTEX_ENTER(&oifq->ifq_lock);
6004 tqe->tqe_touched = ticks;
6005 tqe->tqe_die = ticks + nifq->ifq_ttl;
6007 * Is the operation here going to be a no-op ?
6010 if ((tqe->tqe_next == NULL) ||
6011 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6012 MUTEX_EXIT(&oifq->ifq_lock);
6018 * Remove from the old queue
6020 *tqe->tqe_pnext = tqe->tqe_next;
6022 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6024 oifq->ifq_tail = tqe->tqe_pnext;
6025 tqe->tqe_next = NULL;
6028 * If we're moving from one queue to another, release the
6029 * lock on the old queue and get a lock on the new queue.
6030 * For user defined queues, if we're moving off it, call
6031 * delete in case it can now be freed.
6034 tqe->tqe_ifq = NULL;
6036 (void) ipf_deletetimeoutqueue(oifq);
6038 MUTEX_EXIT(&oifq->ifq_lock);
6040 MUTEX_ENTER(&nifq->ifq_lock);
6042 tqe->tqe_ifq = nifq;
6047 * Add to the bottom of the new queue
6049 tqe->tqe_pnext = nifq->ifq_tail;
6050 *nifq->ifq_tail = tqe;
6051 nifq->ifq_tail = &tqe->tqe_next;
6052 MUTEX_EXIT(&nifq->ifq_lock);
6056 /* ------------------------------------------------------------------------ */
6057 /* Function: ipf_updateipid */
6058 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6059 /* Parameters: fin(I) - pointer to packet information */
6061 /* When we are doing NAT, change the IP of every packet to represent a */
6062 /* single sequence of packets coming from the host, hiding any host */
6063 /* specific sequencing that might otherwise be revealed. If the packet is */
6064 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
6065 /* the fragment cache for non-leading fragments. If a non-leading fragment */
6066 /* has no match in the cache, return an error. */
6067 /* ------------------------------------------------------------------------ */
6072 u_short id, ido, sums;
6077 ido = ntohs(ip->ip_id);
6078 if (fin->fin_off != 0) {
6079 sum = ipf_frag_ipidknown(fin);
6080 if (sum == 0xffffffff)
6084 ip->ip_id = htons(id);
6087 id = ntohs(ip->ip_id);
6088 if ((fin->fin_flx & FI_FRAG) != 0)
6089 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6094 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6095 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6097 sum = (sum >> 16) + (sum & 0xffff);
6098 sum = (sum >> 16) + (sum & 0xffff);
6099 sums = ~(u_short)sum;
6100 ip->ip_sum = htons(sums);
6105 #ifdef NEED_FRGETIFNAME
6106 /* ------------------------------------------------------------------------ */
6107 /* Function: ipf_getifname */
6108 /* Returns: char * - pointer to interface name */
6109 /* Parameters: ifp(I) - pointer to network interface */
6110 /* buffer(O) - pointer to where to store interface name */
6112 /* Constructs an interface name in the buffer passed. The buffer passed is */
6113 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6114 /* as a NULL pointer then return a pointer to a static array. */
6115 /* ------------------------------------------------------------------------ */
6117 ipf_getifname(ifp, buffer)
6121 static char namebuf[LIFNAMSIZ];
6122 # if defined(MENTAT) || defined(__FreeBSD__)
6130 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6131 buffer[LIFNAMSIZ - 1] = '\0';
6132 # if defined(MENTAT) || defined(__FreeBSD__)
6133 for (s = buffer; *s; s++)
6135 unit = ifp->if_unit;
6136 space = LIFNAMSIZ - (s - buffer);
6137 if ((space > 0) && (unit >= 0)) {
6138 # if defined(SNPRINTF) && defined(_KERNEL)
6139 SNPRINTF(temp, sizeof(temp), "%d", unit);
6141 (void) sprintf(temp, "%d", unit);
6143 (void) strncpy(s, temp, space);
6151 /* ------------------------------------------------------------------------ */
6152 /* Function: ipf_ioctlswitch */
6153 /* Returns: int - -1 continue processing, else ioctl return value */
6154 /* Parameters: unit(I) - device unit opened */
6155 /* data(I) - pointer to ioctl data */
6156 /* cmd(I) - ioctl command */
6157 /* mode(I) - mode value */
6158 /* uid(I) - uid making the ioctl call */
6159 /* ctx(I) - pointer to context data */
6161 /* Based on the value of unit, call the appropriate ioctl handler or return */
6162 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6163 /* for the device in order to execute the ioctl. A special case is made */
6164 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6165 /* The context data pointer is passed through as this is used as the key */
6166 /* for locating a matching token for continued access for walking lists, */
6168 /* ------------------------------------------------------------------------ */
6170 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6171 ipf_main_softc_t *softc;
6172 int unit, mode, uid;
6180 case SIOCIPFINTERROR :
6181 error = BCOPYOUT(&softc->ipf_interror, data,
6182 sizeof(softc->ipf_interror));
6195 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6198 if (softc->ipf_running > 0) {
6199 error = ipf_nat_ioctl(softc, data, cmd, mode,
6207 if (softc->ipf_running > 0) {
6208 error = ipf_state_ioctl(softc, data, cmd, mode,
6216 if (softc->ipf_running > 0) {
6217 error = ipf_auth_ioctl(softc, data, cmd, mode,
6225 if (softc->ipf_running > 0) {
6226 error = ipf_sync_ioctl(softc, data, cmd, mode,
6234 #ifdef IPFILTER_SCAN
6235 if (softc->ipf_running > 0)
6236 error = ipf_scan_ioctl(softc, data, cmd, mode,
6245 case IPL_LOGLOOKUP :
6246 if (softc->ipf_running > 0) {
6247 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6265 * This array defines the expected size of objects coming into the kernel
6266 * for the various recognised object types. The first column is flags (see
6267 * below), 2nd column is current size, 3rd column is the version number of
6268 * when the current size became current.
6270 * 1 = minimum size, not absolute size
6272 static int ipf_objbytes[IPFOBJ_COUNT][3] = {
6273 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6274 { 1, sizeof(struct friostat), 5010000 },
6275 { 0, sizeof(struct fr_info), 5010000 },
6276 { 0, sizeof(struct ipf_authstat), 4010100 },
6277 { 0, sizeof(struct ipfrstat), 5010000 },
6278 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6279 { 0, sizeof(struct natstat), 5010000 },
6280 { 0, sizeof(struct ipstate_save), 5010000 },
6281 { 1, sizeof(struct nat_save), 5010000 },
6282 { 0, sizeof(struct natlookup), 5010000 },
6283 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6284 { 0, sizeof(struct ips_stat), 5010000 },
6285 { 0, sizeof(struct frauth), 5010000 },
6286 { 0, sizeof(struct ipftune), 4010100 },
6287 { 0, sizeof(struct nat), 5010000 },
6288 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6289 { 0, sizeof(struct ipfgeniter), 4011400 },
6290 { 0, sizeof(struct ipftable), 4011400 },
6291 { 0, sizeof(struct ipflookupiter), 4011400 },
6292 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6293 { 1, 0, 0 }, /* IPFEXPR */
6294 { 0, 0, 0 }, /* PROXYCTL */
6295 { 0, sizeof (struct fripf), 5010000 }
6299 /* ------------------------------------------------------------------------ */
6300 /* Function: ipf_inobj */
6301 /* Returns: int - 0 = success, else failure */
6302 /* Parameters: softc(I) - soft context pointerto work with */
6303 /* data(I) - pointer to ioctl data */
6304 /* objp(O) - where to store ipfobj structure */
6305 /* ptr(I) - pointer to data to copy out */
6306 /* type(I) - type of structure being moved */
6308 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6309 /* add things to check for version numbers, sizes, etc, to make it backward */
6310 /* compatible at the ABI for user land. */
6311 /* If objp is not NULL then we assume that the caller wants to see what is */
6312 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6313 /* the caller what version of ipfilter the ioctl program was written to. */
6314 /* ------------------------------------------------------------------------ */
6316 ipf_inobj(softc, data, objp, ptr, type)
6317 ipf_main_softc_t *softc;
6327 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6334 error = BCOPYIN(data, objp, sizeof(*objp));
6340 if (objp->ipfo_type != type) {
6345 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6346 if ((ipf_objbytes[type][0] & 1) != 0) {
6347 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6351 size = ipf_objbytes[type][1];
6352 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6353 size = objp->ipfo_size;
6358 error = COPYIN(objp->ipfo_ptr, ptr, size);
6364 #ifdef IPFILTER_COMPAT
6365 error = ipf_in_compat(softc, objp, ptr, 0);
6375 /* ------------------------------------------------------------------------ */
6376 /* Function: ipf_inobjsz */
6377 /* Returns: int - 0 = success, else failure */
6378 /* Parameters: softc(I) - soft context pointerto work with */
6379 /* data(I) - pointer to ioctl data */
6380 /* ptr(I) - pointer to store real data in */
6381 /* type(I) - type of structure being moved */
6382 /* sz(I) - size of data to copy */
6384 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6385 /* but it must not be smaller than the size defined for the type and the */
6386 /* type must allow for varied sized objects. The extra requirement here is */
6387 /* that sz must match the size of the object being passed in - this is not */
6388 /* not possible nor required in ipf_inobj(). */
6389 /* ------------------------------------------------------------------------ */
6391 ipf_inobjsz(softc, data, ptr, type, sz)
6392 ipf_main_softc_t *softc;
6400 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6405 error = BCOPYIN(data, &obj, sizeof(obj));
6411 if (obj.ipfo_type != type) {
6416 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6417 if (((ipf_objbytes[type][0] & 1) == 0) ||
6418 (sz < ipf_objbytes[type][1])) {
6422 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6428 #ifdef IPFILTER_COMPAT
6429 error = ipf_in_compat(softc, &obj, ptr, sz);
6439 /* ------------------------------------------------------------------------ */
6440 /* Function: ipf_outobjsz */
6441 /* Returns: int - 0 = success, else failure */
6442 /* Parameters: data(I) - pointer to ioctl data */
6443 /* ptr(I) - pointer to store real data in */
6444 /* type(I) - type of structure being moved */
6445 /* sz(I) - size of data to copy */
6447 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6448 /* but it must not be smaller than the size defined for the type and the */
6449 /* type must allow for varied sized objects. The extra requirement here is */
6450 /* that sz must match the size of the object being passed in - this is not */
6451 /* not possible nor required in ipf_outobj(). */
6452 /* ------------------------------------------------------------------------ */
6454 ipf_outobjsz(softc, data, ptr, type, sz)
6455 ipf_main_softc_t *softc;
6463 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6468 error = BCOPYIN(data, &obj, sizeof(obj));
6474 if (obj.ipfo_type != type) {
6479 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6480 if (((ipf_objbytes[type][0] & 1) == 0) ||
6481 (sz < ipf_objbytes[type][1])) {
6485 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6491 #ifdef IPFILTER_COMPAT
6492 error = ipf_out_compat(softc, &obj, ptr);
6502 /* ------------------------------------------------------------------------ */
6503 /* Function: ipf_outobj */
6504 /* Returns: int - 0 = success, else failure */
6505 /* Parameters: data(I) - pointer to ioctl data */
6506 /* ptr(I) - pointer to store real data in */
6507 /* type(I) - type of structure being moved */
6509 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6510 /* future, we add things to check for version numbers, sizes, etc, to make */
6511 /* it backward compatible at the ABI for user land. */
6512 /* ------------------------------------------------------------------------ */
6514 ipf_outobj(softc, data, ptr, type)
6515 ipf_main_softc_t *softc;
6523 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6528 error = BCOPYIN(data, &obj, sizeof(obj));
6534 if (obj.ipfo_type != type) {
6539 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6540 if ((ipf_objbytes[type][0] & 1) != 0) {
6541 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6545 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6550 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6556 #ifdef IPFILTER_COMPAT
6557 error = ipf_out_compat(softc, &obj, ptr);
6567 /* ------------------------------------------------------------------------ */
6568 /* Function: ipf_outobjk */
6569 /* Returns: int - 0 = success, else failure */
6570 /* Parameters: obj(I) - pointer to data description structure */
6571 /* ptr(I) - pointer to kernel data to copy out */
6573 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6574 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6575 /* already populated with information and now we just need to use it. */
6576 /* There is no need for this function to have a "type" parameter as there */
6577 /* is no point in validating information that comes from the kernel with */
6579 /* ------------------------------------------------------------------------ */
6581 ipf_outobjk(softc, obj, ptr)
6582 ipf_main_softc_t *softc;
6586 int type = obj->ipfo_type;
6589 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6594 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6595 if ((ipf_objbytes[type][0] & 1) != 0) {
6596 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6601 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6606 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6612 #ifdef IPFILTER_COMPAT
6613 error = ipf_out_compat(softc, obj, ptr);
6623 /* ------------------------------------------------------------------------ */
6624 /* Function: ipf_checkl4sum */
6625 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6626 /* Parameters: fin(I) - pointer to packet information */
6628 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6629 /* not possible, return without indicating a failure or success but in a */
6630 /* way that is ditinguishable. This function should only be called by the */
6631 /* ipf_checkv6sum() for each platform. */
6632 /* ------------------------------------------------------------------------ */
6637 u_short sum, hdrsum, *csump;
6642 * If the TCP packet isn't a fragment, isn't too short and otherwise
6643 * isn't already considered "bad", then validate the checksum. If
6644 * this check fails then considered the packet to be "bad".
6646 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6657 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6663 if (udp->uh_sum != 0) {
6664 csump = &udp->uh_sum;
6670 case IPPROTO_ICMPV6 :
6671 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6677 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6690 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6692 #if !defined(_KERNEL)
6693 if (sum == hdrsum) {
6694 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6696 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6699 DT2(l4sums, u_short, hdrsum, u_short, sum);
6700 if (hdrsum == sum) {
6701 fin->fin_cksum = FI_CK_SUMOK;
6704 fin->fin_cksum = FI_CK_BAD;
6709 /* ------------------------------------------------------------------------ */
6710 /* Function: ipf_ifpfillv4addr */
6711 /* Returns: int - 0 = address update, -1 = address not updated */
6712 /* Parameters: atype(I) - type of network address update to perform */
6713 /* sin(I) - pointer to source of address information */
6714 /* mask(I) - pointer to source of netmask information */
6715 /* inp(I) - pointer to destination address store */
6716 /* inpmask(I) - pointer to destination netmask store */
6718 /* Given a type of network address update (atype) to perform, copy */
6719 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6720 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6721 /* which case the operation fails. For all values of atype other than */
6722 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6724 /* ------------------------------------------------------------------------ */
6726 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6728 struct sockaddr_in *sin, *mask;
6729 struct in_addr *inp, *inpmask;
6731 if (inpmask != NULL && atype != FRI_NETMASKED)
6732 inpmask->s_addr = 0xffffffff;
6734 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6735 if (atype == FRI_NETMASKED) {
6736 if (inpmask == NULL)
6738 inpmask->s_addr = mask->sin_addr.s_addr;
6740 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6742 inp->s_addr = sin->sin_addr.s_addr;
6749 /* ------------------------------------------------------------------------ */
6750 /* Function: ipf_ifpfillv6addr */
6751 /* Returns: int - 0 = address update, -1 = address not updated */
6752 /* Parameters: atype(I) - type of network address update to perform */
6753 /* sin(I) - pointer to source of address information */
6754 /* mask(I) - pointer to source of netmask information */
6755 /* inp(I) - pointer to destination address store */
6756 /* inpmask(I) - pointer to destination netmask store */
6758 /* Given a type of network address update (atype) to perform, copy */
6759 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6760 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6761 /* which case the operation fails. For all values of atype other than */
6762 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6764 /* ------------------------------------------------------------------------ */
6766 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6768 struct sockaddr_in6 *sin, *mask;
6769 i6addr_t *inp, *inpmask;
6771 i6addr_t *src, *and;
6773 src = (i6addr_t *)&sin->sin6_addr;
6774 and = (i6addr_t *)&mask->sin6_addr;
6776 if (inpmask != NULL && atype != FRI_NETMASKED) {
6777 inpmask->i6[0] = 0xffffffff;
6778 inpmask->i6[1] = 0xffffffff;
6779 inpmask->i6[2] = 0xffffffff;
6780 inpmask->i6[3] = 0xffffffff;
6783 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6784 if (atype == FRI_NETMASKED) {
6785 if (inpmask == NULL)
6787 inpmask->i6[0] = and->i6[0];
6788 inpmask->i6[1] = and->i6[1];
6789 inpmask->i6[2] = and->i6[2];
6790 inpmask->i6[3] = and->i6[3];
6793 inp->i6[0] = src->i6[0] & and->i6[0];
6794 inp->i6[1] = src->i6[1] & and->i6[1];
6795 inp->i6[2] = src->i6[2] & and->i6[2];
6796 inp->i6[3] = src->i6[3] & and->i6[3];
6798 inp->i6[0] = src->i6[0];
6799 inp->i6[1] = src->i6[1];
6800 inp->i6[2] = src->i6[2];
6801 inp->i6[3] = src->i6[3];
6808 /* ------------------------------------------------------------------------ */
6809 /* Function: ipf_matchtag */
6810 /* Returns: 0 == mismatch, 1 == match. */
6811 /* Parameters: tag1(I) - pointer to first tag to compare */
6812 /* tag2(I) - pointer to second tag to compare */
6814 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6815 /* considered to be a match or not match, respectively. The tag is 16 */
6816 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6817 /* compare the ints instead, for speed. tag1 is the master of the */
6818 /* comparison. This function should only be called with both tag1 and tag2 */
6819 /* as non-NULL pointers. */
6820 /* ------------------------------------------------------------------------ */
6822 ipf_matchtag(tag1, tag2)
6823 ipftag_t *tag1, *tag2;
6828 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6831 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6832 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6833 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6834 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6840 /* ------------------------------------------------------------------------ */
6841 /* Function: ipf_coalesce */
6842 /* Returns: 1 == success, -1 == failure, 0 == no change */
6843 /* Parameters: fin(I) - pointer to packet information */
6845 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6846 /* If this call returns a failure then the buffers have also been freed. */
6847 /* ------------------------------------------------------------------------ */
6853 if ((fin->fin_flx & FI_COALESCE) != 0)
6857 * If the mbuf pointers indicate that there is no mbuf to work with,
6858 * return but do not indicate success or failure.
6860 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6863 #if defined(_KERNEL)
6864 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6865 ipf_main_softc_t *softc = fin->fin_main_soft;
6867 DT1(frb_coalesce, fr_info_t *, fin);
6868 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6870 FREE_MB_T(*fin->fin_mp);
6872 fin->fin_reason = FRB_COALESCE;
6873 *fin->fin_mp = NULL;
6878 fin = fin; /* LINT */
6885 * The following table lists all of the tunable variables that can be
6886 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6887 * in the table below is as follows:
6889 * pointer to value, name of value, minimum, maximum, size of the value's
6890 * container, value attribute flags
6892 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6893 * means the value can only be written to when IPFilter is loaded but disabled.
6894 * The obvious implication is if neither of these are set then the value can be
6895 * changed at any time without harm.
6899 /* ------------------------------------------------------------------------ */
6900 /* Function: ipf_tune_findbycookie */
6901 /* Returns: NULL = search failed, else pointer to tune struct */
6902 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6903 /* next(O) - pointer to place to store the cookie for the */
6904 /* "next" tuneable, if it is desired. */
6906 /* This function is used to walk through all of the existing tunables with */
6907 /* successive calls. It searches the known tunables for the one which has */
6908 /* a matching value for "cookie" - ie its address. When returning a match, */
6909 /* the next one to be found may be returned inside next. */
6910 /* ------------------------------------------------------------------------ */
6911 static ipftuneable_t *
6912 ipf_tune_findbycookie(ptop, cookie, next)
6913 ipftuneable_t **ptop;
6914 void *cookie, **next;
6916 ipftuneable_t *ta, **tap;
6918 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6922 * If the next entry in the array has a name
6923 * present, then return a pointer to it for
6924 * where to go next, else return a pointer to
6925 * the dynaminc list as a key to search there
6926 * next. This facilitates a weak linking of
6927 * the two "lists" together.
6929 if ((ta + 1)->ipft_name != NULL)
6937 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6938 if (tap == cookie) {
6940 *next = &ta->ipft_next;
6950 /* ------------------------------------------------------------------------ */
6951 /* Function: ipf_tune_findbyname */
6952 /* Returns: NULL = search failed, else pointer to tune struct */
6953 /* Parameters: name(I) - name of the tuneable entry to find. */
6955 /* Search the static array of tuneables and the list of dynamic tuneables */
6956 /* for an entry with a matching name. If we can find one, return a pointer */
6957 /* to the matching structure. */
6958 /* ------------------------------------------------------------------------ */
6959 static ipftuneable_t *
6960 ipf_tune_findbyname(top, name)
6966 for (ta = top; ta != NULL; ta = ta->ipft_next)
6967 if (!strcmp(ta->ipft_name, name)) {
6975 /* ------------------------------------------------------------------------ */
6976 /* Function: ipf_tune_add_array */
6977 /* Returns: int - 0 == success, else failure */
6978 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6980 /* Appends tune structures from the array passed in (newtune) to the end of */
6981 /* the current list of "dynamic" tuneable parameters. */
6982 /* If any entry to be added is already present (by name) then the operation */
6983 /* is aborted - entries that have been added are removed before returning. */
6984 /* An entry with no name (NULL) is used as the indication that the end of */
6985 /* the array has been reached. */
6986 /* ------------------------------------------------------------------------ */
6988 ipf_tune_add_array(softc, newtune)
6989 ipf_main_softc_t *softc;
6990 ipftuneable_t *newtune;
6992 ipftuneable_t *nt, *dt;
6995 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6996 error = ipf_tune_add(softc, nt);
6998 for (dt = newtune; dt != nt; dt++) {
6999 (void) ipf_tune_del(softc, dt);
7008 /* ------------------------------------------------------------------------ */
7009 /* Function: ipf_tune_array_link */
7010 /* Returns: 0 == success, -1 == failure */
7011 /* Parameters: softc(I) - soft context pointerto work with */
7012 /* array(I) - pointer to an array of tuneables */
7014 /* Given an array of tunables (array), append them to the current list of */
7015 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7016 /* the array for being appended to the list, initialise all of the next */
7017 /* pointers so we don't need to walk parts of it with ++ and others with */
7018 /* next. The array is expected to have an entry with a NULL name as the */
7019 /* terminator. Trying to add an array with no non-NULL names will return as */
7021 /* ------------------------------------------------------------------------ */
7023 ipf_tune_array_link(softc, array)
7024 ipf_main_softc_t *softc;
7025 ipftuneable_t *array;
7027 ipftuneable_t *t, **p;
7030 if (t->ipft_name == NULL)
7033 for (; t[1].ipft_name != NULL; t++)
7034 t[0].ipft_next = &t[1];
7035 t->ipft_next = NULL;
7038 * Since a pointer to the last entry isn't kept, we need to find it
7039 * each time we want to add new variables to the list.
7041 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7042 if (t->ipft_name == NULL)
7050 /* ------------------------------------------------------------------------ */
7051 /* Function: ipf_tune_array_unlink */
7052 /* Returns: 0 == success, -1 == failure */
7053 /* Parameters: softc(I) - soft context pointerto work with */
7054 /* array(I) - pointer to an array of tuneables */
7056 /* ------------------------------------------------------------------------ */
7058 ipf_tune_array_unlink(softc, array)
7059 ipf_main_softc_t *softc;
7060 ipftuneable_t *array;
7062 ipftuneable_t *t, **p;
7064 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7070 for (; t[1].ipft_name != NULL; t++)
7079 /* ------------------------------------------------------------------------ */
7080 /* Function: ipf_tune_array_copy */
7081 /* Returns: NULL = failure, else pointer to new array */
7082 /* Parameters: base(I) - pointer to structure base */
7083 /* size(I) - size of the array at template */
7084 /* template(I) - original array to copy */
7086 /* Allocate memory for a new set of tuneable values and copy everything */
7087 /* from template into the new region of memory. The new region is full of */
7088 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7090 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7091 /* In the array template, ipftp_offset is the offset (in bytes) of the */
7092 /* location of the tuneable value inside the structure pointed to by base. */
7093 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
7094 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7095 /* ipftp_void that points to the stored value. */
7096 /* ------------------------------------------------------------------------ */
7098 ipf_tune_array_copy(base, size, template)
7101 ipftuneable_t *template;
7103 ipftuneable_t *copy;
7107 KMALLOCS(copy, ipftuneable_t *, size);
7111 bcopy(template, copy, size);
7113 for (i = 0; copy[i].ipft_name; i++) {
7114 copy[i].ipft_una.ipftp_offset += (u_long)base;
7115 copy[i].ipft_next = copy + i + 1;
7122 /* ------------------------------------------------------------------------ */
7123 /* Function: ipf_tune_add */
7124 /* Returns: int - 0 == success, else failure */
7125 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7127 /* Appends tune structures from the array passed in (newtune) to the end of */
7128 /* the current list of "dynamic" tuneable parameters. Once added, the */
7129 /* owner of the object is not expected to ever change "ipft_next". */
7130 /* ------------------------------------------------------------------------ */
7132 ipf_tune_add(softc, newtune)
7133 ipf_main_softc_t *softc;
7134 ipftuneable_t *newtune;
7136 ipftuneable_t *ta, **tap;
7138 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7144 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7147 newtune->ipft_next = NULL;
7153 /* ------------------------------------------------------------------------ */
7154 /* Function: ipf_tune_del */
7155 /* Returns: int - 0 == success, else failure */
7156 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7157 /* current dynamic tuneables */
7159 /* Search for the tune structure, by pointer, in the list of those that are */
7160 /* dynamically added at run time. If found, adjust the list so that this */
7161 /* structure is no longer part of it. */
7162 /* ------------------------------------------------------------------------ */
7164 ipf_tune_del(softc, oldtune)
7165 ipf_main_softc_t *softc;
7166 ipftuneable_t *oldtune;
7168 ipftuneable_t *ta, **tap;
7171 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7172 tap = &ta->ipft_next) {
7173 if (ta == oldtune) {
7174 *tap = oldtune->ipft_next;
7175 oldtune->ipft_next = NULL;
7188 /* ------------------------------------------------------------------------ */
7189 /* Function: ipf_tune_del_array */
7190 /* Returns: int - 0 == success, else failure */
7191 /* Parameters: oldtune - pointer to tuneables array */
7193 /* Remove each tuneable entry in the array from the list of "dynamic" */
7194 /* tunables. If one entry should fail to be found, an error will be */
7195 /* returned and no further ones removed. */
7196 /* An entry with a NULL name is used as the indicator of the last entry in */
7198 /* ------------------------------------------------------------------------ */
7200 ipf_tune_del_array(softc, oldtune)
7201 ipf_main_softc_t *softc;
7202 ipftuneable_t *oldtune;
7207 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7208 error = ipf_tune_del(softc, ot);
7218 /* ------------------------------------------------------------------------ */
7219 /* Function: ipf_tune */
7220 /* Returns: int - 0 == success, else failure */
7221 /* Parameters: cmd(I) - ioctl command number */
7222 /* data(I) - pointer to ioctl data structure */
7224 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7225 /* three ioctls provide the means to access and control global variables */
7226 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7227 /* changed without rebooting, reloading or recompiling. The initialisation */
7228 /* and 'destruction' routines of the various components of ipfilter are all */
7229 /* each responsible for handling their own values being too big. */
7230 /* ------------------------------------------------------------------------ */
7232 ipf_ipftune(softc, cmd, data)
7233 ipf_main_softc_t *softc;
7242 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7246 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7247 cookie = tu.ipft_cookie;
7252 case SIOCIPFGETNEXT :
7254 * If cookie is non-NULL, assume it to be a pointer to the last
7255 * entry we looked at, so find it (if possible) and return a
7256 * pointer to the next one after it. The last entry in the
7257 * the table is a NULL entry, so when we get to it, set cookie
7258 * to NULL and return that, indicating end of list, erstwhile
7259 * if we come in with cookie set to NULL, we are starting anew
7260 * at the front of the list.
7262 if (cookie != NULL) {
7263 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7264 cookie, &tu.ipft_cookie);
7266 ta = softc->ipf_tuners;
7267 tu.ipft_cookie = ta + 1;
7271 * Entry found, but does the data pointed to by that
7272 * row fit in what we can return?
7274 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7280 if (ta->ipft_sz == sizeof(u_long))
7281 tu.ipft_vlong = *ta->ipft_plong;
7282 else if (ta->ipft_sz == sizeof(u_int))
7283 tu.ipft_vint = *ta->ipft_pint;
7284 else if (ta->ipft_sz == sizeof(u_short))
7285 tu.ipft_vshort = *ta->ipft_pshort;
7286 else if (ta->ipft_sz == sizeof(u_char))
7287 tu.ipft_vchar = *ta->ipft_pchar;
7289 tu.ipft_sz = ta->ipft_sz;
7290 tu.ipft_min = ta->ipft_min;
7291 tu.ipft_max = ta->ipft_max;
7292 tu.ipft_flags = ta->ipft_flags;
7293 bcopy(ta->ipft_name, tu.ipft_name,
7294 MIN(sizeof(tu.ipft_name),
7295 strlen(ta->ipft_name) + 1));
7297 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7303 * Search by name or by cookie value for a particular entry
7304 * in the tuning paramter table.
7308 if (cookie != NULL) {
7309 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7313 } else if (tu.ipft_name[0] != '\0') {
7314 ta = ipf_tune_findbyname(softc->ipf_tuners,
7322 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7324 * Fetch the tuning parameters for a particular value
7327 if (ta->ipft_sz == sizeof(u_long))
7328 tu.ipft_vlong = *ta->ipft_plong;
7329 else if (ta->ipft_sz == sizeof(u_int))
7330 tu.ipft_vint = *ta->ipft_pint;
7331 else if (ta->ipft_sz == sizeof(u_short))
7332 tu.ipft_vshort = *ta->ipft_pshort;
7333 else if (ta->ipft_sz == sizeof(u_char))
7334 tu.ipft_vchar = *ta->ipft_pchar;
7335 tu.ipft_cookie = ta;
7336 tu.ipft_sz = ta->ipft_sz;
7337 tu.ipft_min = ta->ipft_min;
7338 tu.ipft_max = ta->ipft_max;
7339 tu.ipft_flags = ta->ipft_flags;
7340 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7342 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7344 * Set an internal parameter. The hard part here is
7345 * getting the new value safely and correctly out of
7346 * the kernel (given we only know its size, not type.)
7350 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7351 (softc->ipf_running > 0)) {
7358 if (in < ta->ipft_min || in > ta->ipft_max) {
7364 if (ta->ipft_func != NULL) {
7368 error = (*ta->ipft_func)(softc, ta,
7372 } else if (ta->ipft_sz == sizeof(u_long)) {
7373 tu.ipft_vlong = *ta->ipft_plong;
7374 *ta->ipft_plong = in;
7376 } else if (ta->ipft_sz == sizeof(u_int)) {
7377 tu.ipft_vint = *ta->ipft_pint;
7378 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7380 } else if (ta->ipft_sz == sizeof(u_short)) {
7381 tu.ipft_vshort = *ta->ipft_pshort;
7382 *ta->ipft_pshort = (u_short)(in & 0xffff);
7384 } else if (ta->ipft_sz == sizeof(u_char)) {
7385 tu.ipft_vchar = *ta->ipft_pchar;
7386 *ta->ipft_pchar = (u_char)(in & 0xff);
7388 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7402 /* ------------------------------------------------------------------------ */
7403 /* Function: ipf_zerostats */
7404 /* Returns: int - 0 = success, else failure */
7405 /* Parameters: data(O) - pointer to pointer for copying data back to */
7407 /* Copies the current statistics out to userspace and then zero's the */
7408 /* current ones in the kernel. The lock is only held across the bzero() as */
7409 /* the copyout may result in paging (ie network activity.) */
7410 /* ------------------------------------------------------------------------ */
7412 ipf_zerostats(softc, data)
7413 ipf_main_softc_t *softc;
7420 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7423 ipf_getstat(softc, &fio, obj.ipfo_rev);
7424 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7428 WRITE_ENTER(&softc->ipf_mutex);
7429 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7430 RWLOCK_EXIT(&softc->ipf_mutex);
7436 /* ------------------------------------------------------------------------ */
7437 /* Function: ipf_resolvedest */
7439 /* Parameters: softc(I) - pointer to soft context main structure */
7440 /* base(I) - where strings are stored */
7441 /* fdp(IO) - pointer to destination information to resolve */
7442 /* v(I) - IP protocol version to match */
7444 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7445 /* if a matching name can be found for the particular IP protocol version */
7446 /* then store the interface pointer in the frdest struct. If no match is */
7447 /* found, then set the interface pointer to be -1 as NULL is considered to */
7448 /* indicate there is no information at all in the structure. */
7449 /* ------------------------------------------------------------------------ */
7451 ipf_resolvedest(softc, base, fdp, v)
7452 ipf_main_softc_t *softc;
7462 if (fdp->fd_name != -1) {
7463 if (fdp->fd_type == FRD_DSTLIST) {
7464 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7466 base + fdp->fd_name,
7473 ifp = GETIFP(base + fdp->fd_name, v);
7480 if ((ifp != NULL) && (ifp != (void *)-1)) {
7481 fdp->fd_local = ipf_deliverlocal(softc, v, ifp, &fdp->fd_ip6);
7488 /* ------------------------------------------------------------------------ */
7489 /* Function: ipf_resolvenic */
7490 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7491 /* pointer to interface structure for NIC */
7492 /* Parameters: softc(I)- pointer to soft context main structure */
7493 /* name(I) - complete interface name */
7494 /* v(I) - IP protocol version */
7496 /* Look for a network interface structure that firstly has a matching name */
7497 /* to that passed in and that is also being used for that IP protocol */
7498 /* version (necessary on some platforms where there are separate listings */
7499 /* for both IPv4 and IPv6 on the same physical NIC. */
7500 /* ------------------------------------------------------------------------ */
7502 ipf_resolvenic(softc, name, v)
7503 ipf_main_softc_t *softc;
7509 softc = softc; /* gcc -Wextra */
7510 if (name[0] == '\0')
7513 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7517 nic = GETIFP(name, v);
7524 /* ------------------------------------------------------------------------ */
7525 /* Function: ipf_token_expire */
7526 /* Returns: None. */
7527 /* Parameters: softc(I) - pointer to soft context main structure */
7529 /* This function is run every ipf tick to see if there are any tokens that */
7530 /* have been held for too long and need to be freed up. */
7531 /* ------------------------------------------------------------------------ */
7533 ipf_token_expire(softc)
7534 ipf_main_softc_t *softc;
7538 WRITE_ENTER(&softc->ipf_tokens);
7539 while ((it = softc->ipf_token_head) != NULL) {
7540 if (it->ipt_die > softc->ipf_ticks)
7543 ipf_token_deref(softc, it);
7545 RWLOCK_EXIT(&softc->ipf_tokens);
7549 /* ------------------------------------------------------------------------ */
7550 /* Function: ipf_token_flush */
7551 /* Returns: None. */
7552 /* Parameters: softc(I) - pointer to soft context main structure */
7554 /* Loop through all of the existing tokens and call deref to see if they */
7555 /* can be freed. Normally a function like this might just loop on */
7556 /* ipf_token_head but there is a chance that a token might have a ref count */
7557 /* of greater than one and in that case the the reference would drop twice */
7558 /* by code that is only entitled to drop it once. */
7559 /* ------------------------------------------------------------------------ */
7561 ipf_token_flush(softc)
7562 ipf_main_softc_t *softc;
7564 ipftoken_t *it, *next;
7566 WRITE_ENTER(&softc->ipf_tokens);
7567 for (it = softc->ipf_token_head; it != NULL; it = next) {
7568 next = it->ipt_next;
7569 (void) ipf_token_deref(softc, it);
7571 RWLOCK_EXIT(&softc->ipf_tokens);
7575 /* ------------------------------------------------------------------------ */
7576 /* Function: ipf_token_del */
7577 /* Returns: int - 0 = success, else error */
7578 /* Parameters: softc(I)- pointer to soft context main structure */
7579 /* type(I) - the token type to match */
7580 /* uid(I) - uid owning the token */
7581 /* ptr(I) - context pointer for the token */
7583 /* This function looks for a a token in the current list that matches up */
7584 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7585 /* call ipf_token_dewref() to remove it from the list. In the event that */
7586 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7587 /* enables debugging to distinguish between the two paths that ultimately */
7588 /* lead to a token to be deleted. */
7589 /* ------------------------------------------------------------------------ */
7591 ipf_token_del(softc, type, uid, ptr)
7592 ipf_main_softc_t *softc;
7602 WRITE_ENTER(&softc->ipf_tokens);
7603 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7604 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7605 uid == it->ipt_uid) {
7606 it->ipt_complete = 2;
7607 ipf_token_deref(softc, it);
7612 RWLOCK_EXIT(&softc->ipf_tokens);
7618 /* ------------------------------------------------------------------------ */
7619 /* Function: ipf_token_mark_complete */
7620 /* Returns: None. */
7621 /* Parameters: token(I) - pointer to token structure */
7623 /* Mark a token as being ineligable for being found with ipf_token_find. */
7624 /* ------------------------------------------------------------------------ */
7626 ipf_token_mark_complete(token)
7629 if (token->ipt_complete == 0)
7630 token->ipt_complete = 1;
7634 /* ------------------------------------------------------------------------ */
7635 /* Function: ipf_token_find */
7636 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7637 /* Parameters: softc(I)- pointer to soft context main structure */
7638 /* type(I) - the token type to match */
7639 /* uid(I) - uid owning the token */
7640 /* ptr(I) - context pointer for the token */
7642 /* This function looks for a live token in the list of current tokens that */
7643 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7644 /* allocated. If one is found then it is moved to the top of the list of */
7645 /* currently active tokens. */
7646 /* ------------------------------------------------------------------------ */
7648 ipf_token_find(softc, type, uid, ptr)
7649 ipf_main_softc_t *softc;
7653 ipftoken_t *it, *new;
7655 KMALLOC(new, ipftoken_t *);
7657 bzero((char *)new, sizeof(*new));
7659 WRITE_ENTER(&softc->ipf_tokens);
7660 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7661 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7662 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7670 RWLOCK_EXIT(&softc->ipf_tokens);
7675 it->ipt_type = type;
7683 if (it->ipt_complete > 0)
7686 ipf_token_unlink(softc, it);
7690 it->ipt_pnext = softc->ipf_token_tail;
7691 *softc->ipf_token_tail = it;
7692 softc->ipf_token_tail = &it->ipt_next;
7693 it->ipt_next = NULL;
7696 it->ipt_die = softc->ipf_ticks + 20;
7699 RWLOCK_EXIT(&softc->ipf_tokens);
7705 /* ------------------------------------------------------------------------ */
7706 /* Function: ipf_token_unlink */
7707 /* Returns: None. */
7708 /* Parameters: softc(I) - pointer to soft context main structure */
7709 /* token(I) - pointer to token structure */
7710 /* Write Locks: ipf_tokens */
7712 /* This function unlinks a token structure from the linked list of tokens */
7713 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7714 /* but the tail does due to the linked list implementation. */
7715 /* ------------------------------------------------------------------------ */
7717 ipf_token_unlink(softc, token)
7718 ipf_main_softc_t *softc;
7722 if (softc->ipf_token_tail == &token->ipt_next)
7723 softc->ipf_token_tail = token->ipt_pnext;
7725 *token->ipt_pnext = token->ipt_next;
7726 if (token->ipt_next != NULL)
7727 token->ipt_next->ipt_pnext = token->ipt_pnext;
7728 token->ipt_next = NULL;
7729 token->ipt_pnext = NULL;
7733 /* ------------------------------------------------------------------------ */
7734 /* Function: ipf_token_deref */
7735 /* Returns: int - 0 == token freed, else reference count */
7736 /* Parameters: softc(I) - pointer to soft context main structure */
7737 /* token(I) - pointer to token structure */
7738 /* Write Locks: ipf_tokens */
7740 /* Drop the reference count on the token structure and if it drops to zero, */
7741 /* call the dereference function for the token type because it is then */
7742 /* possible to free the token data structure. */
7743 /* ------------------------------------------------------------------------ */
7745 ipf_token_deref(softc, token)
7746 ipf_main_softc_t *softc;
7749 void *data, **datap;
7751 ASSERT(token->ipt_ref > 0);
7753 if (token->ipt_ref > 0)
7754 return token->ipt_ref;
7756 data = token->ipt_data;
7759 if ((data != NULL) && (data != (void *)-1)) {
7760 switch (token->ipt_type)
7762 case IPFGENITER_IPF :
7763 (void) ipf_derefrule(softc, (frentry_t **)datap);
7765 case IPFGENITER_IPNAT :
7766 WRITE_ENTER(&softc->ipf_nat);
7767 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7768 RWLOCK_EXIT(&softc->ipf_nat);
7770 case IPFGENITER_NAT :
7771 ipf_nat_deref(softc, (nat_t **)datap);
7773 case IPFGENITER_STATE :
7774 ipf_state_deref(softc, (ipstate_t **)datap);
7776 case IPFGENITER_FRAG :
7777 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7779 case IPFGENITER_NATFRAG :
7780 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7782 case IPFGENITER_HOSTMAP :
7783 WRITE_ENTER(&softc->ipf_nat);
7784 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7785 RWLOCK_EXIT(&softc->ipf_nat);
7788 ipf_lookup_iterderef(softc, token->ipt_type, data);
7793 ipf_token_unlink(softc, token);
7799 /* ------------------------------------------------------------------------ */
7800 /* Function: ipf_nextrule */
7801 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7802 /* Parameters: softc(I) - pointer to soft context main structure */
7803 /* fr(I) - pointer to filter rule */
7804 /* out(I) - 1 == out rules, 0 == input rules */
7806 /* Starting with "fr", find the next rule to visit. This includes visiting */
7807 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7808 /* last rule in the list. When walking rule lists, it is either input or */
7809 /* output rules that are returned, never both. */
7810 /* ------------------------------------------------------------------------ */
7812 ipf_nextrule(softc, active, unit, fr, out)
7813 ipf_main_softc_t *softc;
7821 if (fr != NULL && fr->fr_group != -1) {
7822 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7823 unit, active, NULL);
7827 fg = softc->ipf_groups[unit][active];
7830 while (fg != NULL) {
7831 next = fg->fg_start;
7832 while (next != NULL) {
7834 if (next->fr_flags & FR_OUTQUE)
7836 } else if (next->fr_flags & FR_INQUE) {
7839 next = next->fr_next;
7848 /* ------------------------------------------------------------------------ */
7849 /* Function: ipf_getnextrule */
7850 /* Returns: int - 0 = success, else error */
7851 /* Parameters: softc(I)- pointer to soft context main structure */
7852 /* t(I) - pointer to destination information to resolve */
7853 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7855 /* This function's first job is to bring in the ipfruleiter_t structure via */
7856 /* the ipfobj_t structure to determine what should be the next rule to */
7857 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7858 /* find the 'next rule'. This may include searching rule group lists or */
7859 /* just be as simple as looking at the 'next' field in the rule structure. */
7860 /* When we have found the rule to return, increase its reference count and */
7861 /* if we used an existing rule to get here, decrease its reference count. */
7862 /* ------------------------------------------------------------------------ */
7864 ipf_getnextrule(softc, t, ptr)
7865 ipf_main_softc_t *softc;
7869 frentry_t *fr, *next, zero;
7878 if (t == NULL || ptr == NULL) {
7883 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7887 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7891 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7895 if (it.iri_nrules == 0) {
7899 if (it.iri_rule == NULL) {
7906 if ((it.iri_inout & F_OUT) != 0)
7910 if ((it.iri_inout & F_ACIN) != 0)
7911 unit = IPL_LOGCOUNT;
7915 READ_ENTER(&softc->ipf_mutex);
7917 if (*it.iri_group == '\0') {
7918 if (unit == IPL_LOGCOUNT) {
7919 next = softc->ipf_acct[out][it.iri_active];
7921 next = softc->ipf_rules[out][it.iri_active];
7924 next = ipf_nextrule(softc, it.iri_active,
7927 fg = ipf_findgroup(softc, it.iri_group, unit,
7928 it.iri_active, NULL);
7930 next = fg->fg_start;
7937 next = ipf_nextrule(softc, it.iri_active, unit,
7941 if (next != NULL && next->fr_next != NULL)
7943 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7949 (void) ipf_derefrule(softc, &fr);
7951 obj.ipfo_type = IPFOBJ_FRENTRY;
7952 dst = (char *)it.iri_rule;
7955 obj.ipfo_size = next->fr_size;
7956 MUTEX_ENTER(&next->fr_lock);
7958 MUTEX_EXIT(&next->fr_lock);
7961 obj.ipfo_size = sizeof(frentry_t);
7962 bzero(&zero, sizeof(zero));
7966 it.iri_rule = predict ? next : NULL;
7968 ipf_token_mark_complete(t);
7970 RWLOCK_EXIT(&softc->ipf_mutex);
7973 error = ipf_outobjk(softc, &obj, next);
7974 if (error == 0 && t->ipt_data != NULL) {
7975 dst += obj.ipfo_size;
7976 if (next->fr_data != NULL) {
7979 if (next->fr_type == FR_T_IPFEXPR)
7980 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7982 dobj.ipfo_type = IPFOBJ_FRIPF;
7983 dobj.ipfo_size = next->fr_dsize;
7984 dobj.ipfo_rev = obj.ipfo_rev;
7985 dobj.ipfo_ptr = dst;
7986 error = ipf_outobjk(softc, &dobj, next->fr_data);
7990 if ((fr != NULL) && (next == &zero))
7991 (void) ipf_derefrule(softc, &fr);
7997 /* ------------------------------------------------------------------------ */
7998 /* Function: ipf_frruleiter */
7999 /* Returns: int - 0 = success, else error */
8000 /* Parameters: softc(I)- pointer to soft context main structure */
8001 /* data(I) - the token type to match */
8002 /* uid(I) - uid owning the token */
8003 /* ptr(I) - context pointer for the token */
8005 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
8006 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
8007 /* the process doing the ioctl and use that to ask for the next rule. */
8008 /* ------------------------------------------------------------------------ */
8010 ipf_frruleiter(softc, data, uid, ctx)
8011 ipf_main_softc_t *softc;
8020 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8021 if (token != NULL) {
8022 error = ipf_getnextrule(softc, token, data);
8023 WRITE_ENTER(&softc->ipf_tokens);
8024 ipf_token_deref(softc, token);
8025 RWLOCK_EXIT(&softc->ipf_tokens);
8027 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8031 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8038 /* ------------------------------------------------------------------------ */
8039 /* Function: ipf_geniter */
8040 /* Returns: int - 0 = success, else error */
8041 /* Parameters: softc(I) - pointer to soft context main structure */
8042 /* token(I) - pointer to ipftoken_t structure */
8043 /* itp(I) - pointer to iterator data */
8045 /* Decide which iterator function to call using information passed through */
8046 /* the ipfgeniter_t structure at itp. */
8047 /* ------------------------------------------------------------------------ */
8049 ipf_geniter(softc, token, itp)
8050 ipf_main_softc_t *softc;
8056 switch (itp->igi_type)
8058 case IPFGENITER_FRAG :
8059 error = ipf_frag_pkt_next(softc, token, itp);
8071 /* ------------------------------------------------------------------------ */
8072 /* Function: ipf_genericiter */
8073 /* Returns: int - 0 = success, else error */
8074 /* Parameters: softc(I)- pointer to soft context main structure */
8075 /* data(I) - the token type to match */
8076 /* uid(I) - uid owning the token */
8077 /* ptr(I) - context pointer for the token */
8079 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8080 /* ------------------------------------------------------------------------ */
8082 ipf_genericiter(softc, data, uid, ctx)
8083 ipf_main_softc_t *softc;
8091 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8095 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8096 if (token != NULL) {
8097 token->ipt_subtype = iter.igi_type;
8098 error = ipf_geniter(softc, token, &iter);
8099 WRITE_ENTER(&softc->ipf_tokens);
8100 ipf_token_deref(softc, token);
8101 RWLOCK_EXIT(&softc->ipf_tokens);
8111 /* ------------------------------------------------------------------------ */
8112 /* Function: ipf_ipf_ioctl */
8113 /* Returns: int - 0 = success, else error */
8114 /* Parameters: softc(I)- pointer to soft context main structure */
8115 /* data(I) - the token type to match */
8116 /* cmd(I) - the ioctl command number */
8117 /* mode(I) - mode flags for the ioctl */
8118 /* uid(I) - uid owning the token */
8119 /* ptr(I) - context pointer for the token */
8121 /* This function handles all of the ioctl command that are actually isssued */
8122 /* to the /dev/ipl device. */
8123 /* ------------------------------------------------------------------------ */
8125 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8126 ipf_main_softc_t *softc;
8140 if (!(mode & FWRITE)) {
8144 error = BCOPYIN(data, &tmp, sizeof(tmp));
8151 WRITE_ENTER(&softc->ipf_global);
8153 if (softc->ipf_running > 0)
8156 error = ipfattach(softc);
8158 softc->ipf_running = 1;
8160 (void) ipfdetach(softc);
8162 if (softc->ipf_running == 1)
8163 error = ipfdetach(softc);
8167 softc->ipf_running = -1;
8169 RWLOCK_EXIT(&softc->ipf_global);
8174 if (!(mode & FWRITE)) {
8180 case SIOCIPFGETNEXT :
8182 error = ipf_ipftune(softc, cmd, (void *)data);
8186 if (!(mode & FWRITE)) {
8190 error = BCOPYIN(data, &softc->ipf_flags,
8191 sizeof(softc->ipf_flags));
8200 error = BCOPYOUT(&softc->ipf_flags, data,
8201 sizeof(softc->ipf_flags));
8209 error = ipf_resolvefunc(softc, (void *)data);
8216 if (!(mode & FWRITE)) {
8220 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8221 softc->ipf_active, 1);
8228 if (!(mode & FWRITE)) {
8232 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8233 1 - softc->ipf_active, 1);
8238 if (!(mode & FWRITE)) {
8242 WRITE_ENTER(&softc->ipf_mutex);
8243 error = BCOPYOUT(&softc->ipf_active, data,
8244 sizeof(softc->ipf_active));
8249 softc->ipf_active = 1 - softc->ipf_active;
8251 RWLOCK_EXIT(&softc->ipf_mutex);
8256 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8260 ipf_getstat(softc, &fio, obj.ipfo_rev);
8261 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8265 if (!(mode & FWRITE)) {
8269 error = ipf_zerostats(softc, (caddr_t)data);
8273 if (!(mode & FWRITE)) {
8277 error = BCOPYIN(data, &tmp, sizeof(tmp));
8279 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8280 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8294 if (!(mode & FWRITE)) {
8298 error = BCOPYIN(data, &tmp, sizeof(tmp));
8300 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8301 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8315 if (!(mode & FWRITE)) {
8319 error = BCOPYIN(data, &tmp, sizeof(tmp));
8321 ipf_state_setlock(softc->ipf_state_soft, tmp);
8322 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8323 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8324 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8334 if (!(mode & FWRITE)) {
8338 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8339 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8346 #endif /* IPFILTER_LOG */
8349 if (!(mode & FWRITE)) {
8353 WRITE_ENTER(&softc->ipf_global);
8354 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8357 ipf_sync(softc, NULL);
8360 RWLOCK_EXIT(&softc->ipf_global);
8366 error = ipf_outobj(softc, (void *)data,
8367 ipf_frag_stats(softc->ipf_frag_soft),
8373 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8374 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8380 error = ipf_frruleiter(softc, data, uid, ctx);
8386 error = ipf_genericiter(softc, data, uid, ctx);
8390 case SIOCIPFDELTOK :
8391 error = BCOPYIN(data, &tmp, sizeof(tmp));
8394 error = ipf_token_del(softc, tmp, uid, ctx);
8409 /* ------------------------------------------------------------------------ */
8410 /* Function: ipf_decaps */
8411 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8412 /* flags indicating packet filtering decision. */
8413 /* Parameters: fin(I) - pointer to packet information */
8414 /* pass(I) - IP protocol version to match */
8415 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8417 /* This function is called for packets that are wrapt up in other packets, */
8418 /* for example, an IP packet that is the entire data segment for another IP */
8419 /* packet. If the basic constraints for this are satisfied, change the */
8420 /* buffer to point to the start of the inner packet and start processing */
8421 /* rules belonging to the head group this rule specifies. */
8422 /* ------------------------------------------------------------------------ */
8424 ipf_decaps(fin, pass, l5proto)
8429 fr_info_t fin2, *fino = NULL;
8435 if ((fin->fin_flx & FI_COALESCE) == 0)
8436 if (ipf_coalesce(fin) == -1)
8440 hlen = fin->fin_hlen;
8446 * In this case, the specific protocol being decapsulated
8447 * inside UDP frames comes from the rule.
8449 nh = fin->fin_fr->fr_icode;
8452 case IPPROTO_GRE : /* 47 */
8453 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8454 hlen += sizeof(grehdr_t);
8455 if (gre.gr_R|gre.gr_s)
8467 * If the routing options flag is set, validate that it is
8468 * there and bounce over it.
8471 /* This is really heavy weight and lots of room for error, */
8472 /* so for now, put it off and get the simple stuff right. */
8474 u_char off, len, *s;
8481 aplen = fin->fin_plen - hlen;
8483 af = (s[0] << 8) | s[1];
8488 if (af == 0 && len == 0) {
8499 hlen = s - (u_char *)fin->fin_dp;
8505 case IPPROTO_IPIP : /* 4 */
8510 default : /* Includes ESP, AH is special for IPv4 */
8523 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8527 #if defined(MENTAT) && defined(_KERNEL)
8533 fin->fin_plen -= elen;
8535 ip = (ip_t *)((char *)fin->fin_ip + elen);
8538 * Make sure we have at least enough data for the network layer
8542 hlen = IP_HL(ip) << 2;
8544 else if (IP_V(ip) == 6)
8545 hlen = sizeof(ip6_t);
8550 if (fin->fin_plen < hlen)
8553 fin->fin_dp = (char *)ip + hlen;
8555 if (IP_V(ip) == 4) {
8557 * Perform IPv4 header checksum validation.
8559 if (ipf_cksum((u_short *)ip, hlen))
8563 if (ipf_makefrip(hlen, ip, fin) == -1) {
8566 #if defined(MENTAT) && defined(_KERNEL)
8574 DT1(frb_decapfrip, fr_info_t *, fin);
8575 pass &= ~FR_CMDMASK;
8576 pass |= FR_BLOCK|FR_QUICK;
8577 fin->fin_reason = FRB_DECAPFRIP;
8581 pass = ipf_scanlist(fin, pass);
8584 * Copy the packet filter "result" fields out of the fr_info_t struct
8585 * that is local to the decapsulation processing and back into the
8586 * one we were called with.
8588 fino->fin_flx = fin->fin_flx;
8589 fino->fin_rev = fin->fin_rev;
8590 fino->fin_icode = fin->fin_icode;
8591 fino->fin_rule = fin->fin_rule;
8592 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8593 fino->fin_fr = fin->fin_fr;
8594 fino->fin_error = fin->fin_error;
8595 fino->fin_mp = fin->fin_mp;
8596 fino->fin_m = fin->fin_m;
8599 #if defined(MENTAT) && defined(_KERNEL)
8610 /* ------------------------------------------------------------------------ */
8611 /* Function: ipf_matcharray_load */
8612 /* Returns: int - 0 = success, else error */
8613 /* Parameters: softc(I) - pointer to soft context main structure */
8614 /* data(I) - pointer to ioctl data */
8615 /* objp(I) - ipfobj_t structure to load data into */
8616 /* arrayptr(I) - pointer to location to store array pointer */
8618 /* This function loads in a mathing array through the ipfobj_t struct that */
8619 /* describes it. Sanity checking and array size limitations are enforced */
8620 /* in this function to prevent userspace from trying to load in something */
8621 /* that is insanely big. Once the size of the array is known, the memory */
8622 /* required is malloc'd and returned through changing *arrayptr. The */
8623 /* contents of the array are verified before returning. Only in the event */
8624 /* of a successful call is the caller required to free up the malloc area. */
8625 /* ------------------------------------------------------------------------ */
8627 ipf_matcharray_load(softc, data, objp, arrayptr)
8628 ipf_main_softc_t *softc;
8633 int arraysize, *array, error;
8637 error = BCOPYIN(data, objp, sizeof(*objp));
8643 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8648 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8649 (objp->ipfo_size > 1024)) {
8654 arraysize = objp->ipfo_size * sizeof(*array);
8655 KMALLOCS(array, int *, arraysize);
8656 if (array == NULL) {
8661 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8663 KFREES(array, arraysize);
8668 if (ipf_matcharray_verify(array, arraysize) != 0) {
8669 KFREES(array, arraysize);
8679 /* ------------------------------------------------------------------------ */
8680 /* Function: ipf_matcharray_verify */
8682 /* Parameters: array(I) - pointer to matching array */
8683 /* arraysize(I) - number of elements in the array */
8685 /* Verify the contents of a matching array by stepping through each element */
8686 /* in it. The actual commands in the array are not verified for */
8687 /* correctness, only that all of the sizes are correctly within limits. */
8688 /* ------------------------------------------------------------------------ */
8690 ipf_matcharray_verify(array, arraysize)
8691 int *array, arraysize;
8693 int i, nelem, maxidx;
8696 nelem = arraysize / sizeof(*array);
8699 * Currently, it makes no sense to have an array less than 6
8700 * elements long - the initial size at the from, a single operation
8701 * (minimum 4 in length) and a trailer, for a total of 6.
8703 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8708 * Verify the size of data pointed to by array with how long
8709 * the array claims to be itself.
8711 if (array[0] * sizeof(*array) != arraysize) {
8717 * The last opcode in this array should be an IPF_EXP_END.
8719 if (array[maxidx] != IPF_EXP_END) {
8723 for (i = 1; i < maxidx; ) {
8724 e = (ipfexp_t *)(array + i);
8727 * The length of the bits to check must be at least 1
8728 * (or else there is nothing to comapre with!) and it
8729 * cannot exceed the length of the data present.
8731 if ((e->ipfe_size < 1 ) ||
8732 (e->ipfe_size + i > maxidx)) {
8741 /* ------------------------------------------------------------------------ */
8742 /* Function: ipf_fr_matcharray */
8743 /* Returns: int - 0 = match failed, else positive match */
8744 /* Parameters: fin(I) - pointer to packet information */
8745 /* array(I) - pointer to matching array */
8747 /* This function is used to apply a matching array against a packet and */
8748 /* return an indication of whether or not the packet successfully matches */
8749 /* all of the commands in it. */
8750 /* ------------------------------------------------------------------------ */
8752 ipf_fr_matcharray(fin, array)
8756 int i, n, *x, rv, p;
8763 for (; n > 0; x += 3 + x[3], rv = 0) {
8765 if (e->ipfe_cmd == IPF_EXP_END)
8770 * The upper 16 bits currently store the protocol value.
8771 * This is currently used with TCP and UDP port compares and
8772 * allows "tcp.port = 80" without requiring an explicit
8773 " "ip.pr = tcp" first.
8775 p = e->ipfe_cmd >> 16;
8776 if ((p != 0) && (p != fin->fin_p))
8779 switch (e->ipfe_cmd)
8781 case IPF_EXP_IP_PR :
8782 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8783 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8787 case IPF_EXP_IP_SRCADDR :
8788 if (fin->fin_v != 4)
8790 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8791 rv |= ((fin->fin_saddr &
8792 e->ipfe_arg0[i * 2 + 1]) ==
8793 e->ipfe_arg0[i * 2]);
8797 case IPF_EXP_IP_DSTADDR :
8798 if (fin->fin_v != 4)
8800 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8801 rv |= ((fin->fin_daddr &
8802 e->ipfe_arg0[i * 2 + 1]) ==
8803 e->ipfe_arg0[i * 2]);
8807 case IPF_EXP_IP_ADDR :
8808 if (fin->fin_v != 4)
8810 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8811 rv |= ((fin->fin_saddr &
8812 e->ipfe_arg0[i * 2 + 1]) ==
8813 e->ipfe_arg0[i * 2]) ||
8815 e->ipfe_arg0[i * 2 + 1]) ==
8816 e->ipfe_arg0[i * 2]);
8821 case IPF_EXP_IP6_SRCADDR :
8822 if (fin->fin_v != 6)
8824 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8825 rv |= IP6_MASKEQ(&fin->fin_src6,
8826 &e->ipfe_arg0[i * 8 + 4],
8827 &e->ipfe_arg0[i * 8]);
8831 case IPF_EXP_IP6_DSTADDR :
8832 if (fin->fin_v != 6)
8834 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8835 rv |= IP6_MASKEQ(&fin->fin_dst6,
8836 &e->ipfe_arg0[i * 8 + 4],
8837 &e->ipfe_arg0[i * 8]);
8841 case IPF_EXP_IP6_ADDR :
8842 if (fin->fin_v != 6)
8844 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8845 rv |= IP6_MASKEQ(&fin->fin_src6,
8846 &e->ipfe_arg0[i * 8 + 4],
8847 &e->ipfe_arg0[i * 8]) ||
8848 IP6_MASKEQ(&fin->fin_dst6,
8849 &e->ipfe_arg0[i * 8 + 4],
8850 &e->ipfe_arg0[i * 8]);
8855 case IPF_EXP_UDP_PORT :
8856 case IPF_EXP_TCP_PORT :
8857 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8858 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8859 (fin->fin_dport == e->ipfe_arg0[i]);
8863 case IPF_EXP_UDP_SPORT :
8864 case IPF_EXP_TCP_SPORT :
8865 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8866 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8870 case IPF_EXP_UDP_DPORT :
8871 case IPF_EXP_TCP_DPORT :
8872 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8873 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8877 case IPF_EXP_TCP_FLAGS :
8878 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8879 rv |= ((fin->fin_tcpf &
8880 e->ipfe_arg0[i * 2 + 1]) ==
8881 e->ipfe_arg0[i * 2]);
8895 /* ------------------------------------------------------------------------ */
8896 /* Function: ipf_queueflush */
8897 /* Returns: int - number of entries flushed (0 = none) */
8898 /* Parameters: softc(I) - pointer to soft context main structure */
8899 /* deletefn(I) - function to call to delete entry */
8900 /* ipfqs(I) - top of the list of ipf internal queues */
8901 /* userqs(I) - top of the list of user defined timeouts */
8903 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8904 /* need to try a bit harder to free up some space. The algorithm used here */
8905 /* split into two parts but both halves have the same goal: to reduce the */
8906 /* number of connections considered to be "active" to the low watermark. */
8907 /* There are two steps in doing this: */
8908 /* 1) Remove any TCP connections that are already considered to be "closed" */
8909 /* but have not yet been removed from the state table. The two states */
8910 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8911 /* candidates for this style of removal. If freeing up entries in */
8912 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8913 /* we do not go on to step 2. */
8915 /* 2) Look for the oldest entries on each timeout queue and free them if */
8916 /* they are within the given window we are considering. Where the */
8917 /* window starts and the steps taken to increase its size depend upon */
8918 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8919 /* last 30 seconds is not touched. */
8921 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8923 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8924 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8926 /* Points to note: */
8927 /* - tqe_die is the time, in the future, when entries die. */
8928 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8930 /* - tqe_touched is when the entry was last used by NAT/state */
8931 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8932 /* ipf_ticks any given timeout queue and vice versa. */
8933 /* - both tqe_die and tqe_touched increase over time */
8934 /* - timeout queues are sorted with the highest value of tqe_die at the */
8935 /* bottom and therefore the smallest values of each are at the top */
8936 /* - the pointer passed in as ipfqs should point to an array of timeout */
8937 /* queues representing each of the TCP states */
8939 /* We start by setting up a maximum range to scan for things to move of */
8940 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8941 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8942 /* we start again with a new value for "iend" and "istart". This is */
8943 /* continued until we either finish the scan of 30 second intervals or the */
8944 /* low water mark is reached. */
8945 /* ------------------------------------------------------------------------ */
8947 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8948 ipf_main_softc_t *softc;
8949 ipftq_delete_fn_t deletefn;
8950 ipftq_t *ipfqs, *userqs;
8954 u_long interval, istart, iend;
8955 ipftq_t *ifq, *ifqnext;
8956 ipftqent_t *tqe, *tqn;
8959 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8960 tqn = tqe->tqe_next;
8961 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8964 if ((*activep * 100 / size) > low) {
8965 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8966 ((tqe = tqn) != NULL); ) {
8967 tqn = tqe->tqe_next;
8968 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8973 if ((*activep * 100 / size) <= low) {
8978 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8979 * used then the operations are upgraded to floating point
8980 * and kernels don't like floating point...
8982 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8983 istart = IPF_TTLVAL(86400 * 4);
8984 interval = IPF_TTLVAL(43200);
8985 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8986 istart = IPF_TTLVAL(43200);
8987 interval = IPF_TTLVAL(1800);
8988 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8989 istart = IPF_TTLVAL(1800);
8990 interval = IPF_TTLVAL(30);
8994 if (istart > softc->ipf_ticks) {
8995 if (softc->ipf_ticks - interval < interval)
8998 istart = (softc->ipf_ticks / interval) * interval;
9001 iend = softc->ipf_ticks - interval;
9003 while ((*activep * 100 / size) > low) {
9006 try = softc->ipf_ticks - istart;
9008 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9009 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9010 if (try < tqe->tqe_touched)
9012 tqn = tqe->tqe_next;
9013 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9018 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9019 ifqnext = ifq->ifq_next;
9021 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9022 if (try < tqe->tqe_touched)
9024 tqn = tqe->tqe_next;
9025 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9031 if (interval == IPF_TTLVAL(43200)) {
9032 interval = IPF_TTLVAL(1800);
9033 } else if (interval == IPF_TTLVAL(1800)) {
9034 interval = IPF_TTLVAL(30);
9038 if (interval >= softc->ipf_ticks)
9041 iend = softc->ipf_ticks - interval;
9050 /* ------------------------------------------------------------------------ */
9051 /* Function: ipf_deliverlocal */
9052 /* Returns: int - 1 = local address, 0 = non-local address */
9053 /* Parameters: softc(I) - pointer to soft context main structure */
9054 /* ipversion(I) - IP protocol version (4 or 6) */
9055 /* ifp(I) - network interface pointer */
9056 /* ipaddr(I) - IPv4/6 destination address */
9058 /* This fucntion is used to determine in the address "ipaddr" belongs to */
9059 /* the network interface represented by ifp. */
9060 /* ------------------------------------------------------------------------ */
9062 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9063 ipf_main_softc_t *softc;
9071 if (ipversion == 4) {
9072 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9073 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9078 } else if (ipversion == 6) {
9079 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9080 if (IP6_EQ(&addr, ipaddr))
9090 /* ------------------------------------------------------------------------ */
9091 /* Function: ipf_settimeout */
9092 /* Returns: int - 0 = success, -1 = failure */
9093 /* Parameters: softc(I) - pointer to soft context main structure */
9094 /* t(I) - pointer to tuneable array entry */
9095 /* p(I) - pointer to values passed in to apply */
9097 /* This function is called to set the timeout values for each distinct */
9098 /* queue timeout that is available. When called, it calls into both the */
9099 /* state and NAT code, telling them to update their timeout queues. */
9100 /* ------------------------------------------------------------------------ */
9102 ipf_settimeout(softc, t, p)
9103 struct ipf_main_softc_s *softc;
9109 * ipf_interror should be set by the functions called here, not
9110 * by this function - it's just a middle man.
9112 if (ipf_state_settimeout(softc, t, p) == -1)
9114 if (ipf_nat_settimeout(softc, t, p) == -1)
9120 /* ------------------------------------------------------------------------ */
9121 /* Function: ipf_apply_timeout */
9122 /* Returns: int - 0 = success, -1 = failure */
9123 /* Parameters: head(I) - pointer to tuneable array entry */
9124 /* seconds(I) - pointer to values passed in to apply */
9126 /* This function applies a timeout of "seconds" to the timeout queue that */
9127 /* is pointed to by "head". All entries on this list have an expiration */
9128 /* set to be the current tick value of ipf plus the ttl. Given that this */
9129 /* function should only be called when the delta is non-zero, the task is */
9130 /* to walk the entire list and apply the change. The sort order will not */
9131 /* change. The only catch is that this is O(n) across the list, so if the */
9132 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
9133 /* could take a relatively long time to work through them all. */
9134 /* ------------------------------------------------------------------------ */
9136 ipf_apply_timeout(head, seconds)
9140 u_int oldtimeout, newtimeout;
9144 MUTEX_ENTER(&head->ifq_lock);
9145 oldtimeout = head->ifq_ttl;
9146 newtimeout = IPF_TTLVAL(seconds);
9147 delta = oldtimeout - newtimeout;
9149 head->ifq_ttl = newtimeout;
9151 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9152 tqe->tqe_die += delta;
9154 MUTEX_EXIT(&head->ifq_lock);
9158 /* ------------------------------------------------------------------------ */
9159 /* Function: ipf_settimeout_tcp */
9160 /* Returns: int - 0 = successfully applied, -1 = failed */
9161 /* Parameters: t(I) - pointer to tuneable to change */
9162 /* p(I) - pointer to new timeout information */
9163 /* tab(I) - pointer to table of TCP queues */
9165 /* This function applies the new timeout (p) to the TCP tunable (t) and */
9166 /* updates all of the entries on the relevant timeout queue by calling */
9167 /* ipf_apply_timeout(). */
9168 /* ------------------------------------------------------------------------ */
9170 ipf_settimeout_tcp(t, p, tab)
9175 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9176 !strcmp(t->ipft_name, "tcp_established")) {
9177 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9178 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9179 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9180 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9181 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9182 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9183 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9184 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9185 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9186 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9187 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9188 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9189 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9190 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9191 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9192 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9193 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9194 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9195 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9196 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9197 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9198 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9199 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9200 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9201 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9204 * ipf_interror isn't set here because it should be set
9205 * by whatever called this function.
9213 /* ------------------------------------------------------------------------ */
9214 /* Function: ipf_main_soft_create */
9215 /* Returns: NULL = failure, else success */
9216 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9218 /* Create the foundation soft context structure. In circumstances where it */
9219 /* is not required to dynamically allocate the context, a pointer can be */
9220 /* passed in (rather than NULL) to a structure to be initialised. */
9221 /* The main thing of interest is that a number of locks are initialised */
9222 /* here instead of in the where might be expected - in the relevant create */
9223 /* function elsewhere. This is done because the current locking design has */
9224 /* some areas where these locks are used outside of their module. */
9225 /* Possibly the most important exercise that is done here is setting of all */
9226 /* the timeout values, allowing them to be changed before init(). */
9227 /* ------------------------------------------------------------------------ */
9229 ipf_main_soft_create(arg)
9232 ipf_main_softc_t *softc;
9235 KMALLOC(softc, ipf_main_softc_t *);
9242 bzero((char *)softc, sizeof(*softc));
9245 * This serves as a flag as to whether or not the softc should be
9246 * free'd when _destroy is called.
9248 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9250 softc->ipf_tuners = ipf_tune_array_copy(softc,
9251 sizeof(ipf_main_tuneables),
9252 ipf_main_tuneables);
9253 if (softc->ipf_tuners == NULL) {
9254 ipf_main_soft_destroy(softc);
9258 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9259 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9260 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9261 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9262 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9263 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9264 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9265 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9266 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9268 softc->ipf_token_head = NULL;
9269 softc->ipf_token_tail = &softc->ipf_token_head;
9271 softc->ipf_tcpidletimeout = FIVE_DAYS;
9272 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9273 softc->ipf_tcplastack = IPF_TTLVAL(30);
9274 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9275 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9276 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9277 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9278 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9279 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9280 softc->ipf_udptimeout = IPF_TTLVAL(120);
9281 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9282 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9283 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9284 softc->ipf_iptimeout = IPF_TTLVAL(60);
9286 #if defined(IPFILTER_DEFAULT_BLOCK)
9287 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9289 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9291 softc->ipf_minttl = 4;
9292 softc->ipf_icmpminfragmtu = 68;
9293 softc->ipf_flags = IPF_LOGGING;
9298 /* ------------------------------------------------------------------------ */
9299 /* Function: ipf_main_soft_init */
9300 /* Returns: 0 = success, -1 = failure */
9301 /* Parameters: softc(I) - pointer to soft context main structure */
9303 /* A null-op function that exists as a placeholder so that the flow in */
9304 /* other functions is obvious. */
9305 /* ------------------------------------------------------------------------ */
9308 ipf_main_soft_init(softc)
9309 ipf_main_softc_t *softc;
9315 /* ------------------------------------------------------------------------ */
9316 /* Function: ipf_main_soft_destroy */
9318 /* Parameters: softc(I) - pointer to soft context main structure */
9320 /* Undo everything that we did in ipf_main_soft_create. */
9322 /* The most important check that needs to be made here is whether or not */
9323 /* the structure was allocated by ipf_main_soft_create() by checking what */
9324 /* value is stored in ipf_dynamic_main. */
9325 /* ------------------------------------------------------------------------ */
9328 ipf_main_soft_destroy(softc)
9329 ipf_main_softc_t *softc;
9332 RW_DESTROY(&softc->ipf_frag);
9333 RW_DESTROY(&softc->ipf_poolrw);
9334 RW_DESTROY(&softc->ipf_nat);
9335 RW_DESTROY(&softc->ipf_state);
9336 RW_DESTROY(&softc->ipf_tokens);
9337 RW_DESTROY(&softc->ipf_mutex);
9338 RW_DESTROY(&softc->ipf_global);
9339 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9340 MUTEX_DESTROY(&softc->ipf_rw);
9342 if (softc->ipf_tuners != NULL) {
9343 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9345 if (softc->ipf_dynamic_softc == 1) {
9351 /* ------------------------------------------------------------------------ */
9352 /* Function: ipf_main_soft_fini */
9353 /* Returns: 0 = success, -1 = failure */
9354 /* Parameters: softc(I) - pointer to soft context main structure */
9356 /* Clean out the rules which have been added since _init was last called, */
9357 /* the only dynamic part of the mainline. */
9358 /* ------------------------------------------------------------------------ */
9360 ipf_main_soft_fini(softc)
9361 ipf_main_softc_t *softc;
9363 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9364 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9365 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9366 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9372 /* ------------------------------------------------------------------------ */
9373 /* Function: ipf_main_load */
9374 /* Returns: 0 = success, -1 = failure */
9375 /* Parameters: none */
9377 /* Handle global initialisation that needs to be done for the base part of */
9378 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9379 /* arrays that get used by the state/NAT code. */
9380 /* ------------------------------------------------------------------------ */
9386 /* fill icmp reply type table */
9387 for (i = 0; i <= ICMP_MAXTYPE; i++)
9388 icmpreplytype4[i] = -1;
9389 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9390 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9391 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9392 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9395 /* fill icmp reply type table */
9396 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9397 icmpreplytype6[i] = -1;
9398 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9399 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9400 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9401 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9402 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9409 /* ------------------------------------------------------------------------ */
9410 /* Function: ipf_main_unload */
9411 /* Returns: 0 = success, -1 = failure */
9412 /* Parameters: none */
9414 /* A null-op function that exists as a placeholder so that the flow in */
9415 /* other functions is obvious. */
9416 /* ------------------------------------------------------------------------ */
9424 /* ------------------------------------------------------------------------ */
9425 /* Function: ipf_load_all */
9426 /* Returns: 0 = success, -1 = failure */
9427 /* Parameters: none */
9429 /* Work through all of the subsystems inside IPFilter and call the load */
9430 /* function for each in an order that won't lead to a crash :) */
9431 /* ------------------------------------------------------------------------ */
9435 if (ipf_main_load() == -1)
9438 if (ipf_state_main_load() == -1)
9441 if (ipf_nat_main_load() == -1)
9444 if (ipf_frag_main_load() == -1)
9447 if (ipf_auth_main_load() == -1)
9450 if (ipf_proxy_main_load() == -1)
9457 /* ------------------------------------------------------------------------ */
9458 /* Function: ipf_unload_all */
9459 /* Returns: 0 = success, -1 = failure */
9460 /* Parameters: none */
9462 /* Work through all of the subsystems inside IPFilter and call the unload */
9463 /* function for each in an order that won't lead to a crash :) */
9464 /* ------------------------------------------------------------------------ */
9468 if (ipf_proxy_main_unload() == -1)
9471 if (ipf_auth_main_unload() == -1)
9474 if (ipf_frag_main_unload() == -1)
9477 if (ipf_nat_main_unload() == -1)
9480 if (ipf_state_main_unload() == -1)
9483 if (ipf_main_unload() == -1)
9490 /* ------------------------------------------------------------------------ */
9491 /* Function: ipf_create_all */
9492 /* Returns: NULL = failure, else success */
9493 /* Parameters: arg(I) - pointer to soft context main structure */
9495 /* Work through all of the subsystems inside IPFilter and call the create */
9496 /* function for each in an order that won't lead to a crash :) */
9497 /* ------------------------------------------------------------------------ */
9502 ipf_main_softc_t *softc;
9504 softc = ipf_main_soft_create(arg);
9509 softc->ipf_log_soft = ipf_log_soft_create(softc);
9510 if (softc->ipf_log_soft == NULL) {
9511 ipf_destroy_all(softc);
9516 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9517 if (softc->ipf_lookup_soft == NULL) {
9518 ipf_destroy_all(softc);
9522 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9523 if (softc->ipf_sync_soft == NULL) {
9524 ipf_destroy_all(softc);
9528 softc->ipf_state_soft = ipf_state_soft_create(softc);
9529 if (softc->ipf_state_soft == NULL) {
9530 ipf_destroy_all(softc);
9534 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9535 if (softc->ipf_nat_soft == NULL) {
9536 ipf_destroy_all(softc);
9540 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9541 if (softc->ipf_frag_soft == NULL) {
9542 ipf_destroy_all(softc);
9546 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9547 if (softc->ipf_auth_soft == NULL) {
9548 ipf_destroy_all(softc);
9552 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9553 if (softc->ipf_proxy_soft == NULL) {
9554 ipf_destroy_all(softc);
9562 /* ------------------------------------------------------------------------ */
9563 /* Function: ipf_destroy_all */
9565 /* Parameters: softc(I) - pointer to soft context main structure */
9567 /* Work through all of the subsystems inside IPFilter and call the destroy */
9568 /* function for each in an order that won't lead to a crash :) */
9570 /* Every one of these functions is expected to succeed, so there is no */
9571 /* checking of return values. */
9572 /* ------------------------------------------------------------------------ */
9574 ipf_destroy_all(softc)
9575 ipf_main_softc_t *softc;
9578 if (softc->ipf_state_soft != NULL) {
9579 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9580 softc->ipf_state_soft = NULL;
9583 if (softc->ipf_nat_soft != NULL) {
9584 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9585 softc->ipf_nat_soft = NULL;
9588 if (softc->ipf_frag_soft != NULL) {
9589 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9590 softc->ipf_frag_soft = NULL;
9593 if (softc->ipf_auth_soft != NULL) {
9594 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9595 softc->ipf_auth_soft = NULL;
9598 if (softc->ipf_proxy_soft != NULL) {
9599 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9600 softc->ipf_proxy_soft = NULL;
9603 if (softc->ipf_sync_soft != NULL) {
9604 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9605 softc->ipf_sync_soft = NULL;
9608 if (softc->ipf_lookup_soft != NULL) {
9609 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9610 softc->ipf_lookup_soft = NULL;
9614 if (softc->ipf_log_soft != NULL) {
9615 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9616 softc->ipf_log_soft = NULL;
9620 ipf_main_soft_destroy(softc);
9624 /* ------------------------------------------------------------------------ */
9625 /* Function: ipf_init_all */
9626 /* Returns: 0 = success, -1 = failure */
9627 /* Parameters: softc(I) - pointer to soft context main structure */
9629 /* Work through all of the subsystems inside IPFilter and call the init */
9630 /* function for each in an order that won't lead to a crash :) */
9631 /* ------------------------------------------------------------------------ */
9634 ipf_main_softc_t *softc;
9637 if (ipf_main_soft_init(softc) == -1)
9641 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9645 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9648 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9651 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9654 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9657 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9660 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9663 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9670 /* ------------------------------------------------------------------------ */
9671 /* Function: ipf_fini_all */
9672 /* Returns: 0 = success, -1 = failure */
9673 /* Parameters: softc(I) - pointer to soft context main structure */
9675 /* Work through all of the subsystems inside IPFilter and call the fini */
9676 /* function for each in an order that won't lead to a crash :) */
9677 /* ------------------------------------------------------------------------ */
9680 ipf_main_softc_t *softc;
9683 ipf_token_flush(softc);
9685 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9688 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9691 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9694 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9697 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9700 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9703 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9707 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9711 if (ipf_main_soft_fini(softc) == -1)
9718 /* ------------------------------------------------------------------------ */
9719 /* Function: ipf_rule_expire */
9721 /* Parameters: softc(I) - pointer to soft context main structure */
9723 /* At present this function exists just to support temporary addition of */
9724 /* firewall rules. Both inactive and active lists are scanned for items to */
9725 /* purge, as by rights, the expiration is computed as soon as the rule is */
9727 /* ------------------------------------------------------------------------ */
9729 ipf_rule_expire(softc)
9730 ipf_main_softc_t *softc;
9734 if ((softc->ipf_rule_explist[0] == NULL) &&
9735 (softc->ipf_rule_explist[1] == NULL))
9738 WRITE_ENTER(&softc->ipf_mutex);
9740 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9742 * Because the list is kept sorted on insertion, the fist
9743 * one that dies in the future means no more work to do.
9745 if (fr->fr_die > softc->ipf_ticks)
9747 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9750 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9752 * Because the list is kept sorted on insertion, the fist
9753 * one that dies in the future means no more work to do.
9755 if (fr->fr_die > softc->ipf_ticks)
9757 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9760 RWLOCK_EXIT(&softc->ipf_mutex);
9764 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9765 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9768 host_node_t RBI_ZERO(ipf_rb);
9769 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9772 /* ------------------------------------------------------------------------ */
9773 /* Function: ipf_ht_node_cmp */
9774 /* Returns: int - 0 == nodes are the same, .. */
9775 /* Parameters: k1(I) - pointer to first key to compare */
9776 /* k2(I) - pointer to second key to compare */
9778 /* The "key" for the node is a combination of two fields: the address */
9779 /* family and the address itself. */
9781 /* Because we're not actually interpreting the address data, it isn't */
9782 /* necessary to convert them to/from network/host byte order. The mask is */
9783 /* just used to remove bits that aren't significant - it doesn't matter */
9784 /* where they are, as long as they're always in the same place. */
9786 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9787 /* this is where individual ones will differ the most - but not true for */
9788 /* for /48's, etc. */
9789 /* ------------------------------------------------------------------------ */
9791 ipf_ht_node_cmp(k1, k2)
9792 struct host_node_s *k1, *k2;
9796 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9800 if (k1->hn_addr.adf_family == AF_INET)
9801 return (k2->hn_addr.adf_addr.in4.s_addr -
9802 k1->hn_addr.adf_addr.in4.s_addr);
9804 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9807 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9810 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9813 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9818 /* ------------------------------------------------------------------------ */
9819 /* Function: ipf_ht_node_make_key */
9821 /* parameters: htp(I) - pointer to address tracking structure */
9822 /* key(I) - where to store masked address for lookup */
9823 /* family(I) - protocol family of address */
9824 /* addr(I) - pointer to network address */
9826 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9827 /* copy the address passed in into the key structure whilst masking out the */
9828 /* bits that we don't want. */
9830 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9831 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9832 /* have to be wary of that and not allow 32-128 to happen. */
9833 /* ------------------------------------------------------------------------ */
9835 ipf_ht_node_make_key(htp, key, family, addr)
9841 key->hn_addr.adf_family = family;
9842 if (family == AF_INET) {
9846 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9847 bits = htp->ht_netmask;
9851 mask = htonl(0xffffffff << (32 - bits));
9853 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9856 int bits = htp->ht_netmask;
9858 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9860 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9861 htonl(0xffffffff << (128 - bits));
9862 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9863 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9864 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9865 } else if (bits > 64) {
9866 key->hn_addr.adf_addr.i6[3] = 0;
9867 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9868 htonl(0xffffffff << (96 - bits));
9869 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9870 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9871 } else if (bits > 32) {
9872 key->hn_addr.adf_addr.i6[3] = 0;
9873 key->hn_addr.adf_addr.i6[2] = 0;
9874 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9875 htonl(0xffffffff << (64 - bits));
9876 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9878 key->hn_addr.adf_addr.i6[3] = 0;
9879 key->hn_addr.adf_addr.i6[2] = 0;
9880 key->hn_addr.adf_addr.i6[1] = 0;
9881 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9882 htonl(0xffffffff << (32 - bits));
9889 /* ------------------------------------------------------------------------ */
9890 /* Function: ipf_ht_node_add */
9891 /* Returns: int - 0 == success, -1 == failure */
9892 /* Parameters: softc(I) - pointer to soft context main structure */
9893 /* htp(I) - pointer to address tracking structure */
9894 /* family(I) - protocol family of address */
9895 /* addr(I) - pointer to network address */
9897 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9898 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9900 /* After preparing the key with the address information to find, look in */
9901 /* the red-black tree to see if the address is known. A successful call to */
9902 /* this function can mean one of two things: a new node was added to the */
9903 /* tree or a matching node exists and we're able to bump up its activity. */
9904 /* ------------------------------------------------------------------------ */
9906 ipf_ht_node_add(softc, htp, family, addr)
9907 ipf_main_softc_t *softc;
9915 ipf_ht_node_make_key(htp, &k, family, addr);
9917 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9919 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9921 KMALLOC(h, host_node_t *);
9924 LBUMP(ipf_rb_no_mem);
9929 * If there was a macro to initialise the RB node then that
9930 * would get used here, but there isn't...
9932 bzero((char *)h, sizeof(*h));
9933 h->hn_addr = k.hn_addr;
9934 h->hn_addr.adf_family = k.hn_addr.adf_family;
9935 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9936 htp->ht_cur_nodes++;
9938 if ((htp->ht_max_per_node != 0) &&
9939 (h->hn_active >= htp->ht_max_per_node)) {
9940 DT(ipf_rb_node_max);
9941 LBUMP(ipf_rb_node_max);
9952 /* ------------------------------------------------------------------------ */
9953 /* Function: ipf_ht_node_del */
9954 /* Returns: int - 0 == success, -1 == failure */
9955 /* parameters: htp(I) - pointer to address tracking structure */
9956 /* family(I) - protocol family of address */
9957 /* addr(I) - pointer to network address */
9959 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9960 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9962 /* Try and find the address passed in amongst the leavese on this tree to */
9963 /* be friend. If found then drop the active account for that node drops by */
9964 /* one. If that count reaches 0, it is time to free it all up. */
9965 /* ------------------------------------------------------------------------ */
9967 ipf_ht_node_del(htp, family, addr)
9975 ipf_ht_node_make_key(htp, &k, family, addr);
9977 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9982 if (h->hn_active == 0) {
9983 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9984 htp->ht_cur_nodes--;
9993 /* ------------------------------------------------------------------------ */
9994 /* Function: ipf_rb_ht_init */
9996 /* Parameters: head(I) - pointer to host tracking structure */
9998 /* Initialise the host tracking structure to be ready for use above. */
9999 /* ------------------------------------------------------------------------ */
10001 ipf_rb_ht_init(head)
10002 host_track_t *head;
10004 RBI_INIT(ipf_rb, &head->ht_root);
10008 /* ------------------------------------------------------------------------ */
10009 /* Function: ipf_rb_ht_freenode */
10011 /* Parameters: head(I) - pointer to host tracking structure */
10012 /* arg(I) - additional argument from walk caller */
10014 /* Free an actual host_node_t structure. */
10015 /* ------------------------------------------------------------------------ */
10017 ipf_rb_ht_freenode(node, arg)
10025 /* ------------------------------------------------------------------------ */
10026 /* Function: ipf_rb_ht_flush */
10028 /* Parameters: head(I) - pointer to host tracking structure */
10030 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
10031 /* and free'ing each one. */
10032 /* ------------------------------------------------------------------------ */
10034 ipf_rb_ht_flush(head)
10035 host_track_t *head;
10037 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10041 /* ------------------------------------------------------------------------ */
10042 /* Function: ipf_slowtimer */
10044 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
10046 /* Slowly expire held state for fragments. Timeouts are set * in */
10047 /* expectation of this being called twice per second. */
10048 /* ------------------------------------------------------------------------ */
10050 ipf_slowtimer(softc)
10051 ipf_main_softc_t *softc;
10054 ipf_token_expire(softc);
10055 ipf_frag_expire(softc);
10056 ipf_state_expire(softc);
10057 ipf_nat_expire(softc);
10058 ipf_auth_expire(softc);
10059 ipf_lookup_expire(softc);
10060 ipf_rule_expire(softc);
10061 ipf_sync_expire(softc);
10062 softc->ipf_ticks++;
10066 /* ------------------------------------------------------------------------ */
10067 /* Function: ipf_inet_mask_add */
10069 /* Parameters: bits(I) - pointer to nat context information */
10070 /* mtab(I) - pointer to mask hash table structure */
10072 /* When called, bits represents the mask of a new NAT rule that has just */
10073 /* been added. This function inserts a bitmask into the array of masks to */
10074 /* search when searching for a matching NAT rule for a packet. */
10075 /* Prevention of duplicate masks is achieved by checking the use count for */
10076 /* a given netmask. */
10077 /* ------------------------------------------------------------------------ */
10079 ipf_inet_mask_add(bits, mtab)
10081 ipf_v4_masktab_t *mtab;
10086 mtab->imt4_masks[bits]++;
10087 if (mtab->imt4_masks[bits] > 1)
10093 mask = 0xffffffff << (32 - bits);
10095 for (i = 0; i < 33; i++) {
10096 if (ntohl(mtab->imt4_active[i]) < mask) {
10097 for (j = 32; j > i; j--)
10098 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10099 mtab->imt4_active[i] = htonl(mask);
10107 /* ------------------------------------------------------------------------ */
10108 /* Function: ipf_inet_mask_del */
10110 /* Parameters: bits(I) - number of bits set in the netmask */
10111 /* mtab(I) - pointer to mask hash table structure */
10113 /* Remove the 32bit bitmask represented by "bits" from the collection of */
10114 /* netmasks stored inside of mtab. */
10115 /* ------------------------------------------------------------------------ */
10117 ipf_inet_mask_del(bits, mtab)
10119 ipf_v4_masktab_t *mtab;
10124 mtab->imt4_masks[bits]--;
10125 if (mtab->imt4_masks[bits] > 0)
10128 mask = htonl(0xffffffff << (32 - bits));
10129 for (i = 0; i < 33; i++) {
10130 if (mtab->imt4_active[i] == mask) {
10131 for (j = i + 1; j < 33; j++)
10132 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10137 ASSERT(mtab->imt4_max >= 0);
10142 /* ------------------------------------------------------------------------ */
10143 /* Function: ipf_inet6_mask_add */
10145 /* Parameters: bits(I) - number of bits set in mask */
10146 /* mask(I) - pointer to mask to add */
10147 /* mtab(I) - pointer to mask hash table structure */
10149 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10150 /* has just been added. This function inserts a bitmask into the array of */
10151 /* masks to search when searching for a matching NAT rule for a packet. */
10152 /* Prevention of duplicate masks is achieved by checking the use count for */
10153 /* a given netmask. */
10154 /* ------------------------------------------------------------------------ */
10156 ipf_inet6_mask_add(bits, mask, mtab)
10159 ipf_v6_masktab_t *mtab;
10164 mtab->imt6_masks[bits]++;
10165 if (mtab->imt6_masks[bits] > 1)
10176 for (i = 0; i < 129; i++) {
10177 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10178 for (j = 128; j > i; j--)
10179 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10180 mtab->imt6_active[i] = *mask;
10188 /* ------------------------------------------------------------------------ */
10189 /* Function: ipf_inet6_mask_del */
10191 /* Parameters: bits(I) - number of bits set in mask */
10192 /* mask(I) - pointer to mask to remove */
10193 /* mtab(I) - pointer to mask hash table structure */
10195 /* Remove the 128bit bitmask represented by "bits" from the collection of */
10196 /* netmasks stored inside of mtab. */
10197 /* ------------------------------------------------------------------------ */
10199 ipf_inet6_mask_del(bits, mask, mtab)
10202 ipf_v6_masktab_t *mtab;
10207 mtab->imt6_masks[bits]--;
10208 if (mtab->imt6_masks[bits] > 0)
10218 for (i = 0; i < 129; i++) {
10219 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10220 for (j = i + 1; j < 129; j++) {
10221 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10222 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10229 ASSERT(mtab->imt6_max >= 0);