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;
1726 if (off == 1 && p == IPPROTO_TCP) {
1727 fin->fin_flx |= FI_SHORT; /* RFC 3128 */
1728 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1731 int morefrag = off & IP_MF;
1733 fi->fi_flx |= FI_FRAG;
1735 fin->fin_flx |= FI_FRAGBODY;
1737 if ((off + fin->fin_dlen > 65535) ||
1738 (fin->fin_dlen == 0) ||
1739 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1741 * The length of the packet, starting at its
1742 * offset cannot exceed 65535 (0xffff) as the
1743 * length of an IP packet is only 16 bits.
1745 * Any fragment that isn't the last fragment
1746 * must have a length greater than 0 and it
1747 * must be an even multiple of 8.
1749 fi->fi_flx |= FI_BAD;
1750 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1756 * Call per-protocol setup and checking
1758 if (p == IPPROTO_AH) {
1760 * Treat AH differently because we expect there to be another
1761 * layer 4 header after it.
1790 * If it is a standard IP header (no options), set the flag fields
1791 * which relate to options to 0.
1793 if (hlen == sizeof(*ip)) {
1801 * So the IP header has some IP options attached. Walk the entire
1802 * list of options present with this packet and set flags to indicate
1803 * which ones are here and which ones are not. For the somewhat out
1804 * of date and obscure security classification options, set a flag to
1805 * represent which classification is present.
1807 fi->fi_flx |= FI_OPTIONS;
1809 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1813 else if (opt == IPOPT_NOP)
1819 if (ol < 2 || ol > hlen)
1822 for (i = 9, mv = 4; mv >= 0; ) {
1825 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1830 case IPOPT_SECURITY :
1831 if (optmsk & op->ol_bit) {
1832 fin->fin_flx |= FI_BAD;
1833 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1835 doi = ipf_checkripso(s);
1837 auth = doi & 0xffff;
1843 if (optmsk & op->ol_bit) {
1844 fin->fin_flx |= FI_BAD;
1845 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1847 doi = ipf_checkcipso(fin,
1850 auth = doi & 0xffff;
1854 optmsk |= op->ol_bit;
1857 if (opt < op->ol_val)
1870 if (auth && !(auth & 0x0100))
1872 fi->fi_optmsk = optmsk;
1873 fi->fi_secmsk = secmsk;
1878 /* ------------------------------------------------------------------------ */
1879 /* Function: ipf_checkripso */
1881 /* Parameters: s(I) - pointer to start of RIPSO option */
1883 /* ------------------------------------------------------------------------ */
1888 const struct optlist *sp;
1889 u_short secmsk = 0, auth = 0;
1893 sec = *(s + 2); /* classification */
1894 for (j = 3, m = 2; m >= 0; ) {
1896 if (sec == sp->ol_val) {
1897 secmsk |= sp->ol_bit;
1903 if (sec < sp->ol_val)
1910 return (secmsk << 16) | auth;
1914 /* ------------------------------------------------------------------------ */
1915 /* Function: ipf_checkcipso */
1916 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1917 /* Parameters: fin(IO) - pointer to packet information */
1918 /* s(I) - pointer to start of CIPSO option */
1919 /* ol(I) - length of CIPSO option field */
1921 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1922 /* header and returns that whilst also storing the highest sensitivity */
1923 /* value found in the fr_info_t structure. */
1925 /* No attempt is made to extract the category bitmaps as these are defined */
1926 /* by the user (rather than the protocol) and can be rather numerous on the */
1928 /* ------------------------------------------------------------------------ */
1930 ipf_checkcipso(fin, s, ol)
1935 ipf_main_softc_t *softc = fin->fin_main_soft;
1938 u_char *t, tag, tlen, sensitivity;
1941 if (ol < 6 || ol > 40) {
1942 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1943 fin->fin_flx |= FI_BAD;
1944 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1949 fi->fi_sensitivity = 0;
1951 * The DOI field MUST be there.
1953 bcopy(s + 2, &doi, sizeof(doi));
1955 t = (u_char *)s + 6;
1956 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1959 if (tlen > len || tlen < 4 || tlen > 34) {
1960 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1961 fin->fin_flx |= FI_BAD;
1962 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1968 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1969 * draft (16 July 1992) that has expired.
1972 fin->fin_flx |= FI_BAD;
1973 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1975 } else if (tag == 1) {
1976 if (*(t + 2) != 0) {
1977 fin->fin_flx |= FI_BAD;
1978 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1981 sensitivity = *(t + 3);
1982 /* Category bitmap for categories 0-239 */
1984 } else if (tag == 4) {
1985 if (*(t + 2) != 0) {
1986 fin->fin_flx |= FI_BAD;
1987 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1990 sensitivity = *(t + 3);
1991 /* Enumerated categories, 16bits each, upto 15 */
1993 } else if (tag == 5) {
1994 if (*(t + 2) != 0) {
1995 fin->fin_flx |= FI_BAD;
1996 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1999 sensitivity = *(t + 3);
2000 /* Range of categories (2*16bits), up to 7 pairs */
2002 } else if (tag > 127) {
2003 /* Custom defined DOI */
2006 fin->fin_flx |= FI_BAD;
2007 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2011 if (sensitivity > fi->fi_sensitivity)
2012 fi->fi_sensitivity = sensitivity;
2019 /* ------------------------------------------------------------------------ */
2020 /* Function: ipf_makefrip */
2021 /* Returns: int - 0 == packet ok, -1 == packet freed */
2022 /* Parameters: hlen(I) - length of IP packet header */
2023 /* ip(I) - pointer to the IP header */
2024 /* fin(IO) - pointer to packet information */
2026 /* Compact the IP header into a structure which contains just the info. */
2027 /* which is useful for comparing IP headers with and store this information */
2028 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2029 /* this function will be called with either an IPv4 or IPv6 packet. */
2030 /* ------------------------------------------------------------------------ */
2032 ipf_makefrip(hlen, ip, fin)
2037 ipf_main_softc_t *softc = fin->fin_main_soft;
2041 fin->fin_hlen = (u_short)hlen;
2043 fin->fin_rule = 0xffffffff;
2044 fin->fin_group[0] = -1;
2045 fin->fin_group[1] = '\0';
2046 fin->fin_dp = (char *)ip + hlen;
2050 fin->fin_plen = ntohs(ip->ip_len);
2051 fin->fin_dlen = fin->fin_plen - hlen;
2052 ipf_pr_ipv4hdr(fin);
2054 } else if (v == 6) {
2055 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2056 fin->fin_dlen = fin->fin_plen;
2057 fin->fin_plen += hlen;
2059 ipf_pr_ipv6hdr(fin);
2062 if (fin->fin_ip == NULL) {
2063 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2070 /* ------------------------------------------------------------------------ */
2071 /* Function: ipf_portcheck */
2072 /* Returns: int - 1 == port matched, 0 == port match failed */
2073 /* Parameters: frp(I) - pointer to port check `expression' */
2074 /* pop(I) - port number to evaluate */
2076 /* Perform a comparison of a port number against some other(s), using a */
2077 /* structure with compare information stored in it. */
2078 /* ------------------------------------------------------------------------ */
2080 ipf_portcheck(frp, pop)
2090 * Do opposite test to that required and continue if that succeeds.
2092 switch (frp->frp_cmp)
2095 if (pop != po) /* EQUAL */
2099 if (pop == po) /* NOTEQUAL */
2103 if (pop >= po) /* LESSTHAN */
2107 if (pop <= po) /* GREATERTHAN */
2111 if (pop > po) /* LT or EQ */
2115 if (pop < po) /* GT or EQ */
2119 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2123 if (pop <= po || pop >= frp->frp_top) /* In range */
2127 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2137 /* ------------------------------------------------------------------------ */
2138 /* Function: ipf_tcpudpchk */
2139 /* Returns: int - 1 == protocol matched, 0 == check failed */
2140 /* Parameters: fda(I) - pointer to packet information */
2141 /* ft(I) - pointer to structure with comparison data */
2143 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2144 /* structure containing information that we want to match against. */
2145 /* ------------------------------------------------------------------------ */
2147 ipf_tcpudpchk(fi, ft)
2154 * Both ports should *always* be in the first fragment.
2155 * So far, I cannot find any cases where they can not be.
2157 * compare destination ports
2160 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2163 * compare source ports
2165 if (err && ft->ftu_scmp)
2166 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2169 * If we don't have all the TCP/UDP header, then how can we
2170 * expect to do any sort of match on it ? If we were looking for
2171 * TCP flags, then NO match. If not, then match (which should
2172 * satisfy the "short" class too).
2174 if (err && (fi->fi_p == IPPROTO_TCP)) {
2175 if (fi->fi_flx & FI_SHORT)
2176 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2178 * Match the flags ? If not, abort this match.
2180 if (ft->ftu_tcpfm &&
2181 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2182 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2183 ft->ftu_tcpfm, ft->ftu_tcpf));
2191 /* ------------------------------------------------------------------------ */
2192 /* Function: ipf_check_ipf */
2193 /* Returns: int - 0 == match, else no match */
2194 /* Parameters: fin(I) - pointer to packet information */
2195 /* fr(I) - pointer to filter rule */
2196 /* portcmp(I) - flag indicating whether to attempt matching on */
2197 /* TCP/UDP port data. */
2199 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2200 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2201 /* this function. */
2202 /* ------------------------------------------------------------------------ */
2204 ipf_check_ipf(fin, fr, portcmp)
2209 u_32_t *ld, *lm, *lip;
2217 lm = (u_32_t *)&fri->fri_mip;
2218 ld = (u_32_t *)&fri->fri_ip;
2221 * first 32 bits to check coversion:
2222 * IP version, TOS, TTL, protocol
2224 i = ((*lip & *lm) != *ld);
2225 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2226 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2231 * Next 32 bits is a constructed bitmask indicating which IP options
2232 * are present (if any) in this packet.
2235 i = ((*lip & *lm) != *ld);
2236 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2237 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2243 * Unrolled loops (4 each, for 32 bits) for address checks.
2246 * Check the source address.
2248 if (fr->fr_satype == FRI_LOOKUP) {
2249 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2250 fi->fi_v, lip, fin->fin_plen);
2257 i = ((*lip & *lm) != *ld);
2258 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2259 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2260 if (fi->fi_v == 6) {
2262 i |= ((*lip & *lm) != *ld);
2263 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2264 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2266 i |= ((*lip & *lm) != *ld);
2267 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2268 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2270 i |= ((*lip & *lm) != *ld);
2271 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2272 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2279 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2284 * Check the destination address.
2287 if (fr->fr_datype == FRI_LOOKUP) {
2288 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2289 fi->fi_v, lip, fin->fin_plen);
2296 i = ((*lip & *lm) != *ld);
2297 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2298 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2299 if (fi->fi_v == 6) {
2301 i |= ((*lip & *lm) != *ld);
2302 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2303 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2305 i |= ((*lip & *lm) != *ld);
2306 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2307 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2309 i |= ((*lip & *lm) != *ld);
2310 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2311 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2318 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2322 * IP addresses matched. The next 32bits contains:
2323 * mast of old IP header security & authentication bits.
2326 i = (*ld - (*lip & *lm));
2327 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2330 * Next we have 32 bits of packet flags.
2333 i |= (*ld - (*lip & *lm));
2334 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2338 * If a fragment, then only the first has what we're
2339 * looking for here...
2342 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2345 if (fr->fr_dcmp || fr->fr_scmp ||
2346 fr->fr_tcpf || fr->fr_tcpfm)
2348 if (fr->fr_icmpm || fr->fr_icmp) {
2349 if (((fi->fi_p != IPPROTO_ICMP) &&
2350 (fi->fi_p != IPPROTO_ICMPV6)) ||
2351 fin->fin_off || (fin->fin_dlen < 2))
2353 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2355 FR_DEBUG(("i. %#x & %#x != %#x\n",
2357 fr->fr_icmpm, fr->fr_icmp));
2367 /* ------------------------------------------------------------------------ */
2368 /* Function: ipf_scanlist */
2369 /* Returns: int - result flags of scanning filter list */
2370 /* Parameters: fin(I) - pointer to packet information */
2371 /* pass(I) - default result to return for filtering */
2373 /* Check the input/output list of rules for a match to the current packet. */
2374 /* If a match is found, the value of fr_flags from the rule becomes the */
2375 /* return value and fin->fin_fr points to the matched rule. */
2377 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2378 /* When unwinding, it should finish up with fin_depth as 0. */
2380 /* Could be per interface, but this gets real nasty when you don't have, */
2381 /* or can't easily change, the kernel source code to . */
2382 /* ------------------------------------------------------------------------ */
2384 ipf_scanlist(fin, pass)
2388 ipf_main_softc_t *softc = fin->fin_main_soft;
2389 int rulen, portcmp, off, skip;
2390 struct frentry *fr, *fnext;
2391 u_32_t passt, passo;
2394 * Do not allow nesting deeper than 16 levels.
2396 if (fin->fin_depth >= 16)
2402 * If there are no rules in this list, return now.
2413 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2416 for (rulen = 0; fr; fr = fnext, rulen++) {
2417 fnext = fr->fr_next;
2419 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2425 * In all checks below, a null (zero) value in the
2426 * filter struture is taken to mean a wildcard.
2428 * check that we are working for the right interface
2431 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2434 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2436 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2437 FR_ISPASS(pass) ? 'p' :
2438 FR_ISACCOUNT(pass) ? 'A' :
2439 FR_ISAUTH(pass) ? 'a' :
2440 (pass & FR_NOMATCH) ? 'n' :'b'));
2441 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2446 switch (fr->fr_type)
2449 case FR_T_IPF_BUILTIN :
2450 if (ipf_check_ipf(fin, fr, portcmp))
2453 #if defined(IPFILTER_BPF)
2455 case FR_T_BPFOPC_BUILTIN :
2460 if (*fin->fin_mp == NULL)
2462 if (fin->fin_family != fr->fr_family)
2464 mc = (u_char *)fin->fin_m;
2465 wlen = fin->fin_dlen + fin->fin_hlen;
2466 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2471 case FR_T_CALLFUNC_BUILTIN :
2475 f = (*fr->fr_func)(fin, &pass);
2484 case FR_T_IPFEXPR_BUILTIN :
2485 if (fin->fin_family != fr->fr_family)
2487 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2495 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2496 if (fin->fin_nattag == NULL)
2498 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2501 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2503 passt = fr->fr_flags;
2506 * If the rule is a "call now" rule, then call the function
2507 * in the rule, if it exists and use the results from that.
2508 * If the function pointer is bad, just make like we ignore
2509 * it, except for increasing the hit counter.
2511 if ((passt & FR_CALLNOW) != 0) {
2514 ATOMIC_INC64(fr->fr_hits);
2515 if ((fr->fr_func == NULL) ||
2516 (fr->fr_func == (ipfunc_t)-1))
2521 fr = (*fr->fr_func)(fin, &passt);
2526 passt = fr->fr_flags;
2532 * Just log this packet...
2534 if ((passt & FR_LOGMASK) == FR_LOG) {
2535 if (ipf_log_pkt(fin, passt) == -1) {
2536 if (passt & FR_LOGORBLOCK) {
2538 passt &= ~FR_CMDMASK;
2539 passt |= FR_BLOCK|FR_QUICK;
2540 fin->fin_reason = FRB_LOGFAIL;
2544 #endif /* IPFILTER_LOG */
2546 MUTEX_ENTER(&fr->fr_lock);
2547 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2549 MUTEX_EXIT(&fr->fr_lock);
2550 fin->fin_rule = rulen;
2553 if (FR_ISSKIP(passt)) {
2556 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2557 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2561 if (passt & (FR_RETICMP|FR_FAKEICMP))
2562 fin->fin_icode = fr->fr_icode;
2564 if (fr->fr_group != -1) {
2565 (void) strncpy(fin->fin_group,
2566 FR_NAME(fr, fr_group),
2567 strlen(FR_NAME(fr, fr_group)));
2569 fin->fin_group[0] = '\0';
2572 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2574 if (fr->fr_grphead != NULL) {
2575 fin->fin_fr = fr->fr_grphead->fg_start;
2576 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2578 if (FR_ISDECAPS(passt))
2579 passt = ipf_decaps(fin, pass, fr->fr_icode);
2581 passt = ipf_scanlist(fin, pass);
2583 if (fin->fin_fr == NULL) {
2584 fin->fin_rule = rulen;
2585 if (fr->fr_group != -1)
2586 (void) strncpy(fin->fin_group,
2589 strlen(fr->fr_names +
2597 if (pass & FR_QUICK) {
2599 * Finally, if we've asked to track state for this
2600 * packet, set it up. Add state for "quick" rules
2601 * here so that if the action fails we can consider
2602 * the rule to "not match" and keep on processing
2605 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2606 !(fin->fin_flx & FI_STATE)) {
2607 int out = fin->fin_out;
2610 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2611 LBUMPD(ipf_stats[out], fr_ads);
2613 LBUMPD(ipf_stats[out], fr_bads);
2626 /* ------------------------------------------------------------------------ */
2627 /* Function: ipf_acctpkt */
2628 /* Returns: frentry_t* - always returns NULL */
2629 /* Parameters: fin(I) - pointer to packet information */
2630 /* passp(IO) - pointer to current/new filter decision (unused) */
2632 /* Checks a packet against accounting rules, if there are any for the given */
2633 /* IP protocol version. */
2635 /* N.B.: this function returns NULL to match the prototype used by other */
2636 /* functions called from the IPFilter "mainline" in ipf_check(). */
2637 /* ------------------------------------------------------------------------ */
2639 ipf_acctpkt(fin, passp)
2643 ipf_main_softc_t *softc = fin->fin_main_soft;
2644 char group[FR_GROUPLEN];
2645 frentry_t *fr, *frsave;
2649 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2652 frsave = fin->fin_fr;
2653 bcopy(fin->fin_group, group, FR_GROUPLEN);
2654 rulen = fin->fin_rule;
2656 pass = ipf_scanlist(fin, FR_NOMATCH);
2657 if (FR_ISACCOUNT(pass)) {
2658 LBUMPD(ipf_stats[0], fr_acct);
2660 fin->fin_fr = frsave;
2661 bcopy(group, fin->fin_group, FR_GROUPLEN);
2662 fin->fin_rule = rulen;
2668 /* ------------------------------------------------------------------------ */
2669 /* Function: ipf_firewall */
2670 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2671 /* were found, returns NULL. */
2672 /* Parameters: fin(I) - pointer to packet information */
2673 /* passp(IO) - pointer to current/new filter decision (unused) */
2675 /* Applies an appropriate set of firewall rules to the packet, to see if */
2676 /* there are any matches. The first check is to see if a match can be seen */
2677 /* in the cache. If not, then search an appropriate list of rules. Once a */
2678 /* matching rule is found, take any appropriate actions as defined by the */
2679 /* rule - except logging. */
2680 /* ------------------------------------------------------------------------ */
2682 ipf_firewall(fin, passp)
2686 ipf_main_softc_t *softc = fin->fin_main_soft;
2695 * This rule cache will only affect packets that are not being
2696 * statefully filtered.
2698 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2699 if (fin->fin_fr != NULL)
2700 pass = ipf_scanlist(fin, softc->ipf_pass);
2702 if ((pass & FR_NOMATCH)) {
2703 LBUMPD(ipf_stats[out], fr_nom);
2708 * Apply packets per second rate-limiting to a rule as required.
2710 if ((fr != NULL) && (fr->fr_pps != 0) &&
2711 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2712 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2713 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2715 LBUMPD(ipf_stats[out], fr_ppshit);
2716 fin->fin_reason = FRB_PPSRATE;
2720 * If we fail to add a packet to the authorization queue, then we
2721 * drop the packet later. However, if it was added then pretend
2722 * we've dropped it already.
2724 if (FR_ISAUTH(pass)) {
2725 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2726 DT1(frb_authnew, fr_info_t *, fin);
2727 fin->fin_m = *fin->fin_mp = NULL;
2728 fin->fin_reason = FRB_AUTHNEW;
2732 fin->fin_error = ENOSPC;
2736 if ((fr != NULL) && (fr->fr_func != NULL) &&
2737 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2738 (void) (*fr->fr_func)(fin, &pass);
2741 * If a rule is a pre-auth rule, check again in the list of rules
2742 * loaded for authenticated use. It does not particulary matter
2743 * if this search fails because a "preauth" result, from a rule,
2744 * is treated as "not a pass", hence the packet is blocked.
2746 if (FR_ISPREAUTH(pass)) {
2747 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2751 * If the rule has "keep frag" and the packet is actually a fragment,
2752 * then create a fragment state entry.
2754 if (pass & FR_KEEPFRAG) {
2755 if (fin->fin_flx & FI_FRAG) {
2756 if (ipf_frag_new(softc, fin, pass) == -1) {
2757 LBUMP(ipf_stats[out].fr_bnfr);
2759 LBUMP(ipf_stats[out].fr_nfr);
2762 LBUMP(ipf_stats[out].fr_cfr);
2773 /* ------------------------------------------------------------------------ */
2774 /* Function: ipf_check */
2775 /* Returns: int - 0 == packet allowed through, */
2777 /* -1 == packet blocked */
2778 /* 1 == packet not matched */
2779 /* -2 == requires authentication */
2781 /* > 0 == filter error # for packet */
2782 /* Parameters: ctx(I) - pointer to the instance context */
2783 /* ip(I) - pointer to start of IPv4/6 packet */
2784 /* hlen(I) - length of header */
2785 /* ifp(I) - pointer to interface this packet is on */
2786 /* out(I) - 0 == packet going in, 1 == packet going out */
2787 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2790 /* qpi(I) - pointer to STREAMS queue information for this */
2791 /* interface & direction. */
2793 /* ipf_check() is the master function for all IPFilter packet processing. */
2794 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2795 /* authorisation (or pre-authorisation), presence of related state info., */
2796 /* generating log entries, IP packet accounting, routing of packets as */
2797 /* directed by firewall rules and of course whether or not to allow the */
2798 /* packet to be further processed by the kernel. */
2800 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2801 /* freed. Packets passed may be returned with the pointer pointed to by */
2802 /* by "mp" changed to a new buffer. */
2803 /* ------------------------------------------------------------------------ */
2805 ipf_check(ctx, ip, hlen, ifp, out
2806 #if defined(_KERNEL) && defined(MENTAT)
2820 * The above really sucks, but short of writing a diff
2822 ipf_main_softc_t *softc = ctx;
2824 fr_info_t *fin = &frinfo;
2825 u_32_t pass = softc->ipf_pass;
2826 frentry_t *fr = NULL;
2831 * The first part of ipf_check() deals with making sure that what goes
2832 * into the filtering engine makes some sense. Information about the
2833 * the packet is distilled, collected into a fr_info_t structure and
2834 * the an attempt to ensure the buffer the packet is in is big enough
2835 * to hold all the required packet headers.
2839 qpktinfo_t *qpi = qif;
2842 if ((u_int)ip & 0x3)
2849 if (softc->ipf_running <= 0) {
2853 bzero((char *)fin, sizeof(*fin));
2856 if (qpi->qpi_flags & QF_BROADCAST)
2857 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2858 if (qpi->qpi_flags & QF_MULTICAST)
2859 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2867 # if defined(M_MCAST)
2868 if ((m->m_flags & M_MCAST) != 0)
2869 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2871 # if defined(M_MLOOP)
2872 if ((m->m_flags & M_MLOOP) != 0)
2873 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2875 # if defined(M_BCAST)
2876 if ((m->m_flags & M_BCAST) != 0)
2877 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2879 # ifdef M_CANFASTFWD
2881 * XXX For now, IP Filter and fast-forwarding of cached flows
2882 * XXX are mutually exclusive. Eventually, IP Filter should
2883 * XXX get a "can-fast-forward" filter rule.
2885 m->m_flags &= ~M_CANFASTFWD;
2886 # endif /* M_CANFASTFWD */
2887 # if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2889 * disable delayed checksums.
2891 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2892 in_delayed_cksum(m);
2893 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2895 # endif /* CSUM_DELAY_DATA */
2896 # endif /* MENTAT */
2898 bzero((char *)fin, sizeof(*fin));
2900 # if defined(M_MCAST)
2901 if ((m->m_flags & M_MCAST) != 0)
2902 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2904 # if defined(M_MLOOP)
2905 if ((m->m_flags & M_MLOOP) != 0)
2906 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2908 # if defined(M_BCAST)
2909 if ((m->m_flags & M_BCAST) != 0)
2910 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2912 #endif /* _KERNEL */
2920 fin->fin_error = ENETUNREACH;
2921 fin->fin_hlen = (u_short)hlen;
2922 fin->fin_dp = (char *)ip + hlen;
2923 fin->fin_main_soft = softc;
2925 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2931 LBUMP(ipf_stats[out].fr_ipv6);
2933 * Jumbo grams are quite likely too big for internal buffer
2934 * structures to handle comfortably, for now, so just drop
2937 if (((ip6_t *)ip)->ip6_plen == 0) {
2938 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2939 pass = FR_BLOCK|FR_NOMATCH;
2940 fin->fin_reason = FRB_JUMBO;
2943 fin->fin_family = AF_INET6;
2947 fin->fin_family = AF_INET;
2950 if (ipf_makefrip(hlen, ip, fin) == -1) {
2951 DT1(frb_makefrip, fr_info_t *, fin);
2952 pass = FR_BLOCK|FR_NOMATCH;
2953 fin->fin_reason = FRB_MAKEFRIP;
2958 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2959 * becomes NULL and so we have no packet to free.
2961 if (*fin->fin_mp == NULL)
2966 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2967 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2968 fin->fin_flx |= FI_BADSRC;
2970 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2971 LBUMPD(ipf_stats[0], fr_v4_badttl);
2972 fin->fin_flx |= FI_LOWTTL;
2977 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2978 LBUMPD(ipf_stats[0], fr_v6_badttl);
2979 fin->fin_flx |= FI_LOWTTL;
2985 if (fin->fin_flx & FI_SHORT) {
2986 LBUMPD(ipf_stats[out], fr_short);
2989 READ_ENTER(&softc->ipf_mutex);
2995 if (ipf_nat_checkin(fin, &pass) == -1) {
3001 if (ipf_nat6_checkin(fin, &pass) == -1) {
3012 * If a packet is found in the auth table, then skip checking
3013 * the access lists for permission but we do need to consider
3014 * the result as if it were from the ACL's. In addition, being
3015 * found in the auth table means it has been seen before, so do
3016 * not pass it through accounting (again), lest it be counted twice.
3018 fr = ipf_auth_check(fin, &pass);
3019 if (!out && (fr == NULL))
3020 (void) ipf_acctpkt(fin, NULL);
3023 if ((fin->fin_flx & FI_FRAG) != 0)
3024 fr = ipf_frag_known(fin, &pass);
3027 fr = ipf_state_check(fin, &pass);
3030 if ((pass & FR_NOMATCH) || (fr == NULL))
3031 fr = ipf_firewall(fin, &pass);
3034 * If we've asked to track state for this packet, set it up.
3035 * Here rather than ipf_firewall because ipf_checkauth may decide
3036 * to return a packet for "keep state"
3038 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3039 !(fin->fin_flx & FI_STATE)) {
3040 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3041 LBUMP(ipf_stats[out].fr_ads);
3043 LBUMP(ipf_stats[out].fr_bads);
3044 if (FR_ISPASS(pass)) {
3046 pass &= ~FR_CMDMASK;
3048 fin->fin_reason = FRB_STATEADD;
3054 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3055 fin->fin_dif = &fr->fr_dif;
3056 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3060 * Only count/translate packets which will be passed on, out the
3063 if (out && FR_ISPASS(pass)) {
3064 (void) ipf_acctpkt(fin, NULL);
3069 if (ipf_nat_checkout(fin, &pass) == -1) {
3071 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3072 if (ipf_updateipid(fin) == -1) {
3074 LBUMP(ipf_stats[1].fr_ipud);
3075 pass &= ~FR_CMDMASK;
3077 fin->fin_reason = FRB_UPDATEIPID;
3079 LBUMP(ipf_stats[0].fr_ipud);
3085 (void) ipf_nat6_checkout(fin, &pass);
3095 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3096 (void) ipf_dolog(fin, &pass);
3101 * The FI_STATE flag is cleared here so that calling ipf_state_check
3102 * will work when called from inside of fr_fastroute. Although
3103 * there is a similar flag, FI_NATED, for NAT, it does have the same
3104 * impact on code execution.
3106 fin->fin_flx &= ~FI_STATE;
3108 #if defined(FASTROUTE_RECURSION)
3110 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3111 * a packet below can sometimes cause a recursive call into IPFilter.
3112 * On those platforms where that does happen, we need to hang onto
3113 * the filter rule just in case someone decides to remove or flush it
3117 MUTEX_ENTER(&fr->fr_lock);
3119 MUTEX_EXIT(&fr->fr_lock);
3122 RWLOCK_EXIT(&softc->ipf_mutex);
3125 if ((pass & FR_RETMASK) != 0) {
3127 * Should we return an ICMP packet to indicate error
3128 * status passing through the packet filter ?
3129 * WARNING: ICMP error packets AND TCP RST packets should
3130 * ONLY be sent in repsonse to incoming packets. Sending
3131 * them in response to outbound packets can result in a
3132 * panic on some operating systems.
3135 if (pass & FR_RETICMP) {
3138 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3142 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3144 LBUMP(ipf_stats[0].fr_ret);
3145 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3146 !(fin->fin_flx & FI_SHORT)) {
3147 if (((fin->fin_flx & FI_OOW) != 0) ||
3148 (ipf_send_reset(fin) == 0)) {
3149 LBUMP(ipf_stats[1].fr_ret);
3154 * When using return-* with auth rules, the auth code
3155 * takes over disposing of this packet.
3157 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3158 DT1(frb_authcapture, fr_info_t *, fin);
3159 fin->fin_m = *fin->fin_mp = NULL;
3160 fin->fin_reason = FRB_AUTHCAPTURE;
3164 if (pass & FR_RETRST) {
3165 fin->fin_error = ECONNRESET;
3171 * After the above so that ICMP unreachables and TCP RSTs get
3174 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3175 ipf_nat_uncreate(fin);
3178 * If we didn't drop off the bottom of the list of rules (and thus
3179 * the 'current' rule fr is not NULL), then we may have some extra
3180 * instructions about what to do with a packet.
3181 * Once we're finished return to our caller, freeing the packet if
3182 * we are dropping it.
3188 * Generate a duplicated packet first because ipf_fastroute
3189 * can lead to fin_m being free'd... not good.
3192 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3193 (fdp->fd_ptr != (void *)-1)) {
3194 mc = M_COPY(fin->fin_m);
3196 ipf_fastroute(mc, &mc, fin, fdp);
3200 if (!out && (pass & FR_FASTROUTE)) {
3202 * For fastroute rule, no destination interface defined
3203 * so pass NULL as the frdest_t parameter
3205 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3207 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3208 (fdp->fd_ptr != (struct ifnet *)-1)) {
3209 /* this is for to rules: */
3210 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3214 #if defined(FASTROUTE_RECURSION)
3215 (void) ipf_derefrule(softc, &fr);
3218 #if !defined(FASTROUTE_RECURSION)
3219 RWLOCK_EXIT(&softc->ipf_mutex);
3223 if (!FR_ISPASS(pass)) {
3224 LBUMP(ipf_stats[out].fr_block);
3232 LBUMP(ipf_stats[out].fr_pass);
3238 if (FR_ISPASS(pass))
3240 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3241 return fin->fin_error;
3244 (*mp)->mb_ifp = fin->fin_ifp;
3245 blockreason = fin->fin_reason;
3246 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3247 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3248 if ((pass & FR_NOMATCH) != 0)
3251 if ((pass & FR_RETMASK) != 0)
3252 switch (pass & FR_RETMASK)
3262 switch (pass & FR_CMDMASK)
3276 #endif /* _KERNEL */
3281 /* ------------------------------------------------------------------------ */
3282 /* Function: ipf_dolog */
3283 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3284 /* Parameters: fin(I) - pointer to packet information */
3285 /* passp(IO) - pointer to current/new filter decision (unused) */
3287 /* Checks flags set to see how a packet should be logged, if it is to be */
3288 /* logged. Adjust statistics based on its success or not. */
3289 /* ------------------------------------------------------------------------ */
3291 ipf_dolog(fin, passp)
3295 ipf_main_softc_t *softc = fin->fin_main_soft;
3302 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3303 pass |= FF_LOGNOMATCH;
3304 LBUMPD(ipf_stats[out], fr_npkl);
3307 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3308 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3309 if ((pass & FR_LOGMASK) != FR_LOGP)
3311 LBUMPD(ipf_stats[out], fr_ppkl);
3314 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3315 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3316 if ((pass & FR_LOGMASK) != FR_LOGB)
3317 pass |= FF_LOGBLOCK;
3318 LBUMPD(ipf_stats[out], fr_bpkl);
3321 if (ipf_log_pkt(fin, pass) == -1) {
3323 * If the "or-block" option has been used then
3324 * block the packet if we failed to log it.
3326 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3327 DT1(frb_logfail2, u_int, pass);
3328 pass &= ~FR_CMDMASK;
3330 fin->fin_reason = FRB_LOGFAIL2;
3338 #endif /* IPFILTER_LOG */
3341 /* ------------------------------------------------------------------------ */
3342 /* Function: ipf_cksum */
3343 /* Returns: u_short - IP header checksum */
3344 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3345 /* len(I) - length of buffer in bytes */
3347 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3349 /* N.B.: addr should be 16bit aligned. */
3350 /* ------------------------------------------------------------------------ */
3352 ipf_cksum(addr, len)
3358 for (sum = 0; len > 1; len -= 2)
3361 /* mop up an odd byte, if necessary */
3363 sum += *(u_char *)addr;
3366 * add back carry outs from top 16 bits to low 16 bits
3368 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3369 sum += (sum >> 16); /* add carry */
3370 return (u_short)(~sum);
3374 /* ------------------------------------------------------------------------ */
3375 /* Function: fr_cksum */
3376 /* Returns: u_short - layer 4 checksum */
3377 /* Parameters: fin(I) - pointer to packet information */
3378 /* ip(I) - pointer to IP header */
3379 /* l4proto(I) - protocol to caclulate checksum for */
3380 /* l4hdr(I) - pointer to layer 4 header */
3382 /* Calculates the TCP checksum for the packet held in "m", using the data */
3383 /* in the IP header "ip" to seed it. */
3385 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3386 /* and the TCP header. We also assume that data blocks aren't allocated in */
3389 /* Expects ip_len and ip_off to be in network byte order when called. */
3390 /* ------------------------------------------------------------------------ */
3392 fr_cksum(fin, ip, l4proto, l4hdr)
3398 u_short *sp, slen, sumsave, *csump;
3413 sum = htons((u_short)l4proto);
3415 * Add up IP Header portion
3418 if (IP_V(ip) == 4) {
3420 hlen = IP_HL(ip) << 2;
3422 sp = (u_short *)&ip->ip_src;
3423 sum += *sp++; /* ip_src */
3425 sum += *sp++; /* ip_dst */
3427 slen = fin->fin_plen - off;
3430 } else if (IP_V(ip) == 6) {
3435 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3436 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3437 return(ipf_pcksum6(fin, ip6, off, len));
3446 csump = &((udphdr_t *)l4hdr)->uh_sum;
3450 csump = &((tcphdr_t *)l4hdr)->th_sum;
3453 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3454 sum = 0; /* Pseudo-checksum is not included */
3457 case IPPROTO_ICMPV6 :
3458 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3465 if (csump != NULL) {
3470 sum2 = ipf_pcksum(fin, off, sum);
3477 /* ------------------------------------------------------------------------ */
3478 /* Function: ipf_findgroup */
3479 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3480 /* Parameters: softc(I) - pointer to soft context main structure */
3481 /* group(I) - group name to search for */
3482 /* unit(I) - device to which this group belongs */
3483 /* set(I) - which set of rules (inactive/inactive) this is */
3484 /* fgpp(O) - pointer to place to store pointer to the pointer */
3485 /* to where to add the next (last) group or where */
3486 /* to delete group from. */
3488 /* Search amongst the defined groups for a particular group number. */
3489 /* ------------------------------------------------------------------------ */
3491 ipf_findgroup(softc, group, unit, set, fgpp)
3492 ipf_main_softc_t *softc;
3498 frgroup_t *fg, **fgp;
3501 * Which list of groups to search in is dependent on which list of
3502 * rules are being operated on.
3504 fgp = &softc->ipf_groups[unit][set];
3506 while ((fg = *fgp) != NULL) {
3507 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3518 /* ------------------------------------------------------------------------ */
3519 /* Function: ipf_group_add */
3520 /* Returns: frgroup_t * - NULL == did not create group, */
3521 /* != NULL == pointer to the group */
3522 /* Parameters: softc(I) - pointer to soft context main structure */
3523 /* num(I) - group number to add */
3524 /* head(I) - rule pointer that is using this as the head */
3525 /* flags(I) - rule flags which describe the type of rule it is */
3526 /* unit(I) - device to which this group will belong to */
3527 /* set(I) - which set of rules (inactive/inactive) this is */
3528 /* Write Locks: ipf_mutex */
3530 /* Add a new group head, or if it already exists, increase the reference */
3532 /* ------------------------------------------------------------------------ */
3534 ipf_group_add(softc, group, head, flags, unit, set)
3535 ipf_main_softc_t *softc;
3542 frgroup_t *fg, **fgp;
3548 if (unit == IPL_LOGIPF && *group == '\0')
3552 gflags = flags & FR_INOUT;
3554 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3556 if (fg->fg_head == NULL && head != NULL)
3558 if (fg->fg_flags == 0)
3559 fg->fg_flags = gflags;
3560 else if (gflags != fg->fg_flags)
3566 KMALLOC(fg, frgroup_t *);
3569 fg->fg_start = NULL;
3571 bcopy(group, fg->fg_name, strlen(group) + 1);
3572 fg->fg_flags = gflags;
3574 fg->fg_set = &softc->ipf_groups[unit][set];
3581 /* ------------------------------------------------------------------------ */
3582 /* Function: ipf_group_del */
3583 /* Returns: int - number of rules deleted */
3584 /* Parameters: softc(I) - pointer to soft context main structure */
3585 /* group(I) - group name to delete */
3586 /* fr(I) - filter rule from which group is referenced */
3587 /* Write Locks: ipf_mutex */
3589 /* This function is called whenever a reference to a group is to be dropped */
3590 /* and thus its reference count needs to be lowered and the group free'd if */
3591 /* the reference count reaches zero. Passing in fr is really for the sole */
3592 /* purpose of knowing when the head rule is being deleted. */
3593 /* ------------------------------------------------------------------------ */
3595 ipf_group_del(softc, group, fr)
3596 ipf_main_softc_t *softc;
3601 if (group->fg_head == fr)
3602 group->fg_head = NULL;
3605 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3606 ipf_group_free(group);
3610 /* ------------------------------------------------------------------------ */
3611 /* Function: ipf_group_free */
3613 /* Parameters: group(I) - pointer to filter rule group */
3615 /* Remove the group from the list of groups and free it. */
3616 /* ------------------------------------------------------------------------ */
3618 ipf_group_free(group)
3623 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3625 *gp = group->fg_next;
3633 /* ------------------------------------------------------------------------ */
3634 /* Function: ipf_group_flush */
3635 /* Returns: int - number of rules flush from group */
3636 /* Parameters: softc(I) - pointer to soft context main structure */
3637 /* Parameters: group(I) - pointer to filter rule group */
3639 /* Remove all of the rules that currently are listed under the given group. */
3640 /* ------------------------------------------------------------------------ */
3642 ipf_group_flush(softc, group)
3643 ipf_main_softc_t *softc;
3648 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3654 /* ------------------------------------------------------------------------ */
3655 /* Function: ipf_getrulen */
3656 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3657 /* Parameters: softc(I) - pointer to soft context main structure */
3658 /* Parameters: unit(I) - device for which to count the rule's number */
3659 /* flags(I) - which set of rules to find the rule in */
3660 /* group(I) - group name */
3661 /* n(I) - rule number to find */
3663 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3664 /* group # g doesn't exist or there are less than n rules in the group. */
3665 /* ------------------------------------------------------------------------ */
3667 ipf_getrulen(softc, unit, group, n)
3668 ipf_main_softc_t *softc;
3676 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3679 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3687 /* ------------------------------------------------------------------------ */
3688 /* Function: ipf_flushlist */
3689 /* Returns: int - >= 0 - number of flushed rules */
3690 /* Parameters: softc(I) - pointer to soft context main structure */
3691 /* nfreedp(O) - pointer to int where flush count is stored */
3692 /* listp(I) - pointer to list to flush pointer */
3693 /* Write Locks: ipf_mutex */
3695 /* Recursively flush rules from the list, descending groups as they are */
3696 /* encountered. if a rule is the head of a group and it has lost all its */
3697 /* group members, then also delete the group reference. nfreedp is needed */
3698 /* to store the accumulating count of rules removed, whereas the returned */
3699 /* value is just the number removed from the current list. The latter is */
3700 /* needed to correctly adjust reference counts on rules that define groups. */
3702 /* NOTE: Rules not loaded from user space cannot be flushed. */
3703 /* ------------------------------------------------------------------------ */
3705 ipf_flushlist(softc, nfreedp, listp)
3706 ipf_main_softc_t *softc;
3713 while ((fp = *listp) != NULL) {
3714 if ((fp->fr_type & FR_T_BUILTIN) ||
3715 !(fp->fr_flags & FR_COPIED)) {
3716 listp = &fp->fr_next;
3719 *listp = fp->fr_next;
3720 if (fp->fr_next != NULL)
3721 fp->fr_next->fr_pnext = fp->fr_pnext;
3722 fp->fr_pnext = NULL;
3724 if (fp->fr_grphead != NULL) {
3725 freed += ipf_group_flush(softc, fp->fr_grphead);
3726 fp->fr_names[fp->fr_grhead] = '\0';
3729 if (fp->fr_icmpgrp != NULL) {
3730 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3731 fp->fr_names[fp->fr_icmphead] = '\0';
3734 if (fp->fr_srctrack.ht_max_nodes)
3735 ipf_rb_ht_flush(&fp->fr_srctrack);
3739 ASSERT(fp->fr_ref > 0);
3740 if (ipf_derefrule(softc, &fp) == 0)
3748 /* ------------------------------------------------------------------------ */
3749 /* Function: ipf_flush */
3750 /* Returns: int - >= 0 - number of flushed rules */
3751 /* Parameters: softc(I) - pointer to soft context main structure */
3752 /* unit(I) - device for which to flush rules */
3753 /* flags(I) - which set of rules to flush */
3755 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3756 /* and IPv6) as defined by the value of flags. */
3757 /* ------------------------------------------------------------------------ */
3759 ipf_flush(softc, unit, flags)
3760 ipf_main_softc_t *softc;
3764 int flushed = 0, set;
3766 WRITE_ENTER(&softc->ipf_mutex);
3768 set = softc->ipf_active;
3769 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3772 if (flags & FR_OUTQUE) {
3773 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3774 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3776 if (flags & FR_INQUE) {
3777 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3778 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3781 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3782 flags & (FR_INQUE|FR_OUTQUE));
3784 RWLOCK_EXIT(&softc->ipf_mutex);
3786 if (unit == IPL_LOGIPF) {
3789 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3797 /* ------------------------------------------------------------------------ */
3798 /* Function: ipf_flush_groups */
3799 /* Returns: int - >= 0 - number of flushed rules */
3800 /* Parameters: softc(I) - soft context pointerto work with */
3801 /* grhead(I) - pointer to the start of the group list to flush */
3802 /* flags(I) - which set of rules to flush */
3804 /* Walk through all of the groups under the given group head and remove all */
3805 /* of those that match the flags passed in. The for loop here is bit more */
3806 /* complicated than usual because the removal of a rule with ipf_derefrule */
3807 /* may end up removing not only the structure pointed to by "fg" but also */
3808 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3809 /* removed from the group then it is necessary to start again. */
3810 /* ------------------------------------------------------------------------ */
3812 ipf_flush_groups(softc, grhead, flags)
3813 ipf_main_softc_t *softc;
3817 frentry_t *fr, **frp;
3818 frgroup_t *fg, **fgp;
3822 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3823 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3828 frp = &fg->fg_start;
3829 while ((removed == 0) && ((fr = *frp) != NULL)) {
3830 if ((fr->fr_flags & flags) == 0) {
3833 if (fr->fr_next != NULL)
3834 fr->fr_next->fr_pnext = fr->fr_pnext;
3836 fr->fr_pnext = NULL;
3838 (void) ipf_derefrule(softc, &fr);
3850 /* ------------------------------------------------------------------------ */
3851 /* Function: memstr */
3852 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3853 /* Parameters: src(I) - pointer to byte sequence to match */
3854 /* dst(I) - pointer to byte sequence to search */
3855 /* slen(I) - match length */
3856 /* dlen(I) - length available to search in */
3858 /* Search dst for a sequence of bytes matching those at src and extend for */
3860 /* ------------------------------------------------------------------------ */
3862 memstr(src, dst, slen, dlen)
3869 while (dlen >= slen) {
3870 if (bcmp(src, dst, slen) == 0) {
3879 /* ------------------------------------------------------------------------ */
3880 /* Function: ipf_fixskip */
3882 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3883 /* rp(I) - rule added/removed with skip in it. */
3884 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3885 /* depending on whether a rule was just added */
3888 /* Adjust all the rules in a list which would have skip'd past the position */
3889 /* where we are inserting to skip to the right place given the change. */
3890 /* ------------------------------------------------------------------------ */
3892 ipf_fixskip(listp, rp, addremove)
3893 frentry_t **listp, *rp;
3900 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3906 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3907 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3908 fp->fr_arg += addremove;
3913 /* ------------------------------------------------------------------------ */
3914 /* Function: count4bits */
3915 /* Returns: int - >= 0 - number of consecutive bits in input */
3916 /* Parameters: ip(I) - 32bit IP address */
3919 /* count consecutive 1's in bit mask. If the mask generated by counting */
3920 /* consecutive 1's is different to that passed, return -1, else return # */
3922 /* ------------------------------------------------------------------------ */
3930 ip = ipn = ntohl(ip);
3931 for (i = 32; i; i--, ipn *= 2)
3932 if (ipn & 0x80000000)
3937 for (i = 32, j = cnt; i; i--, j--) {
3948 /* ------------------------------------------------------------------------ */
3949 /* Function: count6bits */
3950 /* Returns: int - >= 0 - number of consecutive bits in input */
3951 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3954 /* count consecutive 1's in bit mask. */
3955 /* ------------------------------------------------------------------------ */
3964 for (k = 3; k >= 0; k--)
3965 if (msk[k] == 0xffffffff)
3968 for (j = msk[k]; j; j <<= 1)
3975 #endif /* _KERNEL */
3978 /* ------------------------------------------------------------------------ */
3979 /* Function: ipf_synclist */
3980 /* Returns: int - 0 = no failures, else indication of first failure */
3981 /* Parameters: fr(I) - start of filter list to sync interface names for */
3982 /* ifp(I) - interface pointer for limiting sync lookups */
3983 /* Write Locks: ipf_mutex */
3985 /* Walk through a list of filter rules and resolve any interface names into */
3986 /* pointers. Where dynamic addresses are used, also update the IP address */
3987 /* used in the rule. The interface pointer is used to limit the lookups to */
3988 /* a specific set of matching names if it is non-NULL. */
3989 /* Errors can occur when resolving the destination name of to/dup-to fields */
3990 /* when the name points to a pool and that pool doest not exist. If this */
3991 /* does happen then it is necessary to check if there are any lookup refs */
3992 /* that need to be dropped before returning with an error. */
3993 /* ------------------------------------------------------------------------ */
3995 ipf_synclist(softc, fr, ifp)
3996 ipf_main_softc_t *softc;
4000 frentry_t *frt, *start = fr;
4009 for (; fr; fr = fr->fr_next) {
4010 if (fr->fr_family == AF_INET)
4012 else if (fr->fr_family == AF_INET6)
4018 * Lookup all the interface names that are part of the rule.
4020 for (i = 0; i < 4; i++) {
4021 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4023 if (fr->fr_ifnames[i] == -1)
4025 name = FR_NAME(fr, fr_ifnames[i]);
4026 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4029 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4030 if (fr->fr_satype != FRI_NORMAL &&
4031 fr->fr_satype != FRI_LOOKUP) {
4032 ifa = ipf_resolvenic(softc, fr->fr_names +
4034 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4035 &fr->fr_src6, &fr->fr_smsk6);
4037 if (fr->fr_datype != FRI_NORMAL &&
4038 fr->fr_datype != FRI_LOOKUP) {
4039 ifa = ipf_resolvenic(softc, fr->fr_names +
4041 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4042 &fr->fr_dst6, &fr->fr_dmsk6);
4046 fdp = &fr->fr_tifs[0];
4047 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4048 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4053 fdp = &fr->fr_tifs[1];
4054 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4055 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4061 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4062 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4067 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4068 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4069 fr->fr_srcptr = ipf_lookup_res_num(softc,
4075 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4076 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4077 fr->fr_dstptr = ipf_lookup_res_num(softc,
4087 for (frt = start; frt != fr; fr = fr->fr_next) {
4088 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4089 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4090 ipf_lookup_deref(softc, frt->fr_srctype,
4092 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4093 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4094 ipf_lookup_deref(softc, frt->fr_dsttype,
4101 /* ------------------------------------------------------------------------ */
4102 /* Function: ipf_sync */
4104 /* Parameters: Nil */
4106 /* ipf_sync() is called when we suspect that the interface list or */
4107 /* information about interfaces (like IP#) has changed. Go through all */
4108 /* filter rules, NAT entries and the state table and check if anything */
4109 /* needs to be changed/updated. */
4110 /* ------------------------------------------------------------------------ */
4112 ipf_sync(softc, ifp)
4113 ipf_main_softc_t *softc;
4119 ipf_nat_sync(softc, ifp);
4120 ipf_state_sync(softc, ifp);
4121 ipf_lookup_sync(softc, ifp);
4124 WRITE_ENTER(&softc->ipf_mutex);
4125 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4126 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4127 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4128 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4130 for (i = 0; i < IPL_LOGSIZE; i++) {
4133 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4134 (void) ipf_synclist(softc, g->fg_start, ifp);
4135 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4136 (void) ipf_synclist(softc, g->fg_start, ifp);
4138 RWLOCK_EXIT(&softc->ipf_mutex);
4145 * In the functions below, bcopy() is called because the pointer being
4146 * copied _from_ in this instance is a pointer to a char buf (which could
4147 * end up being unaligned) and on the kernel's local stack.
4149 /* ------------------------------------------------------------------------ */
4150 /* Function: copyinptr */
4151 /* Returns: int - 0 = success, else failure */
4152 /* Parameters: src(I) - pointer to the source address */
4153 /* dst(I) - destination address */
4154 /* size(I) - number of bytes to copy */
4156 /* Copy a block of data in from user space, given a pointer to the pointer */
4157 /* to start copying from (src) and a pointer to where to store it (dst). */
4158 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4159 /* ------------------------------------------------------------------------ */
4161 copyinptr(softc, src, dst, size)
4162 ipf_main_softc_t *softc;
4170 error = COPYIN(src, &ca, sizeof(ca));
4174 bcopy(src, (caddr_t)&ca, sizeof(ca));
4176 error = COPYIN(ca, dst, size);
4185 /* ------------------------------------------------------------------------ */
4186 /* Function: copyoutptr */
4187 /* Returns: int - 0 = success, else failure */
4188 /* Parameters: src(I) - pointer to the source address */
4189 /* dst(I) - destination address */
4190 /* size(I) - number of bytes to copy */
4192 /* Copy a block of data out to user space, given a pointer to the pointer */
4193 /* to start copying from (src) and a pointer to where to store it (dst). */
4194 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4195 /* ------------------------------------------------------------------------ */
4197 copyoutptr(softc, src, dst, size)
4198 ipf_main_softc_t *softc;
4205 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4206 error = COPYOUT(src, ca, size);
4215 /* ------------------------------------------------------------------------ */
4216 /* Function: ipf_lock */
4217 /* Returns: int - 0 = success, else error */
4218 /* Parameters: data(I) - pointer to lock value to set */
4219 /* lockp(O) - pointer to location to store old lock value */
4221 /* Get the new value for the lock integer, set it and return the old value */
4223 /* ------------------------------------------------------------------------ */
4225 ipf_lock(data, lockp)
4231 err = BCOPYIN(data, &arg, sizeof(arg));
4234 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4242 /* ------------------------------------------------------------------------ */
4243 /* Function: ipf_getstat */
4245 /* Parameters: softc(I) - pointer to soft context main structure */
4246 /* fiop(I) - pointer to ipfilter stats structure */
4247 /* rev(I) - version claim by program doing ioctl */
4249 /* Stores a copy of current pointers, counters, etc, in the friostat */
4251 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4252 /* program is looking for. This ensure that validation of the version it */
4253 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4254 /* allow older binaries to work but kernels without it will not. */
4255 /* ------------------------------------------------------------------------ */
4258 ipf_getstat(softc, fiop, rev)
4259 ipf_main_softc_t *softc;
4265 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4266 sizeof(ipf_statistics_t) * 2);
4267 fiop->f_locks[IPL_LOGSTATE] = -1;
4268 fiop->f_locks[IPL_LOGNAT] = -1;
4269 fiop->f_locks[IPL_LOGIPF] = -1;
4270 fiop->f_locks[IPL_LOGAUTH] = -1;
4272 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4273 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4274 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4275 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4276 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4277 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4278 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4279 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4281 fiop->f_ticks = softc->ipf_ticks;
4282 fiop->f_active = softc->ipf_active;
4283 fiop->f_froute[0] = softc->ipf_frouteok[0];
4284 fiop->f_froute[1] = softc->ipf_frouteok[1];
4285 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4286 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4288 fiop->f_running = softc->ipf_running;
4289 for (i = 0; i < IPL_LOGSIZE; i++) {
4290 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4291 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4294 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4295 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4296 fiop->f_logging = 1;
4299 fiop->f_log_fail = 0;
4300 fiop->f_logging = 0;
4302 fiop->f_defpass = softc->ipf_pass;
4303 fiop->f_features = ipf_features;
4305 #ifdef IPFILTER_COMPAT
4306 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4307 (rev / 1000000) % 100,
4308 (rev / 10000) % 100,
4312 (void) strncpy(fiop->f_version, ipfilter_version,
4313 sizeof(fiop->f_version));
4319 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4320 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4323 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4324 -1, /* 4: ICMP_SOURCEQUENCH */
4325 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4328 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4330 -1, /* 10: UNUSED */
4331 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4332 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4333 -1, /* 13: ICMP_TSTAMP */
4334 -1, /* 14: ICMP_TSTAMPREPLY */
4335 -1, /* 15: ICMP_IREQ */
4336 -1, /* 16: ICMP_IREQREPLY */
4337 -1, /* 17: ICMP_MASKREQ */
4338 -1, /* 18: ICMP_MASKREPLY */
4342 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4343 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4344 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4345 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4346 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4347 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4348 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4349 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4350 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4351 -1, /* 8: ICMP_UNREACH_ISOLATED */
4352 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4353 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4354 -1, /* 11: ICMP_UNREACH_TOSNET */
4355 -1, /* 12: ICMP_UNREACH_TOSHOST */
4356 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4358 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4361 int icmpreplytype4[ICMP_MAXTYPE + 1];
4364 /* ------------------------------------------------------------------------ */
4365 /* Function: ipf_matchicmpqueryreply */
4366 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4367 /* Parameters: v(I) - IP protocol version (4 or 6) */
4368 /* ic(I) - ICMP information */
4369 /* icmp(I) - ICMP packet header */
4370 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4372 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4373 /* reply to one as described by what's in ic. If it is a match, return 1, */
4374 /* else return 0 for no match. */
4375 /* ------------------------------------------------------------------------ */
4377 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4385 ictype = ic->ici_type;
4389 * If we matched its type on the way in, then when going out
4390 * it will still be the same type.
4392 if ((!rev && (icmp->icmp_type == ictype)) ||
4393 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4394 if (icmp->icmp_type != ICMP_ECHOREPLY)
4396 if (icmp->icmp_id == ic->ici_id)
4402 if ((!rev && (icmp->icmp_type == ictype)) ||
4403 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4404 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4406 if (icmp->icmp_id == ic->ici_id)
4415 /* ------------------------------------------------------------------------ */
4416 /* Function: ipf_rule_compare */
4417 /* Parameters: fr1(I) - first rule structure to compare */
4418 /* fr2(I) - second rule structure to compare */
4419 /* Returns: int - 0 == rules are the same, else mismatch */
4421 /* Compare two rules and return 0 if they match or a number indicating */
4422 /* which of the individual checks failed. */
4423 /* ------------------------------------------------------------------------ */
4425 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4427 if (fr1->fr_cksum != fr2->fr_cksum)
4429 if (fr1->fr_size != fr2->fr_size)
4431 if (fr1->fr_dsize != fr2->fr_dsize)
4433 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4434 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4436 if (fr1->fr_data && !fr2->fr_data)
4438 if (!fr1->fr_data && fr2->fr_data)
4441 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4448 /* ------------------------------------------------------------------------ */
4449 /* Function: frrequest */
4450 /* Returns: int - 0 == success, > 0 == errno value */
4451 /* Parameters: unit(I) - device for which this is for */
4452 /* req(I) - ioctl command (SIOC*) */
4453 /* data(I) - pointr to ioctl data */
4454 /* set(I) - 1 or 0 (filter set) */
4455 /* makecopy(I) - flag indicating whether data points to a rule */
4456 /* in kernel space & hence doesn't need copying. */
4458 /* This function handles all the requests which operate on the list of */
4459 /* filter rules. This includes adding, deleting, insertion. It is also */
4460 /* responsible for creating groups when a "head" rule is loaded. Interface */
4461 /* names are resolved here and other sanity checks are made on the content */
4462 /* of the rule structure being loaded. If a rule has user defined timeouts */
4463 /* then make sure they are created and initialised before exiting. */
4464 /* ------------------------------------------------------------------------ */
4466 frrequest(softc, unit, req, data, set, makecopy)
4467 ipf_main_softc_t *softc;
4473 int error = 0, in, family, addrem, need_free = 0;
4474 frentry_t frd, *fp, *f, **fprev, **ftail;
4475 void *ptr, *uptr, *cptr;
4484 if (makecopy != 0) {
4485 bzero(fp, sizeof(frd));
4486 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4490 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4494 KMALLOCS(f, frentry_t *, fp->fr_size);
4499 bzero(f, fp->fr_size);
4500 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4503 KFREES(f, fp->fr_size);
4510 fp->fr_dnext = NULL;
4511 fp->fr_pnext = NULL;
4512 fp->fr_pdnext = NULL;
4514 fp->fr_grphead = NULL;
4515 fp->fr_icmpgrp = NULL;
4516 fp->fr_isc = (void *)-1;
4519 fp->fr_flags |= FR_COPIED;
4521 fp = (frentry_t *)data;
4522 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4526 fp->fr_flags &= ~FR_COPIED;
4529 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4530 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4536 family = fp->fr_family;
4539 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4540 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4542 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4544 else if (req == (ioctlcmd_t)SIOCZRLST)
4553 * Only filter rules for IPv4 or IPv6 are accepted.
4555 if (family == AF_INET) {
4558 } else if (family == AF_INET6) {
4561 } else if (family != 0) {
4568 * If the rule is being loaded from user space, i.e. we had to copy it
4569 * into kernel space, then do not trust the function pointer in the
4572 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4573 if (ipf_findfunc(fp->fr_func) == NULL) {
4580 error = ipf_funcinit(softc, fp);
4585 if ((fp->fr_flags & FR_CALLNOW) &&
4586 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4591 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4592 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4601 if (FR_ISACCOUNT(fp->fr_flags))
4602 unit = IPL_LOGCOUNT;
4605 * Check that each group name in the rule has a start index that
4608 if (fp->fr_icmphead != -1) {
4609 if ((fp->fr_icmphead < 0) ||
4610 (fp->fr_icmphead >= fp->fr_namelen)) {
4615 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4616 fp->fr_names[fp->fr_icmphead] = '\0';
4619 if (fp->fr_grhead != -1) {
4620 if ((fp->fr_grhead < 0) ||
4621 (fp->fr_grhead >= fp->fr_namelen)) {
4626 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4627 fp->fr_names[fp->fr_grhead] = '\0';
4630 if (fp->fr_group != -1) {
4631 if ((fp->fr_group < 0) ||
4632 (fp->fr_group >= fp->fr_namelen)) {
4637 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4639 * Allow loading rules that are in groups to cause
4640 * them to be created if they don't already exit.
4642 group = FR_NAME(fp, fr_group);
4644 fg = ipf_group_add(softc, group, NULL,
4645 fp->fr_flags, unit, set);
4648 fg = ipf_findgroup(softc, group, unit,
4657 if (fg->fg_flags == 0) {
4658 fg->fg_flags = fp->fr_flags & FR_INOUT;
4659 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4667 * If a rule is going to be part of a group then it does
4668 * not matter whether it is an in or out rule, but if it
4669 * isn't in a group, then it does...
4671 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4677 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4680 * Work out which rule list this change is being applied to.
4684 if (unit == IPL_LOGAUTH) {
4685 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4686 (fp->fr_tifs[1].fd_ptr != NULL) ||
4687 (fp->fr_dif.fd_ptr != NULL) ||
4688 (fp->fr_flags & FR_FASTROUTE)) {
4689 softc->ipf_interror = 145;
4693 fprev = ipf_auth_rulehead(softc);
4695 if (FR_ISACCOUNT(fp->fr_flags))
4696 fprev = &softc->ipf_acct[in][set];
4697 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4698 fprev = &softc->ipf_rules[in][set];
4700 if (fprev == NULL) {
4707 fprev = &fg->fg_start;
4710 * Copy in extra data for the rule.
4712 if (fp->fr_dsize != 0) {
4713 if (makecopy != 0) {
4714 KMALLOCS(ptr, void *, fp->fr_dsize);
4722 * The bcopy case is for when the data is appended
4723 * to the rule by ipf_in_compat().
4725 if (uptr >= (void *)fp &&
4726 uptr < (void *)((char *)fp + fp->fr_size)) {
4727 bcopy(uptr, ptr, fp->fr_dsize);
4730 error = COPYIN(uptr, ptr, fp->fr_dsize);
4746 * Perform per-rule type sanity checks of their members.
4747 * All code after this needs to be aware that allocated memory
4748 * may need to be free'd before exiting.
4750 switch (fp->fr_type & ~FR_T_BUILTIN)
4752 #if defined(IPFILTER_BPF)
4754 if (fp->fr_dsize == 0) {
4759 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4768 * Preparation for error case at the bottom of this function.
4770 if (fp->fr_datype == FRI_LOOKUP)
4771 fp->fr_dstptr = NULL;
4772 if (fp->fr_satype == FRI_LOOKUP)
4773 fp->fr_srcptr = NULL;
4775 if (fp->fr_dsize != sizeof(fripf_t)) {
4782 * Allowing a rule with both "keep state" and "with oow" is
4783 * pointless because adding a state entry to the table will
4784 * fail with the out of window (oow) flag set.
4786 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4792 switch (fp->fr_satype)
4794 case FRI_BROADCAST :
4797 case FRI_NETMASKED :
4799 if (fp->fr_sifpidx < 0) {
4805 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4808 if (fp->fr_srcfunc == NULL) {
4824 switch (fp->fr_datype)
4826 case FRI_BROADCAST :
4829 case FRI_NETMASKED :
4831 if (fp->fr_difpidx < 0) {
4837 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4840 if (fp->fr_dstfunc == NULL) {
4854 case FR_T_CALLFUNC :
4859 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4873 if (fp->fr_tif.fd_name != -1) {
4874 if ((fp->fr_tif.fd_name < 0) ||
4875 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4882 if (fp->fr_dif.fd_name != -1) {
4883 if ((fp->fr_dif.fd_name < 0) ||
4884 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4891 if (fp->fr_rif.fd_name != -1) {
4892 if ((fp->fr_rif.fd_name < 0) ||
4893 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4901 * Lookup all the interface names that are part of the rule.
4903 error = ipf_synclist(softc, fp, NULL);
4906 fp->fr_statecnt = 0;
4907 if (fp->fr_srctrack.ht_max_nodes != 0)
4908 ipf_rb_ht_init(&fp->fr_srctrack);
4911 * Look for an existing matching filter rule, but don't include the
4912 * next or interface pointer in the comparison (fr_next, fr_ifa).
4913 * This elminates rules which are indentical being loaded. Checksum
4914 * the constant part of the filter rule to make comparisons quicker
4915 * (this meaning no pointers are included).
4917 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4920 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4921 for (p = (u_int *)fp->fr_data; p < pp; p++)
4924 WRITE_ENTER(&softc->ipf_mutex);
4927 * Now that the filter rule lists are locked, we can walk the
4928 * chain of them without fear.
4931 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4932 if (fp->fr_collect <= f->fr_collect) {
4940 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4941 if (ipf_rule_compare(fp, f) == 0)
4946 * If zero'ing statistics, copy current to caller and zero.
4954 * Copy and reduce lock because of impending copyout.
4955 * Well we should, but if we do then the atomicity of
4956 * this call and the correctness of fr_hits and
4957 * fr_bytes cannot be guaranteed. As it is, this code
4958 * only resets them to 0 if they are successfully
4959 * copied out into user space.
4961 bcopy((char *)f, (char *)fp, f->fr_size);
4962 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4965 * When we copy this rule back out, set the data
4966 * pointer to be what it was in user space.
4969 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4972 if ((f->fr_dsize != 0) && (uptr != NULL)) {
4973 error = COPYOUT(f->fr_data, uptr,
4986 if (makecopy != 0) {
4988 KFREES(ptr, fp->fr_dsize);
4990 KFREES(fp, fp->fr_size);
4992 RWLOCK_EXIT(&softc->ipf_mutex);
4998 * At the end of this, ftail must point to the place where the
4999 * new rule is to be saved/inserted/added.
5000 * For SIOCAD*FR, this should be the last rule in the group of
5001 * rules that have equal fr_collect fields.
5002 * For SIOCIN*FR, ...
5004 if (req == (ioctlcmd_t)SIOCADAFR ||
5005 req == (ioctlcmd_t)SIOCADIFR) {
5007 for (ftail = fprev; (f = *ftail) != NULL; ) {
5008 if (f->fr_collect > fp->fr_collect)
5010 ftail = &f->fr_next;
5016 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5017 req == (ioctlcmd_t)SIOCINIFR) {
5018 while ((f = *fprev) != NULL) {
5019 if (f->fr_collect >= fp->fr_collect)
5021 fprev = &f->fr_next;
5024 if (fp->fr_hits != 0) {
5025 while (fp->fr_hits && (f = *ftail)) {
5026 if (f->fr_collect != fp->fr_collect)
5029 ftail = &f->fr_next;
5039 * Request to remove a rule.
5047 * Do not allow activity from user space to interfere
5048 * with rules not loaded that way.
5050 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5057 * Return EBUSY if the rule is being reference by
5058 * something else (eg state information.)
5060 if (f->fr_ref > 1) {
5065 #ifdef IPFILTER_SCAN
5066 if (f->fr_isctag != -1 &&
5067 (f->fr_isc != (struct ipscan *)-1))
5068 ipf_scan_detachfr(f);
5071 if (unit == IPL_LOGAUTH) {
5072 error = ipf_auth_precmd(softc, req, f, ftail);
5076 ipf_rule_delete(softc, f, unit, set);
5078 need_free = makecopy;
5082 * Not removing, so we must be adding/inserting a rule.
5089 if (unit == IPL_LOGAUTH) {
5090 error = ipf_auth_precmd(softc, req, fp, ftail);
5094 MUTEX_NUKE(&fp->fr_lock);
5095 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5096 if (fp->fr_die != 0)
5097 ipf_rule_expire_insert(softc, fp, set);
5102 fp->fr_pnext = ftail;
5103 fp->fr_next = *ftail;
5104 if (fp->fr_next != NULL)
5105 fp->fr_next->fr_pnext = &fp->fr_next;
5108 ipf_fixskip(ftail, fp, 1);
5110 fp->fr_icmpgrp = NULL;
5111 if (fp->fr_icmphead != -1) {
5112 group = FR_NAME(fp, fr_icmphead);
5113 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5114 fp->fr_icmpgrp = fg;
5117 fp->fr_grphead = NULL;
5118 if (fp->fr_grhead != -1) {
5119 group = FR_NAME(fp, fr_grhead);
5120 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5122 fp->fr_grphead = fg;
5126 RWLOCK_EXIT(&softc->ipf_mutex);
5128 if (need_free || (error != 0)) {
5129 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5130 if ((fp->fr_satype == FRI_LOOKUP) &&
5131 (fp->fr_srcptr != NULL))
5132 ipf_lookup_deref(softc, fp->fr_srctype,
5134 if ((fp->fr_datype == FRI_LOOKUP) &&
5135 (fp->fr_dstptr != NULL))
5136 ipf_lookup_deref(softc, fp->fr_dsttype,
5139 if (fp->fr_grp != NULL) {
5140 WRITE_ENTER(&softc->ipf_mutex);
5141 ipf_group_del(softc, fp->fr_grp, fp);
5142 RWLOCK_EXIT(&softc->ipf_mutex);
5144 if ((ptr != NULL) && (makecopy != 0)) {
5145 KFREES(ptr, fp->fr_dsize);
5147 KFREES(fp, fp->fr_size);
5153 /* ------------------------------------------------------------------------ */
5154 /* Function: ipf_rule_delete */
5156 /* Parameters: softc(I) - pointer to soft context main structure */
5157 /* f(I) - pointer to the rule being deleted */
5158 /* ftail(I) - pointer to the pointer to f */
5159 /* unit(I) - device for which this is for */
5160 /* set(I) - 1 or 0 (filter set) */
5162 /* This function attempts to do what it can to delete a filter rule: remove */
5163 /* it from any linked lists and remove any groups it is responsible for. */
5164 /* But in the end, removing a rule can only drop the reference count - we */
5165 /* must use that as the guide for whether or not it can be freed. */
5166 /* ------------------------------------------------------------------------ */
5168 ipf_rule_delete(softc, f, unit, set)
5169 ipf_main_softc_t *softc;
5175 * If fr_pdnext is set, then the rule is on the expire list, so
5176 * remove it from there.
5178 if (f->fr_pdnext != NULL) {
5179 *f->fr_pdnext = f->fr_dnext;
5180 if (f->fr_dnext != NULL)
5181 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5182 f->fr_pdnext = NULL;
5186 ipf_fixskip(f->fr_pnext, f, -1);
5187 if (f->fr_pnext != NULL)
5188 *f->fr_pnext = f->fr_next;
5189 if (f->fr_next != NULL)
5190 f->fr_next->fr_pnext = f->fr_pnext;
5194 (void) ipf_derefrule(softc, &f);
5197 /* ------------------------------------------------------------------------ */
5198 /* Function: ipf_rule_expire_insert */
5200 /* Parameters: softc(I) - pointer to soft context main structure */
5201 /* f(I) - pointer to rule to be added to expire list */
5202 /* set(I) - 1 or 0 (filter set) */
5204 /* If the new rule has a given expiration time, insert it into the list of */
5205 /* expiring rules with the ones to be removed first added to the front of */
5206 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5207 /* expiration interval checks. */
5208 /* ------------------------------------------------------------------------ */
5210 ipf_rule_expire_insert(softc, f, set)
5211 ipf_main_softc_t *softc;
5220 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5221 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5222 fr = fr->fr_dnext) {
5223 if (f->fr_die < fr->fr_die)
5225 if (fr->fr_dnext == NULL) {
5227 * We've got to the last rule and everything
5228 * wanted to be expired before this new node,
5229 * so we have to tack it on the end...
5232 f->fr_pdnext = &fr->fr_dnext;
5238 if (softc->ipf_rule_explist[set] == NULL) {
5239 softc->ipf_rule_explist[set] = f;
5240 f->fr_pdnext = &softc->ipf_rule_explist[set];
5241 } else if (fr != NULL) {
5243 f->fr_pdnext = fr->fr_pdnext;
5244 fr->fr_pdnext = &f->fr_dnext;
5249 /* ------------------------------------------------------------------------ */
5250 /* Function: ipf_findlookup */
5251 /* Returns: NULL = failure, else success */
5252 /* Parameters: softc(I) - pointer to soft context main structure */
5253 /* unit(I) - ipf device we want to find match for */
5254 /* fp(I) - rule for which lookup is for */
5255 /* addrp(I) - pointer to lookup information in address struct */
5256 /* maskp(O) - pointer to lookup information for storage */
5258 /* When using pools and hash tables to store addresses for matching in */
5259 /* rules, it is necessary to resolve both the object referred to by the */
5260 /* name or address (and return that pointer) and also provide the means by */
5261 /* which to determine if an address belongs to that object to make the */
5262 /* packet matching quicker. */
5263 /* ------------------------------------------------------------------------ */
5265 ipf_findlookup(softc, unit, fr, addrp, maskp)
5266 ipf_main_softc_t *softc;
5269 i6addr_t *addrp, *maskp;
5273 switch (addrp->iplookupsubtype)
5276 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5278 &maskp->iplookupfunc);
5281 if (addrp->iplookupname < 0)
5283 if (addrp->iplookupname >= fr->fr_namelen)
5285 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5286 fr->fr_names + addrp->iplookupname,
5287 &maskp->iplookupfunc);
5297 /* ------------------------------------------------------------------------ */
5298 /* Function: ipf_funcinit */
5299 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5300 /* Parameters: softc(I) - pointer to soft context main structure */
5301 /* fr(I) - pointer to filter rule */
5303 /* If a rule is a call rule, then check if the function it points to needs */
5304 /* an init function to be called now the rule has been loaded. */
5305 /* ------------------------------------------------------------------------ */
5307 ipf_funcinit(softc, fr)
5308 ipf_main_softc_t *softc;
5311 ipfunc_resolve_t *ft;
5317 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5318 if (ft->ipfu_addr == fr->fr_func) {
5320 if (ft->ipfu_init != NULL)
5321 err = (*ft->ipfu_init)(softc, fr);
5328 /* ------------------------------------------------------------------------ */
5329 /* Function: ipf_funcfini */
5331 /* Parameters: softc(I) - pointer to soft context main structure */
5332 /* fr(I) - pointer to filter rule */
5334 /* For a given filter rule, call the matching "fini" function if the rule */
5335 /* is using a known function that would have resulted in the "init" being */
5336 /* called for ealier. */
5337 /* ------------------------------------------------------------------------ */
5339 ipf_funcfini(softc, fr)
5340 ipf_main_softc_t *softc;
5343 ipfunc_resolve_t *ft;
5345 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5346 if (ft->ipfu_addr == fr->fr_func) {
5347 if (ft->ipfu_fini != NULL)
5348 (void) (*ft->ipfu_fini)(softc, fr);
5354 /* ------------------------------------------------------------------------ */
5355 /* Function: ipf_findfunc */
5356 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5357 /* Parameters: funcptr(I) - function pointer to lookup */
5359 /* Look for a function in the table of known functions. */
5360 /* ------------------------------------------------------------------------ */
5362 ipf_findfunc(funcptr)
5365 ipfunc_resolve_t *ft;
5367 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5368 if (ft->ipfu_addr == funcptr)
5374 /* ------------------------------------------------------------------------ */
5375 /* Function: ipf_resolvefunc */
5376 /* Returns: int - 0 == success, else error */
5377 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5379 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5380 /* This will either be the function name (if the pointer is set) or the */
5381 /* function pointer if the name is set. When found, fill in the other one */
5382 /* so that the entire, complete, structure can be copied back to user space.*/
5383 /* ------------------------------------------------------------------------ */
5385 ipf_resolvefunc(softc, data)
5386 ipf_main_softc_t *softc;
5389 ipfunc_resolve_t res, *ft;
5392 error = BCOPYIN(data, &res, sizeof(res));
5398 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5399 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5400 if (strncmp(res.ipfu_name, ft->ipfu_name,
5401 sizeof(res.ipfu_name)) == 0) {
5402 res.ipfu_addr = ft->ipfu_addr;
5403 res.ipfu_init = ft->ipfu_init;
5404 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5411 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5412 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5413 if (ft->ipfu_addr == res.ipfu_addr) {
5414 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5415 sizeof(res.ipfu_name));
5416 res.ipfu_init = ft->ipfu_init;
5417 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5429 #if !defined(_KERNEL) || SOLARIS
5432 * ppsratecheck(): packets (or events) per second limitation.
5435 ppsratecheck(lasttime, curpps, maxpps)
5436 struct timeval *lasttime;
5438 int maxpps; /* maximum pps allowed */
5440 struct timeval tv, delta;
5445 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5446 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5447 if (delta.tv_usec < 0) {
5449 delta.tv_usec += 1000000;
5453 * check for 0,0 is so that the message will be seen at least once.
5454 * if more than one second have passed since the last update of
5455 * lasttime, reset the counter.
5457 * we do increment *curpps even in *curpps < maxpps case, as some may
5458 * try to use *curpps for stat purposes as well.
5460 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5461 delta.tv_sec >= 1) {
5465 } else if (maxpps < 0)
5467 else if (*curpps < maxpps)
5471 *curpps = *curpps + 1;
5478 /* ------------------------------------------------------------------------ */
5479 /* Function: ipf_derefrule */
5480 /* Returns: int - 0 == rule freed up, else rule not freed */
5481 /* Parameters: fr(I) - pointer to filter rule */
5483 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5484 /* free it and any associated storage space being used by it. */
5485 /* ------------------------------------------------------------------------ */
5487 ipf_derefrule(softc, frp)
5488 ipf_main_softc_t *softc;
5497 MUTEX_ENTER(&fr->fr_lock);
5499 if (fr->fr_ref == 0) {
5500 MUTEX_EXIT(&fr->fr_lock);
5501 MUTEX_DESTROY(&fr->fr_lock);
5503 ipf_funcfini(softc, fr);
5506 if (fdp->fd_type == FRD_DSTLIST)
5507 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5510 if (fdp->fd_type == FRD_DSTLIST)
5511 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5514 if (fdp->fd_type == FRD_DSTLIST)
5515 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5517 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5518 fr->fr_satype == FRI_LOOKUP)
5519 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5520 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5521 fr->fr_datype == FRI_LOOKUP)
5522 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5524 if (fr->fr_grp != NULL)
5525 ipf_group_del(softc, fr->fr_grp, fr);
5527 if (fr->fr_grphead != NULL)
5528 ipf_group_del(softc, fr->fr_grphead, fr);
5530 if (fr->fr_icmpgrp != NULL)
5531 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5533 if ((fr->fr_flags & FR_COPIED) != 0) {
5535 KFREES(fr->fr_data, fr->fr_dsize);
5537 KFREES(fr, fr->fr_size);
5542 MUTEX_EXIT(&fr->fr_lock);
5548 /* ------------------------------------------------------------------------ */
5549 /* Function: ipf_grpmapinit */
5550 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5551 /* Parameters: fr(I) - pointer to rule to find hash table for */
5553 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5554 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5555 /* ------------------------------------------------------------------------ */
5557 ipf_grpmapinit(softc, fr)
5558 ipf_main_softc_t *softc;
5561 char name[FR_GROUPLEN];
5564 #if defined(SNPRINTF) && defined(_KERNEL)
5565 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5567 (void) sprintf(name, "%d", fr->fr_arg);
5569 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5574 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5584 /* ------------------------------------------------------------------------ */
5585 /* Function: ipf_grpmapfini */
5586 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5587 /* Parameters: softc(I) - pointer to soft context main structure */
5588 /* fr(I) - pointer to rule to release hash table for */
5590 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5591 /* be called to undo what ipf_grpmapinit caused to be done. */
5592 /* ------------------------------------------------------------------------ */
5594 ipf_grpmapfini(softc, fr)
5595 ipf_main_softc_t *softc;
5601 ipf_lookup_deref(softc, IPLT_HASH, iph);
5606 /* ------------------------------------------------------------------------ */
5607 /* Function: ipf_srcgrpmap */
5608 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5609 /* Parameters: fin(I) - pointer to packet information */
5610 /* passp(IO) - pointer to current/new filter decision (unused) */
5612 /* Look for a rule group head in a hash table, using the source address as */
5613 /* the key, and descend into that group and continue matching rules against */
5615 /* ------------------------------------------------------------------------ */
5617 ipf_srcgrpmap(fin, passp)
5624 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5630 fin->fin_fr = fg->fg_start;
5631 (void) ipf_scanlist(fin, *passp);
5636 /* ------------------------------------------------------------------------ */
5637 /* Function: ipf_dstgrpmap */
5638 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5639 /* Parameters: fin(I) - pointer to packet information */
5640 /* passp(IO) - pointer to current/new filter decision (unused) */
5642 /* Look for a rule group head in a hash table, using the destination */
5643 /* address as the key, and descend into that group and continue matching */
5644 /* rules against the packet. */
5645 /* ------------------------------------------------------------------------ */
5647 ipf_dstgrpmap(fin, passp)
5654 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5660 fin->fin_fr = fg->fg_start;
5661 (void) ipf_scanlist(fin, *passp);
5668 * These functions manage objects on queues for efficient timeouts. There
5669 * are a number of system defined queues as well as user defined timeouts.
5670 * It is expected that a lock is held in the domain in which the queue
5671 * belongs (i.e. either state or NAT) when calling any of these functions
5672 * that prevents ipf_freetimeoutqueue() from being called at the same time
5677 /* ------------------------------------------------------------------------ */
5678 /* Function: ipf_addtimeoutqueue */
5679 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5680 /* timeout queue with given interval. */
5681 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5682 /* of interface queues. */
5683 /* seconds(I) - timeout value in seconds for this queue. */
5685 /* This routine first looks for a timeout queue that matches the interval */
5686 /* being requested. If it finds one, increments the reference counter and */
5687 /* returns a pointer to it. If none are found, it allocates a new one and */
5688 /* inserts it at the top of the list. */
5691 /* It is assumed that the caller of this function has an appropriate lock */
5692 /* held (exclusively) in the domain that encompases 'parent'. */
5693 /* ------------------------------------------------------------------------ */
5695 ipf_addtimeoutqueue(softc, parent, seconds)
5696 ipf_main_softc_t *softc;
5703 period = seconds * IPF_HZ_DIVIDE;
5705 MUTEX_ENTER(&softc->ipf_timeoutlock);
5706 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5707 if (ifq->ifq_ttl == period) {
5709 * Reset the delete flag, if set, so the structure
5710 * gets reused rather than freed and reallocated.
5712 MUTEX_ENTER(&ifq->ifq_lock);
5713 ifq->ifq_flags &= ~IFQF_DELETE;
5715 MUTEX_EXIT(&ifq->ifq_lock);
5716 MUTEX_EXIT(&softc->ipf_timeoutlock);
5722 KMALLOC(ifq, ipftq_t *);
5724 MUTEX_NUKE(&ifq->ifq_lock);
5725 IPFTQ_INIT(ifq, period, "ipftq mutex");
5726 ifq->ifq_next = *parent;
5727 ifq->ifq_pnext = parent;
5728 ifq->ifq_flags = IFQF_USER;
5731 softc->ipf_userifqs++;
5733 MUTEX_EXIT(&softc->ipf_timeoutlock);
5738 /* ------------------------------------------------------------------------ */
5739 /* Function: ipf_deletetimeoutqueue */
5740 /* Returns: int - new reference count value of the timeout queue */
5741 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5742 /* Locks: ifq->ifq_lock */
5744 /* This routine must be called when we're discarding a pointer to a timeout */
5745 /* queue object, taking care of the reference counter. */
5747 /* Now that this just sets a DELETE flag, it requires the expire code to */
5748 /* check the list of user defined timeout queues and call the free function */
5749 /* below (currently commented out) to stop memory leaking. It is done this */
5750 /* way because the locking may not be sufficient to safely do a free when */
5751 /* this function is called. */
5752 /* ------------------------------------------------------------------------ */
5754 ipf_deletetimeoutqueue(ifq)
5759 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5760 ifq->ifq_flags |= IFQF_DELETE;
5763 return ifq->ifq_ref;
5767 /* ------------------------------------------------------------------------ */
5768 /* Function: ipf_freetimeoutqueue */
5769 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5773 /* It is assumed that the caller of this function has an appropriate lock */
5774 /* held (exclusively) in the domain that encompases the callers "domain". */
5775 /* The ifq_lock for this structure should not be held. */
5777 /* Remove a user defined timeout queue from the list of queues it is in and */
5778 /* tidy up after this is done. */
5779 /* ------------------------------------------------------------------------ */
5781 ipf_freetimeoutqueue(softc, ifq)
5782 ipf_main_softc_t *softc;
5786 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5787 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5788 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5789 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5795 * Remove from its position in the list.
5797 *ifq->ifq_pnext = ifq->ifq_next;
5798 if (ifq->ifq_next != NULL)
5799 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5800 ifq->ifq_next = NULL;
5801 ifq->ifq_pnext = NULL;
5803 MUTEX_DESTROY(&ifq->ifq_lock);
5804 ATOMIC_DEC(softc->ipf_userifqs);
5809 /* ------------------------------------------------------------------------ */
5810 /* Function: ipf_deletequeueentry */
5812 /* Parameters: tqe(I) - timeout queue entry to delete */
5814 /* Remove a tail queue entry from its queue and make it an orphan. */
5815 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5816 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5817 /* the correct lock(s) may not be held that would make it safe to do so. */
5818 /* ------------------------------------------------------------------------ */
5820 ipf_deletequeueentry(tqe)
5827 MUTEX_ENTER(&ifq->ifq_lock);
5829 if (tqe->tqe_pnext != NULL) {
5830 *tqe->tqe_pnext = tqe->tqe_next;
5831 if (tqe->tqe_next != NULL)
5832 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5833 else /* we must be the tail anyway */
5834 ifq->ifq_tail = tqe->tqe_pnext;
5836 tqe->tqe_pnext = NULL;
5837 tqe->tqe_ifq = NULL;
5840 (void) ipf_deletetimeoutqueue(ifq);
5841 ASSERT(ifq->ifq_ref > 0);
5843 MUTEX_EXIT(&ifq->ifq_lock);
5847 /* ------------------------------------------------------------------------ */
5848 /* Function: ipf_queuefront */
5850 /* Parameters: tqe(I) - pointer to timeout queue entry */
5852 /* Move a queue entry to the front of the queue, if it isn't already there. */
5853 /* ------------------------------------------------------------------------ */
5864 MUTEX_ENTER(&ifq->ifq_lock);
5865 if (ifq->ifq_head != tqe) {
5866 *tqe->tqe_pnext = tqe->tqe_next;
5868 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5870 ifq->ifq_tail = tqe->tqe_pnext;
5872 tqe->tqe_next = ifq->ifq_head;
5873 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5874 ifq->ifq_head = tqe;
5875 tqe->tqe_pnext = &ifq->ifq_head;
5877 MUTEX_EXIT(&ifq->ifq_lock);
5881 /* ------------------------------------------------------------------------ */
5882 /* Function: ipf_queueback */
5884 /* Parameters: ticks(I) - ipf tick time to use with this call */
5885 /* tqe(I) - pointer to timeout queue entry */
5887 /* Move a queue entry to the back of the queue, if it isn't already there. */
5888 /* We use use ticks to calculate the expiration and mark for when we last */
5889 /* touched the structure. */
5890 /* ------------------------------------------------------------------------ */
5892 ipf_queueback(ticks, tqe)
5901 tqe->tqe_die = ticks + ifq->ifq_ttl;
5902 tqe->tqe_touched = ticks;
5904 MUTEX_ENTER(&ifq->ifq_lock);
5905 if (tqe->tqe_next != NULL) { /* at the end already ? */
5909 *tqe->tqe_pnext = tqe->tqe_next;
5910 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5913 * Make it the last entry.
5915 tqe->tqe_next = NULL;
5916 tqe->tqe_pnext = ifq->ifq_tail;
5917 *ifq->ifq_tail = tqe;
5918 ifq->ifq_tail = &tqe->tqe_next;
5920 MUTEX_EXIT(&ifq->ifq_lock);
5924 /* ------------------------------------------------------------------------ */
5925 /* Function: ipf_queueappend */
5927 /* Parameters: ticks(I) - ipf tick time to use with this call */
5928 /* tqe(I) - pointer to timeout queue entry */
5929 /* ifq(I) - pointer to timeout queue */
5930 /* parent(I) - owing object pointer */
5932 /* Add a new item to this queue and put it on the very end. */
5933 /* We use use ticks to calculate the expiration and mark for when we last */
5934 /* touched the structure. */
5935 /* ------------------------------------------------------------------------ */
5937 ipf_queueappend(ticks, tqe, ifq, parent)
5944 MUTEX_ENTER(&ifq->ifq_lock);
5945 tqe->tqe_parent = parent;
5946 tqe->tqe_pnext = ifq->ifq_tail;
5947 *ifq->ifq_tail = tqe;
5948 ifq->ifq_tail = &tqe->tqe_next;
5949 tqe->tqe_next = NULL;
5951 tqe->tqe_die = ticks + ifq->ifq_ttl;
5952 tqe->tqe_touched = ticks;
5954 MUTEX_EXIT(&ifq->ifq_lock);
5958 /* ------------------------------------------------------------------------ */
5959 /* Function: ipf_movequeue */
5961 /* Parameters: tq(I) - pointer to timeout queue information */
5962 /* oifp(I) - old timeout queue entry was on */
5963 /* nifp(I) - new timeout queue to put entry on */
5965 /* Move a queue entry from one timeout queue to another timeout queue. */
5966 /* If it notices that the current entry is already last and does not need */
5967 /* to move queue, the return. */
5968 /* ------------------------------------------------------------------------ */
5970 ipf_movequeue(ticks, tqe, oifq, nifq)
5973 ipftq_t *oifq, *nifq;
5977 * If the queue hasn't changed and we last touched this entry at the
5978 * same ipf time, then we're not going to achieve anything by either
5979 * changing the ttl or moving it on the queue.
5981 if (oifq == nifq && tqe->tqe_touched == ticks)
5985 * For any of this to be outside the lock, there is a risk that two
5986 * packets entering simultaneously, with one changing to a different
5987 * queue and one not, could end up with things in a bizarre state.
5989 MUTEX_ENTER(&oifq->ifq_lock);
5991 tqe->tqe_touched = ticks;
5992 tqe->tqe_die = ticks + nifq->ifq_ttl;
5994 * Is the operation here going to be a no-op ?
5997 if ((tqe->tqe_next == NULL) ||
5998 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5999 MUTEX_EXIT(&oifq->ifq_lock);
6005 * Remove from the old queue
6007 *tqe->tqe_pnext = tqe->tqe_next;
6009 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6011 oifq->ifq_tail = tqe->tqe_pnext;
6012 tqe->tqe_next = NULL;
6015 * If we're moving from one queue to another, release the
6016 * lock on the old queue and get a lock on the new queue.
6017 * For user defined queues, if we're moving off it, call
6018 * delete in case it can now be freed.
6021 tqe->tqe_ifq = NULL;
6023 (void) ipf_deletetimeoutqueue(oifq);
6025 MUTEX_EXIT(&oifq->ifq_lock);
6027 MUTEX_ENTER(&nifq->ifq_lock);
6029 tqe->tqe_ifq = nifq;
6034 * Add to the bottom of the new queue
6036 tqe->tqe_pnext = nifq->ifq_tail;
6037 *nifq->ifq_tail = tqe;
6038 nifq->ifq_tail = &tqe->tqe_next;
6039 MUTEX_EXIT(&nifq->ifq_lock);
6043 /* ------------------------------------------------------------------------ */
6044 /* Function: ipf_updateipid */
6045 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6046 /* Parameters: fin(I) - pointer to packet information */
6048 /* When we are doing NAT, change the IP of every packet to represent a */
6049 /* single sequence of packets coming from the host, hiding any host */
6050 /* specific sequencing that might otherwise be revealed. If the packet is */
6051 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
6052 /* the fragment cache for non-leading fragments. If a non-leading fragment */
6053 /* has no match in the cache, return an error. */
6054 /* ------------------------------------------------------------------------ */
6059 u_short id, ido, sums;
6064 ido = ntohs(ip->ip_id);
6065 if (fin->fin_off != 0) {
6066 sum = ipf_frag_ipidknown(fin);
6067 if (sum == 0xffffffff)
6071 ip->ip_id = htons(id);
6074 id = ntohs(ip->ip_id);
6075 if ((fin->fin_flx & FI_FRAG) != 0)
6076 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6081 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6082 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6084 sum = (sum >> 16) + (sum & 0xffff);
6085 sum = (sum >> 16) + (sum & 0xffff);
6086 sums = ~(u_short)sum;
6087 ip->ip_sum = htons(sums);
6092 #ifdef NEED_FRGETIFNAME
6093 /* ------------------------------------------------------------------------ */
6094 /* Function: ipf_getifname */
6095 /* Returns: char * - pointer to interface name */
6096 /* Parameters: ifp(I) - pointer to network interface */
6097 /* buffer(O) - pointer to where to store interface name */
6099 /* Constructs an interface name in the buffer passed. The buffer passed is */
6100 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6101 /* as a NULL pointer then return a pointer to a static array. */
6102 /* ------------------------------------------------------------------------ */
6104 ipf_getifname(ifp, buffer)
6108 static char namebuf[LIFNAMSIZ];
6109 # if defined(MENTAT) || defined(__FreeBSD__)
6117 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6118 buffer[LIFNAMSIZ - 1] = '\0';
6119 # if defined(MENTAT) || defined(__FreeBSD__)
6120 for (s = buffer; *s; s++)
6122 unit = ifp->if_unit;
6123 space = LIFNAMSIZ - (s - buffer);
6124 if ((space > 0) && (unit >= 0)) {
6125 # if defined(SNPRINTF) && defined(_KERNEL)
6126 SNPRINTF(temp, sizeof(temp), "%d", unit);
6128 (void) sprintf(temp, "%d", unit);
6130 (void) strncpy(s, temp, space);
6138 /* ------------------------------------------------------------------------ */
6139 /* Function: ipf_ioctlswitch */
6140 /* Returns: int - -1 continue processing, else ioctl return value */
6141 /* Parameters: unit(I) - device unit opened */
6142 /* data(I) - pointer to ioctl data */
6143 /* cmd(I) - ioctl command */
6144 /* mode(I) - mode value */
6145 /* uid(I) - uid making the ioctl call */
6146 /* ctx(I) - pointer to context data */
6148 /* Based on the value of unit, call the appropriate ioctl handler or return */
6149 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6150 /* for the device in order to execute the ioctl. A special case is made */
6151 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6152 /* The context data pointer is passed through as this is used as the key */
6153 /* for locating a matching token for continued access for walking lists, */
6155 /* ------------------------------------------------------------------------ */
6157 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6158 ipf_main_softc_t *softc;
6159 int unit, mode, uid;
6167 case SIOCIPFINTERROR :
6168 error = BCOPYOUT(&softc->ipf_interror, data,
6169 sizeof(softc->ipf_interror));
6182 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6185 if (softc->ipf_running > 0) {
6186 error = ipf_nat_ioctl(softc, data, cmd, mode,
6194 if (softc->ipf_running > 0) {
6195 error = ipf_state_ioctl(softc, data, cmd, mode,
6203 if (softc->ipf_running > 0) {
6204 error = ipf_auth_ioctl(softc, data, cmd, mode,
6212 if (softc->ipf_running > 0) {
6213 error = ipf_sync_ioctl(softc, data, cmd, mode,
6221 #ifdef IPFILTER_SCAN
6222 if (softc->ipf_running > 0)
6223 error = ipf_scan_ioctl(softc, data, cmd, mode,
6232 case IPL_LOGLOOKUP :
6233 if (softc->ipf_running > 0) {
6234 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6252 * This array defines the expected size of objects coming into the kernel
6253 * for the various recognised object types. The first column is flags (see
6254 * below), 2nd column is current size, 3rd column is the version number of
6255 * when the current size became current.
6257 * 1 = minimum size, not absolute size
6259 static const int ipf_objbytes[IPFOBJ_COUNT][3] = {
6260 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6261 { 1, sizeof(struct friostat), 5010000 },
6262 { 0, sizeof(struct fr_info), 5010000 },
6263 { 0, sizeof(struct ipf_authstat), 4010100 },
6264 { 0, sizeof(struct ipfrstat), 5010000 },
6265 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6266 { 0, sizeof(struct natstat), 5010000 },
6267 { 0, sizeof(struct ipstate_save), 5010000 },
6268 { 1, sizeof(struct nat_save), 5010000 },
6269 { 0, sizeof(struct natlookup), 5010000 },
6270 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6271 { 0, sizeof(struct ips_stat), 5010000 },
6272 { 0, sizeof(struct frauth), 5010000 },
6273 { 0, sizeof(struct ipftune), 4010100 },
6274 { 0, sizeof(struct nat), 5010000 },
6275 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6276 { 0, sizeof(struct ipfgeniter), 4011400 },
6277 { 0, sizeof(struct ipftable), 4011400 },
6278 { 0, sizeof(struct ipflookupiter), 4011400 },
6279 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6280 { 1, 0, 0 }, /* IPFEXPR */
6281 { 0, 0, 0 }, /* PROXYCTL */
6282 { 0, sizeof (struct fripf), 5010000 }
6286 /* ------------------------------------------------------------------------ */
6287 /* Function: ipf_inobj */
6288 /* Returns: int - 0 = success, else failure */
6289 /* Parameters: softc(I) - soft context pointerto work with */
6290 /* data(I) - pointer to ioctl data */
6291 /* objp(O) - where to store ipfobj structure */
6292 /* ptr(I) - pointer to data to copy out */
6293 /* type(I) - type of structure being moved */
6295 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6296 /* add things to check for version numbers, sizes, etc, to make it backward */
6297 /* compatible at the ABI for user land. */
6298 /* If objp is not NULL then we assume that the caller wants to see what is */
6299 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6300 /* the caller what version of ipfilter the ioctl program was written to. */
6301 /* ------------------------------------------------------------------------ */
6303 ipf_inobj(softc, data, objp, ptr, type)
6304 ipf_main_softc_t *softc;
6314 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6321 error = BCOPYIN(data, objp, sizeof(*objp));
6327 if (objp->ipfo_type != type) {
6332 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6333 if ((ipf_objbytes[type][0] & 1) != 0) {
6334 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6338 size = ipf_objbytes[type][1];
6339 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6340 size = objp->ipfo_size;
6345 error = COPYIN(objp->ipfo_ptr, ptr, size);
6351 #ifdef IPFILTER_COMPAT
6352 error = ipf_in_compat(softc, objp, ptr, 0);
6362 /* ------------------------------------------------------------------------ */
6363 /* Function: ipf_inobjsz */
6364 /* Returns: int - 0 = success, else failure */
6365 /* Parameters: softc(I) - soft context pointerto work with */
6366 /* data(I) - pointer to ioctl data */
6367 /* ptr(I) - pointer to store real data in */
6368 /* type(I) - type of structure being moved */
6369 /* sz(I) - size of data to copy */
6371 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6372 /* but it must not be smaller than the size defined for the type and the */
6373 /* type must allow for varied sized objects. The extra requirement here is */
6374 /* that sz must match the size of the object being passed in - this is not */
6375 /* not possible nor required in ipf_inobj(). */
6376 /* ------------------------------------------------------------------------ */
6378 ipf_inobjsz(softc, data, ptr, type, sz)
6379 ipf_main_softc_t *softc;
6387 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6392 error = BCOPYIN(data, &obj, sizeof(obj));
6398 if (obj.ipfo_type != type) {
6403 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6404 if (((ipf_objbytes[type][0] & 1) == 0) ||
6405 (sz < ipf_objbytes[type][1])) {
6409 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6415 #ifdef IPFILTER_COMPAT
6416 error = ipf_in_compat(softc, &obj, ptr, sz);
6426 /* ------------------------------------------------------------------------ */
6427 /* Function: ipf_outobjsz */
6428 /* Returns: int - 0 = success, else failure */
6429 /* Parameters: data(I) - pointer to ioctl data */
6430 /* ptr(I) - pointer to store real data in */
6431 /* type(I) - type of structure being moved */
6432 /* sz(I) - size of data to copy */
6434 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6435 /* but it must not be smaller than the size defined for the type and the */
6436 /* type must allow for varied sized objects. The extra requirement here is */
6437 /* that sz must match the size of the object being passed in - this is not */
6438 /* not possible nor required in ipf_outobj(). */
6439 /* ------------------------------------------------------------------------ */
6441 ipf_outobjsz(softc, data, ptr, type, sz)
6442 ipf_main_softc_t *softc;
6450 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6455 error = BCOPYIN(data, &obj, sizeof(obj));
6461 if (obj.ipfo_type != type) {
6466 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6467 if (((ipf_objbytes[type][0] & 1) == 0) ||
6468 (sz < ipf_objbytes[type][1])) {
6472 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6478 #ifdef IPFILTER_COMPAT
6479 error = ipf_out_compat(softc, &obj, ptr);
6489 /* ------------------------------------------------------------------------ */
6490 /* Function: ipf_outobj */
6491 /* Returns: int - 0 = success, else failure */
6492 /* Parameters: data(I) - pointer to ioctl data */
6493 /* ptr(I) - pointer to store real data in */
6494 /* type(I) - type of structure being moved */
6496 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6497 /* future, we add things to check for version numbers, sizes, etc, to make */
6498 /* it backward compatible at the ABI for user land. */
6499 /* ------------------------------------------------------------------------ */
6501 ipf_outobj(softc, data, ptr, type)
6502 ipf_main_softc_t *softc;
6510 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6515 error = BCOPYIN(data, &obj, sizeof(obj));
6521 if (obj.ipfo_type != type) {
6526 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6527 if ((ipf_objbytes[type][0] & 1) != 0) {
6528 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6532 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6537 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6543 #ifdef IPFILTER_COMPAT
6544 error = ipf_out_compat(softc, &obj, ptr);
6554 /* ------------------------------------------------------------------------ */
6555 /* Function: ipf_outobjk */
6556 /* Returns: int - 0 = success, else failure */
6557 /* Parameters: obj(I) - pointer to data description structure */
6558 /* ptr(I) - pointer to kernel data to copy out */
6560 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6561 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6562 /* already populated with information and now we just need to use it. */
6563 /* There is no need for this function to have a "type" parameter as there */
6564 /* is no point in validating information that comes from the kernel with */
6566 /* ------------------------------------------------------------------------ */
6568 ipf_outobjk(softc, obj, ptr)
6569 ipf_main_softc_t *softc;
6573 int type = obj->ipfo_type;
6576 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6581 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6582 if ((ipf_objbytes[type][0] & 1) != 0) {
6583 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6588 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6593 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6599 #ifdef IPFILTER_COMPAT
6600 error = ipf_out_compat(softc, obj, ptr);
6610 /* ------------------------------------------------------------------------ */
6611 /* Function: ipf_checkl4sum */
6612 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6613 /* Parameters: fin(I) - pointer to packet information */
6615 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6616 /* not possible, return without indicating a failure or success but in a */
6617 /* way that is ditinguishable. This function should only be called by the */
6618 /* ipf_checkv6sum() for each platform. */
6619 /* ------------------------------------------------------------------------ */
6624 u_short sum, hdrsum, *csump;
6629 * If the TCP packet isn't a fragment, isn't too short and otherwise
6630 * isn't already considered "bad", then validate the checksum. If
6631 * this check fails then considered the packet to be "bad".
6633 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6636 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6637 if (fin->fin_out == 1) {
6638 fin->fin_cksum = FI_CK_SUMOK;
6650 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6656 if (udp->uh_sum != 0) {
6657 csump = &udp->uh_sum;
6663 case IPPROTO_ICMPV6 :
6664 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6670 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6683 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6685 #if !defined(_KERNEL)
6686 if (sum == hdrsum) {
6687 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6689 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6692 DT2(l4sums, u_short, hdrsum, u_short, sum);
6694 if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6696 if (hdrsum == sum) {
6698 fin->fin_cksum = FI_CK_SUMOK;
6701 fin->fin_cksum = FI_CK_BAD;
6706 /* ------------------------------------------------------------------------ */
6707 /* Function: ipf_ifpfillv4addr */
6708 /* Returns: int - 0 = address update, -1 = address not updated */
6709 /* Parameters: atype(I) - type of network address update to perform */
6710 /* sin(I) - pointer to source of address information */
6711 /* mask(I) - pointer to source of netmask information */
6712 /* inp(I) - pointer to destination address store */
6713 /* inpmask(I) - pointer to destination netmask store */
6715 /* Given a type of network address update (atype) to perform, copy */
6716 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6717 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6718 /* which case the operation fails. For all values of atype other than */
6719 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6721 /* ------------------------------------------------------------------------ */
6723 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6725 struct sockaddr_in *sin, *mask;
6726 struct in_addr *inp, *inpmask;
6728 if (inpmask != NULL && atype != FRI_NETMASKED)
6729 inpmask->s_addr = 0xffffffff;
6731 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6732 if (atype == FRI_NETMASKED) {
6733 if (inpmask == NULL)
6735 inpmask->s_addr = mask->sin_addr.s_addr;
6737 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6739 inp->s_addr = sin->sin_addr.s_addr;
6746 /* ------------------------------------------------------------------------ */
6747 /* Function: ipf_ifpfillv6addr */
6748 /* Returns: int - 0 = address update, -1 = address not updated */
6749 /* Parameters: atype(I) - type of network address update to perform */
6750 /* sin(I) - pointer to source of address information */
6751 /* mask(I) - pointer to source of netmask information */
6752 /* inp(I) - pointer to destination address store */
6753 /* inpmask(I) - pointer to destination netmask store */
6755 /* Given a type of network address update (atype) to perform, copy */
6756 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6757 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6758 /* which case the operation fails. For all values of atype other than */
6759 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6761 /* ------------------------------------------------------------------------ */
6763 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6765 struct sockaddr_in6 *sin, *mask;
6766 i6addr_t *inp, *inpmask;
6768 i6addr_t *src, *and;
6770 src = (i6addr_t *)&sin->sin6_addr;
6771 and = (i6addr_t *)&mask->sin6_addr;
6773 if (inpmask != NULL && atype != FRI_NETMASKED) {
6774 inpmask->i6[0] = 0xffffffff;
6775 inpmask->i6[1] = 0xffffffff;
6776 inpmask->i6[2] = 0xffffffff;
6777 inpmask->i6[3] = 0xffffffff;
6780 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6781 if (atype == FRI_NETMASKED) {
6782 if (inpmask == NULL)
6784 inpmask->i6[0] = and->i6[0];
6785 inpmask->i6[1] = and->i6[1];
6786 inpmask->i6[2] = and->i6[2];
6787 inpmask->i6[3] = and->i6[3];
6790 inp->i6[0] = src->i6[0] & and->i6[0];
6791 inp->i6[1] = src->i6[1] & and->i6[1];
6792 inp->i6[2] = src->i6[2] & and->i6[2];
6793 inp->i6[3] = src->i6[3] & and->i6[3];
6795 inp->i6[0] = src->i6[0];
6796 inp->i6[1] = src->i6[1];
6797 inp->i6[2] = src->i6[2];
6798 inp->i6[3] = src->i6[3];
6805 /* ------------------------------------------------------------------------ */
6806 /* Function: ipf_matchtag */
6807 /* Returns: 0 == mismatch, 1 == match. */
6808 /* Parameters: tag1(I) - pointer to first tag to compare */
6809 /* tag2(I) - pointer to second tag to compare */
6811 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6812 /* considered to be a match or not match, respectively. The tag is 16 */
6813 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6814 /* compare the ints instead, for speed. tag1 is the master of the */
6815 /* comparison. This function should only be called with both tag1 and tag2 */
6816 /* as non-NULL pointers. */
6817 /* ------------------------------------------------------------------------ */
6819 ipf_matchtag(tag1, tag2)
6820 ipftag_t *tag1, *tag2;
6825 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6828 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6829 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6830 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6831 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6837 /* ------------------------------------------------------------------------ */
6838 /* Function: ipf_coalesce */
6839 /* Returns: 1 == success, -1 == failure, 0 == no change */
6840 /* Parameters: fin(I) - pointer to packet information */
6842 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6843 /* If this call returns a failure then the buffers have also been freed. */
6844 /* ------------------------------------------------------------------------ */
6850 if ((fin->fin_flx & FI_COALESCE) != 0)
6854 * If the mbuf pointers indicate that there is no mbuf to work with,
6855 * return but do not indicate success or failure.
6857 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6860 #if defined(_KERNEL)
6861 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6862 ipf_main_softc_t *softc = fin->fin_main_soft;
6864 DT1(frb_coalesce, fr_info_t *, fin);
6865 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6867 FREE_MB_T(*fin->fin_mp);
6869 fin->fin_reason = FRB_COALESCE;
6870 *fin->fin_mp = NULL;
6875 fin = fin; /* LINT */
6882 * The following table lists all of the tunable variables that can be
6883 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6884 * in the table below is as follows:
6886 * pointer to value, name of value, minimum, maximum, size of the value's
6887 * container, value attribute flags
6889 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6890 * means the value can only be written to when IPFilter is loaded but disabled.
6891 * The obvious implication is if neither of these are set then the value can be
6892 * changed at any time without harm.
6896 /* ------------------------------------------------------------------------ */
6897 /* Function: ipf_tune_findbycookie */
6898 /* Returns: NULL = search failed, else pointer to tune struct */
6899 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6900 /* next(O) - pointer to place to store the cookie for the */
6901 /* "next" tuneable, if it is desired. */
6903 /* This function is used to walk through all of the existing tunables with */
6904 /* successive calls. It searches the known tunables for the one which has */
6905 /* a matching value for "cookie" - ie its address. When returning a match, */
6906 /* the next one to be found may be returned inside next. */
6907 /* ------------------------------------------------------------------------ */
6908 static ipftuneable_t *
6909 ipf_tune_findbycookie(ptop, cookie, next)
6910 ipftuneable_t **ptop;
6911 void *cookie, **next;
6913 ipftuneable_t *ta, **tap;
6915 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6919 * If the next entry in the array has a name
6920 * present, then return a pointer to it for
6921 * where to go next, else return a pointer to
6922 * the dynaminc list as a key to search there
6923 * next. This facilitates a weak linking of
6924 * the two "lists" together.
6926 if ((ta + 1)->ipft_name != NULL)
6934 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6935 if (tap == cookie) {
6937 *next = &ta->ipft_next;
6947 /* ------------------------------------------------------------------------ */
6948 /* Function: ipf_tune_findbyname */
6949 /* Returns: NULL = search failed, else pointer to tune struct */
6950 /* Parameters: name(I) - name of the tuneable entry to find. */
6952 /* Search the static array of tuneables and the list of dynamic tuneables */
6953 /* for an entry with a matching name. If we can find one, return a pointer */
6954 /* to the matching structure. */
6955 /* ------------------------------------------------------------------------ */
6956 static ipftuneable_t *
6957 ipf_tune_findbyname(top, name)
6963 for (ta = top; ta != NULL; ta = ta->ipft_next)
6964 if (!strcmp(ta->ipft_name, name)) {
6972 /* ------------------------------------------------------------------------ */
6973 /* Function: ipf_tune_add_array */
6974 /* Returns: int - 0 == success, else failure */
6975 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6977 /* Appends tune structures from the array passed in (newtune) to the end of */
6978 /* the current list of "dynamic" tuneable parameters. */
6979 /* If any entry to be added is already present (by name) then the operation */
6980 /* is aborted - entries that have been added are removed before returning. */
6981 /* An entry with no name (NULL) is used as the indication that the end of */
6982 /* the array has been reached. */
6983 /* ------------------------------------------------------------------------ */
6985 ipf_tune_add_array(softc, newtune)
6986 ipf_main_softc_t *softc;
6987 ipftuneable_t *newtune;
6989 ipftuneable_t *nt, *dt;
6992 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6993 error = ipf_tune_add(softc, nt);
6995 for (dt = newtune; dt != nt; dt++) {
6996 (void) ipf_tune_del(softc, dt);
7005 /* ------------------------------------------------------------------------ */
7006 /* Function: ipf_tune_array_link */
7007 /* Returns: 0 == success, -1 == failure */
7008 /* Parameters: softc(I) - soft context pointerto work with */
7009 /* array(I) - pointer to an array of tuneables */
7011 /* Given an array of tunables (array), append them to the current list of */
7012 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7013 /* the array for being appended to the list, initialise all of the next */
7014 /* pointers so we don't need to walk parts of it with ++ and others with */
7015 /* next. The array is expected to have an entry with a NULL name as the */
7016 /* terminator. Trying to add an array with no non-NULL names will return as */
7018 /* ------------------------------------------------------------------------ */
7020 ipf_tune_array_link(softc, array)
7021 ipf_main_softc_t *softc;
7022 ipftuneable_t *array;
7024 ipftuneable_t *t, **p;
7027 if (t->ipft_name == NULL)
7030 for (; t[1].ipft_name != NULL; t++)
7031 t[0].ipft_next = &t[1];
7032 t->ipft_next = NULL;
7035 * Since a pointer to the last entry isn't kept, we need to find it
7036 * each time we want to add new variables to the list.
7038 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7039 if (t->ipft_name == NULL)
7047 /* ------------------------------------------------------------------------ */
7048 /* Function: ipf_tune_array_unlink */
7049 /* Returns: 0 == success, -1 == failure */
7050 /* Parameters: softc(I) - soft context pointerto work with */
7051 /* array(I) - pointer to an array of tuneables */
7053 /* ------------------------------------------------------------------------ */
7055 ipf_tune_array_unlink(softc, array)
7056 ipf_main_softc_t *softc;
7057 ipftuneable_t *array;
7059 ipftuneable_t *t, **p;
7061 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7067 for (; t[1].ipft_name != NULL; t++)
7076 /* ------------------------------------------------------------------------ */
7077 /* Function: ipf_tune_array_copy */
7078 /* Returns: NULL = failure, else pointer to new array */
7079 /* Parameters: base(I) - pointer to structure base */
7080 /* size(I) - size of the array at template */
7081 /* template(I) - original array to copy */
7083 /* Allocate memory for a new set of tuneable values and copy everything */
7084 /* from template into the new region of memory. The new region is full of */
7085 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7087 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7088 /* In the array template, ipftp_offset is the offset (in bytes) of the */
7089 /* location of the tuneable value inside the structure pointed to by base. */
7090 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
7091 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7092 /* ipftp_void that points to the stored value. */
7093 /* ------------------------------------------------------------------------ */
7095 ipf_tune_array_copy(base, size, template)
7098 ipftuneable_t *template;
7100 ipftuneable_t *copy;
7104 KMALLOCS(copy, ipftuneable_t *, size);
7108 bcopy(template, copy, size);
7110 for (i = 0; copy[i].ipft_name; i++) {
7111 copy[i].ipft_una.ipftp_offset += (u_long)base;
7112 copy[i].ipft_next = copy + i + 1;
7119 /* ------------------------------------------------------------------------ */
7120 /* Function: ipf_tune_add */
7121 /* Returns: int - 0 == success, else failure */
7122 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7124 /* Appends tune structures from the array passed in (newtune) to the end of */
7125 /* the current list of "dynamic" tuneable parameters. Once added, the */
7126 /* owner of the object is not expected to ever change "ipft_next". */
7127 /* ------------------------------------------------------------------------ */
7129 ipf_tune_add(softc, newtune)
7130 ipf_main_softc_t *softc;
7131 ipftuneable_t *newtune;
7133 ipftuneable_t *ta, **tap;
7135 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7141 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7144 newtune->ipft_next = NULL;
7150 /* ------------------------------------------------------------------------ */
7151 /* Function: ipf_tune_del */
7152 /* Returns: int - 0 == success, else failure */
7153 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7154 /* current dynamic tuneables */
7156 /* Search for the tune structure, by pointer, in the list of those that are */
7157 /* dynamically added at run time. If found, adjust the list so that this */
7158 /* structure is no longer part of it. */
7159 /* ------------------------------------------------------------------------ */
7161 ipf_tune_del(softc, oldtune)
7162 ipf_main_softc_t *softc;
7163 ipftuneable_t *oldtune;
7165 ipftuneable_t *ta, **tap;
7168 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7169 tap = &ta->ipft_next) {
7170 if (ta == oldtune) {
7171 *tap = oldtune->ipft_next;
7172 oldtune->ipft_next = NULL;
7185 /* ------------------------------------------------------------------------ */
7186 /* Function: ipf_tune_del_array */
7187 /* Returns: int - 0 == success, else failure */
7188 /* Parameters: oldtune - pointer to tuneables array */
7190 /* Remove each tuneable entry in the array from the list of "dynamic" */
7191 /* tunables. If one entry should fail to be found, an error will be */
7192 /* returned and no further ones removed. */
7193 /* An entry with a NULL name is used as the indicator of the last entry in */
7195 /* ------------------------------------------------------------------------ */
7197 ipf_tune_del_array(softc, oldtune)
7198 ipf_main_softc_t *softc;
7199 ipftuneable_t *oldtune;
7204 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7205 error = ipf_tune_del(softc, ot);
7215 /* ------------------------------------------------------------------------ */
7216 /* Function: ipf_tune */
7217 /* Returns: int - 0 == success, else failure */
7218 /* Parameters: cmd(I) - ioctl command number */
7219 /* data(I) - pointer to ioctl data structure */
7221 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7222 /* three ioctls provide the means to access and control global variables */
7223 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7224 /* changed without rebooting, reloading or recompiling. The initialisation */
7225 /* and 'destruction' routines of the various components of ipfilter are all */
7226 /* each responsible for handling their own values being too big. */
7227 /* ------------------------------------------------------------------------ */
7229 ipf_ipftune(softc, cmd, data)
7230 ipf_main_softc_t *softc;
7239 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7243 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7244 cookie = tu.ipft_cookie;
7249 case SIOCIPFGETNEXT :
7251 * If cookie is non-NULL, assume it to be a pointer to the last
7252 * entry we looked at, so find it (if possible) and return a
7253 * pointer to the next one after it. The last entry in the
7254 * the table is a NULL entry, so when we get to it, set cookie
7255 * to NULL and return that, indicating end of list, erstwhile
7256 * if we come in with cookie set to NULL, we are starting anew
7257 * at the front of the list.
7259 if (cookie != NULL) {
7260 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7261 cookie, &tu.ipft_cookie);
7263 ta = softc->ipf_tuners;
7264 tu.ipft_cookie = ta + 1;
7268 * Entry found, but does the data pointed to by that
7269 * row fit in what we can return?
7271 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7277 if (ta->ipft_sz == sizeof(u_long))
7278 tu.ipft_vlong = *ta->ipft_plong;
7279 else if (ta->ipft_sz == sizeof(u_int))
7280 tu.ipft_vint = *ta->ipft_pint;
7281 else if (ta->ipft_sz == sizeof(u_short))
7282 tu.ipft_vshort = *ta->ipft_pshort;
7283 else if (ta->ipft_sz == sizeof(u_char))
7284 tu.ipft_vchar = *ta->ipft_pchar;
7286 tu.ipft_sz = ta->ipft_sz;
7287 tu.ipft_min = ta->ipft_min;
7288 tu.ipft_max = ta->ipft_max;
7289 tu.ipft_flags = ta->ipft_flags;
7290 bcopy(ta->ipft_name, tu.ipft_name,
7291 MIN(sizeof(tu.ipft_name),
7292 strlen(ta->ipft_name) + 1));
7294 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7300 * Search by name or by cookie value for a particular entry
7301 * in the tuning paramter table.
7305 if (cookie != NULL) {
7306 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7310 } else if (tu.ipft_name[0] != '\0') {
7311 ta = ipf_tune_findbyname(softc->ipf_tuners,
7319 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7321 * Fetch the tuning parameters for a particular value
7324 if (ta->ipft_sz == sizeof(u_long))
7325 tu.ipft_vlong = *ta->ipft_plong;
7326 else if (ta->ipft_sz == sizeof(u_int))
7327 tu.ipft_vint = *ta->ipft_pint;
7328 else if (ta->ipft_sz == sizeof(u_short))
7329 tu.ipft_vshort = *ta->ipft_pshort;
7330 else if (ta->ipft_sz == sizeof(u_char))
7331 tu.ipft_vchar = *ta->ipft_pchar;
7332 tu.ipft_cookie = ta;
7333 tu.ipft_sz = ta->ipft_sz;
7334 tu.ipft_min = ta->ipft_min;
7335 tu.ipft_max = ta->ipft_max;
7336 tu.ipft_flags = ta->ipft_flags;
7337 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7339 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7341 * Set an internal parameter. The hard part here is
7342 * getting the new value safely and correctly out of
7343 * the kernel (given we only know its size, not type.)
7347 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7348 (softc->ipf_running > 0)) {
7355 if (in < ta->ipft_min || in > ta->ipft_max) {
7361 if (ta->ipft_func != NULL) {
7365 error = (*ta->ipft_func)(softc, ta,
7369 } else if (ta->ipft_sz == sizeof(u_long)) {
7370 tu.ipft_vlong = *ta->ipft_plong;
7371 *ta->ipft_plong = in;
7373 } else if (ta->ipft_sz == sizeof(u_int)) {
7374 tu.ipft_vint = *ta->ipft_pint;
7375 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7377 } else if (ta->ipft_sz == sizeof(u_short)) {
7378 tu.ipft_vshort = *ta->ipft_pshort;
7379 *ta->ipft_pshort = (u_short)(in & 0xffff);
7381 } else if (ta->ipft_sz == sizeof(u_char)) {
7382 tu.ipft_vchar = *ta->ipft_pchar;
7383 *ta->ipft_pchar = (u_char)(in & 0xff);
7385 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7399 /* ------------------------------------------------------------------------ */
7400 /* Function: ipf_zerostats */
7401 /* Returns: int - 0 = success, else failure */
7402 /* Parameters: data(O) - pointer to pointer for copying data back to */
7404 /* Copies the current statistics out to userspace and then zero's the */
7405 /* current ones in the kernel. The lock is only held across the bzero() as */
7406 /* the copyout may result in paging (ie network activity.) */
7407 /* ------------------------------------------------------------------------ */
7409 ipf_zerostats(softc, data)
7410 ipf_main_softc_t *softc;
7417 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7420 ipf_getstat(softc, &fio, obj.ipfo_rev);
7421 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7425 WRITE_ENTER(&softc->ipf_mutex);
7426 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7427 RWLOCK_EXIT(&softc->ipf_mutex);
7433 /* ------------------------------------------------------------------------ */
7434 /* Function: ipf_resolvedest */
7436 /* Parameters: softc(I) - pointer to soft context main structure */
7437 /* base(I) - where strings are stored */
7438 /* fdp(IO) - pointer to destination information to resolve */
7439 /* v(I) - IP protocol version to match */
7441 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7442 /* if a matching name can be found for the particular IP protocol version */
7443 /* then store the interface pointer in the frdest struct. If no match is */
7444 /* found, then set the interface pointer to be -1 as NULL is considered to */
7445 /* indicate there is no information at all in the structure. */
7446 /* ------------------------------------------------------------------------ */
7448 ipf_resolvedest(softc, base, fdp, v)
7449 ipf_main_softc_t *softc;
7459 if (fdp->fd_name != -1) {
7460 if (fdp->fd_type == FRD_DSTLIST) {
7461 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7463 base + fdp->fd_name,
7470 ifp = GETIFP(base + fdp->fd_name, v);
7481 /* ------------------------------------------------------------------------ */
7482 /* Function: ipf_resolvenic */
7483 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7484 /* pointer to interface structure for NIC */
7485 /* Parameters: softc(I)- pointer to soft context main structure */
7486 /* name(I) - complete interface name */
7487 /* v(I) - IP protocol version */
7489 /* Look for a network interface structure that firstly has a matching name */
7490 /* to that passed in and that is also being used for that IP protocol */
7491 /* version (necessary on some platforms where there are separate listings */
7492 /* for both IPv4 and IPv6 on the same physical NIC. */
7493 /* ------------------------------------------------------------------------ */
7495 ipf_resolvenic(softc, name, v)
7496 ipf_main_softc_t *softc;
7502 softc = softc; /* gcc -Wextra */
7503 if (name[0] == '\0')
7506 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7510 nic = GETIFP(name, v);
7517 /* ------------------------------------------------------------------------ */
7518 /* Function: ipf_token_expire */
7519 /* Returns: None. */
7520 /* Parameters: softc(I) - pointer to soft context main structure */
7522 /* This function is run every ipf tick to see if there are any tokens that */
7523 /* have been held for too long and need to be freed up. */
7524 /* ------------------------------------------------------------------------ */
7526 ipf_token_expire(softc)
7527 ipf_main_softc_t *softc;
7531 WRITE_ENTER(&softc->ipf_tokens);
7532 while ((it = softc->ipf_token_head) != NULL) {
7533 if (it->ipt_die > softc->ipf_ticks)
7536 ipf_token_deref(softc, it);
7538 RWLOCK_EXIT(&softc->ipf_tokens);
7542 /* ------------------------------------------------------------------------ */
7543 /* Function: ipf_token_flush */
7544 /* Returns: None. */
7545 /* Parameters: softc(I) - pointer to soft context main structure */
7547 /* Loop through all of the existing tokens and call deref to see if they */
7548 /* can be freed. Normally a function like this might just loop on */
7549 /* ipf_token_head but there is a chance that a token might have a ref count */
7550 /* of greater than one and in that case the the reference would drop twice */
7551 /* by code that is only entitled to drop it once. */
7552 /* ------------------------------------------------------------------------ */
7554 ipf_token_flush(softc)
7555 ipf_main_softc_t *softc;
7557 ipftoken_t *it, *next;
7559 WRITE_ENTER(&softc->ipf_tokens);
7560 for (it = softc->ipf_token_head; it != NULL; it = next) {
7561 next = it->ipt_next;
7562 (void) ipf_token_deref(softc, it);
7564 RWLOCK_EXIT(&softc->ipf_tokens);
7568 /* ------------------------------------------------------------------------ */
7569 /* Function: ipf_token_del */
7570 /* Returns: int - 0 = success, else error */
7571 /* Parameters: softc(I)- pointer to soft context main structure */
7572 /* type(I) - the token type to match */
7573 /* uid(I) - uid owning the token */
7574 /* ptr(I) - context pointer for the token */
7576 /* This function looks for a a token in the current list that matches up */
7577 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7578 /* call ipf_token_dewref() to remove it from the list. In the event that */
7579 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7580 /* enables debugging to distinguish between the two paths that ultimately */
7581 /* lead to a token to be deleted. */
7582 /* ------------------------------------------------------------------------ */
7584 ipf_token_del(softc, type, uid, ptr)
7585 ipf_main_softc_t *softc;
7595 WRITE_ENTER(&softc->ipf_tokens);
7596 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7597 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7598 uid == it->ipt_uid) {
7599 it->ipt_complete = 2;
7600 ipf_token_deref(softc, it);
7605 RWLOCK_EXIT(&softc->ipf_tokens);
7611 /* ------------------------------------------------------------------------ */
7612 /* Function: ipf_token_mark_complete */
7613 /* Returns: None. */
7614 /* Parameters: token(I) - pointer to token structure */
7616 /* Mark a token as being ineligable for being found with ipf_token_find. */
7617 /* ------------------------------------------------------------------------ */
7619 ipf_token_mark_complete(token)
7622 if (token->ipt_complete == 0)
7623 token->ipt_complete = 1;
7627 /* ------------------------------------------------------------------------ */
7628 /* Function: ipf_token_find */
7629 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7630 /* Parameters: softc(I)- pointer to soft context main structure */
7631 /* type(I) - the token type to match */
7632 /* uid(I) - uid owning the token */
7633 /* ptr(I) - context pointer for the token */
7635 /* This function looks for a live token in the list of current tokens that */
7636 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7637 /* allocated. If one is found then it is moved to the top of the list of */
7638 /* currently active tokens. */
7639 /* ------------------------------------------------------------------------ */
7641 ipf_token_find(softc, type, uid, ptr)
7642 ipf_main_softc_t *softc;
7646 ipftoken_t *it, *new;
7648 KMALLOC(new, ipftoken_t *);
7650 bzero((char *)new, sizeof(*new));
7652 WRITE_ENTER(&softc->ipf_tokens);
7653 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7654 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7655 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7663 RWLOCK_EXIT(&softc->ipf_tokens);
7668 it->ipt_type = type;
7676 if (it->ipt_complete > 0)
7679 ipf_token_unlink(softc, it);
7683 it->ipt_pnext = softc->ipf_token_tail;
7684 *softc->ipf_token_tail = it;
7685 softc->ipf_token_tail = &it->ipt_next;
7686 it->ipt_next = NULL;
7689 it->ipt_die = softc->ipf_ticks + 20;
7692 RWLOCK_EXIT(&softc->ipf_tokens);
7698 /* ------------------------------------------------------------------------ */
7699 /* Function: ipf_token_unlink */
7700 /* Returns: None. */
7701 /* Parameters: softc(I) - pointer to soft context main structure */
7702 /* token(I) - pointer to token structure */
7703 /* Write Locks: ipf_tokens */
7705 /* This function unlinks a token structure from the linked list of tokens */
7706 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7707 /* but the tail does due to the linked list implementation. */
7708 /* ------------------------------------------------------------------------ */
7710 ipf_token_unlink(softc, token)
7711 ipf_main_softc_t *softc;
7715 if (softc->ipf_token_tail == &token->ipt_next)
7716 softc->ipf_token_tail = token->ipt_pnext;
7718 *token->ipt_pnext = token->ipt_next;
7719 if (token->ipt_next != NULL)
7720 token->ipt_next->ipt_pnext = token->ipt_pnext;
7721 token->ipt_next = NULL;
7722 token->ipt_pnext = NULL;
7726 /* ------------------------------------------------------------------------ */
7727 /* Function: ipf_token_deref */
7728 /* Returns: int - 0 == token freed, else reference count */
7729 /* Parameters: softc(I) - pointer to soft context main structure */
7730 /* token(I) - pointer to token structure */
7731 /* Write Locks: ipf_tokens */
7733 /* Drop the reference count on the token structure and if it drops to zero, */
7734 /* call the dereference function for the token type because it is then */
7735 /* possible to free the token data structure. */
7736 /* ------------------------------------------------------------------------ */
7738 ipf_token_deref(softc, token)
7739 ipf_main_softc_t *softc;
7742 void *data, **datap;
7744 ASSERT(token->ipt_ref > 0);
7746 if (token->ipt_ref > 0)
7747 return token->ipt_ref;
7749 data = token->ipt_data;
7752 if ((data != NULL) && (data != (void *)-1)) {
7753 switch (token->ipt_type)
7755 case IPFGENITER_IPF :
7756 (void) ipf_derefrule(softc, (frentry_t **)datap);
7758 case IPFGENITER_IPNAT :
7759 WRITE_ENTER(&softc->ipf_nat);
7760 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7761 RWLOCK_EXIT(&softc->ipf_nat);
7763 case IPFGENITER_NAT :
7764 ipf_nat_deref(softc, (nat_t **)datap);
7766 case IPFGENITER_STATE :
7767 ipf_state_deref(softc, (ipstate_t **)datap);
7769 case IPFGENITER_FRAG :
7770 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7772 case IPFGENITER_NATFRAG :
7773 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7775 case IPFGENITER_HOSTMAP :
7776 WRITE_ENTER(&softc->ipf_nat);
7777 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7778 RWLOCK_EXIT(&softc->ipf_nat);
7781 ipf_lookup_iterderef(softc, token->ipt_type, data);
7786 ipf_token_unlink(softc, token);
7792 /* ------------------------------------------------------------------------ */
7793 /* Function: ipf_nextrule */
7794 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7795 /* Parameters: softc(I) - pointer to soft context main structure */
7796 /* fr(I) - pointer to filter rule */
7797 /* out(I) - 1 == out rules, 0 == input rules */
7799 /* Starting with "fr", find the next rule to visit. This includes visiting */
7800 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7801 /* last rule in the list. When walking rule lists, it is either input or */
7802 /* output rules that are returned, never both. */
7803 /* ------------------------------------------------------------------------ */
7805 ipf_nextrule(softc, active, unit, fr, out)
7806 ipf_main_softc_t *softc;
7814 if (fr != NULL && fr->fr_group != -1) {
7815 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7816 unit, active, NULL);
7820 fg = softc->ipf_groups[unit][active];
7823 while (fg != NULL) {
7824 next = fg->fg_start;
7825 while (next != NULL) {
7827 if (next->fr_flags & FR_OUTQUE)
7829 } else if (next->fr_flags & FR_INQUE) {
7832 next = next->fr_next;
7841 /* ------------------------------------------------------------------------ */
7842 /* Function: ipf_getnextrule */
7843 /* Returns: int - 0 = success, else error */
7844 /* Parameters: softc(I)- pointer to soft context main structure */
7845 /* t(I) - pointer to destination information to resolve */
7846 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7848 /* This function's first job is to bring in the ipfruleiter_t structure via */
7849 /* the ipfobj_t structure to determine what should be the next rule to */
7850 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7851 /* find the 'next rule'. This may include searching rule group lists or */
7852 /* just be as simple as looking at the 'next' field in the rule structure. */
7853 /* When we have found the rule to return, increase its reference count and */
7854 /* if we used an existing rule to get here, decrease its reference count. */
7855 /* ------------------------------------------------------------------------ */
7857 ipf_getnextrule(softc, t, ptr)
7858 ipf_main_softc_t *softc;
7862 frentry_t *fr, *next, zero;
7871 if (t == NULL || ptr == NULL) {
7876 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7880 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7884 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7888 if (it.iri_nrules == 0) {
7892 if (it.iri_rule == NULL) {
7899 if ((it.iri_inout & F_OUT) != 0)
7903 if ((it.iri_inout & F_ACIN) != 0)
7904 unit = IPL_LOGCOUNT;
7908 READ_ENTER(&softc->ipf_mutex);
7910 if (*it.iri_group == '\0') {
7911 if (unit == IPL_LOGCOUNT) {
7912 next = softc->ipf_acct[out][it.iri_active];
7914 next = softc->ipf_rules[out][it.iri_active];
7917 next = ipf_nextrule(softc, it.iri_active,
7920 fg = ipf_findgroup(softc, it.iri_group, unit,
7921 it.iri_active, NULL);
7923 next = fg->fg_start;
7930 next = ipf_nextrule(softc, it.iri_active, unit,
7934 if (next != NULL && next->fr_next != NULL)
7936 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7942 (void) ipf_derefrule(softc, &fr);
7944 obj.ipfo_type = IPFOBJ_FRENTRY;
7945 dst = (char *)it.iri_rule;
7948 obj.ipfo_size = next->fr_size;
7949 MUTEX_ENTER(&next->fr_lock);
7951 MUTEX_EXIT(&next->fr_lock);
7954 obj.ipfo_size = sizeof(frentry_t);
7955 bzero(&zero, sizeof(zero));
7959 it.iri_rule = predict ? next : NULL;
7961 ipf_token_mark_complete(t);
7963 RWLOCK_EXIT(&softc->ipf_mutex);
7966 error = ipf_outobjk(softc, &obj, next);
7967 if (error == 0 && t->ipt_data != NULL) {
7968 dst += obj.ipfo_size;
7969 if (next->fr_data != NULL) {
7972 if (next->fr_type == FR_T_IPFEXPR)
7973 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7975 dobj.ipfo_type = IPFOBJ_FRIPF;
7976 dobj.ipfo_size = next->fr_dsize;
7977 dobj.ipfo_rev = obj.ipfo_rev;
7978 dobj.ipfo_ptr = dst;
7979 error = ipf_outobjk(softc, &dobj, next->fr_data);
7983 if ((fr != NULL) && (next == &zero))
7984 (void) ipf_derefrule(softc, &fr);
7990 /* ------------------------------------------------------------------------ */
7991 /* Function: ipf_frruleiter */
7992 /* Returns: int - 0 = success, else error */
7993 /* Parameters: softc(I)- pointer to soft context main structure */
7994 /* data(I) - the token type to match */
7995 /* uid(I) - uid owning the token */
7996 /* ptr(I) - context pointer for the token */
7998 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
7999 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
8000 /* the process doing the ioctl and use that to ask for the next rule. */
8001 /* ------------------------------------------------------------------------ */
8003 ipf_frruleiter(softc, data, uid, ctx)
8004 ipf_main_softc_t *softc;
8013 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8014 if (token != NULL) {
8015 error = ipf_getnextrule(softc, token, data);
8016 WRITE_ENTER(&softc->ipf_tokens);
8017 ipf_token_deref(softc, token);
8018 RWLOCK_EXIT(&softc->ipf_tokens);
8020 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8024 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8031 /* ------------------------------------------------------------------------ */
8032 /* Function: ipf_geniter */
8033 /* Returns: int - 0 = success, else error */
8034 /* Parameters: softc(I) - pointer to soft context main structure */
8035 /* token(I) - pointer to ipftoken_t structure */
8036 /* itp(I) - pointer to iterator data */
8038 /* Decide which iterator function to call using information passed through */
8039 /* the ipfgeniter_t structure at itp. */
8040 /* ------------------------------------------------------------------------ */
8042 ipf_geniter(softc, token, itp)
8043 ipf_main_softc_t *softc;
8049 switch (itp->igi_type)
8051 case IPFGENITER_FRAG :
8052 error = ipf_frag_pkt_next(softc, token, itp);
8064 /* ------------------------------------------------------------------------ */
8065 /* Function: ipf_genericiter */
8066 /* Returns: int - 0 = success, else error */
8067 /* Parameters: softc(I)- pointer to soft context main structure */
8068 /* data(I) - the token type to match */
8069 /* uid(I) - uid owning the token */
8070 /* ptr(I) - context pointer for the token */
8072 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8073 /* ------------------------------------------------------------------------ */
8075 ipf_genericiter(softc, data, uid, ctx)
8076 ipf_main_softc_t *softc;
8084 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8088 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8089 if (token != NULL) {
8090 token->ipt_subtype = iter.igi_type;
8091 error = ipf_geniter(softc, token, &iter);
8092 WRITE_ENTER(&softc->ipf_tokens);
8093 ipf_token_deref(softc, token);
8094 RWLOCK_EXIT(&softc->ipf_tokens);
8104 /* ------------------------------------------------------------------------ */
8105 /* Function: ipf_ipf_ioctl */
8106 /* Returns: int - 0 = success, else error */
8107 /* Parameters: softc(I)- pointer to soft context main structure */
8108 /* data(I) - the token type to match */
8109 /* cmd(I) - the ioctl command number */
8110 /* mode(I) - mode flags for the ioctl */
8111 /* uid(I) - uid owning the token */
8112 /* ptr(I) - context pointer for the token */
8114 /* This function handles all of the ioctl command that are actually isssued */
8115 /* to the /dev/ipl device. */
8116 /* ------------------------------------------------------------------------ */
8118 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8119 ipf_main_softc_t *softc;
8133 if (!(mode & FWRITE)) {
8137 error = BCOPYIN(data, &tmp, sizeof(tmp));
8144 WRITE_ENTER(&softc->ipf_global);
8146 if (softc->ipf_running > 0)
8149 error = ipfattach(softc);
8151 softc->ipf_running = 1;
8153 (void) ipfdetach(softc);
8155 if (softc->ipf_running == 1)
8156 error = ipfdetach(softc);
8160 softc->ipf_running = -1;
8162 RWLOCK_EXIT(&softc->ipf_global);
8167 if (!(mode & FWRITE)) {
8173 case SIOCIPFGETNEXT :
8175 error = ipf_ipftune(softc, cmd, (void *)data);
8179 if (!(mode & FWRITE)) {
8183 error = BCOPYIN(data, &softc->ipf_flags,
8184 sizeof(softc->ipf_flags));
8193 error = BCOPYOUT(&softc->ipf_flags, data,
8194 sizeof(softc->ipf_flags));
8202 error = ipf_resolvefunc(softc, (void *)data);
8209 if (!(mode & FWRITE)) {
8213 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8214 softc->ipf_active, 1);
8221 if (!(mode & FWRITE)) {
8225 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8226 1 - softc->ipf_active, 1);
8231 if (!(mode & FWRITE)) {
8235 WRITE_ENTER(&softc->ipf_mutex);
8236 error = BCOPYOUT(&softc->ipf_active, data,
8237 sizeof(softc->ipf_active));
8242 softc->ipf_active = 1 - softc->ipf_active;
8244 RWLOCK_EXIT(&softc->ipf_mutex);
8249 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8253 ipf_getstat(softc, &fio, obj.ipfo_rev);
8254 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8258 if (!(mode & FWRITE)) {
8262 error = ipf_zerostats(softc, (caddr_t)data);
8266 if (!(mode & FWRITE)) {
8270 error = BCOPYIN(data, &tmp, sizeof(tmp));
8272 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8273 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8287 if (!(mode & FWRITE)) {
8291 error = BCOPYIN(data, &tmp, sizeof(tmp));
8293 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8294 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8308 if (!(mode & FWRITE)) {
8312 error = BCOPYIN(data, &tmp, sizeof(tmp));
8314 ipf_state_setlock(softc->ipf_state_soft, tmp);
8315 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8316 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8317 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8327 if (!(mode & FWRITE)) {
8331 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8332 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8339 #endif /* IPFILTER_LOG */
8342 if (!(mode & FWRITE)) {
8346 WRITE_ENTER(&softc->ipf_global);
8347 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8350 ipf_sync(softc, NULL);
8353 RWLOCK_EXIT(&softc->ipf_global);
8359 error = ipf_outobj(softc, (void *)data,
8360 ipf_frag_stats(softc->ipf_frag_soft),
8366 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8367 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8373 error = ipf_frruleiter(softc, data, uid, ctx);
8379 error = ipf_genericiter(softc, data, uid, ctx);
8383 case SIOCIPFDELTOK :
8384 error = BCOPYIN(data, &tmp, sizeof(tmp));
8387 error = ipf_token_del(softc, tmp, uid, ctx);
8402 /* ------------------------------------------------------------------------ */
8403 /* Function: ipf_decaps */
8404 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8405 /* flags indicating packet filtering decision. */
8406 /* Parameters: fin(I) - pointer to packet information */
8407 /* pass(I) - IP protocol version to match */
8408 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8410 /* This function is called for packets that are wrapt up in other packets, */
8411 /* for example, an IP packet that is the entire data segment for another IP */
8412 /* packet. If the basic constraints for this are satisfied, change the */
8413 /* buffer to point to the start of the inner packet and start processing */
8414 /* rules belonging to the head group this rule specifies. */
8415 /* ------------------------------------------------------------------------ */
8417 ipf_decaps(fin, pass, l5proto)
8422 fr_info_t fin2, *fino = NULL;
8428 if ((fin->fin_flx & FI_COALESCE) == 0)
8429 if (ipf_coalesce(fin) == -1)
8433 hlen = fin->fin_hlen;
8439 * In this case, the specific protocol being decapsulated
8440 * inside UDP frames comes from the rule.
8442 nh = fin->fin_fr->fr_icode;
8445 case IPPROTO_GRE : /* 47 */
8446 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8447 hlen += sizeof(grehdr_t);
8448 if (gre.gr_R|gre.gr_s)
8460 * If the routing options flag is set, validate that it is
8461 * there and bounce over it.
8464 /* This is really heavy weight and lots of room for error, */
8465 /* so for now, put it off and get the simple stuff right. */
8467 u_char off, len, *s;
8474 aplen = fin->fin_plen - hlen;
8476 af = (s[0] << 8) | s[1];
8481 if (af == 0 && len == 0) {
8492 hlen = s - (u_char *)fin->fin_dp;
8498 case IPPROTO_IPIP : /* 4 */
8503 default : /* Includes ESP, AH is special for IPv4 */
8516 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8520 #if defined(MENTAT) && defined(_KERNEL)
8526 fin->fin_plen -= elen;
8528 ip = (ip_t *)((char *)fin->fin_ip + elen);
8531 * Make sure we have at least enough data for the network layer
8535 hlen = IP_HL(ip) << 2;
8537 else if (IP_V(ip) == 6)
8538 hlen = sizeof(ip6_t);
8543 if (fin->fin_plen < hlen)
8546 fin->fin_dp = (char *)ip + hlen;
8548 if (IP_V(ip) == 4) {
8550 * Perform IPv4 header checksum validation.
8552 if (ipf_cksum((u_short *)ip, hlen))
8556 if (ipf_makefrip(hlen, ip, fin) == -1) {
8559 #if defined(MENTAT) && defined(_KERNEL)
8567 DT1(frb_decapfrip, fr_info_t *, fin);
8568 pass &= ~FR_CMDMASK;
8569 pass |= FR_BLOCK|FR_QUICK;
8570 fin->fin_reason = FRB_DECAPFRIP;
8574 pass = ipf_scanlist(fin, pass);
8577 * Copy the packet filter "result" fields out of the fr_info_t struct
8578 * that is local to the decapsulation processing and back into the
8579 * one we were called with.
8581 fino->fin_flx = fin->fin_flx;
8582 fino->fin_rev = fin->fin_rev;
8583 fino->fin_icode = fin->fin_icode;
8584 fino->fin_rule = fin->fin_rule;
8585 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8586 fino->fin_fr = fin->fin_fr;
8587 fino->fin_error = fin->fin_error;
8588 fino->fin_mp = fin->fin_mp;
8589 fino->fin_m = fin->fin_m;
8592 #if defined(MENTAT) && defined(_KERNEL)
8603 /* ------------------------------------------------------------------------ */
8604 /* Function: ipf_matcharray_load */
8605 /* Returns: int - 0 = success, else error */
8606 /* Parameters: softc(I) - pointer to soft context main structure */
8607 /* data(I) - pointer to ioctl data */
8608 /* objp(I) - ipfobj_t structure to load data into */
8609 /* arrayptr(I) - pointer to location to store array pointer */
8611 /* This function loads in a mathing array through the ipfobj_t struct that */
8612 /* describes it. Sanity checking and array size limitations are enforced */
8613 /* in this function to prevent userspace from trying to load in something */
8614 /* that is insanely big. Once the size of the array is known, the memory */
8615 /* required is malloc'd and returned through changing *arrayptr. The */
8616 /* contents of the array are verified before returning. Only in the event */
8617 /* of a successful call is the caller required to free up the malloc area. */
8618 /* ------------------------------------------------------------------------ */
8620 ipf_matcharray_load(softc, data, objp, arrayptr)
8621 ipf_main_softc_t *softc;
8626 int arraysize, *array, error;
8630 error = BCOPYIN(data, objp, sizeof(*objp));
8636 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8641 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8642 (objp->ipfo_size > 1024)) {
8647 arraysize = objp->ipfo_size * sizeof(*array);
8648 KMALLOCS(array, int *, arraysize);
8649 if (array == NULL) {
8654 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8656 KFREES(array, arraysize);
8661 if (ipf_matcharray_verify(array, arraysize) != 0) {
8662 KFREES(array, arraysize);
8672 /* ------------------------------------------------------------------------ */
8673 /* Function: ipf_matcharray_verify */
8675 /* Parameters: array(I) - pointer to matching array */
8676 /* arraysize(I) - number of elements in the array */
8678 /* Verify the contents of a matching array by stepping through each element */
8679 /* in it. The actual commands in the array are not verified for */
8680 /* correctness, only that all of the sizes are correctly within limits. */
8681 /* ------------------------------------------------------------------------ */
8683 ipf_matcharray_verify(array, arraysize)
8684 int *array, arraysize;
8686 int i, nelem, maxidx;
8689 nelem = arraysize / sizeof(*array);
8692 * Currently, it makes no sense to have an array less than 6
8693 * elements long - the initial size at the from, a single operation
8694 * (minimum 4 in length) and a trailer, for a total of 6.
8696 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8701 * Verify the size of data pointed to by array with how long
8702 * the array claims to be itself.
8704 if (array[0] * sizeof(*array) != arraysize) {
8710 * The last opcode in this array should be an IPF_EXP_END.
8712 if (array[maxidx] != IPF_EXP_END) {
8716 for (i = 1; i < maxidx; ) {
8717 e = (ipfexp_t *)(array + i);
8720 * The length of the bits to check must be at least 1
8721 * (or else there is nothing to comapre with!) and it
8722 * cannot exceed the length of the data present.
8724 if ((e->ipfe_size < 1 ) ||
8725 (e->ipfe_size + i > maxidx)) {
8734 /* ------------------------------------------------------------------------ */
8735 /* Function: ipf_fr_matcharray */
8736 /* Returns: int - 0 = match failed, else positive match */
8737 /* Parameters: fin(I) - pointer to packet information */
8738 /* array(I) - pointer to matching array */
8740 /* This function is used to apply a matching array against a packet and */
8741 /* return an indication of whether or not the packet successfully matches */
8742 /* all of the commands in it. */
8743 /* ------------------------------------------------------------------------ */
8745 ipf_fr_matcharray(fin, array)
8749 int i, n, *x, rv, p;
8756 for (; n > 0; x += 3 + x[3], rv = 0) {
8758 if (e->ipfe_cmd == IPF_EXP_END)
8763 * The upper 16 bits currently store the protocol value.
8764 * This is currently used with TCP and UDP port compares and
8765 * allows "tcp.port = 80" without requiring an explicit
8766 " "ip.pr = tcp" first.
8768 p = e->ipfe_cmd >> 16;
8769 if ((p != 0) && (p != fin->fin_p))
8772 switch (e->ipfe_cmd)
8774 case IPF_EXP_IP_PR :
8775 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8776 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8780 case IPF_EXP_IP_SRCADDR :
8781 if (fin->fin_v != 4)
8783 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8784 rv |= ((fin->fin_saddr &
8785 e->ipfe_arg0[i * 2 + 1]) ==
8786 e->ipfe_arg0[i * 2]);
8790 case IPF_EXP_IP_DSTADDR :
8791 if (fin->fin_v != 4)
8793 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8794 rv |= ((fin->fin_daddr &
8795 e->ipfe_arg0[i * 2 + 1]) ==
8796 e->ipfe_arg0[i * 2]);
8800 case IPF_EXP_IP_ADDR :
8801 if (fin->fin_v != 4)
8803 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8804 rv |= ((fin->fin_saddr &
8805 e->ipfe_arg0[i * 2 + 1]) ==
8806 e->ipfe_arg0[i * 2]) ||
8808 e->ipfe_arg0[i * 2 + 1]) ==
8809 e->ipfe_arg0[i * 2]);
8814 case IPF_EXP_IP6_SRCADDR :
8815 if (fin->fin_v != 6)
8817 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8818 rv |= IP6_MASKEQ(&fin->fin_src6,
8819 &e->ipfe_arg0[i * 8 + 4],
8820 &e->ipfe_arg0[i * 8]);
8824 case IPF_EXP_IP6_DSTADDR :
8825 if (fin->fin_v != 6)
8827 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8828 rv |= IP6_MASKEQ(&fin->fin_dst6,
8829 &e->ipfe_arg0[i * 8 + 4],
8830 &e->ipfe_arg0[i * 8]);
8834 case IPF_EXP_IP6_ADDR :
8835 if (fin->fin_v != 6)
8837 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8838 rv |= IP6_MASKEQ(&fin->fin_src6,
8839 &e->ipfe_arg0[i * 8 + 4],
8840 &e->ipfe_arg0[i * 8]) ||
8841 IP6_MASKEQ(&fin->fin_dst6,
8842 &e->ipfe_arg0[i * 8 + 4],
8843 &e->ipfe_arg0[i * 8]);
8848 case IPF_EXP_UDP_PORT :
8849 case IPF_EXP_TCP_PORT :
8850 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8851 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8852 (fin->fin_dport == e->ipfe_arg0[i]);
8856 case IPF_EXP_UDP_SPORT :
8857 case IPF_EXP_TCP_SPORT :
8858 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8859 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8863 case IPF_EXP_UDP_DPORT :
8864 case IPF_EXP_TCP_DPORT :
8865 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8866 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8870 case IPF_EXP_TCP_FLAGS :
8871 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8872 rv |= ((fin->fin_tcpf &
8873 e->ipfe_arg0[i * 2 + 1]) ==
8874 e->ipfe_arg0[i * 2]);
8888 /* ------------------------------------------------------------------------ */
8889 /* Function: ipf_queueflush */
8890 /* Returns: int - number of entries flushed (0 = none) */
8891 /* Parameters: softc(I) - pointer to soft context main structure */
8892 /* deletefn(I) - function to call to delete entry */
8893 /* ipfqs(I) - top of the list of ipf internal queues */
8894 /* userqs(I) - top of the list of user defined timeouts */
8896 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8897 /* need to try a bit harder to free up some space. The algorithm used here */
8898 /* split into two parts but both halves have the same goal: to reduce the */
8899 /* number of connections considered to be "active" to the low watermark. */
8900 /* There are two steps in doing this: */
8901 /* 1) Remove any TCP connections that are already considered to be "closed" */
8902 /* but have not yet been removed from the state table. The two states */
8903 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8904 /* candidates for this style of removal. If freeing up entries in */
8905 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8906 /* we do not go on to step 2. */
8908 /* 2) Look for the oldest entries on each timeout queue and free them if */
8909 /* they are within the given window we are considering. Where the */
8910 /* window starts and the steps taken to increase its size depend upon */
8911 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8912 /* last 30 seconds is not touched. */
8914 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8916 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8917 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8919 /* Points to note: */
8920 /* - tqe_die is the time, in the future, when entries die. */
8921 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8923 /* - tqe_touched is when the entry was last used by NAT/state */
8924 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8925 /* ipf_ticks any given timeout queue and vice versa. */
8926 /* - both tqe_die and tqe_touched increase over time */
8927 /* - timeout queues are sorted with the highest value of tqe_die at the */
8928 /* bottom and therefore the smallest values of each are at the top */
8929 /* - the pointer passed in as ipfqs should point to an array of timeout */
8930 /* queues representing each of the TCP states */
8932 /* We start by setting up a maximum range to scan for things to move of */
8933 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8934 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8935 /* we start again with a new value for "iend" and "istart". This is */
8936 /* continued until we either finish the scan of 30 second intervals or the */
8937 /* low water mark is reached. */
8938 /* ------------------------------------------------------------------------ */
8940 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8941 ipf_main_softc_t *softc;
8942 ipftq_delete_fn_t deletefn;
8943 ipftq_t *ipfqs, *userqs;
8947 u_long interval, istart, iend;
8948 ipftq_t *ifq, *ifqnext;
8949 ipftqent_t *tqe, *tqn;
8952 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8953 tqn = tqe->tqe_next;
8954 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8957 if ((*activep * 100 / size) > low) {
8958 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8959 ((tqe = tqn) != NULL); ) {
8960 tqn = tqe->tqe_next;
8961 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8966 if ((*activep * 100 / size) <= low) {
8971 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8972 * used then the operations are upgraded to floating point
8973 * and kernels don't like floating point...
8975 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8976 istart = IPF_TTLVAL(86400 * 4);
8977 interval = IPF_TTLVAL(43200);
8978 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8979 istart = IPF_TTLVAL(43200);
8980 interval = IPF_TTLVAL(1800);
8981 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8982 istart = IPF_TTLVAL(1800);
8983 interval = IPF_TTLVAL(30);
8987 if (istart > softc->ipf_ticks) {
8988 if (softc->ipf_ticks - interval < interval)
8991 istart = (softc->ipf_ticks / interval) * interval;
8994 iend = softc->ipf_ticks - interval;
8996 while ((*activep * 100 / size) > low) {
8999 try = softc->ipf_ticks - istart;
9001 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9002 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9003 if (try < tqe->tqe_touched)
9005 tqn = tqe->tqe_next;
9006 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9011 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9012 ifqnext = ifq->ifq_next;
9014 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9015 if (try < tqe->tqe_touched)
9017 tqn = tqe->tqe_next;
9018 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9024 if (interval == IPF_TTLVAL(43200)) {
9025 interval = IPF_TTLVAL(1800);
9026 } else if (interval == IPF_TTLVAL(1800)) {
9027 interval = IPF_TTLVAL(30);
9031 if (interval >= softc->ipf_ticks)
9034 iend = softc->ipf_ticks - interval;
9043 /* ------------------------------------------------------------------------ */
9044 /* Function: ipf_deliverlocal */
9045 /* Returns: int - 1 = local address, 0 = non-local address */
9046 /* Parameters: softc(I) - pointer to soft context main structure */
9047 /* ipversion(I) - IP protocol version (4 or 6) */
9048 /* ifp(I) - network interface pointer */
9049 /* ipaddr(I) - IPv4/6 destination address */
9051 /* This fucntion is used to determine in the address "ipaddr" belongs to */
9052 /* the network interface represented by ifp. */
9053 /* ------------------------------------------------------------------------ */
9055 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9056 ipf_main_softc_t *softc;
9064 if (ipversion == 4) {
9065 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9066 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9071 } else if (ipversion == 6) {
9072 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9073 if (IP6_EQ(&addr, ipaddr))
9083 /* ------------------------------------------------------------------------ */
9084 /* Function: ipf_settimeout */
9085 /* Returns: int - 0 = success, -1 = failure */
9086 /* Parameters: softc(I) - pointer to soft context main structure */
9087 /* t(I) - pointer to tuneable array entry */
9088 /* p(I) - pointer to values passed in to apply */
9090 /* This function is called to set the timeout values for each distinct */
9091 /* queue timeout that is available. When called, it calls into both the */
9092 /* state and NAT code, telling them to update their timeout queues. */
9093 /* ------------------------------------------------------------------------ */
9095 ipf_settimeout(softc, t, p)
9096 struct ipf_main_softc_s *softc;
9102 * ipf_interror should be set by the functions called here, not
9103 * by this function - it's just a middle man.
9105 if (ipf_state_settimeout(softc, t, p) == -1)
9107 if (ipf_nat_settimeout(softc, t, p) == -1)
9113 /* ------------------------------------------------------------------------ */
9114 /* Function: ipf_apply_timeout */
9115 /* Returns: int - 0 = success, -1 = failure */
9116 /* Parameters: head(I) - pointer to tuneable array entry */
9117 /* seconds(I) - pointer to values passed in to apply */
9119 /* This function applies a timeout of "seconds" to the timeout queue that */
9120 /* is pointed to by "head". All entries on this list have an expiration */
9121 /* set to be the current tick value of ipf plus the ttl. Given that this */
9122 /* function should only be called when the delta is non-zero, the task is */
9123 /* to walk the entire list and apply the change. The sort order will not */
9124 /* change. The only catch is that this is O(n) across the list, so if the */
9125 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
9126 /* could take a relatively long time to work through them all. */
9127 /* ------------------------------------------------------------------------ */
9129 ipf_apply_timeout(head, seconds)
9133 u_int oldtimeout, newtimeout;
9137 MUTEX_ENTER(&head->ifq_lock);
9138 oldtimeout = head->ifq_ttl;
9139 newtimeout = IPF_TTLVAL(seconds);
9140 delta = oldtimeout - newtimeout;
9142 head->ifq_ttl = newtimeout;
9144 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9145 tqe->tqe_die += delta;
9147 MUTEX_EXIT(&head->ifq_lock);
9151 /* ------------------------------------------------------------------------ */
9152 /* Function: ipf_settimeout_tcp */
9153 /* Returns: int - 0 = successfully applied, -1 = failed */
9154 /* Parameters: t(I) - pointer to tuneable to change */
9155 /* p(I) - pointer to new timeout information */
9156 /* tab(I) - pointer to table of TCP queues */
9158 /* This function applies the new timeout (p) to the TCP tunable (t) and */
9159 /* updates all of the entries on the relevant timeout queue by calling */
9160 /* ipf_apply_timeout(). */
9161 /* ------------------------------------------------------------------------ */
9163 ipf_settimeout_tcp(t, p, tab)
9168 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9169 !strcmp(t->ipft_name, "tcp_established")) {
9170 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9171 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9172 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9173 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9174 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9175 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9176 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9177 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9178 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9179 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9180 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9181 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9182 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9183 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9184 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9185 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9186 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9187 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9188 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9189 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9190 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9191 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9192 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9193 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9194 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9197 * ipf_interror isn't set here because it should be set
9198 * by whatever called this function.
9206 /* ------------------------------------------------------------------------ */
9207 /* Function: ipf_main_soft_create */
9208 /* Returns: NULL = failure, else success */
9209 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9211 /* Create the foundation soft context structure. In circumstances where it */
9212 /* is not required to dynamically allocate the context, a pointer can be */
9213 /* passed in (rather than NULL) to a structure to be initialised. */
9214 /* The main thing of interest is that a number of locks are initialised */
9215 /* here instead of in the where might be expected - in the relevant create */
9216 /* function elsewhere. This is done because the current locking design has */
9217 /* some areas where these locks are used outside of their module. */
9218 /* Possibly the most important exercise that is done here is setting of all */
9219 /* the timeout values, allowing them to be changed before init(). */
9220 /* ------------------------------------------------------------------------ */
9222 ipf_main_soft_create(arg)
9225 ipf_main_softc_t *softc;
9228 KMALLOC(softc, ipf_main_softc_t *);
9235 bzero((char *)softc, sizeof(*softc));
9238 * This serves as a flag as to whether or not the softc should be
9239 * free'd when _destroy is called.
9241 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9243 softc->ipf_tuners = ipf_tune_array_copy(softc,
9244 sizeof(ipf_main_tuneables),
9245 ipf_main_tuneables);
9246 if (softc->ipf_tuners == NULL) {
9247 ipf_main_soft_destroy(softc);
9251 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9252 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9253 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9254 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9255 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9256 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9257 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9258 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9259 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9261 softc->ipf_token_head = NULL;
9262 softc->ipf_token_tail = &softc->ipf_token_head;
9264 softc->ipf_tcpidletimeout = FIVE_DAYS;
9265 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9266 softc->ipf_tcplastack = IPF_TTLVAL(30);
9267 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9268 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9269 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9270 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9271 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9272 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9273 softc->ipf_udptimeout = IPF_TTLVAL(120);
9274 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9275 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9276 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9277 softc->ipf_iptimeout = IPF_TTLVAL(60);
9279 #if defined(IPFILTER_DEFAULT_BLOCK)
9280 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9282 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9284 softc->ipf_minttl = 4;
9285 softc->ipf_icmpminfragmtu = 68;
9286 softc->ipf_flags = IPF_LOGGING;
9291 /* ------------------------------------------------------------------------ */
9292 /* Function: ipf_main_soft_init */
9293 /* Returns: 0 = success, -1 = failure */
9294 /* Parameters: softc(I) - pointer to soft context main structure */
9296 /* A null-op function that exists as a placeholder so that the flow in */
9297 /* other functions is obvious. */
9298 /* ------------------------------------------------------------------------ */
9301 ipf_main_soft_init(softc)
9302 ipf_main_softc_t *softc;
9308 /* ------------------------------------------------------------------------ */
9309 /* Function: ipf_main_soft_destroy */
9311 /* Parameters: softc(I) - pointer to soft context main structure */
9313 /* Undo everything that we did in ipf_main_soft_create. */
9315 /* The most important check that needs to be made here is whether or not */
9316 /* the structure was allocated by ipf_main_soft_create() by checking what */
9317 /* value is stored in ipf_dynamic_main. */
9318 /* ------------------------------------------------------------------------ */
9321 ipf_main_soft_destroy(softc)
9322 ipf_main_softc_t *softc;
9325 RW_DESTROY(&softc->ipf_frag);
9326 RW_DESTROY(&softc->ipf_poolrw);
9327 RW_DESTROY(&softc->ipf_nat);
9328 RW_DESTROY(&softc->ipf_state);
9329 RW_DESTROY(&softc->ipf_tokens);
9330 RW_DESTROY(&softc->ipf_mutex);
9331 RW_DESTROY(&softc->ipf_global);
9332 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9333 MUTEX_DESTROY(&softc->ipf_rw);
9335 if (softc->ipf_tuners != NULL) {
9336 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9338 if (softc->ipf_dynamic_softc == 1) {
9344 /* ------------------------------------------------------------------------ */
9345 /* Function: ipf_main_soft_fini */
9346 /* Returns: 0 = success, -1 = failure */
9347 /* Parameters: softc(I) - pointer to soft context main structure */
9349 /* Clean out the rules which have been added since _init was last called, */
9350 /* the only dynamic part of the mainline. */
9351 /* ------------------------------------------------------------------------ */
9353 ipf_main_soft_fini(softc)
9354 ipf_main_softc_t *softc;
9356 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9357 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9358 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9359 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9365 /* ------------------------------------------------------------------------ */
9366 /* Function: ipf_main_load */
9367 /* Returns: 0 = success, -1 = failure */
9368 /* Parameters: none */
9370 /* Handle global initialisation that needs to be done for the base part of */
9371 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9372 /* arrays that get used by the state/NAT code. */
9373 /* ------------------------------------------------------------------------ */
9379 /* fill icmp reply type table */
9380 for (i = 0; i <= ICMP_MAXTYPE; i++)
9381 icmpreplytype4[i] = -1;
9382 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9383 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9384 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9385 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9388 /* fill icmp reply type table */
9389 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9390 icmpreplytype6[i] = -1;
9391 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9392 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9393 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9394 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9395 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9402 /* ------------------------------------------------------------------------ */
9403 /* Function: ipf_main_unload */
9404 /* Returns: 0 = success, -1 = failure */
9405 /* Parameters: none */
9407 /* A null-op function that exists as a placeholder so that the flow in */
9408 /* other functions is obvious. */
9409 /* ------------------------------------------------------------------------ */
9417 /* ------------------------------------------------------------------------ */
9418 /* Function: ipf_load_all */
9419 /* Returns: 0 = success, -1 = failure */
9420 /* Parameters: none */
9422 /* Work through all of the subsystems inside IPFilter and call the load */
9423 /* function for each in an order that won't lead to a crash :) */
9424 /* ------------------------------------------------------------------------ */
9428 if (ipf_main_load() == -1)
9431 if (ipf_state_main_load() == -1)
9434 if (ipf_nat_main_load() == -1)
9437 if (ipf_frag_main_load() == -1)
9440 if (ipf_auth_main_load() == -1)
9443 if (ipf_proxy_main_load() == -1)
9450 /* ------------------------------------------------------------------------ */
9451 /* Function: ipf_unload_all */
9452 /* Returns: 0 = success, -1 = failure */
9453 /* Parameters: none */
9455 /* Work through all of the subsystems inside IPFilter and call the unload */
9456 /* function for each in an order that won't lead to a crash :) */
9457 /* ------------------------------------------------------------------------ */
9461 if (ipf_proxy_main_unload() == -1)
9464 if (ipf_auth_main_unload() == -1)
9467 if (ipf_frag_main_unload() == -1)
9470 if (ipf_nat_main_unload() == -1)
9473 if (ipf_state_main_unload() == -1)
9476 if (ipf_main_unload() == -1)
9483 /* ------------------------------------------------------------------------ */
9484 /* Function: ipf_create_all */
9485 /* Returns: NULL = failure, else success */
9486 /* Parameters: arg(I) - pointer to soft context main structure */
9488 /* Work through all of the subsystems inside IPFilter and call the create */
9489 /* function for each in an order that won't lead to a crash :) */
9490 /* ------------------------------------------------------------------------ */
9495 ipf_main_softc_t *softc;
9497 softc = ipf_main_soft_create(arg);
9502 softc->ipf_log_soft = ipf_log_soft_create(softc);
9503 if (softc->ipf_log_soft == NULL) {
9504 ipf_destroy_all(softc);
9509 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9510 if (softc->ipf_lookup_soft == NULL) {
9511 ipf_destroy_all(softc);
9515 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9516 if (softc->ipf_sync_soft == NULL) {
9517 ipf_destroy_all(softc);
9521 softc->ipf_state_soft = ipf_state_soft_create(softc);
9522 if (softc->ipf_state_soft == NULL) {
9523 ipf_destroy_all(softc);
9527 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9528 if (softc->ipf_nat_soft == NULL) {
9529 ipf_destroy_all(softc);
9533 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9534 if (softc->ipf_frag_soft == NULL) {
9535 ipf_destroy_all(softc);
9539 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9540 if (softc->ipf_auth_soft == NULL) {
9541 ipf_destroy_all(softc);
9545 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9546 if (softc->ipf_proxy_soft == NULL) {
9547 ipf_destroy_all(softc);
9555 /* ------------------------------------------------------------------------ */
9556 /* Function: ipf_destroy_all */
9558 /* Parameters: softc(I) - pointer to soft context main structure */
9560 /* Work through all of the subsystems inside IPFilter and call the destroy */
9561 /* function for each in an order that won't lead to a crash :) */
9563 /* Every one of these functions is expected to succeed, so there is no */
9564 /* checking of return values. */
9565 /* ------------------------------------------------------------------------ */
9567 ipf_destroy_all(softc)
9568 ipf_main_softc_t *softc;
9571 if (softc->ipf_state_soft != NULL) {
9572 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9573 softc->ipf_state_soft = NULL;
9576 if (softc->ipf_nat_soft != NULL) {
9577 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9578 softc->ipf_nat_soft = NULL;
9581 if (softc->ipf_frag_soft != NULL) {
9582 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9583 softc->ipf_frag_soft = NULL;
9586 if (softc->ipf_auth_soft != NULL) {
9587 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9588 softc->ipf_auth_soft = NULL;
9591 if (softc->ipf_proxy_soft != NULL) {
9592 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9593 softc->ipf_proxy_soft = NULL;
9596 if (softc->ipf_sync_soft != NULL) {
9597 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9598 softc->ipf_sync_soft = NULL;
9601 if (softc->ipf_lookup_soft != NULL) {
9602 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9603 softc->ipf_lookup_soft = NULL;
9607 if (softc->ipf_log_soft != NULL) {
9608 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9609 softc->ipf_log_soft = NULL;
9613 ipf_main_soft_destroy(softc);
9617 /* ------------------------------------------------------------------------ */
9618 /* Function: ipf_init_all */
9619 /* Returns: 0 = success, -1 = failure */
9620 /* Parameters: softc(I) - pointer to soft context main structure */
9622 /* Work through all of the subsystems inside IPFilter and call the init */
9623 /* function for each in an order that won't lead to a crash :) */
9624 /* ------------------------------------------------------------------------ */
9627 ipf_main_softc_t *softc;
9630 if (ipf_main_soft_init(softc) == -1)
9634 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9638 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9641 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9644 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9647 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9650 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9653 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9656 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9663 /* ------------------------------------------------------------------------ */
9664 /* Function: ipf_fini_all */
9665 /* Returns: 0 = success, -1 = failure */
9666 /* Parameters: softc(I) - pointer to soft context main structure */
9668 /* Work through all of the subsystems inside IPFilter and call the fini */
9669 /* function for each in an order that won't lead to a crash :) */
9670 /* ------------------------------------------------------------------------ */
9673 ipf_main_softc_t *softc;
9676 ipf_token_flush(softc);
9678 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9681 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9684 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9687 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9690 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9693 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9696 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9700 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9704 if (ipf_main_soft_fini(softc) == -1)
9711 /* ------------------------------------------------------------------------ */
9712 /* Function: ipf_rule_expire */
9714 /* Parameters: softc(I) - pointer to soft context main structure */
9716 /* At present this function exists just to support temporary addition of */
9717 /* firewall rules. Both inactive and active lists are scanned for items to */
9718 /* purge, as by rights, the expiration is computed as soon as the rule is */
9720 /* ------------------------------------------------------------------------ */
9722 ipf_rule_expire(softc)
9723 ipf_main_softc_t *softc;
9727 if ((softc->ipf_rule_explist[0] == NULL) &&
9728 (softc->ipf_rule_explist[1] == NULL))
9731 WRITE_ENTER(&softc->ipf_mutex);
9733 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9735 * Because the list is kept sorted on insertion, the fist
9736 * one that dies in the future means no more work to do.
9738 if (fr->fr_die > softc->ipf_ticks)
9740 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9743 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9745 * Because the list is kept sorted on insertion, the fist
9746 * one that dies in the future means no more work to do.
9748 if (fr->fr_die > softc->ipf_ticks)
9750 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9753 RWLOCK_EXIT(&softc->ipf_mutex);
9757 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9758 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9761 host_node_t RBI_ZERO(ipf_rb);
9762 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9765 /* ------------------------------------------------------------------------ */
9766 /* Function: ipf_ht_node_cmp */
9767 /* Returns: int - 0 == nodes are the same, .. */
9768 /* Parameters: k1(I) - pointer to first key to compare */
9769 /* k2(I) - pointer to second key to compare */
9771 /* The "key" for the node is a combination of two fields: the address */
9772 /* family and the address itself. */
9774 /* Because we're not actually interpreting the address data, it isn't */
9775 /* necessary to convert them to/from network/host byte order. The mask is */
9776 /* just used to remove bits that aren't significant - it doesn't matter */
9777 /* where they are, as long as they're always in the same place. */
9779 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9780 /* this is where individual ones will differ the most - but not true for */
9781 /* for /48's, etc. */
9782 /* ------------------------------------------------------------------------ */
9784 ipf_ht_node_cmp(k1, k2)
9785 struct host_node_s *k1, *k2;
9789 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9793 if (k1->hn_addr.adf_family == AF_INET)
9794 return (k2->hn_addr.adf_addr.in4.s_addr -
9795 k1->hn_addr.adf_addr.in4.s_addr);
9797 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9800 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9803 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9806 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9811 /* ------------------------------------------------------------------------ */
9812 /* Function: ipf_ht_node_make_key */
9814 /* parameters: htp(I) - pointer to address tracking structure */
9815 /* key(I) - where to store masked address for lookup */
9816 /* family(I) - protocol family of address */
9817 /* addr(I) - pointer to network address */
9819 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9820 /* copy the address passed in into the key structure whilst masking out the */
9821 /* bits that we don't want. */
9823 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9824 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9825 /* have to be wary of that and not allow 32-128 to happen. */
9826 /* ------------------------------------------------------------------------ */
9828 ipf_ht_node_make_key(htp, key, family, addr)
9834 key->hn_addr.adf_family = family;
9835 if (family == AF_INET) {
9839 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9840 bits = htp->ht_netmask;
9844 mask = htonl(0xffffffff << (32 - bits));
9846 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9849 int bits = htp->ht_netmask;
9851 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9853 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9854 htonl(0xffffffff << (128 - bits));
9855 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9856 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9857 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9858 } else if (bits > 64) {
9859 key->hn_addr.adf_addr.i6[3] = 0;
9860 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9861 htonl(0xffffffff << (96 - bits));
9862 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9863 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9864 } else if (bits > 32) {
9865 key->hn_addr.adf_addr.i6[3] = 0;
9866 key->hn_addr.adf_addr.i6[2] = 0;
9867 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9868 htonl(0xffffffff << (64 - bits));
9869 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9871 key->hn_addr.adf_addr.i6[3] = 0;
9872 key->hn_addr.adf_addr.i6[2] = 0;
9873 key->hn_addr.adf_addr.i6[1] = 0;
9874 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9875 htonl(0xffffffff << (32 - bits));
9882 /* ------------------------------------------------------------------------ */
9883 /* Function: ipf_ht_node_add */
9884 /* Returns: int - 0 == success, -1 == failure */
9885 /* Parameters: softc(I) - pointer to soft context main structure */
9886 /* htp(I) - pointer to address tracking structure */
9887 /* family(I) - protocol family of address */
9888 /* addr(I) - pointer to network address */
9890 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9891 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9893 /* After preparing the key with the address information to find, look in */
9894 /* the red-black tree to see if the address is known. A successful call to */
9895 /* this function can mean one of two things: a new node was added to the */
9896 /* tree or a matching node exists and we're able to bump up its activity. */
9897 /* ------------------------------------------------------------------------ */
9899 ipf_ht_node_add(softc, htp, family, addr)
9900 ipf_main_softc_t *softc;
9908 ipf_ht_node_make_key(htp, &k, family, addr);
9910 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9912 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9914 KMALLOC(h, host_node_t *);
9917 LBUMP(ipf_rb_no_mem);
9922 * If there was a macro to initialise the RB node then that
9923 * would get used here, but there isn't...
9925 bzero((char *)h, sizeof(*h));
9926 h->hn_addr = k.hn_addr;
9927 h->hn_addr.adf_family = k.hn_addr.adf_family;
9928 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9929 htp->ht_cur_nodes++;
9931 if ((htp->ht_max_per_node != 0) &&
9932 (h->hn_active >= htp->ht_max_per_node)) {
9933 DT(ipf_rb_node_max);
9934 LBUMP(ipf_rb_node_max);
9945 /* ------------------------------------------------------------------------ */
9946 /* Function: ipf_ht_node_del */
9947 /* Returns: int - 0 == success, -1 == failure */
9948 /* parameters: htp(I) - pointer to address tracking structure */
9949 /* family(I) - protocol family of address */
9950 /* addr(I) - pointer to network address */
9952 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9953 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9955 /* Try and find the address passed in amongst the leavese on this tree to */
9956 /* be friend. If found then drop the active account for that node drops by */
9957 /* one. If that count reaches 0, it is time to free it all up. */
9958 /* ------------------------------------------------------------------------ */
9960 ipf_ht_node_del(htp, family, addr)
9968 ipf_ht_node_make_key(htp, &k, family, addr);
9970 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9975 if (h->hn_active == 0) {
9976 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9977 htp->ht_cur_nodes--;
9986 /* ------------------------------------------------------------------------ */
9987 /* Function: ipf_rb_ht_init */
9989 /* Parameters: head(I) - pointer to host tracking structure */
9991 /* Initialise the host tracking structure to be ready for use above. */
9992 /* ------------------------------------------------------------------------ */
9994 ipf_rb_ht_init(head)
9997 RBI_INIT(ipf_rb, &head->ht_root);
10001 /* ------------------------------------------------------------------------ */
10002 /* Function: ipf_rb_ht_freenode */
10004 /* Parameters: head(I) - pointer to host tracking structure */
10005 /* arg(I) - additional argument from walk caller */
10007 /* Free an actual host_node_t structure. */
10008 /* ------------------------------------------------------------------------ */
10010 ipf_rb_ht_freenode(node, arg)
10018 /* ------------------------------------------------------------------------ */
10019 /* Function: ipf_rb_ht_flush */
10021 /* Parameters: head(I) - pointer to host tracking structure */
10023 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
10024 /* and free'ing each one. */
10025 /* ------------------------------------------------------------------------ */
10027 ipf_rb_ht_flush(head)
10028 host_track_t *head;
10030 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10034 /* ------------------------------------------------------------------------ */
10035 /* Function: ipf_slowtimer */
10037 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
10039 /* Slowly expire held state for fragments. Timeouts are set * in */
10040 /* expectation of this being called twice per second. */
10041 /* ------------------------------------------------------------------------ */
10043 ipf_slowtimer(softc)
10044 ipf_main_softc_t *softc;
10047 ipf_token_expire(softc);
10048 ipf_frag_expire(softc);
10049 ipf_state_expire(softc);
10050 ipf_nat_expire(softc);
10051 ipf_auth_expire(softc);
10052 ipf_lookup_expire(softc);
10053 ipf_rule_expire(softc);
10054 ipf_sync_expire(softc);
10055 softc->ipf_ticks++;
10059 /* ------------------------------------------------------------------------ */
10060 /* Function: ipf_inet_mask_add */
10062 /* Parameters: bits(I) - pointer to nat context information */
10063 /* mtab(I) - pointer to mask hash table structure */
10065 /* When called, bits represents the mask of a new NAT rule that has just */
10066 /* been added. This function inserts a bitmask into the array of masks to */
10067 /* search when searching for a matching NAT rule for a packet. */
10068 /* Prevention of duplicate masks is achieved by checking the use count for */
10069 /* a given netmask. */
10070 /* ------------------------------------------------------------------------ */
10072 ipf_inet_mask_add(bits, mtab)
10074 ipf_v4_masktab_t *mtab;
10079 mtab->imt4_masks[bits]++;
10080 if (mtab->imt4_masks[bits] > 1)
10086 mask = 0xffffffff << (32 - bits);
10088 for (i = 0; i < 33; i++) {
10089 if (ntohl(mtab->imt4_active[i]) < mask) {
10090 for (j = 32; j > i; j--)
10091 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10092 mtab->imt4_active[i] = htonl(mask);
10100 /* ------------------------------------------------------------------------ */
10101 /* Function: ipf_inet_mask_del */
10103 /* Parameters: bits(I) - number of bits set in the netmask */
10104 /* mtab(I) - pointer to mask hash table structure */
10106 /* Remove the 32bit bitmask represented by "bits" from the collection of */
10107 /* netmasks stored inside of mtab. */
10108 /* ------------------------------------------------------------------------ */
10110 ipf_inet_mask_del(bits, mtab)
10112 ipf_v4_masktab_t *mtab;
10117 mtab->imt4_masks[bits]--;
10118 if (mtab->imt4_masks[bits] > 0)
10121 mask = htonl(0xffffffff << (32 - bits));
10122 for (i = 0; i < 33; i++) {
10123 if (mtab->imt4_active[i] == mask) {
10124 for (j = i + 1; j < 33; j++)
10125 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10130 ASSERT(mtab->imt4_max >= 0);
10135 /* ------------------------------------------------------------------------ */
10136 /* Function: ipf_inet6_mask_add */
10138 /* Parameters: bits(I) - number of bits set in mask */
10139 /* mask(I) - pointer to mask to add */
10140 /* mtab(I) - pointer to mask hash table structure */
10142 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10143 /* has just been added. This function inserts a bitmask into the array of */
10144 /* masks to search when searching for a matching NAT rule for a packet. */
10145 /* Prevention of duplicate masks is achieved by checking the use count for */
10146 /* a given netmask. */
10147 /* ------------------------------------------------------------------------ */
10149 ipf_inet6_mask_add(bits, mask, mtab)
10152 ipf_v6_masktab_t *mtab;
10157 mtab->imt6_masks[bits]++;
10158 if (mtab->imt6_masks[bits] > 1)
10169 for (i = 0; i < 129; i++) {
10170 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10171 for (j = 128; j > i; j--)
10172 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10173 mtab->imt6_active[i] = *mask;
10181 /* ------------------------------------------------------------------------ */
10182 /* Function: ipf_inet6_mask_del */
10184 /* Parameters: bits(I) - number of bits set in mask */
10185 /* mask(I) - pointer to mask to remove */
10186 /* mtab(I) - pointer to mask hash table structure */
10188 /* Remove the 128bit bitmask represented by "bits" from the collection of */
10189 /* netmasks stored inside of mtab. */
10190 /* ------------------------------------------------------------------------ */
10192 ipf_inet6_mask_del(bits, mask, mtab)
10195 ipf_v6_masktab_t *mtab;
10200 mtab->imt6_masks[bits]--;
10201 if (mtab->imt6_masks[bits] > 0)
10211 for (i = 0; i < 129; i++) {
10212 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10213 for (j = i + 1; j < 129; j++) {
10214 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10215 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10222 ASSERT(mtab->imt6_max >= 0);