4 * Copyright (C) 2012 by Darren Reed.
6 * See the IPFILTER.LICENCE file for details on licencing.
8 * Copyright 2008 Sun Microsystems.
13 #if defined(KERNEL) || defined(_KERNEL)
19 #include <sys/errno.h>
20 #include <sys/types.h>
21 #include <sys/param.h>
23 #if defined(_KERNEL) && defined(__FreeBSD_version)
24 # if !defined(IPFILTER_LKM)
25 # include "opt_inet6.h"
27 # include <sys/filio.h>
29 # include <sys/ioctl.h>
31 #if defined(__SVR4) || defined(sun) /* SOLARIS */
32 # include <sys/filio.h>
34 # include <sys/fcntl.h>
36 # include <sys/systm.h>
37 # include <sys/file.h>
43 # include <sys/file.h>
49 # include <sys/mbuf.h>
51 # include <sys/byteorder.h>
52 # if (SOLARIS2 < 5) && defined(sun)
53 # include <sys/dditypes.h>
56 # include <sys/protosw.h>
57 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66 # include <netinet/udp.h>
67 # include <netinet/ip_icmp.h>
68 #include "netinet/ip_compat.h"
70 # include <netinet/icmp6.h>
71 # if !SOLARIS && defined(_KERNEL)
72 # include <netinet6/in6_var.h>
75 #include "netinet/ip_fil.h"
76 #include "netinet/ip_nat.h"
77 #include "netinet/ip_frag.h"
78 #include "netinet/ip_state.h"
79 #include "netinet/ip_proxy.h"
80 #include "netinet/ip_auth.h"
82 # include "netinet/ip_scan.h"
84 #include "netinet/ip_sync.h"
85 #include "netinet/ip_lookup.h"
86 #include "netinet/ip_pool.h"
87 #include "netinet/ip_htable.h"
88 #ifdef IPFILTER_COMPILED
89 # include "netinet/ip_rules.h"
91 #if defined(IPFILTER_BPF) && defined(_KERNEL)
94 #if defined(__FreeBSD_version)
95 # include <sys/malloc.h>
97 #include "netinet/ipl.h"
99 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100 # include <sys/callout.h>
101 extern struct callout ipf_slowtimer_ch;
103 /* END OF INCLUDES */
106 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
107 static const char rcsid[] = "@(#)$FreeBSD$";
108 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
115 extern int blockreason;
118 #define LBUMP(x) softc->x++
119 #define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
121 static INLINE int ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122 static u_32_t ipf_checkcipso __P((fr_info_t *, u_char *, int));
123 static u_32_t ipf_checkripso __P((u_char *));
124 static u_32_t ipf_decaps __P((fr_info_t *, u_32_t, int));
126 static frentry_t *ipf_dolog __P((fr_info_t *, u_32_t *));
128 static int ipf_flushlist __P((ipf_main_softc_t *, int *,
130 static int ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
132 static ipfunc_t ipf_findfunc __P((ipfunc_t));
133 static void *ipf_findlookup __P((ipf_main_softc_t *, int,
135 i6addr_t *, i6addr_t *));
136 static frentry_t *ipf_firewall __P((fr_info_t *, u_32_t *));
137 static int ipf_fr_matcharray __P((fr_info_t *, int *));
138 static int ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
140 static void ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141 static int ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142 static int ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
144 static void ipf_getstat __P((ipf_main_softc_t *,
145 struct friostat *, int));
146 static int ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147 static void ipf_group_free __P((frgroup_t *));
148 static int ipf_grpmapfini __P((struct ipf_main_softc_s *,
150 static int ipf_grpmapinit __P((struct ipf_main_softc_s *,
152 static frentry_t *ipf_nextrule __P((ipf_main_softc_t *, int, int,
154 static int ipf_portcheck __P((frpcmp_t *, u_32_t));
155 static INLINE int ipf_pr_ah __P((fr_info_t *));
156 static INLINE void ipf_pr_esp __P((fr_info_t *));
157 static INLINE void ipf_pr_gre __P((fr_info_t *));
158 static INLINE void ipf_pr_udp __P((fr_info_t *));
159 static INLINE void ipf_pr_tcp __P((fr_info_t *));
160 static INLINE void ipf_pr_icmp __P((fr_info_t *));
161 static INLINE void ipf_pr_ipv4hdr __P((fr_info_t *));
162 static INLINE void ipf_pr_short __P((fr_info_t *, int));
163 static INLINE int ipf_pr_tcpcommon __P((fr_info_t *));
164 static INLINE int ipf_pr_udpcommon __P((fr_info_t *));
165 static void ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
167 static void ipf_rule_expire_insert __P((ipf_main_softc_t *,
169 static int ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
171 static void ipf_token_flush __P((ipf_main_softc_t *));
172 static void ipf_token_unlink __P((ipf_main_softc_t *,
174 static ipftuneable_t *ipf_tune_findbyname __P((ipftuneable_t *,
176 static ipftuneable_t *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
178 static int ipf_updateipid __P((fr_info_t *));
179 static int ipf_settimeout __P((struct ipf_main_softc_s *,
180 struct ipftuneable *,
182 #if !defined(_KERNEL) || SOLARIS
183 static int ppsratecheck(struct timeval *, int *, int);
188 * bit values for identifying presence of individual IP options
189 * All of these tables should be ordered by increasing key value on the left
190 * hand side to allow for binary searching of the array and include a trailer
191 * with a 0 for the bitmask for linear searches to easily find the end with.
193 static const struct optlist ipopts[20] = {
194 { IPOPT_NOP, 0x000001 },
195 { IPOPT_RR, 0x000002 },
196 { IPOPT_ZSU, 0x000004 },
197 { IPOPT_MTUP, 0x000008 },
198 { IPOPT_MTUR, 0x000010 },
199 { IPOPT_ENCODE, 0x000020 },
200 { IPOPT_TS, 0x000040 },
201 { IPOPT_TR, 0x000080 },
202 { IPOPT_SECURITY, 0x000100 },
203 { IPOPT_LSRR, 0x000200 },
204 { IPOPT_E_SEC, 0x000400 },
205 { IPOPT_CIPSO, 0x000800 },
206 { IPOPT_SATID, 0x001000 },
207 { IPOPT_SSRR, 0x002000 },
208 { IPOPT_ADDEXT, 0x004000 },
209 { IPOPT_VISA, 0x008000 },
210 { IPOPT_IMITD, 0x010000 },
211 { IPOPT_EIP, 0x020000 },
212 { IPOPT_FINN, 0x040000 },
217 static const struct optlist ip6exthdr[] = {
218 { IPPROTO_HOPOPTS, 0x000001 },
219 { IPPROTO_IPV6, 0x000002 },
220 { IPPROTO_ROUTING, 0x000004 },
221 { IPPROTO_FRAGMENT, 0x000008 },
222 { IPPROTO_ESP, 0x000010 },
223 { IPPROTO_AH, 0x000020 },
224 { IPPROTO_NONE, 0x000040 },
225 { IPPROTO_DSTOPTS, 0x000080 },
226 { IPPROTO_MOBILITY, 0x000100 },
232 * bit values for identifying presence of individual IP security options
234 static const struct optlist secopt[8] = {
235 { IPSO_CLASS_RES4, 0x01 },
236 { IPSO_CLASS_TOPS, 0x02 },
237 { IPSO_CLASS_SECR, 0x04 },
238 { IPSO_CLASS_RES3, 0x08 },
239 { IPSO_CLASS_CONF, 0x10 },
240 { IPSO_CLASS_UNCL, 0x20 },
241 { IPSO_CLASS_RES2, 0x40 },
242 { IPSO_CLASS_RES1, 0x80 }
245 char ipfilter_version[] = IPL_VERSION;
258 #ifdef IPFILTER_COMPILED
261 #ifdef IPFILTER_CKSUM
275 * Table of functions available for use with call rules.
277 static ipfunc_resolve_t ipf_availfuncs[] = {
278 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280 { "", NULL, NULL, NULL }
283 static ipftuneable_t ipf_main_tuneables[] = {
284 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285 "ipf_flags", 0, 0xffffffff,
286 stsizeof(ipf_main_softc_t, ipf_flags),
288 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
290 stsizeof(ipf_main_softc_t, ipf_active),
291 IPFT_RDONLY, NULL, NULL },
292 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293 "control_forwarding", 0, 1,
294 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
296 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
298 stsizeof(ipf_main_softc_t, ipf_update_ipid),
300 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
302 stsizeof(ipf_main_softc_t, ipf_chksrc),
304 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
306 stsizeof(ipf_main_softc_t, ipf_minttl),
308 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309 "icmp_minfragmtu", 0, 1,
310 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
312 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313 "default_pass", 0, 0xffffffff,
314 stsizeof(ipf_main_softc_t, ipf_pass),
316 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317 "tcp_idle_timeout", 1, 0x7fffffff,
318 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319 0, NULL, ipf_settimeout },
320 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321 "tcp_close_wait", 1, 0x7fffffff,
322 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323 0, NULL, ipf_settimeout },
324 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325 "tcp_last_ack", 1, 0x7fffffff,
326 stsizeof(ipf_main_softc_t, ipf_tcplastack),
327 0, NULL, ipf_settimeout },
328 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329 "tcp_timeout", 1, 0x7fffffff,
330 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331 0, NULL, ipf_settimeout },
332 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333 "tcp_syn_sent", 1, 0x7fffffff,
334 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335 0, NULL, ipf_settimeout },
336 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337 "tcp_syn_received", 1, 0x7fffffff,
338 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339 0, NULL, ipf_settimeout },
340 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341 "tcp_closed", 1, 0x7fffffff,
342 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343 0, NULL, ipf_settimeout },
344 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345 "tcp_half_closed", 1, 0x7fffffff,
346 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347 0, NULL, ipf_settimeout },
348 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349 "tcp_time_wait", 1, 0x7fffffff,
350 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351 0, NULL, ipf_settimeout },
352 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353 "udp_timeout", 1, 0x7fffffff,
354 stsizeof(ipf_main_softc_t, ipf_udptimeout),
355 0, NULL, ipf_settimeout },
356 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357 "udp_ack_timeout", 1, 0x7fffffff,
358 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359 0, NULL, ipf_settimeout },
360 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361 "icmp_timeout", 1, 0x7fffffff,
362 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363 0, NULL, ipf_settimeout },
364 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365 "icmp_ack_timeout", 1, 0x7fffffff,
366 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367 0, NULL, ipf_settimeout },
368 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369 "ip_timeout", 1, 0x7fffffff,
370 stsizeof(ipf_main_softc_t, ipf_iptimeout),
371 0, NULL, ipf_settimeout },
372 #if defined(INSTANCES) && defined(_KERNEL)
373 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374 "intercept_loopback", 0, 1,
375 stsizeof(ipf_main_softc_t, ipf_get_loopback),
376 0, NULL, ipf_set_loopback },
386 * The next section of code is a collection of small routines that set
387 * fields in the fr_info_t structure passed based on properties of the
388 * current packet. There are different routines for the same protocol
389 * for each of IPv4 and IPv6. Adding a new protocol, for which there
390 * will "special" inspection for setup, is now more easily done by adding
391 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392 * adding more code to a growing switch statement.
395 static INLINE int ipf_pr_ah6 __P((fr_info_t *));
396 static INLINE void ipf_pr_esp6 __P((fr_info_t *));
397 static INLINE void ipf_pr_gre6 __P((fr_info_t *));
398 static INLINE void ipf_pr_udp6 __P((fr_info_t *));
399 static INLINE void ipf_pr_tcp6 __P((fr_info_t *));
400 static INLINE void ipf_pr_icmp6 __P((fr_info_t *));
401 static INLINE void ipf_pr_ipv6hdr __P((fr_info_t *));
402 static INLINE void ipf_pr_short6 __P((fr_info_t *, int));
403 static INLINE int ipf_pr_hopopts6 __P((fr_info_t *));
404 static INLINE int ipf_pr_mobility6 __P((fr_info_t *));
405 static INLINE int ipf_pr_routing6 __P((fr_info_t *));
406 static INLINE int ipf_pr_dstopts6 __P((fr_info_t *));
407 static INLINE int ipf_pr_fragment6 __P((fr_info_t *));
408 static INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
411 /* ------------------------------------------------------------------------ */
412 /* Function: ipf_pr_short6 */
414 /* Parameters: fin(I) - pointer to packet information */
415 /* xmin(I) - minimum header size */
418 /* This is function enforces the 'is a packet too short to be legit' rule */
419 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
420 /* for ipf_pr_short() for more details. */
421 /* ------------------------------------------------------------------------ */
423 ipf_pr_short6(fin, xmin)
428 if (fin->fin_dlen < xmin)
429 fin->fin_flx |= FI_SHORT;
433 /* ------------------------------------------------------------------------ */
434 /* Function: ipf_pr_ipv6hdr */
436 /* Parameters: fin(I) - pointer to packet information */
439 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
440 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
441 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
442 /* of that possibility arising. */
443 /* ------------------------------------------------------------------------ */
448 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449 int p, go = 1, i, hdrcount;
450 fr_ip_t *fi = &fin->fin_fi;
461 fi->fi_ttl = ip6->ip6_hlim;
462 fi->fi_src.in6 = ip6->ip6_src;
463 fin->fin_crc += fi->fi_src.i6[0];
464 fin->fin_crc += fi->fi_src.i6[1];
465 fin->fin_crc += fi->fi_src.i6[2];
466 fin->fin_crc += fi->fi_src.i6[3];
467 fi->fi_dst.in6 = ip6->ip6_dst;
468 fin->fin_crc += fi->fi_dst.i6[0];
469 fin->fin_crc += fi->fi_dst.i6[1];
470 fin->fin_crc += fi->fi_dst.i6[2];
471 fin->fin_crc += fi->fi_dst.i6[3];
473 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
477 while (go && !(fin->fin_flx & FI_SHORT)) {
490 case IPPROTO_ICMPV6 :
500 case IPPROTO_HOPOPTS :
501 p = ipf_pr_hopopts6(fin);
504 case IPPROTO_MOBILITY :
505 p = ipf_pr_mobility6(fin);
508 case IPPROTO_DSTOPTS :
509 p = ipf_pr_dstopts6(fin);
512 case IPPROTO_ROUTING :
513 p = ipf_pr_routing6(fin);
526 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527 if (ip6exthdr[i].ol_val == p) {
528 fin->fin_flx |= ip6exthdr[i].ol_bit;
538 case IPPROTO_FRAGMENT :
539 p = ipf_pr_fragment6(fin);
541 * Given that the only fragments we want to let through
542 * (where fin_off != 0) are those where the non-first
543 * fragments only have data, we can safely stop looking
544 * at headers if this is a non-leading fragment.
546 if (fin->fin_off != 0)
557 * It is important to note that at this point, for the
558 * extension headers (go != 0), the entire header may not have
559 * been pulled up when the code gets to this point. This is
560 * only done for "go != 0" because the other header handlers
561 * will all pullup their complete header. The other indicator
562 * of an incomplete packet is that this was just an extension
565 if ((go != 0) && (p != IPPROTO_NONE) &&
566 (ipf_pr_pullup(fin, 0) == -1)) {
573 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574 * and destroy whatever packet was here. The caller of this function
575 * expects us to return if there is a problem with ipf_pullup.
577 if (fin->fin_m == NULL) {
578 ipf_main_softc_t *softc = fin->fin_main_soft;
580 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
587 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
590 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591 ipf_main_softc_t *softc = fin->fin_main_soft;
593 fin->fin_flx |= FI_BAD;
594 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
601 /* ------------------------------------------------------------------------ */
602 /* Function: ipf_pr_ipv6exthdr */
603 /* Returns: struct ip6_ext * - pointer to the start of the next header */
604 /* or NULL if there is a prolblem. */
605 /* Parameters: fin(I) - pointer to packet information */
606 /* multiple(I) - flag indicating yes/no if multiple occurances */
607 /* of this extension header are allowed. */
608 /* proto(I) - protocol number for this extension header */
611 /* This function embodies a number of common checks that all IPv6 extension */
612 /* headers must be subjected to. For example, making sure the packet is */
613 /* big enough for it to be in, checking if it is repeated and setting a */
614 /* flag to indicate its presence. */
615 /* ------------------------------------------------------------------------ */
616 static INLINE struct ip6_ext *
617 ipf_pr_ipv6exthdr(fin, multiple, proto)
621 ipf_main_softc_t *softc = fin->fin_main_soft;
626 fin->fin_flx |= FI_V6EXTHDR;
628 /* 8 is default length of extension hdr */
629 if ((fin->fin_dlen - 8) < 0) {
630 fin->fin_flx |= FI_SHORT;
631 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
635 if (ipf_pr_pullup(fin, 8) == -1) {
636 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
643 case IPPROTO_FRAGMENT :
647 shift = 8 + (hdr->ip6e_len << 3);
651 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
652 fin->fin_flx |= FI_BAD;
653 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
658 fin->fin_dp = (char *)fin->fin_dp + shift;
659 fin->fin_dlen -= shift;
662 * If we have seen a fragment header, do not set any flags to indicate
663 * the presence of this extension header as it has no impact on the
664 * end result until after it has been defragmented.
666 if (fin->fin_flx & FI_FRAG)
669 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670 if (ip6exthdr[i].ol_val == proto) {
672 * Most IPv6 extension headers are only allowed once.
674 if ((multiple == 0) &&
675 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676 fin->fin_flx |= FI_BAD;
677 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
679 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
687 /* ------------------------------------------------------------------------ */
688 /* Function: ipf_pr_hopopts6 */
689 /* Returns: int - value of the next header or IPPROTO_NONE if error */
690 /* Parameters: fin(I) - pointer to packet information */
693 /* This is function checks pending hop by hop options extension header */
694 /* ------------------------------------------------------------------------ */
701 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
704 return hdr->ip6e_nxt;
708 /* ------------------------------------------------------------------------ */
709 /* Function: ipf_pr_mobility6 */
710 /* Returns: int - value of the next header or IPPROTO_NONE if error */
711 /* Parameters: fin(I) - pointer to packet information */
714 /* This is function checks the IPv6 mobility extension header */
715 /* ------------------------------------------------------------------------ */
717 ipf_pr_mobility6(fin)
722 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
725 return hdr->ip6e_nxt;
729 /* ------------------------------------------------------------------------ */
730 /* Function: ipf_pr_routing6 */
731 /* Returns: int - value of the next header or IPPROTO_NONE if error */
732 /* Parameters: fin(I) - pointer to packet information */
735 /* This is function checks pending routing extension header */
736 /* ------------------------------------------------------------------------ */
741 struct ip6_routing *hdr;
743 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
747 switch (hdr->ip6r_type)
751 * Nasty extension header length?
753 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755 ipf_main_softc_t *softc = fin->fin_main_soft;
757 fin->fin_flx |= FI_BAD;
758 DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
768 return hdr->ip6r_nxt;
772 /* ------------------------------------------------------------------------ */
773 /* Function: ipf_pr_fragment6 */
774 /* Returns: int - value of the next header or IPPROTO_NONE if error */
775 /* Parameters: fin(I) - pointer to packet information */
778 /* Examine the IPv6 fragment header and extract fragment offset information.*/
780 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
782 /* packets with a fragment header can fit into. They are as follows: */
784 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
785 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
786 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
787 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
788 /* 5. [IPV6][0-n EH][FH][data] */
790 /* IPV6 = IPv6 header, FH = Fragment Header, */
791 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
793 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
794 /* scenario in which they happen is in extreme circumstances that are most */
795 /* likely to be an indication of an attack rather than normal traffic. */
796 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
797 /* are two rules that can be used to guard against type 3 packets: L4 */
798 /* headers must always be in a packet that has the offset field set to 0 */
799 /* and no packet is allowed to overlay that where offset = 0. */
800 /* ------------------------------------------------------------------------ */
802 ipf_pr_fragment6(fin)
805 ipf_main_softc_t *softc = fin->fin_main_soft;
806 struct ip6_frag *frag;
808 fin->fin_flx |= FI_FRAG;
810 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
812 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
816 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
818 * Any fragment that isn't the last fragment must have its
819 * length as a multiple of 8.
821 if ((fin->fin_plen & 7) != 0) {
822 fin->fin_flx |= FI_BAD;
823 DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
827 fin->fin_fraghdr = frag;
828 fin->fin_id = frag->ip6f_ident;
829 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830 if (fin->fin_off != 0)
831 fin->fin_flx |= FI_FRAGBODY;
834 * Jumbograms aren't handled, so the max. length is 64k
836 if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837 fin->fin_flx |= FI_BAD;
838 DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
842 * We don't know where the transport layer header (or whatever is next
843 * is), as it could be behind destination options (amongst others) so
844 * return the fragment header as the type of packet this is. Note that
845 * this effectively disables the fragment cache for > 1 protocol at a
848 return frag->ip6f_nxt;
852 /* ------------------------------------------------------------------------ */
853 /* Function: ipf_pr_dstopts6 */
854 /* Returns: int - value of the next header or IPPROTO_NONE if error */
855 /* Parameters: fin(I) - pointer to packet information */
858 /* This is function checks pending destination options extension header */
859 /* ------------------------------------------------------------------------ */
864 ipf_main_softc_t *softc = fin->fin_main_soft;
867 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
869 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
872 return hdr->ip6e_nxt;
876 /* ------------------------------------------------------------------------ */
877 /* Function: ipf_pr_icmp6 */
879 /* Parameters: fin(I) - pointer to packet information */
882 /* This routine is mainly concerned with determining the minimum valid size */
883 /* for an ICMPv6 packet. */
884 /* ------------------------------------------------------------------------ */
889 int minicmpsz = sizeof(struct icmp6_hdr);
890 struct icmp6_hdr *icmp6;
892 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893 ipf_main_softc_t *softc = fin->fin_main_soft;
895 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
899 if (fin->fin_dlen > 1) {
904 fin->fin_data[0] = *(u_short *)icmp6;
906 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907 fin->fin_flx |= FI_ICMPQUERY;
909 switch (icmp6->icmp6_type)
911 case ICMP6_ECHO_REPLY :
912 case ICMP6_ECHO_REQUEST :
913 if (fin->fin_dlen >= 6)
914 fin->fin_data[1] = icmp6->icmp6_id;
915 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
918 case ICMP6_DST_UNREACH :
919 case ICMP6_PACKET_TOO_BIG :
920 case ICMP6_TIME_EXCEEDED :
921 case ICMP6_PARAM_PROB :
922 fin->fin_flx |= FI_ICMPERR;
923 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
927 if (M_LEN(fin->fin_m) < fin->fin_plen) {
928 if (ipf_coalesce(fin) != 1)
932 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
936 * If the destination of this packet doesn't match the
937 * source of the original packet then this packet is
941 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942 if (IP6_NEQ(&fin->fin_fi.fi_dst,
943 (i6addr_t *)&ip6->ip6_src)) {
944 fin->fin_flx |= FI_BAD;
945 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
953 ipf_pr_short6(fin, minicmpsz);
954 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955 u_char p = fin->fin_p;
957 fin->fin_p = IPPROTO_ICMPV6;
964 /* ------------------------------------------------------------------------ */
965 /* Function: ipf_pr_udp6 */
967 /* Parameters: fin(I) - pointer to packet information */
970 /* Analyse the packet for IPv6/UDP properties. */
971 /* Is not expected to be called for fragmented packets. */
972 /* ------------------------------------------------------------------------ */
978 if (ipf_pr_udpcommon(fin) == 0) {
979 u_char p = fin->fin_p;
981 fin->fin_p = IPPROTO_UDP;
988 /* ------------------------------------------------------------------------ */
989 /* Function: ipf_pr_tcp6 */
991 /* Parameters: fin(I) - pointer to packet information */
994 /* Analyse the packet for IPv6/TCP properties. */
995 /* Is not expected to be called for fragmented packets. */
996 /* ------------------------------------------------------------------------ */
1002 if (ipf_pr_tcpcommon(fin) == 0) {
1003 u_char p = fin->fin_p;
1005 fin->fin_p = IPPROTO_TCP;
1006 ipf_checkv6sum(fin);
1012 /* ------------------------------------------------------------------------ */
1013 /* Function: ipf_pr_esp6 */
1015 /* Parameters: fin(I) - pointer to packet information */
1018 /* Analyse the packet for ESP properties. */
1019 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1020 /* even though the newer ESP packets must also have a sequence number that */
1021 /* is 32bits as well, it is not possible(?) to determine the version from a */
1022 /* simple packet header. */
1023 /* ------------------------------------------------------------------------ */
1029 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030 ipf_main_softc_t *softc = fin->fin_main_soft;
1032 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1038 /* ------------------------------------------------------------------------ */
1039 /* Function: ipf_pr_ah6 */
1040 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1041 /* Parameters: fin(I) - pointer to packet information */
1044 /* Analyse the packet for AH properties. */
1045 /* The minimum length is taken to be the combination of all fields in the */
1046 /* header being present and no authentication data (null algorithm used.) */
1047 /* ------------------------------------------------------------------------ */
1054 fin->fin_flx |= FI_AH;
1056 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1058 ipf_main_softc_t *softc = fin->fin_main_soft;
1060 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061 return IPPROTO_NONE;
1064 ipf_pr_short6(fin, sizeof(*ah));
1067 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068 * enough data to satisfy ah_next (the very first one.)
1074 /* ------------------------------------------------------------------------ */
1075 /* Function: ipf_pr_gre6 */
1077 /* Parameters: fin(I) - pointer to packet information */
1079 /* Analyse the packet for GRE properties. */
1080 /* ------------------------------------------------------------------------ */
1087 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088 ipf_main_softc_t *softc = fin->fin_main_soft;
1090 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1095 if (GRE_REV(gre->gr_flags) == 1)
1096 fin->fin_data[0] = gre->gr_call;
1098 #endif /* USE_INET6 */
1101 /* ------------------------------------------------------------------------ */
1102 /* Function: ipf_pr_pullup */
1103 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1104 /* Parameters: fin(I) - pointer to packet information */
1105 /* plen(I) - length (excluding L3 header) to pullup */
1107 /* Short inline function to cut down on code duplication to perform a call */
1108 /* to ipf_pullup to ensure there is the required amount of data, */
1109 /* consecutively in the packet buffer. */
1111 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1112 /* points to the first byte after the complete layer 3 header, which will */
1113 /* include all of the known extension headers for IPv6 or options for IPv4. */
1115 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1116 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1117 /* - fin_ip) to what is passed through. */
1118 /* ------------------------------------------------------------------------ */
1120 ipf_pr_pullup(fin, plen)
1124 ipf_main_softc_t *softc = fin->fin_main_soft;
1126 if (fin->fin_m != NULL) {
1127 if (fin->fin_dp != NULL)
1128 plen += (char *)fin->fin_dp -
1129 ((char *)fin->fin_ip + fin->fin_hlen);
1130 plen += fin->fin_hlen;
1131 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132 #if defined(_KERNEL)
1133 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134 DT(ipf_pullup_fail);
1135 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1138 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1140 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1142 * Fake ipf_pullup failing
1144 fin->fin_reason = FRB_PULLUP;
1145 *fin->fin_mp = NULL;
1156 /* ------------------------------------------------------------------------ */
1157 /* Function: ipf_pr_short */
1159 /* Parameters: fin(I) - pointer to packet information */
1160 /* xmin(I) - minimum header size */
1162 /* Check if a packet is "short" as defined by xmin. The rule we are */
1163 /* applying here is that the packet must not be fragmented within the layer */
1164 /* 4 header. That is, it must not be a fragment that has its offset set to */
1165 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1166 /* entire layer 4 header must be present (min). */
1167 /* ------------------------------------------------------------------------ */
1169 ipf_pr_short(fin, xmin)
1174 if (fin->fin_off == 0) {
1175 if (fin->fin_dlen < xmin)
1176 fin->fin_flx |= FI_SHORT;
1177 } else if (fin->fin_off < xmin) {
1178 fin->fin_flx |= FI_SHORT;
1183 /* ------------------------------------------------------------------------ */
1184 /* Function: ipf_pr_icmp */
1186 /* Parameters: fin(I) - pointer to packet information */
1189 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1190 /* except extrememly bad packets, both type and code will be present. */
1191 /* The expected minimum size of an ICMP packet is very much dependent on */
1192 /* the type of it. */
1194 /* XXX - other ICMP sanity checks? */
1195 /* ------------------------------------------------------------------------ */
1200 ipf_main_softc_t *softc = fin->fin_main_soft;
1201 int minicmpsz = sizeof(struct icmp);
1205 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1207 if (fin->fin_off != 0) {
1208 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1212 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1219 fin->fin_data[0] = *(u_short *)icmp;
1220 fin->fin_data[1] = icmp->icmp_id;
1222 switch (icmp->icmp_type)
1224 case ICMP_ECHOREPLY :
1226 /* Router discovery messaes - RFC 1256 */
1227 case ICMP_ROUTERADVERT :
1228 case ICMP_ROUTERSOLICIT :
1229 fin->fin_flx |= FI_ICMPQUERY;
1230 minicmpsz = ICMP_MINLEN;
1233 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234 * 3 * timestamp(3 * 4)
1237 case ICMP_TSTAMPREPLY :
1238 fin->fin_flx |= FI_ICMPQUERY;
1242 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1246 case ICMP_IREQREPLY :
1248 case ICMP_MASKREPLY :
1249 fin->fin_flx |= FI_ICMPQUERY;
1253 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1257 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259 fin->fin_flx |= FI_BAD;
1260 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1265 case ICMP_SOURCEQUENCH :
1266 case ICMP_REDIRECT :
1267 case ICMP_TIMXCEED :
1268 case ICMP_PARAMPROB :
1269 fin->fin_flx |= FI_ICMPERR;
1270 if (ipf_coalesce(fin) != 1) {
1271 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1276 * ICMP error packets should not be generated for IP
1277 * packets that are a fragment that isn't the first
1280 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282 fin->fin_flx |= FI_BAD;
1283 DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1287 * If the destination of this packet doesn't match the
1288 * source of the original packet then this packet is
1291 if (oip->ip_src.s_addr != fin->fin_daddr) {
1292 fin->fin_flx |= FI_BAD;
1293 DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1300 ipf_pr_short(fin, minicmpsz);
1302 ipf_checkv4sum(fin);
1306 /* ------------------------------------------------------------------------ */
1307 /* Function: ipf_pr_tcpcommon */
1308 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1309 /* Parameters: fin(I) - pointer to packet information */
1311 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1312 /* and make some checks with how they interact with other fields. */
1313 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1314 /* valid and mark the packet as bad if not. */
1315 /* ------------------------------------------------------------------------ */
1317 ipf_pr_tcpcommon(fin)
1320 ipf_main_softc_t *softc = fin->fin_main_soft;
1324 fin->fin_flx |= FI_TCPUDP;
1325 if (fin->fin_off != 0) {
1326 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1330 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1336 if (fin->fin_dlen > 3) {
1337 fin->fin_sport = ntohs(tcp->th_sport);
1338 fin->fin_dport = ntohs(tcp->th_dport);
1341 if ((fin->fin_flx & FI_SHORT) != 0) {
1342 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1347 * Use of the TCP data offset *must* result in a value that is at
1348 * least the same size as the TCP header.
1350 tlen = TCP_OFF(tcp) << 2;
1351 if (tlen < sizeof(tcphdr_t)) {
1352 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353 fin->fin_flx |= FI_BAD;
1354 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1358 flags = tcp->th_flags;
1359 fin->fin_tcpf = tcp->th_flags;
1362 * If the urgent flag is set, then the urgent pointer must
1363 * also be set and vice versa. Good TCP packets do not have
1364 * just one of these set.
1366 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367 fin->fin_flx |= FI_BAD;
1368 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1370 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1372 * Ignore this case (#if 0) as it shows up in "real"
1373 * traffic with bogus values in the urgent pointer field.
1375 fin->fin_flx |= FI_BAD;
1376 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1378 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381 fin->fin_flx |= FI_BAD;
1382 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1384 } else if (((flags & TH_SYN) != 0) &&
1385 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1387 * SYN with URG and PUSH set is not for normal TCP but it is
1388 * possible(?) with T/TCP...but who uses T/TCP?
1390 fin->fin_flx |= FI_BAD;
1391 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1393 } else if (!(flags & TH_ACK)) {
1395 * If the ack bit isn't set, then either the SYN or
1396 * RST bit must be set. If the SYN bit is set, then
1397 * we expect the ACK field to be 0. If the ACK is
1398 * not set and if URG, PSH or FIN are set, consdier
1399 * that to indicate a bad TCP packet.
1401 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1403 * Cisco PIX sets the ACK field to a random value.
1404 * In light of this, do not set FI_BAD until a patch
1405 * is available from Cisco to ensure that
1406 * interoperability between existing systems is
1409 /*fin->fin_flx |= FI_BAD*/;
1410 /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411 } else if (!(flags & (TH_RST|TH_SYN))) {
1412 fin->fin_flx |= FI_BAD;
1413 DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415 fin->fin_flx |= FI_BAD;
1416 DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1419 if (fin->fin_flx & FI_BAD) {
1420 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1425 * At this point, it's not exactly clear what is to be gained by
1426 * marking up which TCP options are and are not present. The one we
1427 * are most interested in is the TCP window scale. This is only in
1428 * a SYN packet [RFC1323] so we don't need this here...?
1429 * Now if we were to analyse the header for passive fingerprinting,
1430 * then that might add some weight to adding this...
1432 if (tlen == sizeof(tcphdr_t)) {
1436 if (ipf_pr_pullup(fin, tlen) == -1) {
1437 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1444 s = (u_char *)(tcp + 1);
1445 off = IP_HL(ip) << 2;
1447 if (fin->fin_mp != NULL) {
1448 mb_t *m = *fin->fin_mp;
1450 if (off + tlen > M_LEN(m))
1454 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1458 else if (opt == TCPOPT_NOP)
1464 if (ol < 2 || ol > tlen)
1468 for (i = 9, mv = 4; mv >= 0; ) {
1470 if (opt == (u_char)op->ol_val) {
1471 optmsk |= op->ol_bit;
1485 /* ------------------------------------------------------------------------ */
1486 /* Function: ipf_pr_udpcommon */
1487 /* Returns: int - 0 = header ok, 1 = bad packet */
1488 /* Parameters: fin(I) - pointer to packet information */
1490 /* Extract the UDP source and destination ports, if present. If compiled */
1491 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1492 /* ------------------------------------------------------------------------ */
1494 ipf_pr_udpcommon(fin)
1499 fin->fin_flx |= FI_TCPUDP;
1501 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503 ipf_main_softc_t *softc = fin->fin_main_soft;
1505 fin->fin_flx |= FI_SHORT;
1506 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1512 fin->fin_sport = ntohs(udp->uh_sport);
1513 fin->fin_dport = ntohs(udp->uh_dport);
1520 /* ------------------------------------------------------------------------ */
1521 /* Function: ipf_pr_tcp */
1523 /* Parameters: fin(I) - pointer to packet information */
1526 /* Analyse the packet for IPv4/TCP properties. */
1527 /* ------------------------------------------------------------------------ */
1533 ipf_pr_short(fin, sizeof(tcphdr_t));
1535 if (ipf_pr_tcpcommon(fin) == 0)
1536 ipf_checkv4sum(fin);
1540 /* ------------------------------------------------------------------------ */
1541 /* Function: ipf_pr_udp */
1543 /* Parameters: fin(I) - pointer to packet information */
1546 /* Analyse the packet for IPv4/UDP properties. */
1547 /* ------------------------------------------------------------------------ */
1553 ipf_pr_short(fin, sizeof(udphdr_t));
1555 if (ipf_pr_udpcommon(fin) == 0)
1556 ipf_checkv4sum(fin);
1560 /* ------------------------------------------------------------------------ */
1561 /* Function: ipf_pr_esp */
1563 /* Parameters: fin(I) - pointer to packet information */
1565 /* Analyse the packet for ESP properties. */
1566 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1567 /* even though the newer ESP packets must also have a sequence number that */
1568 /* is 32bits as well, it is not possible(?) to determine the version from a */
1569 /* simple packet header. */
1570 /* ------------------------------------------------------------------------ */
1576 if (fin->fin_off == 0) {
1577 ipf_pr_short(fin, 8);
1578 if (ipf_pr_pullup(fin, 8) == -1) {
1579 ipf_main_softc_t *softc = fin->fin_main_soft;
1581 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1587 /* ------------------------------------------------------------------------ */
1588 /* Function: ipf_pr_ah */
1589 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1590 /* Parameters: fin(I) - pointer to packet information */
1592 /* Analyse the packet for AH properties. */
1593 /* The minimum length is taken to be the combination of all fields in the */
1594 /* header being present and no authentication data (null algorithm used.) */
1595 /* ------------------------------------------------------------------------ */
1600 ipf_main_softc_t *softc = fin->fin_main_soft;
1604 fin->fin_flx |= FI_AH;
1605 ipf_pr_short(fin, sizeof(*ah));
1607 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609 return IPPROTO_NONE;
1612 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613 DT(fr_v4_ah_pullup_1);
1614 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615 return IPPROTO_NONE;
1618 ah = (authhdr_t *)fin->fin_dp;
1620 len = (ah->ah_plen + 2) << 2;
1621 ipf_pr_short(fin, len);
1622 if (ipf_pr_pullup(fin, len) == -1) {
1623 DT(fr_v4_ah_pullup_2);
1624 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625 return IPPROTO_NONE;
1629 * Adjust fin_dp and fin_dlen for skipping over the authentication
1632 fin->fin_dp = (char *)fin->fin_dp + len;
1633 fin->fin_dlen -= len;
1638 /* ------------------------------------------------------------------------ */
1639 /* Function: ipf_pr_gre */
1641 /* Parameters: fin(I) - pointer to packet information */
1643 /* Analyse the packet for GRE properties. */
1644 /* ------------------------------------------------------------------------ */
1649 ipf_main_softc_t *softc = fin->fin_main_soft;
1652 ipf_pr_short(fin, sizeof(grehdr_t));
1654 if (fin->fin_off != 0) {
1655 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1659 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1665 if (GRE_REV(gre->gr_flags) == 1)
1666 fin->fin_data[0] = gre->gr_call;
1670 /* ------------------------------------------------------------------------ */
1671 /* Function: ipf_pr_ipv4hdr */
1673 /* Parameters: fin(I) - pointer to packet information */
1676 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1677 /* Check all options present and flag their presence if any exist. */
1678 /* ------------------------------------------------------------------------ */
1683 u_short optmsk = 0, secmsk = 0, auth = 0;
1684 int hlen, ol, mv, p, i;
1685 const struct optlist *op;
1692 hlen = fin->fin_hlen;
1698 fi->fi_tos = ip->ip_tos;
1699 fin->fin_id = ip->ip_id;
1700 off = ntohs(ip->ip_off);
1702 /* Get both TTL and protocol */
1703 fi->fi_p = ip->ip_p;
1704 fi->fi_ttl = ip->ip_ttl;
1706 /* Zero out bits not used in IPv6 address */
1707 fi->fi_src.i6[1] = 0;
1708 fi->fi_src.i6[2] = 0;
1709 fi->fi_src.i6[3] = 0;
1710 fi->fi_dst.i6[1] = 0;
1711 fi->fi_dst.i6[2] = 0;
1712 fi->fi_dst.i6[3] = 0;
1714 fi->fi_saddr = ip->ip_src.s_addr;
1715 fin->fin_crc += fi->fi_saddr;
1716 fi->fi_daddr = ip->ip_dst.s_addr;
1717 fin->fin_crc += fi->fi_daddr;
1718 if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1722 * set packet attribute flags based on the offset and
1723 * calculate the byte offset that it represents.
1725 off &= IP_MF|IP_OFFMASK;
1727 int morefrag = off & IP_MF;
1729 fi->fi_flx |= FI_FRAG;
1731 if (off == 1 && p == IPPROTO_TCP) {
1732 fin->fin_flx |= FI_SHORT; /* RFC 3128 */
1733 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1736 fin->fin_flx |= FI_FRAGBODY;
1738 if ((off + fin->fin_dlen > 65535) ||
1739 (fin->fin_dlen == 0) ||
1740 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1742 * The length of the packet, starting at its
1743 * offset cannot exceed 65535 (0xffff) as the
1744 * length of an IP packet is only 16 bits.
1746 * Any fragment that isn't the last fragment
1747 * must have a length greater than 0 and it
1748 * must be an even multiple of 8.
1750 fi->fi_flx |= FI_BAD;
1751 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1758 * Call per-protocol setup and checking
1760 if (p == IPPROTO_AH) {
1762 * Treat AH differently because we expect there to be another
1763 * layer 4 header after it.
1792 * If it is a standard IP header (no options), set the flag fields
1793 * which relate to options to 0.
1795 if (hlen == sizeof(*ip)) {
1803 * So the IP header has some IP options attached. Walk the entire
1804 * list of options present with this packet and set flags to indicate
1805 * which ones are here and which ones are not. For the somewhat out
1806 * of date and obscure security classification options, set a flag to
1807 * represent which classification is present.
1809 fi->fi_flx |= FI_OPTIONS;
1811 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1815 else if (opt == IPOPT_NOP)
1821 if (ol < 2 || ol > hlen)
1824 for (i = 9, mv = 4; mv >= 0; ) {
1827 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1832 case IPOPT_SECURITY :
1833 if (optmsk & op->ol_bit) {
1834 fin->fin_flx |= FI_BAD;
1835 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1837 doi = ipf_checkripso(s);
1839 auth = doi & 0xffff;
1845 if (optmsk & op->ol_bit) {
1846 fin->fin_flx |= FI_BAD;
1847 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1849 doi = ipf_checkcipso(fin,
1852 auth = doi & 0xffff;
1856 optmsk |= op->ol_bit;
1859 if (opt < op->ol_val)
1872 if (auth && !(auth & 0x0100))
1874 fi->fi_optmsk = optmsk;
1875 fi->fi_secmsk = secmsk;
1880 /* ------------------------------------------------------------------------ */
1881 /* Function: ipf_checkripso */
1883 /* Parameters: s(I) - pointer to start of RIPSO option */
1885 /* ------------------------------------------------------------------------ */
1890 const struct optlist *sp;
1891 u_short secmsk = 0, auth = 0;
1895 sec = *(s + 2); /* classification */
1896 for (j = 3, m = 2; m >= 0; ) {
1898 if (sec == sp->ol_val) {
1899 secmsk |= sp->ol_bit;
1905 if (sec < sp->ol_val)
1912 return (secmsk << 16) | auth;
1916 /* ------------------------------------------------------------------------ */
1917 /* Function: ipf_checkcipso */
1918 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1919 /* Parameters: fin(IO) - pointer to packet information */
1920 /* s(I) - pointer to start of CIPSO option */
1921 /* ol(I) - length of CIPSO option field */
1923 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1924 /* header and returns that whilst also storing the highest sensitivity */
1925 /* value found in the fr_info_t structure. */
1927 /* No attempt is made to extract the category bitmaps as these are defined */
1928 /* by the user (rather than the protocol) and can be rather numerous on the */
1930 /* ------------------------------------------------------------------------ */
1932 ipf_checkcipso(fin, s, ol)
1937 ipf_main_softc_t *softc = fin->fin_main_soft;
1940 u_char *t, tag, tlen, sensitivity;
1943 if (ol < 6 || ol > 40) {
1944 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1945 fin->fin_flx |= FI_BAD;
1946 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1951 fi->fi_sensitivity = 0;
1953 * The DOI field MUST be there.
1955 bcopy(s + 2, &doi, sizeof(doi));
1957 t = (u_char *)s + 6;
1958 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1961 if (tlen > len || tlen < 4 || tlen > 34) {
1962 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1963 fin->fin_flx |= FI_BAD;
1964 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1970 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1971 * draft (16 July 1992) that has expired.
1974 fin->fin_flx |= FI_BAD;
1975 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1977 } else if (tag == 1) {
1978 if (*(t + 2) != 0) {
1979 fin->fin_flx |= FI_BAD;
1980 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1983 sensitivity = *(t + 3);
1984 /* Category bitmap for categories 0-239 */
1986 } else if (tag == 4) {
1987 if (*(t + 2) != 0) {
1988 fin->fin_flx |= FI_BAD;
1989 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1992 sensitivity = *(t + 3);
1993 /* Enumerated categories, 16bits each, upto 15 */
1995 } else if (tag == 5) {
1996 if (*(t + 2) != 0) {
1997 fin->fin_flx |= FI_BAD;
1998 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
2001 sensitivity = *(t + 3);
2002 /* Range of categories (2*16bits), up to 7 pairs */
2004 } else if (tag > 127) {
2005 /* Custom defined DOI */
2008 fin->fin_flx |= FI_BAD;
2009 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2013 if (sensitivity > fi->fi_sensitivity)
2014 fi->fi_sensitivity = sensitivity;
2021 /* ------------------------------------------------------------------------ */
2022 /* Function: ipf_makefrip */
2023 /* Returns: int - 0 == packet ok, -1 == packet freed */
2024 /* Parameters: hlen(I) - length of IP packet header */
2025 /* ip(I) - pointer to the IP header */
2026 /* fin(IO) - pointer to packet information */
2028 /* Compact the IP header into a structure which contains just the info. */
2029 /* which is useful for comparing IP headers with and store this information */
2030 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
2031 /* this function will be called with either an IPv4 or IPv6 packet. */
2032 /* ------------------------------------------------------------------------ */
2034 ipf_makefrip(hlen, ip, fin)
2039 ipf_main_softc_t *softc = fin->fin_main_soft;
2043 fin->fin_hlen = (u_short)hlen;
2045 fin->fin_rule = 0xffffffff;
2046 fin->fin_group[0] = -1;
2047 fin->fin_group[1] = '\0';
2048 fin->fin_dp = (char *)ip + hlen;
2052 fin->fin_plen = ntohs(ip->ip_len);
2053 fin->fin_dlen = fin->fin_plen - hlen;
2054 ipf_pr_ipv4hdr(fin);
2056 } else if (v == 6) {
2057 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2058 fin->fin_dlen = fin->fin_plen;
2059 fin->fin_plen += hlen;
2061 ipf_pr_ipv6hdr(fin);
2064 if (fin->fin_ip == NULL) {
2065 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2072 /* ------------------------------------------------------------------------ */
2073 /* Function: ipf_portcheck */
2074 /* Returns: int - 1 == port matched, 0 == port match failed */
2075 /* Parameters: frp(I) - pointer to port check `expression' */
2076 /* pop(I) - port number to evaluate */
2078 /* Perform a comparison of a port number against some other(s), using a */
2079 /* structure with compare information stored in it. */
2080 /* ------------------------------------------------------------------------ */
2082 ipf_portcheck(frp, pop)
2092 * Do opposite test to that required and continue if that succeeds.
2094 switch (frp->frp_cmp)
2097 if (pop != po) /* EQUAL */
2101 if (pop == po) /* NOTEQUAL */
2105 if (pop >= po) /* LESSTHAN */
2109 if (pop <= po) /* GREATERTHAN */
2113 if (pop > po) /* LT or EQ */
2117 if (pop < po) /* GT or EQ */
2121 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2125 if (pop <= po || pop >= frp->frp_top) /* In range */
2129 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2139 /* ------------------------------------------------------------------------ */
2140 /* Function: ipf_tcpudpchk */
2141 /* Returns: int - 1 == protocol matched, 0 == check failed */
2142 /* Parameters: fda(I) - pointer to packet information */
2143 /* ft(I) - pointer to structure with comparison data */
2145 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2146 /* structure containing information that we want to match against. */
2147 /* ------------------------------------------------------------------------ */
2149 ipf_tcpudpchk(fi, ft)
2156 * Both ports should *always* be in the first fragment.
2157 * So far, I cannot find any cases where they can not be.
2159 * compare destination ports
2162 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2165 * compare source ports
2167 if (err && ft->ftu_scmp)
2168 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2171 * If we don't have all the TCP/UDP header, then how can we
2172 * expect to do any sort of match on it ? If we were looking for
2173 * TCP flags, then NO match. If not, then match (which should
2174 * satisfy the "short" class too).
2176 if (err && (fi->fi_p == IPPROTO_TCP)) {
2177 if (fi->fi_flx & FI_SHORT)
2178 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2180 * Match the flags ? If not, abort this match.
2182 if (ft->ftu_tcpfm &&
2183 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2184 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2185 ft->ftu_tcpfm, ft->ftu_tcpf));
2193 /* ------------------------------------------------------------------------ */
2194 /* Function: ipf_check_ipf */
2195 /* Returns: int - 0 == match, else no match */
2196 /* Parameters: fin(I) - pointer to packet information */
2197 /* fr(I) - pointer to filter rule */
2198 /* portcmp(I) - flag indicating whether to attempt matching on */
2199 /* TCP/UDP port data. */
2201 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2202 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2203 /* this function. */
2204 /* ------------------------------------------------------------------------ */
2206 ipf_check_ipf(fin, fr, portcmp)
2211 u_32_t *ld, *lm, *lip;
2219 lm = (u_32_t *)&fri->fri_mip;
2220 ld = (u_32_t *)&fri->fri_ip;
2223 * first 32 bits to check coversion:
2224 * IP version, TOS, TTL, protocol
2226 i = ((*lip & *lm) != *ld);
2227 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2228 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2233 * Next 32 bits is a constructed bitmask indicating which IP options
2234 * are present (if any) in this packet.
2237 i = ((*lip & *lm) != *ld);
2238 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2239 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2245 * Unrolled loops (4 each, for 32 bits) for address checks.
2248 * Check the source address.
2250 if (fr->fr_satype == FRI_LOOKUP) {
2251 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2252 fi->fi_v, lip, fin->fin_plen);
2259 i = ((*lip & *lm) != *ld);
2260 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2261 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262 if (fi->fi_v == 6) {
2264 i |= ((*lip & *lm) != *ld);
2265 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2266 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2268 i |= ((*lip & *lm) != *ld);
2269 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2270 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2272 i |= ((*lip & *lm) != *ld);
2273 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2274 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2281 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2286 * Check the destination address.
2289 if (fr->fr_datype == FRI_LOOKUP) {
2290 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2291 fi->fi_v, lip, fin->fin_plen);
2298 i = ((*lip & *lm) != *ld);
2299 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2300 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2301 if (fi->fi_v == 6) {
2303 i |= ((*lip & *lm) != *ld);
2304 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2305 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2307 i |= ((*lip & *lm) != *ld);
2308 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2309 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2311 i |= ((*lip & *lm) != *ld);
2312 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2313 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2320 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2324 * IP addresses matched. The next 32bits contains:
2325 * mast of old IP header security & authentication bits.
2328 i = (*ld - (*lip & *lm));
2329 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2332 * Next we have 32 bits of packet flags.
2335 i |= (*ld - (*lip & *lm));
2336 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2340 * If a fragment, then only the first has what we're
2341 * looking for here...
2344 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2347 if (fr->fr_dcmp || fr->fr_scmp ||
2348 fr->fr_tcpf || fr->fr_tcpfm)
2350 if (fr->fr_icmpm || fr->fr_icmp) {
2351 if (((fi->fi_p != IPPROTO_ICMP) &&
2352 (fi->fi_p != IPPROTO_ICMPV6)) ||
2353 fin->fin_off || (fin->fin_dlen < 2))
2355 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2357 FR_DEBUG(("i. %#x & %#x != %#x\n",
2359 fr->fr_icmpm, fr->fr_icmp));
2369 /* ------------------------------------------------------------------------ */
2370 /* Function: ipf_scanlist */
2371 /* Returns: int - result flags of scanning filter list */
2372 /* Parameters: fin(I) - pointer to packet information */
2373 /* pass(I) - default result to return for filtering */
2375 /* Check the input/output list of rules for a match to the current packet. */
2376 /* If a match is found, the value of fr_flags from the rule becomes the */
2377 /* return value and fin->fin_fr points to the matched rule. */
2379 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2380 /* When unwinding, it should finish up with fin_depth as 0. */
2382 /* Could be per interface, but this gets real nasty when you don't have, */
2383 /* or can't easily change, the kernel source code to . */
2384 /* ------------------------------------------------------------------------ */
2386 ipf_scanlist(fin, pass)
2390 ipf_main_softc_t *softc = fin->fin_main_soft;
2391 int rulen, portcmp, off, skip;
2392 struct frentry *fr, *fnext;
2393 u_32_t passt, passo;
2396 * Do not allow nesting deeper than 16 levels.
2398 if (fin->fin_depth >= 16)
2404 * If there are no rules in this list, return now.
2415 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2418 for (rulen = 0; fr; fr = fnext, rulen++) {
2419 fnext = fr->fr_next;
2421 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2427 * In all checks below, a null (zero) value in the
2428 * filter struture is taken to mean a wildcard.
2430 * check that we are working for the right interface
2433 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2436 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2438 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2439 FR_ISPASS(pass) ? 'p' :
2440 FR_ISACCOUNT(pass) ? 'A' :
2441 FR_ISAUTH(pass) ? 'a' :
2442 (pass & FR_NOMATCH) ? 'n' :'b'));
2443 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2448 switch (fr->fr_type)
2451 case FR_T_IPF_BUILTIN :
2452 if (ipf_check_ipf(fin, fr, portcmp))
2455 #if defined(IPFILTER_BPF)
2457 case FR_T_BPFOPC_BUILTIN :
2462 if (*fin->fin_mp == NULL)
2464 if (fin->fin_family != fr->fr_family)
2466 mc = (u_char *)fin->fin_m;
2467 wlen = fin->fin_dlen + fin->fin_hlen;
2468 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2473 case FR_T_CALLFUNC_BUILTIN :
2477 f = (*fr->fr_func)(fin, &pass);
2486 case FR_T_IPFEXPR_BUILTIN :
2487 if (fin->fin_family != fr->fr_family)
2489 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2497 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2498 if (fin->fin_nattag == NULL)
2500 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2503 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2505 passt = fr->fr_flags;
2508 * If the rule is a "call now" rule, then call the function
2509 * in the rule, if it exists and use the results from that.
2510 * If the function pointer is bad, just make like we ignore
2511 * it, except for increasing the hit counter.
2513 if ((passt & FR_CALLNOW) != 0) {
2516 ATOMIC_INC64(fr->fr_hits);
2517 if ((fr->fr_func == NULL) ||
2518 (fr->fr_func == (ipfunc_t)-1))
2523 fr = (*fr->fr_func)(fin, &passt);
2528 passt = fr->fr_flags;
2534 * Just log this packet...
2536 if ((passt & FR_LOGMASK) == FR_LOG) {
2537 if (ipf_log_pkt(fin, passt) == -1) {
2538 if (passt & FR_LOGORBLOCK) {
2540 passt &= ~FR_CMDMASK;
2541 passt |= FR_BLOCK|FR_QUICK;
2542 fin->fin_reason = FRB_LOGFAIL;
2546 #endif /* IPFILTER_LOG */
2548 MUTEX_ENTER(&fr->fr_lock);
2549 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2551 MUTEX_EXIT(&fr->fr_lock);
2552 fin->fin_rule = rulen;
2555 if (FR_ISSKIP(passt)) {
2558 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2559 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2563 if (passt & (FR_RETICMP|FR_FAKEICMP))
2564 fin->fin_icode = fr->fr_icode;
2566 if (fr->fr_group != -1) {
2567 (void) strncpy(fin->fin_group,
2568 FR_NAME(fr, fr_group),
2569 strlen(FR_NAME(fr, fr_group)));
2571 fin->fin_group[0] = '\0';
2574 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2576 if (fr->fr_grphead != NULL) {
2577 fin->fin_fr = fr->fr_grphead->fg_start;
2578 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2580 if (FR_ISDECAPS(passt))
2581 passt = ipf_decaps(fin, pass, fr->fr_icode);
2583 passt = ipf_scanlist(fin, pass);
2585 if (fin->fin_fr == NULL) {
2586 fin->fin_rule = rulen;
2587 if (fr->fr_group != -1)
2588 (void) strncpy(fin->fin_group,
2591 strlen(fr->fr_names +
2599 if (pass & FR_QUICK) {
2601 * Finally, if we've asked to track state for this
2602 * packet, set it up. Add state for "quick" rules
2603 * here so that if the action fails we can consider
2604 * the rule to "not match" and keep on processing
2607 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2608 !(fin->fin_flx & FI_STATE)) {
2609 int out = fin->fin_out;
2612 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2613 LBUMPD(ipf_stats[out], fr_ads);
2615 LBUMPD(ipf_stats[out], fr_bads);
2628 /* ------------------------------------------------------------------------ */
2629 /* Function: ipf_acctpkt */
2630 /* Returns: frentry_t* - always returns NULL */
2631 /* Parameters: fin(I) - pointer to packet information */
2632 /* passp(IO) - pointer to current/new filter decision (unused) */
2634 /* Checks a packet against accounting rules, if there are any for the given */
2635 /* IP protocol version. */
2637 /* N.B.: this function returns NULL to match the prototype used by other */
2638 /* functions called from the IPFilter "mainline" in ipf_check(). */
2639 /* ------------------------------------------------------------------------ */
2641 ipf_acctpkt(fin, passp)
2645 ipf_main_softc_t *softc = fin->fin_main_soft;
2646 char group[FR_GROUPLEN];
2647 frentry_t *fr, *frsave;
2651 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2654 frsave = fin->fin_fr;
2655 bcopy(fin->fin_group, group, FR_GROUPLEN);
2656 rulen = fin->fin_rule;
2658 pass = ipf_scanlist(fin, FR_NOMATCH);
2659 if (FR_ISACCOUNT(pass)) {
2660 LBUMPD(ipf_stats[0], fr_acct);
2662 fin->fin_fr = frsave;
2663 bcopy(group, fin->fin_group, FR_GROUPLEN);
2664 fin->fin_rule = rulen;
2670 /* ------------------------------------------------------------------------ */
2671 /* Function: ipf_firewall */
2672 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2673 /* were found, returns NULL. */
2674 /* Parameters: fin(I) - pointer to packet information */
2675 /* passp(IO) - pointer to current/new filter decision (unused) */
2677 /* Applies an appropriate set of firewall rules to the packet, to see if */
2678 /* there are any matches. The first check is to see if a match can be seen */
2679 /* in the cache. If not, then search an appropriate list of rules. Once a */
2680 /* matching rule is found, take any appropriate actions as defined by the */
2681 /* rule - except logging. */
2682 /* ------------------------------------------------------------------------ */
2684 ipf_firewall(fin, passp)
2688 ipf_main_softc_t *softc = fin->fin_main_soft;
2697 * This rule cache will only affect packets that are not being
2698 * statefully filtered.
2700 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2701 if (fin->fin_fr != NULL)
2702 pass = ipf_scanlist(fin, softc->ipf_pass);
2704 if ((pass & FR_NOMATCH)) {
2705 LBUMPD(ipf_stats[out], fr_nom);
2710 * Apply packets per second rate-limiting to a rule as required.
2712 if ((fr != NULL) && (fr->fr_pps != 0) &&
2713 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2714 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2715 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2717 LBUMPD(ipf_stats[out], fr_ppshit);
2718 fin->fin_reason = FRB_PPSRATE;
2722 * If we fail to add a packet to the authorization queue, then we
2723 * drop the packet later. However, if it was added then pretend
2724 * we've dropped it already.
2726 if (FR_ISAUTH(pass)) {
2727 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2728 DT1(frb_authnew, fr_info_t *, fin);
2729 fin->fin_m = *fin->fin_mp = NULL;
2730 fin->fin_reason = FRB_AUTHNEW;
2734 fin->fin_error = ENOSPC;
2738 if ((fr != NULL) && (fr->fr_func != NULL) &&
2739 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2740 (void) (*fr->fr_func)(fin, &pass);
2743 * If a rule is a pre-auth rule, check again in the list of rules
2744 * loaded for authenticated use. It does not particulary matter
2745 * if this search fails because a "preauth" result, from a rule,
2746 * is treated as "not a pass", hence the packet is blocked.
2748 if (FR_ISPREAUTH(pass)) {
2749 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2753 * If the rule has "keep frag" and the packet is actually a fragment,
2754 * then create a fragment state entry.
2756 if (pass & FR_KEEPFRAG) {
2757 if (fin->fin_flx & FI_FRAG) {
2758 if (ipf_frag_new(softc, fin, pass) == -1) {
2759 LBUMP(ipf_stats[out].fr_bnfr);
2761 LBUMP(ipf_stats[out].fr_nfr);
2764 LBUMP(ipf_stats[out].fr_cfr);
2775 /* ------------------------------------------------------------------------ */
2776 /* Function: ipf_check */
2777 /* Returns: int - 0 == packet allowed through, */
2779 /* -1 == packet blocked */
2780 /* 1 == packet not matched */
2781 /* -2 == requires authentication */
2783 /* > 0 == filter error # for packet */
2784 /* Parameters: ctx(I) - pointer to the instance context */
2785 /* ip(I) - pointer to start of IPv4/6 packet */
2786 /* hlen(I) - length of header */
2787 /* ifp(I) - pointer to interface this packet is on */
2788 /* out(I) - 0 == packet going in, 1 == packet going out */
2789 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2792 /* qpi(I) - pointer to STREAMS queue information for this */
2793 /* interface & direction. */
2795 /* ipf_check() is the master function for all IPFilter packet processing. */
2796 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2797 /* authorisation (or pre-authorisation), presence of related state info., */
2798 /* generating log entries, IP packet accounting, routing of packets as */
2799 /* directed by firewall rules and of course whether or not to allow the */
2800 /* packet to be further processed by the kernel. */
2802 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2803 /* freed. Packets passed may be returned with the pointer pointed to by */
2804 /* by "mp" changed to a new buffer. */
2805 /* ------------------------------------------------------------------------ */
2807 ipf_check(ctx, ip, hlen, ifp, out
2808 #if defined(_KERNEL) && defined(MENTAT)
2822 * The above really sucks, but short of writing a diff
2824 ipf_main_softc_t *softc = ctx;
2826 fr_info_t *fin = &frinfo;
2827 u_32_t pass = softc->ipf_pass;
2828 frentry_t *fr = NULL;
2833 * The first part of ipf_check() deals with making sure that what goes
2834 * into the filtering engine makes some sense. Information about the
2835 * the packet is distilled, collected into a fr_info_t structure and
2836 * the an attempt to ensure the buffer the packet is in is big enough
2837 * to hold all the required packet headers.
2841 qpktinfo_t *qpi = qif;
2844 if ((u_int)ip & 0x3)
2851 if (softc->ipf_running <= 0) {
2855 bzero((char *)fin, sizeof(*fin));
2858 if (qpi->qpi_flags & QF_BROADCAST)
2859 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2860 if (qpi->qpi_flags & QF_MULTICAST)
2861 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2869 # if defined(M_MCAST)
2870 if ((m->m_flags & M_MCAST) != 0)
2871 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2873 # if defined(M_MLOOP)
2874 if ((m->m_flags & M_MLOOP) != 0)
2875 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2877 # if defined(M_BCAST)
2878 if ((m->m_flags & M_BCAST) != 0)
2879 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2881 # ifdef M_CANFASTFWD
2883 * XXX For now, IP Filter and fast-forwarding of cached flows
2884 * XXX are mutually exclusive. Eventually, IP Filter should
2885 * XXX get a "can-fast-forward" filter rule.
2887 m->m_flags &= ~M_CANFASTFWD;
2888 # endif /* M_CANFASTFWD */
2889 # if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2891 * disable delayed checksums.
2893 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2894 in_delayed_cksum(m);
2895 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2897 # endif /* CSUM_DELAY_DATA */
2898 # endif /* MENTAT */
2900 bzero((char *)fin, sizeof(*fin));
2902 # if defined(M_MCAST)
2903 if ((m->m_flags & M_MCAST) != 0)
2904 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2906 # if defined(M_MLOOP)
2907 if ((m->m_flags & M_MLOOP) != 0)
2908 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2910 # if defined(M_BCAST)
2911 if ((m->m_flags & M_BCAST) != 0)
2912 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2914 #endif /* _KERNEL */
2922 fin->fin_error = ENETUNREACH;
2923 fin->fin_hlen = (u_short)hlen;
2924 fin->fin_dp = (char *)ip + hlen;
2925 fin->fin_main_soft = softc;
2927 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2933 LBUMP(ipf_stats[out].fr_ipv6);
2935 * Jumbo grams are quite likely too big for internal buffer
2936 * structures to handle comfortably, for now, so just drop
2939 if (((ip6_t *)ip)->ip6_plen == 0) {
2940 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2941 pass = FR_BLOCK|FR_NOMATCH;
2942 fin->fin_reason = FRB_JUMBO;
2945 fin->fin_family = AF_INET6;
2949 fin->fin_family = AF_INET;
2952 if (ipf_makefrip(hlen, ip, fin) == -1) {
2953 DT1(frb_makefrip, fr_info_t *, fin);
2954 pass = FR_BLOCK|FR_NOMATCH;
2955 fin->fin_reason = FRB_MAKEFRIP;
2960 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2961 * becomes NULL and so we have no packet to free.
2963 if (*fin->fin_mp == NULL)
2968 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2969 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2970 fin->fin_flx |= FI_BADSRC;
2972 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2973 LBUMPD(ipf_stats[0], fr_v4_badttl);
2974 fin->fin_flx |= FI_LOWTTL;
2979 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2980 LBUMPD(ipf_stats[0], fr_v6_badttl);
2981 fin->fin_flx |= FI_LOWTTL;
2987 if (fin->fin_flx & FI_SHORT) {
2988 LBUMPD(ipf_stats[out], fr_short);
2991 READ_ENTER(&softc->ipf_mutex);
2997 if (ipf_nat_checkin(fin, &pass) == -1) {
3003 if (ipf_nat6_checkin(fin, &pass) == -1) {
3014 * If a packet is found in the auth table, then skip checking
3015 * the access lists for permission but we do need to consider
3016 * the result as if it were from the ACL's. In addition, being
3017 * found in the auth table means it has been seen before, so do
3018 * not pass it through accounting (again), lest it be counted twice.
3020 fr = ipf_auth_check(fin, &pass);
3021 if (!out && (fr == NULL))
3022 (void) ipf_acctpkt(fin, NULL);
3025 if ((fin->fin_flx & FI_FRAG) != 0)
3026 fr = ipf_frag_known(fin, &pass);
3029 fr = ipf_state_check(fin, &pass);
3032 if ((pass & FR_NOMATCH) || (fr == NULL))
3033 fr = ipf_firewall(fin, &pass);
3036 * If we've asked to track state for this packet, set it up.
3037 * Here rather than ipf_firewall because ipf_checkauth may decide
3038 * to return a packet for "keep state"
3040 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3041 !(fin->fin_flx & FI_STATE)) {
3042 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3043 LBUMP(ipf_stats[out].fr_ads);
3045 LBUMP(ipf_stats[out].fr_bads);
3046 if (FR_ISPASS(pass)) {
3048 pass &= ~FR_CMDMASK;
3050 fin->fin_reason = FRB_STATEADD;
3056 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3057 fin->fin_dif = &fr->fr_dif;
3058 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3062 * Only count/translate packets which will be passed on, out the
3065 if (out && FR_ISPASS(pass)) {
3066 (void) ipf_acctpkt(fin, NULL);
3071 if (ipf_nat_checkout(fin, &pass) == -1) {
3073 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3074 if (ipf_updateipid(fin) == -1) {
3076 LBUMP(ipf_stats[1].fr_ipud);
3077 pass &= ~FR_CMDMASK;
3079 fin->fin_reason = FRB_UPDATEIPID;
3081 LBUMP(ipf_stats[0].fr_ipud);
3087 (void) ipf_nat6_checkout(fin, &pass);
3097 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3098 (void) ipf_dolog(fin, &pass);
3103 * The FI_STATE flag is cleared here so that calling ipf_state_check
3104 * will work when called from inside of fr_fastroute. Although
3105 * there is a similar flag, FI_NATED, for NAT, it does have the same
3106 * impact on code execution.
3108 fin->fin_flx &= ~FI_STATE;
3110 #if defined(FASTROUTE_RECURSION)
3112 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3113 * a packet below can sometimes cause a recursive call into IPFilter.
3114 * On those platforms where that does happen, we need to hang onto
3115 * the filter rule just in case someone decides to remove or flush it
3119 MUTEX_ENTER(&fr->fr_lock);
3121 MUTEX_EXIT(&fr->fr_lock);
3124 RWLOCK_EXIT(&softc->ipf_mutex);
3127 if ((pass & FR_RETMASK) != 0) {
3129 * Should we return an ICMP packet to indicate error
3130 * status passing through the packet filter ?
3131 * WARNING: ICMP error packets AND TCP RST packets should
3132 * ONLY be sent in repsonse to incoming packets. Sending
3133 * them in response to outbound packets can result in a
3134 * panic on some operating systems.
3137 if (pass & FR_RETICMP) {
3140 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3144 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3146 LBUMP(ipf_stats[0].fr_ret);
3147 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3148 !(fin->fin_flx & FI_SHORT)) {
3149 if (((fin->fin_flx & FI_OOW) != 0) ||
3150 (ipf_send_reset(fin) == 0)) {
3151 LBUMP(ipf_stats[1].fr_ret);
3156 * When using return-* with auth rules, the auth code
3157 * takes over disposing of this packet.
3159 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3160 DT1(frb_authcapture, fr_info_t *, fin);
3161 fin->fin_m = *fin->fin_mp = NULL;
3162 fin->fin_reason = FRB_AUTHCAPTURE;
3166 if (pass & FR_RETRST) {
3167 fin->fin_error = ECONNRESET;
3173 * After the above so that ICMP unreachables and TCP RSTs get
3176 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3177 ipf_nat_uncreate(fin);
3180 * If we didn't drop off the bottom of the list of rules (and thus
3181 * the 'current' rule fr is not NULL), then we may have some extra
3182 * instructions about what to do with a packet.
3183 * Once we're finished return to our caller, freeing the packet if
3184 * we are dropping it.
3190 * Generate a duplicated packet first because ipf_fastroute
3191 * can lead to fin_m being free'd... not good.
3194 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3195 (fdp->fd_ptr != (void *)-1)) {
3196 mc = M_COPY(fin->fin_m);
3198 ipf_fastroute(mc, &mc, fin, fdp);
3202 if (!out && (pass & FR_FASTROUTE)) {
3204 * For fastroute rule, no destination interface defined
3205 * so pass NULL as the frdest_t parameter
3207 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3209 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3210 (fdp->fd_ptr != (struct ifnet *)-1)) {
3211 /* this is for to rules: */
3212 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3216 #if defined(FASTROUTE_RECURSION)
3217 (void) ipf_derefrule(softc, &fr);
3220 #if !defined(FASTROUTE_RECURSION)
3221 RWLOCK_EXIT(&softc->ipf_mutex);
3225 if (!FR_ISPASS(pass)) {
3226 LBUMP(ipf_stats[out].fr_block);
3234 LBUMP(ipf_stats[out].fr_pass);
3240 if (FR_ISPASS(pass))
3242 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3243 return fin->fin_error;
3246 (*mp)->mb_ifp = fin->fin_ifp;
3247 blockreason = fin->fin_reason;
3248 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3249 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3250 if ((pass & FR_NOMATCH) != 0)
3253 if ((pass & FR_RETMASK) != 0)
3254 switch (pass & FR_RETMASK)
3264 switch (pass & FR_CMDMASK)
3278 #endif /* _KERNEL */
3283 /* ------------------------------------------------------------------------ */
3284 /* Function: ipf_dolog */
3285 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3286 /* Parameters: fin(I) - pointer to packet information */
3287 /* passp(IO) - pointer to current/new filter decision (unused) */
3289 /* Checks flags set to see how a packet should be logged, if it is to be */
3290 /* logged. Adjust statistics based on its success or not. */
3291 /* ------------------------------------------------------------------------ */
3293 ipf_dolog(fin, passp)
3297 ipf_main_softc_t *softc = fin->fin_main_soft;
3304 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3305 pass |= FF_LOGNOMATCH;
3306 LBUMPD(ipf_stats[out], fr_npkl);
3309 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3310 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3311 if ((pass & FR_LOGMASK) != FR_LOGP)
3313 LBUMPD(ipf_stats[out], fr_ppkl);
3316 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3317 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3318 if ((pass & FR_LOGMASK) != FR_LOGB)
3319 pass |= FF_LOGBLOCK;
3320 LBUMPD(ipf_stats[out], fr_bpkl);
3323 if (ipf_log_pkt(fin, pass) == -1) {
3325 * If the "or-block" option has been used then
3326 * block the packet if we failed to log it.
3328 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3329 DT1(frb_logfail2, u_int, pass);
3330 pass &= ~FR_CMDMASK;
3332 fin->fin_reason = FRB_LOGFAIL2;
3340 #endif /* IPFILTER_LOG */
3343 /* ------------------------------------------------------------------------ */
3344 /* Function: ipf_cksum */
3345 /* Returns: u_short - IP header checksum */
3346 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3347 /* len(I) - length of buffer in bytes */
3349 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3351 /* N.B.: addr should be 16bit aligned. */
3352 /* ------------------------------------------------------------------------ */
3354 ipf_cksum(addr, len)
3360 for (sum = 0; len > 1; len -= 2)
3363 /* mop up an odd byte, if necessary */
3365 sum += *(u_char *)addr;
3368 * add back carry outs from top 16 bits to low 16 bits
3370 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3371 sum += (sum >> 16); /* add carry */
3372 return (u_short)(~sum);
3376 /* ------------------------------------------------------------------------ */
3377 /* Function: fr_cksum */
3378 /* Returns: u_short - layer 4 checksum */
3379 /* Parameters: fin(I) - pointer to packet information */
3380 /* ip(I) - pointer to IP header */
3381 /* l4proto(I) - protocol to caclulate checksum for */
3382 /* l4hdr(I) - pointer to layer 4 header */
3384 /* Calculates the TCP checksum for the packet held in "m", using the data */
3385 /* in the IP header "ip" to seed it. */
3387 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3388 /* and the TCP header. We also assume that data blocks aren't allocated in */
3391 /* Expects ip_len and ip_off to be in network byte order when called. */
3392 /* ------------------------------------------------------------------------ */
3394 fr_cksum(fin, ip, l4proto, l4hdr)
3400 u_short *sp, slen, sumsave, *csump;
3415 sum = htons((u_short)l4proto);
3417 * Add up IP Header portion
3420 if (IP_V(ip) == 4) {
3422 hlen = IP_HL(ip) << 2;
3424 sp = (u_short *)&ip->ip_src;
3425 sum += *sp++; /* ip_src */
3427 sum += *sp++; /* ip_dst */
3429 slen = fin->fin_plen - off;
3432 } else if (IP_V(ip) == 6) {
3437 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3438 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3439 return(ipf_pcksum6(fin, ip6, off, len));
3448 csump = &((udphdr_t *)l4hdr)->uh_sum;
3452 csump = &((tcphdr_t *)l4hdr)->th_sum;
3455 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3456 sum = 0; /* Pseudo-checksum is not included */
3459 case IPPROTO_ICMPV6 :
3460 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3467 if (csump != NULL) {
3472 sum2 = ipf_pcksum(fin, off, sum);
3479 /* ------------------------------------------------------------------------ */
3480 /* Function: ipf_findgroup */
3481 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3482 /* Parameters: softc(I) - pointer to soft context main structure */
3483 /* group(I) - group name to search for */
3484 /* unit(I) - device to which this group belongs */
3485 /* set(I) - which set of rules (inactive/inactive) this is */
3486 /* fgpp(O) - pointer to place to store pointer to the pointer */
3487 /* to where to add the next (last) group or where */
3488 /* to delete group from. */
3490 /* Search amongst the defined groups for a particular group number. */
3491 /* ------------------------------------------------------------------------ */
3493 ipf_findgroup(softc, group, unit, set, fgpp)
3494 ipf_main_softc_t *softc;
3500 frgroup_t *fg, **fgp;
3503 * Which list of groups to search in is dependent on which list of
3504 * rules are being operated on.
3506 fgp = &softc->ipf_groups[unit][set];
3508 while ((fg = *fgp) != NULL) {
3509 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3520 /* ------------------------------------------------------------------------ */
3521 /* Function: ipf_group_add */
3522 /* Returns: frgroup_t * - NULL == did not create group, */
3523 /* != NULL == pointer to the group */
3524 /* Parameters: softc(I) - pointer to soft context main structure */
3525 /* num(I) - group number to add */
3526 /* head(I) - rule pointer that is using this as the head */
3527 /* flags(I) - rule flags which describe the type of rule it is */
3528 /* unit(I) - device to which this group will belong to */
3529 /* set(I) - which set of rules (inactive/inactive) this is */
3530 /* Write Locks: ipf_mutex */
3532 /* Add a new group head, or if it already exists, increase the reference */
3534 /* ------------------------------------------------------------------------ */
3536 ipf_group_add(softc, group, head, flags, unit, set)
3537 ipf_main_softc_t *softc;
3544 frgroup_t *fg, **fgp;
3550 if (unit == IPL_LOGIPF && *group == '\0')
3554 gflags = flags & FR_INOUT;
3556 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3558 if (fg->fg_head == NULL && head != NULL)
3560 if (fg->fg_flags == 0)
3561 fg->fg_flags = gflags;
3562 else if (gflags != fg->fg_flags)
3568 KMALLOC(fg, frgroup_t *);
3571 fg->fg_start = NULL;
3573 bcopy(group, fg->fg_name, strlen(group) + 1);
3574 fg->fg_flags = gflags;
3576 fg->fg_set = &softc->ipf_groups[unit][set];
3583 /* ------------------------------------------------------------------------ */
3584 /* Function: ipf_group_del */
3585 /* Returns: int - number of rules deleted */
3586 /* Parameters: softc(I) - pointer to soft context main structure */
3587 /* group(I) - group name to delete */
3588 /* fr(I) - filter rule from which group is referenced */
3589 /* Write Locks: ipf_mutex */
3591 /* This function is called whenever a reference to a group is to be dropped */
3592 /* and thus its reference count needs to be lowered and the group free'd if */
3593 /* the reference count reaches zero. Passing in fr is really for the sole */
3594 /* purpose of knowing when the head rule is being deleted. */
3595 /* ------------------------------------------------------------------------ */
3597 ipf_group_del(softc, group, fr)
3598 ipf_main_softc_t *softc;
3603 if (group->fg_head == fr)
3604 group->fg_head = NULL;
3607 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3608 ipf_group_free(group);
3612 /* ------------------------------------------------------------------------ */
3613 /* Function: ipf_group_free */
3615 /* Parameters: group(I) - pointer to filter rule group */
3617 /* Remove the group from the list of groups and free it. */
3618 /* ------------------------------------------------------------------------ */
3620 ipf_group_free(group)
3625 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3627 *gp = group->fg_next;
3635 /* ------------------------------------------------------------------------ */
3636 /* Function: ipf_group_flush */
3637 /* Returns: int - number of rules flush from group */
3638 /* Parameters: softc(I) - pointer to soft context main structure */
3639 /* Parameters: group(I) - pointer to filter rule group */
3641 /* Remove all of the rules that currently are listed under the given group. */
3642 /* ------------------------------------------------------------------------ */
3644 ipf_group_flush(softc, group)
3645 ipf_main_softc_t *softc;
3650 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3656 /* ------------------------------------------------------------------------ */
3657 /* Function: ipf_getrulen */
3658 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3659 /* Parameters: softc(I) - pointer to soft context main structure */
3660 /* Parameters: unit(I) - device for which to count the rule's number */
3661 /* flags(I) - which set of rules to find the rule in */
3662 /* group(I) - group name */
3663 /* n(I) - rule number to find */
3665 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3666 /* group # g doesn't exist or there are less than n rules in the group. */
3667 /* ------------------------------------------------------------------------ */
3669 ipf_getrulen(softc, unit, group, n)
3670 ipf_main_softc_t *softc;
3678 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3681 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3689 /* ------------------------------------------------------------------------ */
3690 /* Function: ipf_flushlist */
3691 /* Returns: int - >= 0 - number of flushed rules */
3692 /* Parameters: softc(I) - pointer to soft context main structure */
3693 /* nfreedp(O) - pointer to int where flush count is stored */
3694 /* listp(I) - pointer to list to flush pointer */
3695 /* Write Locks: ipf_mutex */
3697 /* Recursively flush rules from the list, descending groups as they are */
3698 /* encountered. if a rule is the head of a group and it has lost all its */
3699 /* group members, then also delete the group reference. nfreedp is needed */
3700 /* to store the accumulating count of rules removed, whereas the returned */
3701 /* value is just the number removed from the current list. The latter is */
3702 /* needed to correctly adjust reference counts on rules that define groups. */
3704 /* NOTE: Rules not loaded from user space cannot be flushed. */
3705 /* ------------------------------------------------------------------------ */
3707 ipf_flushlist(softc, nfreedp, listp)
3708 ipf_main_softc_t *softc;
3715 while ((fp = *listp) != NULL) {
3716 if ((fp->fr_type & FR_T_BUILTIN) ||
3717 !(fp->fr_flags & FR_COPIED)) {
3718 listp = &fp->fr_next;
3721 *listp = fp->fr_next;
3722 if (fp->fr_next != NULL)
3723 fp->fr_next->fr_pnext = fp->fr_pnext;
3724 fp->fr_pnext = NULL;
3726 if (fp->fr_grphead != NULL) {
3727 freed += ipf_group_flush(softc, fp->fr_grphead);
3728 fp->fr_names[fp->fr_grhead] = '\0';
3731 if (fp->fr_icmpgrp != NULL) {
3732 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3733 fp->fr_names[fp->fr_icmphead] = '\0';
3736 if (fp->fr_srctrack.ht_max_nodes)
3737 ipf_rb_ht_flush(&fp->fr_srctrack);
3741 ASSERT(fp->fr_ref > 0);
3742 if (ipf_derefrule(softc, &fp) == 0)
3750 /* ------------------------------------------------------------------------ */
3751 /* Function: ipf_flush */
3752 /* Returns: int - >= 0 - number of flushed rules */
3753 /* Parameters: softc(I) - pointer to soft context main structure */
3754 /* unit(I) - device for which to flush rules */
3755 /* flags(I) - which set of rules to flush */
3757 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3758 /* and IPv6) as defined by the value of flags. */
3759 /* ------------------------------------------------------------------------ */
3761 ipf_flush(softc, unit, flags)
3762 ipf_main_softc_t *softc;
3766 int flushed = 0, set;
3768 WRITE_ENTER(&softc->ipf_mutex);
3770 set = softc->ipf_active;
3771 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3774 if (flags & FR_OUTQUE) {
3775 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3776 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3778 if (flags & FR_INQUE) {
3779 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3780 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3783 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3784 flags & (FR_INQUE|FR_OUTQUE));
3786 RWLOCK_EXIT(&softc->ipf_mutex);
3788 if (unit == IPL_LOGIPF) {
3791 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3799 /* ------------------------------------------------------------------------ */
3800 /* Function: ipf_flush_groups */
3801 /* Returns: int - >= 0 - number of flushed rules */
3802 /* Parameters: softc(I) - soft context pointerto work with */
3803 /* grhead(I) - pointer to the start of the group list to flush */
3804 /* flags(I) - which set of rules to flush */
3806 /* Walk through all of the groups under the given group head and remove all */
3807 /* of those that match the flags passed in. The for loop here is bit more */
3808 /* complicated than usual because the removal of a rule with ipf_derefrule */
3809 /* may end up removing not only the structure pointed to by "fg" but also */
3810 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3811 /* removed from the group then it is necessary to start again. */
3812 /* ------------------------------------------------------------------------ */
3814 ipf_flush_groups(softc, grhead, flags)
3815 ipf_main_softc_t *softc;
3819 frentry_t *fr, **frp;
3820 frgroup_t *fg, **fgp;
3824 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3825 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3830 frp = &fg->fg_start;
3831 while ((removed == 0) && ((fr = *frp) != NULL)) {
3832 if ((fr->fr_flags & flags) == 0) {
3835 if (fr->fr_next != NULL)
3836 fr->fr_next->fr_pnext = fr->fr_pnext;
3838 fr->fr_pnext = NULL;
3840 (void) ipf_derefrule(softc, &fr);
3852 /* ------------------------------------------------------------------------ */
3853 /* Function: memstr */
3854 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3855 /* Parameters: src(I) - pointer to byte sequence to match */
3856 /* dst(I) - pointer to byte sequence to search */
3857 /* slen(I) - match length */
3858 /* dlen(I) - length available to search in */
3860 /* Search dst for a sequence of bytes matching those at src and extend for */
3862 /* ------------------------------------------------------------------------ */
3864 memstr(src, dst, slen, dlen)
3871 while (dlen >= slen) {
3872 if (bcmp(src, dst, slen) == 0) {
3881 /* ------------------------------------------------------------------------ */
3882 /* Function: ipf_fixskip */
3884 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3885 /* rp(I) - rule added/removed with skip in it. */
3886 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3887 /* depending on whether a rule was just added */
3890 /* Adjust all the rules in a list which would have skip'd past the position */
3891 /* where we are inserting to skip to the right place given the change. */
3892 /* ------------------------------------------------------------------------ */
3894 ipf_fixskip(listp, rp, addremove)
3895 frentry_t **listp, *rp;
3902 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3908 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3909 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3910 fp->fr_arg += addremove;
3915 /* ------------------------------------------------------------------------ */
3916 /* Function: count4bits */
3917 /* Returns: int - >= 0 - number of consecutive bits in input */
3918 /* Parameters: ip(I) - 32bit IP address */
3921 /* count consecutive 1's in bit mask. If the mask generated by counting */
3922 /* consecutive 1's is different to that passed, return -1, else return # */
3924 /* ------------------------------------------------------------------------ */
3932 ip = ipn = ntohl(ip);
3933 for (i = 32; i; i--, ipn *= 2)
3934 if (ipn & 0x80000000)
3939 for (i = 32, j = cnt; i; i--, j--) {
3950 /* ------------------------------------------------------------------------ */
3951 /* Function: count6bits */
3952 /* Returns: int - >= 0 - number of consecutive bits in input */
3953 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3956 /* count consecutive 1's in bit mask. */
3957 /* ------------------------------------------------------------------------ */
3966 for (k = 3; k >= 0; k--)
3967 if (msk[k] == 0xffffffff)
3970 for (j = msk[k]; j; j <<= 1)
3977 #endif /* _KERNEL */
3980 /* ------------------------------------------------------------------------ */
3981 /* Function: ipf_synclist */
3982 /* Returns: int - 0 = no failures, else indication of first failure */
3983 /* Parameters: fr(I) - start of filter list to sync interface names for */
3984 /* ifp(I) - interface pointer for limiting sync lookups */
3985 /* Write Locks: ipf_mutex */
3987 /* Walk through a list of filter rules and resolve any interface names into */
3988 /* pointers. Where dynamic addresses are used, also update the IP address */
3989 /* used in the rule. The interface pointer is used to limit the lookups to */
3990 /* a specific set of matching names if it is non-NULL. */
3991 /* Errors can occur when resolving the destination name of to/dup-to fields */
3992 /* when the name points to a pool and that pool doest not exist. If this */
3993 /* does happen then it is necessary to check if there are any lookup refs */
3994 /* that need to be dropped before returning with an error. */
3995 /* ------------------------------------------------------------------------ */
3997 ipf_synclist(softc, fr, ifp)
3998 ipf_main_softc_t *softc;
4002 frentry_t *frt, *start = fr;
4011 for (; fr; fr = fr->fr_next) {
4012 if (fr->fr_family == AF_INET)
4014 else if (fr->fr_family == AF_INET6)
4020 * Lookup all the interface names that are part of the rule.
4022 for (i = 0; i < 4; i++) {
4023 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4025 if (fr->fr_ifnames[i] == -1)
4027 name = FR_NAME(fr, fr_ifnames[i]);
4028 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4031 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4032 if (fr->fr_satype != FRI_NORMAL &&
4033 fr->fr_satype != FRI_LOOKUP) {
4034 ifa = ipf_resolvenic(softc, fr->fr_names +
4036 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4037 &fr->fr_src6, &fr->fr_smsk6);
4039 if (fr->fr_datype != FRI_NORMAL &&
4040 fr->fr_datype != FRI_LOOKUP) {
4041 ifa = ipf_resolvenic(softc, fr->fr_names +
4043 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4044 &fr->fr_dst6, &fr->fr_dmsk6);
4048 fdp = &fr->fr_tifs[0];
4049 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4050 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4055 fdp = &fr->fr_tifs[1];
4056 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4057 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4063 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4064 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4069 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4070 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4071 fr->fr_srcptr = ipf_lookup_res_num(softc,
4077 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4078 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4079 fr->fr_dstptr = ipf_lookup_res_num(softc,
4089 for (frt = start; frt != fr; fr = fr->fr_next) {
4090 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4091 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4092 ipf_lookup_deref(softc, frt->fr_srctype,
4094 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4095 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4096 ipf_lookup_deref(softc, frt->fr_dsttype,
4103 /* ------------------------------------------------------------------------ */
4104 /* Function: ipf_sync */
4106 /* Parameters: Nil */
4108 /* ipf_sync() is called when we suspect that the interface list or */
4109 /* information about interfaces (like IP#) has changed. Go through all */
4110 /* filter rules, NAT entries and the state table and check if anything */
4111 /* needs to be changed/updated. */
4112 /* ------------------------------------------------------------------------ */
4114 ipf_sync(softc, ifp)
4115 ipf_main_softc_t *softc;
4121 ipf_nat_sync(softc, ifp);
4122 ipf_state_sync(softc, ifp);
4123 ipf_lookup_sync(softc, ifp);
4126 WRITE_ENTER(&softc->ipf_mutex);
4127 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4128 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4129 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4130 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4132 for (i = 0; i < IPL_LOGSIZE; i++) {
4135 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4136 (void) ipf_synclist(softc, g->fg_start, ifp);
4137 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4138 (void) ipf_synclist(softc, g->fg_start, ifp);
4140 RWLOCK_EXIT(&softc->ipf_mutex);
4147 * In the functions below, bcopy() is called because the pointer being
4148 * copied _from_ in this instance is a pointer to a char buf (which could
4149 * end up being unaligned) and on the kernel's local stack.
4151 /* ------------------------------------------------------------------------ */
4152 /* Function: copyinptr */
4153 /* Returns: int - 0 = success, else failure */
4154 /* Parameters: src(I) - pointer to the source address */
4155 /* dst(I) - destination address */
4156 /* size(I) - number of bytes to copy */
4158 /* Copy a block of data in from user space, given a pointer to the pointer */
4159 /* to start copying from (src) and a pointer to where to store it (dst). */
4160 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4161 /* ------------------------------------------------------------------------ */
4163 copyinptr(softc, src, dst, size)
4164 ipf_main_softc_t *softc;
4172 error = COPYIN(src, &ca, sizeof(ca));
4176 bcopy(src, (caddr_t)&ca, sizeof(ca));
4178 error = COPYIN(ca, dst, size);
4187 /* ------------------------------------------------------------------------ */
4188 /* Function: copyoutptr */
4189 /* Returns: int - 0 = success, else failure */
4190 /* Parameters: src(I) - pointer to the source address */
4191 /* dst(I) - destination address */
4192 /* size(I) - number of bytes to copy */
4194 /* Copy a block of data out to user space, given a pointer to the pointer */
4195 /* to start copying from (src) and a pointer to where to store it (dst). */
4196 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4197 /* ------------------------------------------------------------------------ */
4199 copyoutptr(softc, src, dst, size)
4200 ipf_main_softc_t *softc;
4207 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4208 error = COPYOUT(src, ca, size);
4217 /* ------------------------------------------------------------------------ */
4218 /* Function: ipf_lock */
4219 /* Returns: int - 0 = success, else error */
4220 /* Parameters: data(I) - pointer to lock value to set */
4221 /* lockp(O) - pointer to location to store old lock value */
4223 /* Get the new value for the lock integer, set it and return the old value */
4225 /* ------------------------------------------------------------------------ */
4227 ipf_lock(data, lockp)
4233 err = BCOPYIN(data, &arg, sizeof(arg));
4236 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4244 /* ------------------------------------------------------------------------ */
4245 /* Function: ipf_getstat */
4247 /* Parameters: softc(I) - pointer to soft context main structure */
4248 /* fiop(I) - pointer to ipfilter stats structure */
4249 /* rev(I) - version claim by program doing ioctl */
4251 /* Stores a copy of current pointers, counters, etc, in the friostat */
4253 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4254 /* program is looking for. This ensure that validation of the version it */
4255 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4256 /* allow older binaries to work but kernels without it will not. */
4257 /* ------------------------------------------------------------------------ */
4260 ipf_getstat(softc, fiop, rev)
4261 ipf_main_softc_t *softc;
4267 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4268 sizeof(ipf_statistics_t) * 2);
4269 fiop->f_locks[IPL_LOGSTATE] = -1;
4270 fiop->f_locks[IPL_LOGNAT] = -1;
4271 fiop->f_locks[IPL_LOGIPF] = -1;
4272 fiop->f_locks[IPL_LOGAUTH] = -1;
4274 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4275 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4276 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4277 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4278 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4279 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4280 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4281 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4283 fiop->f_ticks = softc->ipf_ticks;
4284 fiop->f_active = softc->ipf_active;
4285 fiop->f_froute[0] = softc->ipf_frouteok[0];
4286 fiop->f_froute[1] = softc->ipf_frouteok[1];
4287 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4288 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4290 fiop->f_running = softc->ipf_running;
4291 for (i = 0; i < IPL_LOGSIZE; i++) {
4292 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4293 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4296 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4297 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4298 fiop->f_logging = 1;
4301 fiop->f_log_fail = 0;
4302 fiop->f_logging = 0;
4304 fiop->f_defpass = softc->ipf_pass;
4305 fiop->f_features = ipf_features;
4307 #ifdef IPFILTER_COMPAT
4308 sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4309 (rev / 1000000) % 100,
4310 (rev / 10000) % 100,
4314 (void) strncpy(fiop->f_version, ipfilter_version,
4315 sizeof(fiop->f_version));
4321 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4322 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4325 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4326 -1, /* 4: ICMP_SOURCEQUENCH */
4327 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4330 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4332 -1, /* 10: UNUSED */
4333 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4334 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4335 -1, /* 13: ICMP_TSTAMP */
4336 -1, /* 14: ICMP_TSTAMPREPLY */
4337 -1, /* 15: ICMP_IREQ */
4338 -1, /* 16: ICMP_IREQREPLY */
4339 -1, /* 17: ICMP_MASKREQ */
4340 -1, /* 18: ICMP_MASKREPLY */
4344 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4345 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4346 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4347 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4348 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4349 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4350 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4351 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4352 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4353 -1, /* 8: ICMP_UNREACH_ISOLATED */
4354 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4355 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4356 -1, /* 11: ICMP_UNREACH_TOSNET */
4357 -1, /* 12: ICMP_UNREACH_TOSHOST */
4358 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4360 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4363 int icmpreplytype4[ICMP_MAXTYPE + 1];
4366 /* ------------------------------------------------------------------------ */
4367 /* Function: ipf_matchicmpqueryreply */
4368 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4369 /* Parameters: v(I) - IP protocol version (4 or 6) */
4370 /* ic(I) - ICMP information */
4371 /* icmp(I) - ICMP packet header */
4372 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4374 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4375 /* reply to one as described by what's in ic. If it is a match, return 1, */
4376 /* else return 0 for no match. */
4377 /* ------------------------------------------------------------------------ */
4379 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4387 ictype = ic->ici_type;
4391 * If we matched its type on the way in, then when going out
4392 * it will still be the same type.
4394 if ((!rev && (icmp->icmp_type == ictype)) ||
4395 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4396 if (icmp->icmp_type != ICMP_ECHOREPLY)
4398 if (icmp->icmp_id == ic->ici_id)
4404 if ((!rev && (icmp->icmp_type == ictype)) ||
4405 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4406 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4408 if (icmp->icmp_id == ic->ici_id)
4417 /* ------------------------------------------------------------------------ */
4418 /* Function: ipf_rule_compare */
4419 /* Parameters: fr1(I) - first rule structure to compare */
4420 /* fr2(I) - second rule structure to compare */
4421 /* Returns: int - 0 == rules are the same, else mismatch */
4423 /* Compare two rules and return 0 if they match or a number indicating */
4424 /* which of the individual checks failed. */
4425 /* ------------------------------------------------------------------------ */
4427 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4429 if (fr1->fr_cksum != fr2->fr_cksum)
4431 if (fr1->fr_size != fr2->fr_size)
4433 if (fr1->fr_dsize != fr2->fr_dsize)
4435 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4436 fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4438 if (fr1->fr_data && !fr2->fr_data)
4440 if (!fr1->fr_data && fr2->fr_data)
4443 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4450 /* ------------------------------------------------------------------------ */
4451 /* Function: frrequest */
4452 /* Returns: int - 0 == success, > 0 == errno value */
4453 /* Parameters: unit(I) - device for which this is for */
4454 /* req(I) - ioctl command (SIOC*) */
4455 /* data(I) - pointr to ioctl data */
4456 /* set(I) - 1 or 0 (filter set) */
4457 /* makecopy(I) - flag indicating whether data points to a rule */
4458 /* in kernel space & hence doesn't need copying. */
4460 /* This function handles all the requests which operate on the list of */
4461 /* filter rules. This includes adding, deleting, insertion. It is also */
4462 /* responsible for creating groups when a "head" rule is loaded. Interface */
4463 /* names are resolved here and other sanity checks are made on the content */
4464 /* of the rule structure being loaded. If a rule has user defined timeouts */
4465 /* then make sure they are created and initialised before exiting. */
4466 /* ------------------------------------------------------------------------ */
4468 frrequest(softc, unit, req, data, set, makecopy)
4469 ipf_main_softc_t *softc;
4475 int error = 0, in, family, need_free = 0;
4476 enum { OP_ADD, /* add rule */
4477 OP_REM, /* remove rule */
4478 OP_ZERO /* zero statistics and counters */ }
4480 frentry_t frd, *fp, *f, **fprev, **ftail;
4481 void *ptr, *uptr, *cptr;
4490 if (makecopy != 0) {
4491 bzero(fp, sizeof(frd));
4492 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4496 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4500 KMALLOCS(f, frentry_t *, fp->fr_size);
4505 bzero(f, fp->fr_size);
4506 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4509 KFREES(f, fp->fr_size);
4516 fp->fr_dnext = NULL;
4517 fp->fr_pnext = NULL;
4518 fp->fr_pdnext = NULL;
4520 fp->fr_grphead = NULL;
4521 fp->fr_icmpgrp = NULL;
4522 fp->fr_isc = (void *)-1;
4525 fp->fr_flags |= FR_COPIED;
4527 fp = (frentry_t *)data;
4528 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4532 fp->fr_flags &= ~FR_COPIED;
4535 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4536 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4542 family = fp->fr_family;
4545 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4546 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4547 addrem = OP_ADD; /* Add rule */
4548 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4549 addrem = OP_REM; /* Remove rule */
4550 else if (req == (ioctlcmd_t)SIOCZRLST)
4551 addrem = OP_ZERO; /* Zero statistics and counters */
4559 * Only filter rules for IPv4 or IPv6 are accepted.
4561 if (family == AF_INET) {
4564 } else if (family == AF_INET6) {
4567 } else if (family != 0) {
4574 * If the rule is being loaded from user space, i.e. we had to copy it
4575 * into kernel space, then do not trust the function pointer in the
4578 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4579 if (ipf_findfunc(fp->fr_func) == NULL) {
4585 if (addrem == OP_ADD) {
4586 error = ipf_funcinit(softc, fp);
4591 if ((fp->fr_flags & FR_CALLNOW) &&
4592 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4597 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4598 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4607 if (FR_ISACCOUNT(fp->fr_flags))
4608 unit = IPL_LOGCOUNT;
4611 * Check that each group name in the rule has a start index that
4614 if (fp->fr_icmphead != -1) {
4615 if ((fp->fr_icmphead < 0) ||
4616 (fp->fr_icmphead >= fp->fr_namelen)) {
4621 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4622 fp->fr_names[fp->fr_icmphead] = '\0';
4625 if (fp->fr_grhead != -1) {
4626 if ((fp->fr_grhead < 0) ||
4627 (fp->fr_grhead >= fp->fr_namelen)) {
4632 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4633 fp->fr_names[fp->fr_grhead] = '\0';
4636 if (fp->fr_group != -1) {
4637 if ((fp->fr_group < 0) ||
4638 (fp->fr_group >= fp->fr_namelen)) {
4643 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4645 * Allow loading rules that are in groups to cause
4646 * them to be created if they don't already exit.
4648 group = FR_NAME(fp, fr_group);
4649 if (addrem == OP_ADD) {
4650 fg = ipf_group_add(softc, group, NULL,
4651 fp->fr_flags, unit, set);
4654 fg = ipf_findgroup(softc, group, unit,
4663 if (fg->fg_flags == 0) {
4664 fg->fg_flags = fp->fr_flags & FR_INOUT;
4665 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4673 * If a rule is going to be part of a group then it does
4674 * not matter whether it is an in or out rule, but if it
4675 * isn't in a group, then it does...
4677 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4683 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4686 * Work out which rule list this change is being applied to.
4690 if (unit == IPL_LOGAUTH) {
4691 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4692 (fp->fr_tifs[1].fd_ptr != NULL) ||
4693 (fp->fr_dif.fd_ptr != NULL) ||
4694 (fp->fr_flags & FR_FASTROUTE)) {
4695 softc->ipf_interror = 145;
4699 fprev = ipf_auth_rulehead(softc);
4701 if (FR_ISACCOUNT(fp->fr_flags))
4702 fprev = &softc->ipf_acct[in][set];
4703 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4704 fprev = &softc->ipf_rules[in][set];
4706 if (fprev == NULL) {
4713 fprev = &fg->fg_start;
4716 * Copy in extra data for the rule.
4718 if (fp->fr_dsize != 0) {
4719 if (makecopy != 0) {
4720 KMALLOCS(ptr, void *, fp->fr_dsize);
4728 * The bcopy case is for when the data is appended
4729 * to the rule by ipf_in_compat().
4731 if (uptr >= (void *)fp &&
4732 uptr < (void *)((char *)fp + fp->fr_size)) {
4733 bcopy(uptr, ptr, fp->fr_dsize);
4736 error = COPYIN(uptr, ptr, fp->fr_dsize);
4752 * Perform per-rule type sanity checks of their members.
4753 * All code after this needs to be aware that allocated memory
4754 * may need to be free'd before exiting.
4756 switch (fp->fr_type & ~FR_T_BUILTIN)
4758 #if defined(IPFILTER_BPF)
4760 if (fp->fr_dsize == 0) {
4765 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4774 * Preparation for error case at the bottom of this function.
4776 if (fp->fr_datype == FRI_LOOKUP)
4777 fp->fr_dstptr = NULL;
4778 if (fp->fr_satype == FRI_LOOKUP)
4779 fp->fr_srcptr = NULL;
4781 if (fp->fr_dsize != sizeof(fripf_t)) {
4788 * Allowing a rule with both "keep state" and "with oow" is
4789 * pointless because adding a state entry to the table will
4790 * fail with the out of window (oow) flag set.
4792 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4798 switch (fp->fr_satype)
4800 case FRI_BROADCAST :
4803 case FRI_NETMASKED :
4805 if (fp->fr_sifpidx < 0) {
4811 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4814 if (fp->fr_srcfunc == NULL) {
4830 switch (fp->fr_datype)
4832 case FRI_BROADCAST :
4835 case FRI_NETMASKED :
4837 if (fp->fr_difpidx < 0) {
4843 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4846 if (fp->fr_dstfunc == NULL) {
4860 case FR_T_CALLFUNC :
4865 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4879 if (fp->fr_tif.fd_name != -1) {
4880 if ((fp->fr_tif.fd_name < 0) ||
4881 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4888 if (fp->fr_dif.fd_name != -1) {
4889 if ((fp->fr_dif.fd_name < 0) ||
4890 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4897 if (fp->fr_rif.fd_name != -1) {
4898 if ((fp->fr_rif.fd_name < 0) ||
4899 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4907 * Lookup all the interface names that are part of the rule.
4909 error = ipf_synclist(softc, fp, NULL);
4912 fp->fr_statecnt = 0;
4913 if (fp->fr_srctrack.ht_max_nodes != 0)
4914 ipf_rb_ht_init(&fp->fr_srctrack);
4917 * Look for an existing matching filter rule, but don't include the
4918 * next or interface pointer in the comparison (fr_next, fr_ifa).
4919 * This elminates rules which are indentical being loaded. Checksum
4920 * the constant part of the filter rule to make comparisons quicker
4921 * (this meaning no pointers are included).
4923 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4926 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4927 for (p = (u_int *)fp->fr_data; p < pp; p++)
4930 WRITE_ENTER(&softc->ipf_mutex);
4933 * Now that the filter rule lists are locked, we can walk the
4934 * chain of them without fear.
4937 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4938 if (fp->fr_collect <= f->fr_collect) {
4946 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4947 if (ipf_rule_compare(fp, f) == 0)
4952 * If zero'ing statistics, copy current to caller and zero.
4954 if (addrem == OP_ZERO) {
4960 * Copy and reduce lock because of impending copyout.
4961 * Well we should, but if we do then the atomicity of
4962 * this call and the correctness of fr_hits and
4963 * fr_bytes cannot be guaranteed. As it is, this code
4964 * only resets them to 0 if they are successfully
4965 * copied out into user space.
4967 bcopy((char *)f, (char *)fp, f->fr_size);
4968 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4971 * When we copy this rule back out, set the data
4972 * pointer to be what it was in user space.
4975 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4978 if ((f->fr_dsize != 0) && (uptr != NULL)) {
4979 error = COPYOUT(f->fr_data, uptr,
4992 if (makecopy != 0) {
4994 KFREES(ptr, fp->fr_dsize);
4996 KFREES(fp, fp->fr_size);
4998 RWLOCK_EXIT(&softc->ipf_mutex);
5004 * At the end of this, ftail must point to the place where the
5005 * new rule is to be saved/inserted/added.
5006 * For SIOCAD*FR, this should be the last rule in the group of
5007 * rules that have equal fr_collect fields.
5008 * For SIOCIN*FR, ...
5010 if (req == (ioctlcmd_t)SIOCADAFR ||
5011 req == (ioctlcmd_t)SIOCADIFR) {
5013 for (ftail = fprev; (f = *ftail) != NULL; ) {
5014 if (f->fr_collect > fp->fr_collect)
5016 ftail = &f->fr_next;
5022 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5023 req == (ioctlcmd_t)SIOCINIFR) {
5024 while ((f = *fprev) != NULL) {
5025 if (f->fr_collect >= fp->fr_collect)
5027 fprev = &f->fr_next;
5030 if (fp->fr_hits != 0) {
5031 while (fp->fr_hits && (f = *ftail)) {
5032 if (f->fr_collect != fp->fr_collect)
5035 ftail = &f->fr_next;
5045 * Request to remove a rule.
5047 if (addrem == OP_REM) {
5053 * Do not allow activity from user space to interfere
5054 * with rules not loaded that way.
5056 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5063 * Return EBUSY if the rule is being reference by
5064 * something else (eg state information.)
5066 if (f->fr_ref > 1) {
5071 #ifdef IPFILTER_SCAN
5072 if (f->fr_isctag != -1 &&
5073 (f->fr_isc != (struct ipscan *)-1))
5074 ipf_scan_detachfr(f);
5077 if (unit == IPL_LOGAUTH) {
5078 error = ipf_auth_precmd(softc, req, f, ftail);
5082 ipf_rule_delete(softc, f, unit, set);
5084 need_free = makecopy;
5088 * Not removing, so we must be adding/inserting a rule.
5095 if (unit == IPL_LOGAUTH) {
5096 error = ipf_auth_precmd(softc, req, fp, ftail);
5100 MUTEX_NUKE(&fp->fr_lock);
5101 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5102 if (fp->fr_die != 0)
5103 ipf_rule_expire_insert(softc, fp, set);
5108 fp->fr_pnext = ftail;
5109 fp->fr_next = *ftail;
5110 if (fp->fr_next != NULL)
5111 fp->fr_next->fr_pnext = &fp->fr_next;
5113 ipf_fixskip(ftail, fp, 1);
5115 fp->fr_icmpgrp = NULL;
5116 if (fp->fr_icmphead != -1) {
5117 group = FR_NAME(fp, fr_icmphead);
5118 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5119 fp->fr_icmpgrp = fg;
5122 fp->fr_grphead = NULL;
5123 if (fp->fr_grhead != -1) {
5124 group = FR_NAME(fp, fr_grhead);
5125 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5127 fp->fr_grphead = fg;
5131 RWLOCK_EXIT(&softc->ipf_mutex);
5133 if (need_free || (error != 0)) {
5134 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5135 if ((fp->fr_satype == FRI_LOOKUP) &&
5136 (fp->fr_srcptr != NULL))
5137 ipf_lookup_deref(softc, fp->fr_srctype,
5139 if ((fp->fr_datype == FRI_LOOKUP) &&
5140 (fp->fr_dstptr != NULL))
5141 ipf_lookup_deref(softc, fp->fr_dsttype,
5144 if (fp->fr_grp != NULL) {
5145 WRITE_ENTER(&softc->ipf_mutex);
5146 ipf_group_del(softc, fp->fr_grp, fp);
5147 RWLOCK_EXIT(&softc->ipf_mutex);
5149 if ((ptr != NULL) && (makecopy != 0)) {
5150 KFREES(ptr, fp->fr_dsize);
5152 KFREES(fp, fp->fr_size);
5158 /* ------------------------------------------------------------------------ */
5159 /* Function: ipf_rule_delete */
5161 /* Parameters: softc(I) - pointer to soft context main structure */
5162 /* f(I) - pointer to the rule being deleted */
5163 /* ftail(I) - pointer to the pointer to f */
5164 /* unit(I) - device for which this is for */
5165 /* set(I) - 1 or 0 (filter set) */
5167 /* This function attempts to do what it can to delete a filter rule: remove */
5168 /* it from any linked lists and remove any groups it is responsible for. */
5169 /* But in the end, removing a rule can only drop the reference count - we */
5170 /* must use that as the guide for whether or not it can be freed. */
5171 /* ------------------------------------------------------------------------ */
5173 ipf_rule_delete(softc, f, unit, set)
5174 ipf_main_softc_t *softc;
5180 * If fr_pdnext is set, then the rule is on the expire list, so
5181 * remove it from there.
5183 if (f->fr_pdnext != NULL) {
5184 *f->fr_pdnext = f->fr_dnext;
5185 if (f->fr_dnext != NULL)
5186 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5187 f->fr_pdnext = NULL;
5191 ipf_fixskip(f->fr_pnext, f, -1);
5192 if (f->fr_pnext != NULL)
5193 *f->fr_pnext = f->fr_next;
5194 if (f->fr_next != NULL)
5195 f->fr_next->fr_pnext = f->fr_pnext;
5199 (void) ipf_derefrule(softc, &f);
5202 /* ------------------------------------------------------------------------ */
5203 /* Function: ipf_rule_expire_insert */
5205 /* Parameters: softc(I) - pointer to soft context main structure */
5206 /* f(I) - pointer to rule to be added to expire list */
5207 /* set(I) - 1 or 0 (filter set) */
5209 /* If the new rule has a given expiration time, insert it into the list of */
5210 /* expiring rules with the ones to be removed first added to the front of */
5211 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5212 /* expiration interval checks. */
5213 /* ------------------------------------------------------------------------ */
5215 ipf_rule_expire_insert(softc, f, set)
5216 ipf_main_softc_t *softc;
5225 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5226 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5227 fr = fr->fr_dnext) {
5228 if (f->fr_die < fr->fr_die)
5230 if (fr->fr_dnext == NULL) {
5232 * We've got to the last rule and everything
5233 * wanted to be expired before this new node,
5234 * so we have to tack it on the end...
5237 f->fr_pdnext = &fr->fr_dnext;
5243 if (softc->ipf_rule_explist[set] == NULL) {
5244 softc->ipf_rule_explist[set] = f;
5245 f->fr_pdnext = &softc->ipf_rule_explist[set];
5246 } else if (fr != NULL) {
5248 f->fr_pdnext = fr->fr_pdnext;
5249 fr->fr_pdnext = &f->fr_dnext;
5254 /* ------------------------------------------------------------------------ */
5255 /* Function: ipf_findlookup */
5256 /* Returns: NULL = failure, else success */
5257 /* Parameters: softc(I) - pointer to soft context main structure */
5258 /* unit(I) - ipf device we want to find match for */
5259 /* fp(I) - rule for which lookup is for */
5260 /* addrp(I) - pointer to lookup information in address struct */
5261 /* maskp(O) - pointer to lookup information for storage */
5263 /* When using pools and hash tables to store addresses for matching in */
5264 /* rules, it is necessary to resolve both the object referred to by the */
5265 /* name or address (and return that pointer) and also provide the means by */
5266 /* which to determine if an address belongs to that object to make the */
5267 /* packet matching quicker. */
5268 /* ------------------------------------------------------------------------ */
5270 ipf_findlookup(softc, unit, fr, addrp, maskp)
5271 ipf_main_softc_t *softc;
5274 i6addr_t *addrp, *maskp;
5278 switch (addrp->iplookupsubtype)
5281 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5283 &maskp->iplookupfunc);
5286 if (addrp->iplookupname < 0)
5288 if (addrp->iplookupname >= fr->fr_namelen)
5290 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5291 fr->fr_names + addrp->iplookupname,
5292 &maskp->iplookupfunc);
5302 /* ------------------------------------------------------------------------ */
5303 /* Function: ipf_funcinit */
5304 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5305 /* Parameters: softc(I) - pointer to soft context main structure */
5306 /* fr(I) - pointer to filter rule */
5308 /* If a rule is a call rule, then check if the function it points to needs */
5309 /* an init function to be called now the rule has been loaded. */
5310 /* ------------------------------------------------------------------------ */
5312 ipf_funcinit(softc, fr)
5313 ipf_main_softc_t *softc;
5316 ipfunc_resolve_t *ft;
5322 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5323 if (ft->ipfu_addr == fr->fr_func) {
5325 if (ft->ipfu_init != NULL)
5326 err = (*ft->ipfu_init)(softc, fr);
5333 /* ------------------------------------------------------------------------ */
5334 /* Function: ipf_funcfini */
5336 /* Parameters: softc(I) - pointer to soft context main structure */
5337 /* fr(I) - pointer to filter rule */
5339 /* For a given filter rule, call the matching "fini" function if the rule */
5340 /* is using a known function that would have resulted in the "init" being */
5341 /* called for ealier. */
5342 /* ------------------------------------------------------------------------ */
5344 ipf_funcfini(softc, fr)
5345 ipf_main_softc_t *softc;
5348 ipfunc_resolve_t *ft;
5350 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5351 if (ft->ipfu_addr == fr->fr_func) {
5352 if (ft->ipfu_fini != NULL)
5353 (void) (*ft->ipfu_fini)(softc, fr);
5359 /* ------------------------------------------------------------------------ */
5360 /* Function: ipf_findfunc */
5361 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5362 /* Parameters: funcptr(I) - function pointer to lookup */
5364 /* Look for a function in the table of known functions. */
5365 /* ------------------------------------------------------------------------ */
5367 ipf_findfunc(funcptr)
5370 ipfunc_resolve_t *ft;
5372 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5373 if (ft->ipfu_addr == funcptr)
5379 /* ------------------------------------------------------------------------ */
5380 /* Function: ipf_resolvefunc */
5381 /* Returns: int - 0 == success, else error */
5382 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5384 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5385 /* This will either be the function name (if the pointer is set) or the */
5386 /* function pointer if the name is set. When found, fill in the other one */
5387 /* so that the entire, complete, structure can be copied back to user space.*/
5388 /* ------------------------------------------------------------------------ */
5390 ipf_resolvefunc(softc, data)
5391 ipf_main_softc_t *softc;
5394 ipfunc_resolve_t res, *ft;
5397 error = BCOPYIN(data, &res, sizeof(res));
5403 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5404 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5405 if (strncmp(res.ipfu_name, ft->ipfu_name,
5406 sizeof(res.ipfu_name)) == 0) {
5407 res.ipfu_addr = ft->ipfu_addr;
5408 res.ipfu_init = ft->ipfu_init;
5409 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5416 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5417 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5418 if (ft->ipfu_addr == res.ipfu_addr) {
5419 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5420 sizeof(res.ipfu_name));
5421 res.ipfu_init = ft->ipfu_init;
5422 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5434 #if !defined(_KERNEL) || SOLARIS
5437 * ppsratecheck(): packets (or events) per second limitation.
5440 ppsratecheck(lasttime, curpps, maxpps)
5441 struct timeval *lasttime;
5443 int maxpps; /* maximum pps allowed */
5445 struct timeval tv, delta;
5450 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5451 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5452 if (delta.tv_usec < 0) {
5454 delta.tv_usec += 1000000;
5458 * check for 0,0 is so that the message will be seen at least once.
5459 * if more than one second have passed since the last update of
5460 * lasttime, reset the counter.
5462 * we do increment *curpps even in *curpps < maxpps case, as some may
5463 * try to use *curpps for stat purposes as well.
5465 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5466 delta.tv_sec >= 1) {
5470 } else if (maxpps < 0)
5472 else if (*curpps < maxpps)
5476 *curpps = *curpps + 1;
5483 /* ------------------------------------------------------------------------ */
5484 /* Function: ipf_derefrule */
5485 /* Returns: int - 0 == rule freed up, else rule not freed */
5486 /* Parameters: fr(I) - pointer to filter rule */
5488 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5489 /* free it and any associated storage space being used by it. */
5490 /* ------------------------------------------------------------------------ */
5492 ipf_derefrule(softc, frp)
5493 ipf_main_softc_t *softc;
5502 MUTEX_ENTER(&fr->fr_lock);
5504 if (fr->fr_ref == 0) {
5505 MUTEX_EXIT(&fr->fr_lock);
5506 MUTEX_DESTROY(&fr->fr_lock);
5508 ipf_funcfini(softc, fr);
5511 if (fdp->fd_type == FRD_DSTLIST)
5512 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5515 if (fdp->fd_type == FRD_DSTLIST)
5516 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5519 if (fdp->fd_type == FRD_DSTLIST)
5520 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5522 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5523 fr->fr_satype == FRI_LOOKUP)
5524 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5525 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5526 fr->fr_datype == FRI_LOOKUP)
5527 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5529 if (fr->fr_grp != NULL)
5530 ipf_group_del(softc, fr->fr_grp, fr);
5532 if (fr->fr_grphead != NULL)
5533 ipf_group_del(softc, fr->fr_grphead, fr);
5535 if (fr->fr_icmpgrp != NULL)
5536 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5538 if ((fr->fr_flags & FR_COPIED) != 0) {
5540 KFREES(fr->fr_data, fr->fr_dsize);
5542 KFREES(fr, fr->fr_size);
5547 MUTEX_EXIT(&fr->fr_lock);
5553 /* ------------------------------------------------------------------------ */
5554 /* Function: ipf_grpmapinit */
5555 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5556 /* Parameters: fr(I) - pointer to rule to find hash table for */
5558 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5559 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5560 /* ------------------------------------------------------------------------ */
5562 ipf_grpmapinit(softc, fr)
5563 ipf_main_softc_t *softc;
5566 char name[FR_GROUPLEN];
5569 #if defined(SNPRINTF) && defined(_KERNEL)
5570 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5572 (void) sprintf(name, "%d", fr->fr_arg);
5574 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5579 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5589 /* ------------------------------------------------------------------------ */
5590 /* Function: ipf_grpmapfini */
5591 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5592 /* Parameters: softc(I) - pointer to soft context main structure */
5593 /* fr(I) - pointer to rule to release hash table for */
5595 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5596 /* be called to undo what ipf_grpmapinit caused to be done. */
5597 /* ------------------------------------------------------------------------ */
5599 ipf_grpmapfini(softc, fr)
5600 ipf_main_softc_t *softc;
5606 ipf_lookup_deref(softc, IPLT_HASH, iph);
5611 /* ------------------------------------------------------------------------ */
5612 /* Function: ipf_srcgrpmap */
5613 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5614 /* Parameters: fin(I) - pointer to packet information */
5615 /* passp(IO) - pointer to current/new filter decision (unused) */
5617 /* Look for a rule group head in a hash table, using the source address as */
5618 /* the key, and descend into that group and continue matching rules against */
5620 /* ------------------------------------------------------------------------ */
5622 ipf_srcgrpmap(fin, passp)
5629 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5635 fin->fin_fr = fg->fg_start;
5636 (void) ipf_scanlist(fin, *passp);
5641 /* ------------------------------------------------------------------------ */
5642 /* Function: ipf_dstgrpmap */
5643 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5644 /* Parameters: fin(I) - pointer to packet information */
5645 /* passp(IO) - pointer to current/new filter decision (unused) */
5647 /* Look for a rule group head in a hash table, using the destination */
5648 /* address as the key, and descend into that group and continue matching */
5649 /* rules against the packet. */
5650 /* ------------------------------------------------------------------------ */
5652 ipf_dstgrpmap(fin, passp)
5659 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5665 fin->fin_fr = fg->fg_start;
5666 (void) ipf_scanlist(fin, *passp);
5673 * These functions manage objects on queues for efficient timeouts. There
5674 * are a number of system defined queues as well as user defined timeouts.
5675 * It is expected that a lock is held in the domain in which the queue
5676 * belongs (i.e. either state or NAT) when calling any of these functions
5677 * that prevents ipf_freetimeoutqueue() from being called at the same time
5682 /* ------------------------------------------------------------------------ */
5683 /* Function: ipf_addtimeoutqueue */
5684 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5685 /* timeout queue with given interval. */
5686 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5687 /* of interface queues. */
5688 /* seconds(I) - timeout value in seconds for this queue. */
5690 /* This routine first looks for a timeout queue that matches the interval */
5691 /* being requested. If it finds one, increments the reference counter and */
5692 /* returns a pointer to it. If none are found, it allocates a new one and */
5693 /* inserts it at the top of the list. */
5696 /* It is assumed that the caller of this function has an appropriate lock */
5697 /* held (exclusively) in the domain that encompases 'parent'. */
5698 /* ------------------------------------------------------------------------ */
5700 ipf_addtimeoutqueue(softc, parent, seconds)
5701 ipf_main_softc_t *softc;
5708 period = seconds * IPF_HZ_DIVIDE;
5710 MUTEX_ENTER(&softc->ipf_timeoutlock);
5711 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5712 if (ifq->ifq_ttl == period) {
5714 * Reset the delete flag, if set, so the structure
5715 * gets reused rather than freed and reallocated.
5717 MUTEX_ENTER(&ifq->ifq_lock);
5718 ifq->ifq_flags &= ~IFQF_DELETE;
5720 MUTEX_EXIT(&ifq->ifq_lock);
5721 MUTEX_EXIT(&softc->ipf_timeoutlock);
5727 KMALLOC(ifq, ipftq_t *);
5729 MUTEX_NUKE(&ifq->ifq_lock);
5730 IPFTQ_INIT(ifq, period, "ipftq mutex");
5731 ifq->ifq_next = *parent;
5732 ifq->ifq_pnext = parent;
5733 ifq->ifq_flags = IFQF_USER;
5736 softc->ipf_userifqs++;
5738 MUTEX_EXIT(&softc->ipf_timeoutlock);
5743 /* ------------------------------------------------------------------------ */
5744 /* Function: ipf_deletetimeoutqueue */
5745 /* Returns: int - new reference count value of the timeout queue */
5746 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5747 /* Locks: ifq->ifq_lock */
5749 /* This routine must be called when we're discarding a pointer to a timeout */
5750 /* queue object, taking care of the reference counter. */
5752 /* Now that this just sets a DELETE flag, it requires the expire code to */
5753 /* check the list of user defined timeout queues and call the free function */
5754 /* below (currently commented out) to stop memory leaking. It is done this */
5755 /* way because the locking may not be sufficient to safely do a free when */
5756 /* this function is called. */
5757 /* ------------------------------------------------------------------------ */
5759 ipf_deletetimeoutqueue(ifq)
5764 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5765 ifq->ifq_flags |= IFQF_DELETE;
5768 return ifq->ifq_ref;
5772 /* ------------------------------------------------------------------------ */
5773 /* Function: ipf_freetimeoutqueue */
5774 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5778 /* It is assumed that the caller of this function has an appropriate lock */
5779 /* held (exclusively) in the domain that encompases the callers "domain". */
5780 /* The ifq_lock for this structure should not be held. */
5782 /* Remove a user defined timeout queue from the list of queues it is in and */
5783 /* tidy up after this is done. */
5784 /* ------------------------------------------------------------------------ */
5786 ipf_freetimeoutqueue(softc, ifq)
5787 ipf_main_softc_t *softc;
5791 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5792 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5793 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5794 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5800 * Remove from its position in the list.
5802 *ifq->ifq_pnext = ifq->ifq_next;
5803 if (ifq->ifq_next != NULL)
5804 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5805 ifq->ifq_next = NULL;
5806 ifq->ifq_pnext = NULL;
5808 MUTEX_DESTROY(&ifq->ifq_lock);
5809 ATOMIC_DEC(softc->ipf_userifqs);
5814 /* ------------------------------------------------------------------------ */
5815 /* Function: ipf_deletequeueentry */
5817 /* Parameters: tqe(I) - timeout queue entry to delete */
5819 /* Remove a tail queue entry from its queue and make it an orphan. */
5820 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5821 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5822 /* the correct lock(s) may not be held that would make it safe to do so. */
5823 /* ------------------------------------------------------------------------ */
5825 ipf_deletequeueentry(tqe)
5832 MUTEX_ENTER(&ifq->ifq_lock);
5834 if (tqe->tqe_pnext != NULL) {
5835 *tqe->tqe_pnext = tqe->tqe_next;
5836 if (tqe->tqe_next != NULL)
5837 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5838 else /* we must be the tail anyway */
5839 ifq->ifq_tail = tqe->tqe_pnext;
5841 tqe->tqe_pnext = NULL;
5842 tqe->tqe_ifq = NULL;
5845 (void) ipf_deletetimeoutqueue(ifq);
5846 ASSERT(ifq->ifq_ref > 0);
5848 MUTEX_EXIT(&ifq->ifq_lock);
5852 /* ------------------------------------------------------------------------ */
5853 /* Function: ipf_queuefront */
5855 /* Parameters: tqe(I) - pointer to timeout queue entry */
5857 /* Move a queue entry to the front of the queue, if it isn't already there. */
5858 /* ------------------------------------------------------------------------ */
5869 MUTEX_ENTER(&ifq->ifq_lock);
5870 if (ifq->ifq_head != tqe) {
5871 *tqe->tqe_pnext = tqe->tqe_next;
5873 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5875 ifq->ifq_tail = tqe->tqe_pnext;
5877 tqe->tqe_next = ifq->ifq_head;
5878 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5879 ifq->ifq_head = tqe;
5880 tqe->tqe_pnext = &ifq->ifq_head;
5882 MUTEX_EXIT(&ifq->ifq_lock);
5886 /* ------------------------------------------------------------------------ */
5887 /* Function: ipf_queueback */
5889 /* Parameters: ticks(I) - ipf tick time to use with this call */
5890 /* tqe(I) - pointer to timeout queue entry */
5892 /* Move a queue entry to the back of the queue, if it isn't already there. */
5893 /* We use use ticks to calculate the expiration and mark for when we last */
5894 /* touched the structure. */
5895 /* ------------------------------------------------------------------------ */
5897 ipf_queueback(ticks, tqe)
5906 tqe->tqe_die = ticks + ifq->ifq_ttl;
5907 tqe->tqe_touched = ticks;
5909 MUTEX_ENTER(&ifq->ifq_lock);
5910 if (tqe->tqe_next != NULL) { /* at the end already ? */
5914 *tqe->tqe_pnext = tqe->tqe_next;
5915 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5918 * Make it the last entry.
5920 tqe->tqe_next = NULL;
5921 tqe->tqe_pnext = ifq->ifq_tail;
5922 *ifq->ifq_tail = tqe;
5923 ifq->ifq_tail = &tqe->tqe_next;
5925 MUTEX_EXIT(&ifq->ifq_lock);
5929 /* ------------------------------------------------------------------------ */
5930 /* Function: ipf_queueappend */
5932 /* Parameters: ticks(I) - ipf tick time to use with this call */
5933 /* tqe(I) - pointer to timeout queue entry */
5934 /* ifq(I) - pointer to timeout queue */
5935 /* parent(I) - owing object pointer */
5937 /* Add a new item to this queue and put it on the very end. */
5938 /* We use use ticks to calculate the expiration and mark for when we last */
5939 /* touched the structure. */
5940 /* ------------------------------------------------------------------------ */
5942 ipf_queueappend(ticks, tqe, ifq, parent)
5949 MUTEX_ENTER(&ifq->ifq_lock);
5950 tqe->tqe_parent = parent;
5951 tqe->tqe_pnext = ifq->ifq_tail;
5952 *ifq->ifq_tail = tqe;
5953 ifq->ifq_tail = &tqe->tqe_next;
5954 tqe->tqe_next = NULL;
5956 tqe->tqe_die = ticks + ifq->ifq_ttl;
5957 tqe->tqe_touched = ticks;
5959 MUTEX_EXIT(&ifq->ifq_lock);
5963 /* ------------------------------------------------------------------------ */
5964 /* Function: ipf_movequeue */
5966 /* Parameters: tq(I) - pointer to timeout queue information */
5967 /* oifp(I) - old timeout queue entry was on */
5968 /* nifp(I) - new timeout queue to put entry on */
5970 /* Move a queue entry from one timeout queue to another timeout queue. */
5971 /* If it notices that the current entry is already last and does not need */
5972 /* to move queue, the return. */
5973 /* ------------------------------------------------------------------------ */
5975 ipf_movequeue(ticks, tqe, oifq, nifq)
5978 ipftq_t *oifq, *nifq;
5982 * If the queue hasn't changed and we last touched this entry at the
5983 * same ipf time, then we're not going to achieve anything by either
5984 * changing the ttl or moving it on the queue.
5986 if (oifq == nifq && tqe->tqe_touched == ticks)
5990 * For any of this to be outside the lock, there is a risk that two
5991 * packets entering simultaneously, with one changing to a different
5992 * queue and one not, could end up with things in a bizarre state.
5994 MUTEX_ENTER(&oifq->ifq_lock);
5996 tqe->tqe_touched = ticks;
5997 tqe->tqe_die = ticks + nifq->ifq_ttl;
5999 * Is the operation here going to be a no-op ?
6002 if ((tqe->tqe_next == NULL) ||
6003 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6004 MUTEX_EXIT(&oifq->ifq_lock);
6010 * Remove from the old queue
6012 *tqe->tqe_pnext = tqe->tqe_next;
6014 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6016 oifq->ifq_tail = tqe->tqe_pnext;
6017 tqe->tqe_next = NULL;
6020 * If we're moving from one queue to another, release the
6021 * lock on the old queue and get a lock on the new queue.
6022 * For user defined queues, if we're moving off it, call
6023 * delete in case it can now be freed.
6026 tqe->tqe_ifq = NULL;
6028 (void) ipf_deletetimeoutqueue(oifq);
6030 MUTEX_EXIT(&oifq->ifq_lock);
6032 MUTEX_ENTER(&nifq->ifq_lock);
6034 tqe->tqe_ifq = nifq;
6039 * Add to the bottom of the new queue
6041 tqe->tqe_pnext = nifq->ifq_tail;
6042 *nifq->ifq_tail = tqe;
6043 nifq->ifq_tail = &tqe->tqe_next;
6044 MUTEX_EXIT(&nifq->ifq_lock);
6048 /* ------------------------------------------------------------------------ */
6049 /* Function: ipf_updateipid */
6050 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
6051 /* Parameters: fin(I) - pointer to packet information */
6053 /* When we are doing NAT, change the IP of every packet to represent a */
6054 /* single sequence of packets coming from the host, hiding any host */
6055 /* specific sequencing that might otherwise be revealed. If the packet is */
6056 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
6057 /* the fragment cache for non-leading fragments. If a non-leading fragment */
6058 /* has no match in the cache, return an error. */
6059 /* ------------------------------------------------------------------------ */
6064 u_short id, ido, sums;
6069 ido = ntohs(ip->ip_id);
6070 if (fin->fin_off != 0) {
6071 sum = ipf_frag_ipidknown(fin);
6072 if (sum == 0xffffffff)
6076 ip->ip_id = htons(id);
6079 id = ntohs(ip->ip_id);
6080 if ((fin->fin_flx & FI_FRAG) != 0)
6081 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6086 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6087 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6089 sum = (sum >> 16) + (sum & 0xffff);
6090 sum = (sum >> 16) + (sum & 0xffff);
6091 sums = ~(u_short)sum;
6092 ip->ip_sum = htons(sums);
6097 #ifdef NEED_FRGETIFNAME
6098 /* ------------------------------------------------------------------------ */
6099 /* Function: ipf_getifname */
6100 /* Returns: char * - pointer to interface name */
6101 /* Parameters: ifp(I) - pointer to network interface */
6102 /* buffer(O) - pointer to where to store interface name */
6104 /* Constructs an interface name in the buffer passed. The buffer passed is */
6105 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6106 /* as a NULL pointer then return a pointer to a static array. */
6107 /* ------------------------------------------------------------------------ */
6109 ipf_getifname(ifp, buffer)
6113 static char namebuf[LIFNAMSIZ];
6114 # if defined(MENTAT) || defined(__FreeBSD__)
6122 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6123 buffer[LIFNAMSIZ - 1] = '\0';
6124 # if defined(MENTAT) || defined(__FreeBSD__)
6125 for (s = buffer; *s; s++)
6127 unit = ifp->if_unit;
6128 space = LIFNAMSIZ - (s - buffer);
6129 if ((space > 0) && (unit >= 0)) {
6130 # if defined(SNPRINTF) && defined(_KERNEL)
6131 SNPRINTF(temp, sizeof(temp), "%d", unit);
6133 (void) sprintf(temp, "%d", unit);
6135 (void) strncpy(s, temp, space);
6143 /* ------------------------------------------------------------------------ */
6144 /* Function: ipf_ioctlswitch */
6145 /* Returns: int - -1 continue processing, else ioctl return value */
6146 /* Parameters: unit(I) - device unit opened */
6147 /* data(I) - pointer to ioctl data */
6148 /* cmd(I) - ioctl command */
6149 /* mode(I) - mode value */
6150 /* uid(I) - uid making the ioctl call */
6151 /* ctx(I) - pointer to context data */
6153 /* Based on the value of unit, call the appropriate ioctl handler or return */
6154 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6155 /* for the device in order to execute the ioctl. A special case is made */
6156 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6157 /* The context data pointer is passed through as this is used as the key */
6158 /* for locating a matching token for continued access for walking lists, */
6160 /* ------------------------------------------------------------------------ */
6162 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6163 ipf_main_softc_t *softc;
6164 int unit, mode, uid;
6172 case SIOCIPFINTERROR :
6173 error = BCOPYOUT(&softc->ipf_interror, data,
6174 sizeof(softc->ipf_interror));
6187 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6190 if (softc->ipf_running > 0) {
6191 error = ipf_nat_ioctl(softc, data, cmd, mode,
6199 if (softc->ipf_running > 0) {
6200 error = ipf_state_ioctl(softc, data, cmd, mode,
6208 if (softc->ipf_running > 0) {
6209 error = ipf_auth_ioctl(softc, data, cmd, mode,
6217 if (softc->ipf_running > 0) {
6218 error = ipf_sync_ioctl(softc, data, cmd, mode,
6226 #ifdef IPFILTER_SCAN
6227 if (softc->ipf_running > 0)
6228 error = ipf_scan_ioctl(softc, data, cmd, mode,
6237 case IPL_LOGLOOKUP :
6238 if (softc->ipf_running > 0) {
6239 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6257 * This array defines the expected size of objects coming into the kernel
6258 * for the various recognised object types. The first column is flags (see
6259 * below), 2nd column is current size, 3rd column is the version number of
6260 * when the current size became current.
6262 * 1 = minimum size, not absolute size
6264 static const int ipf_objbytes[IPFOBJ_COUNT][3] = {
6265 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6266 { 1, sizeof(struct friostat), 5010000 },
6267 { 0, sizeof(struct fr_info), 5010000 },
6268 { 0, sizeof(struct ipf_authstat), 4010100 },
6269 { 0, sizeof(struct ipfrstat), 5010000 },
6270 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6271 { 0, sizeof(struct natstat), 5010000 },
6272 { 0, sizeof(struct ipstate_save), 5010000 },
6273 { 1, sizeof(struct nat_save), 5010000 },
6274 { 0, sizeof(struct natlookup), 5010000 },
6275 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6276 { 0, sizeof(struct ips_stat), 5010000 },
6277 { 0, sizeof(struct frauth), 5010000 },
6278 { 0, sizeof(struct ipftune), 4010100 },
6279 { 0, sizeof(struct nat), 5010000 },
6280 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6281 { 0, sizeof(struct ipfgeniter), 4011400 },
6282 { 0, sizeof(struct ipftable), 4011400 },
6283 { 0, sizeof(struct ipflookupiter), 4011400 },
6284 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6285 { 1, 0, 0 }, /* IPFEXPR */
6286 { 0, 0, 0 }, /* PROXYCTL */
6287 { 0, sizeof (struct fripf), 5010000 }
6291 /* ------------------------------------------------------------------------ */
6292 /* Function: ipf_inobj */
6293 /* Returns: int - 0 = success, else failure */
6294 /* Parameters: softc(I) - soft context pointerto work with */
6295 /* data(I) - pointer to ioctl data */
6296 /* objp(O) - where to store ipfobj structure */
6297 /* ptr(I) - pointer to data to copy out */
6298 /* type(I) - type of structure being moved */
6300 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6301 /* add things to check for version numbers, sizes, etc, to make it backward */
6302 /* compatible at the ABI for user land. */
6303 /* If objp is not NULL then we assume that the caller wants to see what is */
6304 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6305 /* the caller what version of ipfilter the ioctl program was written to. */
6306 /* ------------------------------------------------------------------------ */
6308 ipf_inobj(softc, data, objp, ptr, type)
6309 ipf_main_softc_t *softc;
6319 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6326 error = BCOPYIN(data, objp, sizeof(*objp));
6332 if (objp->ipfo_type != type) {
6337 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6338 if ((ipf_objbytes[type][0] & 1) != 0) {
6339 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6343 size = ipf_objbytes[type][1];
6344 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6345 size = objp->ipfo_size;
6350 error = COPYIN(objp->ipfo_ptr, ptr, size);
6356 #ifdef IPFILTER_COMPAT
6357 error = ipf_in_compat(softc, objp, ptr, 0);
6367 /* ------------------------------------------------------------------------ */
6368 /* Function: ipf_inobjsz */
6369 /* Returns: int - 0 = success, else failure */
6370 /* Parameters: softc(I) - soft context pointerto work with */
6371 /* data(I) - pointer to ioctl data */
6372 /* ptr(I) - pointer to store real data in */
6373 /* type(I) - type of structure being moved */
6374 /* sz(I) - size of data to copy */
6376 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6377 /* but it must not be smaller than the size defined for the type and the */
6378 /* type must allow for varied sized objects. The extra requirement here is */
6379 /* that sz must match the size of the object being passed in - this is not */
6380 /* not possible nor required in ipf_inobj(). */
6381 /* ------------------------------------------------------------------------ */
6383 ipf_inobjsz(softc, data, ptr, type, sz)
6384 ipf_main_softc_t *softc;
6392 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6397 error = BCOPYIN(data, &obj, sizeof(obj));
6403 if (obj.ipfo_type != type) {
6408 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6409 if (((ipf_objbytes[type][0] & 1) == 0) ||
6410 (sz < ipf_objbytes[type][1])) {
6414 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6420 #ifdef IPFILTER_COMPAT
6421 error = ipf_in_compat(softc, &obj, ptr, sz);
6431 /* ------------------------------------------------------------------------ */
6432 /* Function: ipf_outobjsz */
6433 /* Returns: int - 0 = success, else failure */
6434 /* Parameters: data(I) - pointer to ioctl data */
6435 /* ptr(I) - pointer to store real data in */
6436 /* type(I) - type of structure being moved */
6437 /* sz(I) - size of data to copy */
6439 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6440 /* but it must not be smaller than the size defined for the type and the */
6441 /* type must allow for varied sized objects. The extra requirement here is */
6442 /* that sz must match the size of the object being passed in - this is not */
6443 /* not possible nor required in ipf_outobj(). */
6444 /* ------------------------------------------------------------------------ */
6446 ipf_outobjsz(softc, data, ptr, type, sz)
6447 ipf_main_softc_t *softc;
6455 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6460 error = BCOPYIN(data, &obj, sizeof(obj));
6466 if (obj.ipfo_type != type) {
6471 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6472 if (((ipf_objbytes[type][0] & 1) == 0) ||
6473 (sz < ipf_objbytes[type][1])) {
6477 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6483 #ifdef IPFILTER_COMPAT
6484 error = ipf_out_compat(softc, &obj, ptr);
6494 /* ------------------------------------------------------------------------ */
6495 /* Function: ipf_outobj */
6496 /* Returns: int - 0 = success, else failure */
6497 /* Parameters: data(I) - pointer to ioctl data */
6498 /* ptr(I) - pointer to store real data in */
6499 /* type(I) - type of structure being moved */
6501 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6502 /* future, we add things to check for version numbers, sizes, etc, to make */
6503 /* it backward compatible at the ABI for user land. */
6504 /* ------------------------------------------------------------------------ */
6506 ipf_outobj(softc, data, ptr, type)
6507 ipf_main_softc_t *softc;
6515 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6520 error = BCOPYIN(data, &obj, sizeof(obj));
6526 if (obj.ipfo_type != type) {
6531 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6532 if ((ipf_objbytes[type][0] & 1) != 0) {
6533 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6537 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6542 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6548 #ifdef IPFILTER_COMPAT
6549 error = ipf_out_compat(softc, &obj, ptr);
6559 /* ------------------------------------------------------------------------ */
6560 /* Function: ipf_outobjk */
6561 /* Returns: int - 0 = success, else failure */
6562 /* Parameters: obj(I) - pointer to data description structure */
6563 /* ptr(I) - pointer to kernel data to copy out */
6565 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6566 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6567 /* already populated with information and now we just need to use it. */
6568 /* There is no need for this function to have a "type" parameter as there */
6569 /* is no point in validating information that comes from the kernel with */
6571 /* ------------------------------------------------------------------------ */
6573 ipf_outobjk(softc, obj, ptr)
6574 ipf_main_softc_t *softc;
6578 int type = obj->ipfo_type;
6581 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6586 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6587 if ((ipf_objbytes[type][0] & 1) != 0) {
6588 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6593 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6598 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6604 #ifdef IPFILTER_COMPAT
6605 error = ipf_out_compat(softc, obj, ptr);
6615 /* ------------------------------------------------------------------------ */
6616 /* Function: ipf_checkl4sum */
6617 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6618 /* Parameters: fin(I) - pointer to packet information */
6620 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6621 /* not possible, return without indicating a failure or success but in a */
6622 /* way that is ditinguishable. This function should only be called by the */
6623 /* ipf_checkv6sum() for each platform. */
6624 /* ------------------------------------------------------------------------ */
6629 u_short sum, hdrsum, *csump;
6634 * If the TCP packet isn't a fragment, isn't too short and otherwise
6635 * isn't already considered "bad", then validate the checksum. If
6636 * this check fails then considered the packet to be "bad".
6638 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6641 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6642 if (fin->fin_out == 1) {
6643 fin->fin_cksum = FI_CK_SUMOK;
6655 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6661 if (udp->uh_sum != 0) {
6662 csump = &udp->uh_sum;
6668 case IPPROTO_ICMPV6 :
6669 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6675 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6688 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6690 #if !defined(_KERNEL)
6691 if (sum == hdrsum) {
6692 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6694 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6697 DT2(l4sums, u_short, hdrsum, u_short, sum);
6699 if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6701 if (hdrsum == sum) {
6703 fin->fin_cksum = FI_CK_SUMOK;
6706 fin->fin_cksum = FI_CK_BAD;
6711 /* ------------------------------------------------------------------------ */
6712 /* Function: ipf_ifpfillv4addr */
6713 /* Returns: int - 0 = address update, -1 = address not updated */
6714 /* Parameters: atype(I) - type of network address update to perform */
6715 /* sin(I) - pointer to source of address information */
6716 /* mask(I) - pointer to source of netmask information */
6717 /* inp(I) - pointer to destination address store */
6718 /* inpmask(I) - pointer to destination netmask store */
6720 /* Given a type of network address update (atype) to perform, copy */
6721 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6722 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6723 /* which case the operation fails. For all values of atype other than */
6724 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6726 /* ------------------------------------------------------------------------ */
6728 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6730 struct sockaddr_in *sin, *mask;
6731 struct in_addr *inp, *inpmask;
6733 if (inpmask != NULL && atype != FRI_NETMASKED)
6734 inpmask->s_addr = 0xffffffff;
6736 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6737 if (atype == FRI_NETMASKED) {
6738 if (inpmask == NULL)
6740 inpmask->s_addr = mask->sin_addr.s_addr;
6742 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6744 inp->s_addr = sin->sin_addr.s_addr;
6751 /* ------------------------------------------------------------------------ */
6752 /* Function: ipf_ifpfillv6addr */
6753 /* Returns: int - 0 = address update, -1 = address not updated */
6754 /* Parameters: atype(I) - type of network address update to perform */
6755 /* sin(I) - pointer to source of address information */
6756 /* mask(I) - pointer to source of netmask information */
6757 /* inp(I) - pointer to destination address store */
6758 /* inpmask(I) - pointer to destination netmask store */
6760 /* Given a type of network address update (atype) to perform, copy */
6761 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6762 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6763 /* which case the operation fails. For all values of atype other than */
6764 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6766 /* ------------------------------------------------------------------------ */
6768 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6770 struct sockaddr_in6 *sin, *mask;
6771 i6addr_t *inp, *inpmask;
6773 i6addr_t *src, *and;
6775 src = (i6addr_t *)&sin->sin6_addr;
6776 and = (i6addr_t *)&mask->sin6_addr;
6778 if (inpmask != NULL && atype != FRI_NETMASKED) {
6779 inpmask->i6[0] = 0xffffffff;
6780 inpmask->i6[1] = 0xffffffff;
6781 inpmask->i6[2] = 0xffffffff;
6782 inpmask->i6[3] = 0xffffffff;
6785 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6786 if (atype == FRI_NETMASKED) {
6787 if (inpmask == NULL)
6789 inpmask->i6[0] = and->i6[0];
6790 inpmask->i6[1] = and->i6[1];
6791 inpmask->i6[2] = and->i6[2];
6792 inpmask->i6[3] = and->i6[3];
6795 inp->i6[0] = src->i6[0] & and->i6[0];
6796 inp->i6[1] = src->i6[1] & and->i6[1];
6797 inp->i6[2] = src->i6[2] & and->i6[2];
6798 inp->i6[3] = src->i6[3] & and->i6[3];
6800 inp->i6[0] = src->i6[0];
6801 inp->i6[1] = src->i6[1];
6802 inp->i6[2] = src->i6[2];
6803 inp->i6[3] = src->i6[3];
6810 /* ------------------------------------------------------------------------ */
6811 /* Function: ipf_matchtag */
6812 /* Returns: 0 == mismatch, 1 == match. */
6813 /* Parameters: tag1(I) - pointer to first tag to compare */
6814 /* tag2(I) - pointer to second tag to compare */
6816 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6817 /* considered to be a match or not match, respectively. The tag is 16 */
6818 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6819 /* compare the ints instead, for speed. tag1 is the master of the */
6820 /* comparison. This function should only be called with both tag1 and tag2 */
6821 /* as non-NULL pointers. */
6822 /* ------------------------------------------------------------------------ */
6824 ipf_matchtag(tag1, tag2)
6825 ipftag_t *tag1, *tag2;
6830 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6833 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6834 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6835 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6836 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6842 /* ------------------------------------------------------------------------ */
6843 /* Function: ipf_coalesce */
6844 /* Returns: 1 == success, -1 == failure, 0 == no change */
6845 /* Parameters: fin(I) - pointer to packet information */
6847 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6848 /* If this call returns a failure then the buffers have also been freed. */
6849 /* ------------------------------------------------------------------------ */
6855 if ((fin->fin_flx & FI_COALESCE) != 0)
6859 * If the mbuf pointers indicate that there is no mbuf to work with,
6860 * return but do not indicate success or failure.
6862 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6865 #if defined(_KERNEL)
6866 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6867 ipf_main_softc_t *softc = fin->fin_main_soft;
6869 DT1(frb_coalesce, fr_info_t *, fin);
6870 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6872 FREE_MB_T(*fin->fin_mp);
6874 fin->fin_reason = FRB_COALESCE;
6875 *fin->fin_mp = NULL;
6880 fin = fin; /* LINT */
6887 * The following table lists all of the tunable variables that can be
6888 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6889 * in the table below is as follows:
6891 * pointer to value, name of value, minimum, maximum, size of the value's
6892 * container, value attribute flags
6894 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6895 * means the value can only be written to when IPFilter is loaded but disabled.
6896 * The obvious implication is if neither of these are set then the value can be
6897 * changed at any time without harm.
6901 /* ------------------------------------------------------------------------ */
6902 /* Function: ipf_tune_findbycookie */
6903 /* Returns: NULL = search failed, else pointer to tune struct */
6904 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6905 /* next(O) - pointer to place to store the cookie for the */
6906 /* "next" tuneable, if it is desired. */
6908 /* This function is used to walk through all of the existing tunables with */
6909 /* successive calls. It searches the known tunables for the one which has */
6910 /* a matching value for "cookie" - ie its address. When returning a match, */
6911 /* the next one to be found may be returned inside next. */
6912 /* ------------------------------------------------------------------------ */
6913 static ipftuneable_t *
6914 ipf_tune_findbycookie(ptop, cookie, next)
6915 ipftuneable_t **ptop;
6916 void *cookie, **next;
6918 ipftuneable_t *ta, **tap;
6920 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6924 * If the next entry in the array has a name
6925 * present, then return a pointer to it for
6926 * where to go next, else return a pointer to
6927 * the dynaminc list as a key to search there
6928 * next. This facilitates a weak linking of
6929 * the two "lists" together.
6931 if ((ta + 1)->ipft_name != NULL)
6939 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6940 if (tap == cookie) {
6942 *next = &ta->ipft_next;
6952 /* ------------------------------------------------------------------------ */
6953 /* Function: ipf_tune_findbyname */
6954 /* Returns: NULL = search failed, else pointer to tune struct */
6955 /* Parameters: name(I) - name of the tuneable entry to find. */
6957 /* Search the static array of tuneables and the list of dynamic tuneables */
6958 /* for an entry with a matching name. If we can find one, return a pointer */
6959 /* to the matching structure. */
6960 /* ------------------------------------------------------------------------ */
6961 static ipftuneable_t *
6962 ipf_tune_findbyname(top, name)
6968 for (ta = top; ta != NULL; ta = ta->ipft_next)
6969 if (!strcmp(ta->ipft_name, name)) {
6977 /* ------------------------------------------------------------------------ */
6978 /* Function: ipf_tune_add_array */
6979 /* Returns: int - 0 == success, else failure */
6980 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6982 /* Appends tune structures from the array passed in (newtune) to the end of */
6983 /* the current list of "dynamic" tuneable parameters. */
6984 /* If any entry to be added is already present (by name) then the operation */
6985 /* is aborted - entries that have been added are removed before returning. */
6986 /* An entry with no name (NULL) is used as the indication that the end of */
6987 /* the array has been reached. */
6988 /* ------------------------------------------------------------------------ */
6990 ipf_tune_add_array(softc, newtune)
6991 ipf_main_softc_t *softc;
6992 ipftuneable_t *newtune;
6994 ipftuneable_t *nt, *dt;
6997 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6998 error = ipf_tune_add(softc, nt);
7000 for (dt = newtune; dt != nt; dt++) {
7001 (void) ipf_tune_del(softc, dt);
7010 /* ------------------------------------------------------------------------ */
7011 /* Function: ipf_tune_array_link */
7012 /* Returns: 0 == success, -1 == failure */
7013 /* Parameters: softc(I) - soft context pointerto work with */
7014 /* array(I) - pointer to an array of tuneables */
7016 /* Given an array of tunables (array), append them to the current list of */
7017 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
7018 /* the array for being appended to the list, initialise all of the next */
7019 /* pointers so we don't need to walk parts of it with ++ and others with */
7020 /* next. The array is expected to have an entry with a NULL name as the */
7021 /* terminator. Trying to add an array with no non-NULL names will return as */
7023 /* ------------------------------------------------------------------------ */
7025 ipf_tune_array_link(softc, array)
7026 ipf_main_softc_t *softc;
7027 ipftuneable_t *array;
7029 ipftuneable_t *t, **p;
7032 if (t->ipft_name == NULL)
7035 for (; t[1].ipft_name != NULL; t++)
7036 t[0].ipft_next = &t[1];
7037 t->ipft_next = NULL;
7040 * Since a pointer to the last entry isn't kept, we need to find it
7041 * each time we want to add new variables to the list.
7043 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7044 if (t->ipft_name == NULL)
7052 /* ------------------------------------------------------------------------ */
7053 /* Function: ipf_tune_array_unlink */
7054 /* Returns: 0 == success, -1 == failure */
7055 /* Parameters: softc(I) - soft context pointerto work with */
7056 /* array(I) - pointer to an array of tuneables */
7058 /* ------------------------------------------------------------------------ */
7060 ipf_tune_array_unlink(softc, array)
7061 ipf_main_softc_t *softc;
7062 ipftuneable_t *array;
7064 ipftuneable_t *t, **p;
7066 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7072 for (; t[1].ipft_name != NULL; t++)
7081 /* ------------------------------------------------------------------------ */
7082 /* Function: ipf_tune_array_copy */
7083 /* Returns: NULL = failure, else pointer to new array */
7084 /* Parameters: base(I) - pointer to structure base */
7085 /* size(I) - size of the array at template */
7086 /* template(I) - original array to copy */
7088 /* Allocate memory for a new set of tuneable values and copy everything */
7089 /* from template into the new region of memory. The new region is full of */
7090 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
7092 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
7093 /* In the array template, ipftp_offset is the offset (in bytes) of the */
7094 /* location of the tuneable value inside the structure pointed to by base. */
7095 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
7096 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
7097 /* ipftp_void that points to the stored value. */
7098 /* ------------------------------------------------------------------------ */
7100 ipf_tune_array_copy(base, size, template)
7103 ipftuneable_t *template;
7105 ipftuneable_t *copy;
7109 KMALLOCS(copy, ipftuneable_t *, size);
7113 bcopy(template, copy, size);
7115 for (i = 0; copy[i].ipft_name; i++) {
7116 copy[i].ipft_una.ipftp_offset += (u_long)base;
7117 copy[i].ipft_next = copy + i + 1;
7124 /* ------------------------------------------------------------------------ */
7125 /* Function: ipf_tune_add */
7126 /* Returns: int - 0 == success, else failure */
7127 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7129 /* Appends tune structures from the array passed in (newtune) to the end of */
7130 /* the current list of "dynamic" tuneable parameters. Once added, the */
7131 /* owner of the object is not expected to ever change "ipft_next". */
7132 /* ------------------------------------------------------------------------ */
7134 ipf_tune_add(softc, newtune)
7135 ipf_main_softc_t *softc;
7136 ipftuneable_t *newtune;
7138 ipftuneable_t *ta, **tap;
7140 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7146 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7149 newtune->ipft_next = NULL;
7155 /* ------------------------------------------------------------------------ */
7156 /* Function: ipf_tune_del */
7157 /* Returns: int - 0 == success, else failure */
7158 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7159 /* current dynamic tuneables */
7161 /* Search for the tune structure, by pointer, in the list of those that are */
7162 /* dynamically added at run time. If found, adjust the list so that this */
7163 /* structure is no longer part of it. */
7164 /* ------------------------------------------------------------------------ */
7166 ipf_tune_del(softc, oldtune)
7167 ipf_main_softc_t *softc;
7168 ipftuneable_t *oldtune;
7170 ipftuneable_t *ta, **tap;
7173 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7174 tap = &ta->ipft_next) {
7175 if (ta == oldtune) {
7176 *tap = oldtune->ipft_next;
7177 oldtune->ipft_next = NULL;
7190 /* ------------------------------------------------------------------------ */
7191 /* Function: ipf_tune_del_array */
7192 /* Returns: int - 0 == success, else failure */
7193 /* Parameters: oldtune - pointer to tuneables array */
7195 /* Remove each tuneable entry in the array from the list of "dynamic" */
7196 /* tunables. If one entry should fail to be found, an error will be */
7197 /* returned and no further ones removed. */
7198 /* An entry with a NULL name is used as the indicator of the last entry in */
7200 /* ------------------------------------------------------------------------ */
7202 ipf_tune_del_array(softc, oldtune)
7203 ipf_main_softc_t *softc;
7204 ipftuneable_t *oldtune;
7209 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7210 error = ipf_tune_del(softc, ot);
7220 /* ------------------------------------------------------------------------ */
7221 /* Function: ipf_tune */
7222 /* Returns: int - 0 == success, else failure */
7223 /* Parameters: cmd(I) - ioctl command number */
7224 /* data(I) - pointer to ioctl data structure */
7226 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7227 /* three ioctls provide the means to access and control global variables */
7228 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7229 /* changed without rebooting, reloading or recompiling. The initialisation */
7230 /* and 'destruction' routines of the various components of ipfilter are all */
7231 /* each responsible for handling their own values being too big. */
7232 /* ------------------------------------------------------------------------ */
7234 ipf_ipftune(softc, cmd, data)
7235 ipf_main_softc_t *softc;
7244 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7248 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7249 cookie = tu.ipft_cookie;
7254 case SIOCIPFGETNEXT :
7256 * If cookie is non-NULL, assume it to be a pointer to the last
7257 * entry we looked at, so find it (if possible) and return a
7258 * pointer to the next one after it. The last entry in the
7259 * the table is a NULL entry, so when we get to it, set cookie
7260 * to NULL and return that, indicating end of list, erstwhile
7261 * if we come in with cookie set to NULL, we are starting anew
7262 * at the front of the list.
7264 if (cookie != NULL) {
7265 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7266 cookie, &tu.ipft_cookie);
7268 ta = softc->ipf_tuners;
7269 tu.ipft_cookie = ta + 1;
7273 * Entry found, but does the data pointed to by that
7274 * row fit in what we can return?
7276 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7282 if (ta->ipft_sz == sizeof(u_long))
7283 tu.ipft_vlong = *ta->ipft_plong;
7284 else if (ta->ipft_sz == sizeof(u_int))
7285 tu.ipft_vint = *ta->ipft_pint;
7286 else if (ta->ipft_sz == sizeof(u_short))
7287 tu.ipft_vshort = *ta->ipft_pshort;
7288 else if (ta->ipft_sz == sizeof(u_char))
7289 tu.ipft_vchar = *ta->ipft_pchar;
7291 tu.ipft_sz = ta->ipft_sz;
7292 tu.ipft_min = ta->ipft_min;
7293 tu.ipft_max = ta->ipft_max;
7294 tu.ipft_flags = ta->ipft_flags;
7295 bcopy(ta->ipft_name, tu.ipft_name,
7296 MIN(sizeof(tu.ipft_name),
7297 strlen(ta->ipft_name) + 1));
7299 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7305 * Search by name or by cookie value for a particular entry
7306 * in the tuning paramter table.
7310 if (cookie != NULL) {
7311 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7315 } else if (tu.ipft_name[0] != '\0') {
7316 ta = ipf_tune_findbyname(softc->ipf_tuners,
7324 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7326 * Fetch the tuning parameters for a particular value
7329 if (ta->ipft_sz == sizeof(u_long))
7330 tu.ipft_vlong = *ta->ipft_plong;
7331 else if (ta->ipft_sz == sizeof(u_int))
7332 tu.ipft_vint = *ta->ipft_pint;
7333 else if (ta->ipft_sz == sizeof(u_short))
7334 tu.ipft_vshort = *ta->ipft_pshort;
7335 else if (ta->ipft_sz == sizeof(u_char))
7336 tu.ipft_vchar = *ta->ipft_pchar;
7337 tu.ipft_cookie = ta;
7338 tu.ipft_sz = ta->ipft_sz;
7339 tu.ipft_min = ta->ipft_min;
7340 tu.ipft_max = ta->ipft_max;
7341 tu.ipft_flags = ta->ipft_flags;
7342 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7344 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7346 * Set an internal parameter. The hard part here is
7347 * getting the new value safely and correctly out of
7348 * the kernel (given we only know its size, not type.)
7352 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7353 (softc->ipf_running > 0)) {
7360 if (in < ta->ipft_min || in > ta->ipft_max) {
7366 if (ta->ipft_func != NULL) {
7370 error = (*ta->ipft_func)(softc, ta,
7374 } else if (ta->ipft_sz == sizeof(u_long)) {
7375 tu.ipft_vlong = *ta->ipft_plong;
7376 *ta->ipft_plong = in;
7378 } else if (ta->ipft_sz == sizeof(u_int)) {
7379 tu.ipft_vint = *ta->ipft_pint;
7380 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7382 } else if (ta->ipft_sz == sizeof(u_short)) {
7383 tu.ipft_vshort = *ta->ipft_pshort;
7384 *ta->ipft_pshort = (u_short)(in & 0xffff);
7386 } else if (ta->ipft_sz == sizeof(u_char)) {
7387 tu.ipft_vchar = *ta->ipft_pchar;
7388 *ta->ipft_pchar = (u_char)(in & 0xff);
7390 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7404 /* ------------------------------------------------------------------------ */
7405 /* Function: ipf_zerostats */
7406 /* Returns: int - 0 = success, else failure */
7407 /* Parameters: data(O) - pointer to pointer for copying data back to */
7409 /* Copies the current statistics out to userspace and then zero's the */
7410 /* current ones in the kernel. The lock is only held across the bzero() as */
7411 /* the copyout may result in paging (ie network activity.) */
7412 /* ------------------------------------------------------------------------ */
7414 ipf_zerostats(softc, data)
7415 ipf_main_softc_t *softc;
7422 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7425 ipf_getstat(softc, &fio, obj.ipfo_rev);
7426 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7430 WRITE_ENTER(&softc->ipf_mutex);
7431 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7432 RWLOCK_EXIT(&softc->ipf_mutex);
7438 /* ------------------------------------------------------------------------ */
7439 /* Function: ipf_resolvedest */
7441 /* Parameters: softc(I) - pointer to soft context main structure */
7442 /* base(I) - where strings are stored */
7443 /* fdp(IO) - pointer to destination information to resolve */
7444 /* v(I) - IP protocol version to match */
7446 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7447 /* if a matching name can be found for the particular IP protocol version */
7448 /* then store the interface pointer in the frdest struct. If no match is */
7449 /* found, then set the interface pointer to be -1 as NULL is considered to */
7450 /* indicate there is no information at all in the structure. */
7451 /* ------------------------------------------------------------------------ */
7453 ipf_resolvedest(softc, base, fdp, v)
7454 ipf_main_softc_t *softc;
7464 if (fdp->fd_name != -1) {
7465 if (fdp->fd_type == FRD_DSTLIST) {
7466 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7468 base + fdp->fd_name,
7475 ifp = GETIFP(base + fdp->fd_name, v);
7486 /* ------------------------------------------------------------------------ */
7487 /* Function: ipf_resolvenic */
7488 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7489 /* pointer to interface structure for NIC */
7490 /* Parameters: softc(I)- pointer to soft context main structure */
7491 /* name(I) - complete interface name */
7492 /* v(I) - IP protocol version */
7494 /* Look for a network interface structure that firstly has a matching name */
7495 /* to that passed in and that is also being used for that IP protocol */
7496 /* version (necessary on some platforms where there are separate listings */
7497 /* for both IPv4 and IPv6 on the same physical NIC. */
7498 /* ------------------------------------------------------------------------ */
7500 ipf_resolvenic(softc, name, v)
7501 ipf_main_softc_t *softc;
7507 softc = softc; /* gcc -Wextra */
7508 if (name[0] == '\0')
7511 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7515 nic = GETIFP(name, v);
7522 /* ------------------------------------------------------------------------ */
7523 /* Function: ipf_token_expire */
7524 /* Returns: None. */
7525 /* Parameters: softc(I) - pointer to soft context main structure */
7527 /* This function is run every ipf tick to see if there are any tokens that */
7528 /* have been held for too long and need to be freed up. */
7529 /* ------------------------------------------------------------------------ */
7531 ipf_token_expire(softc)
7532 ipf_main_softc_t *softc;
7536 WRITE_ENTER(&softc->ipf_tokens);
7537 while ((it = softc->ipf_token_head) != NULL) {
7538 if (it->ipt_die > softc->ipf_ticks)
7541 ipf_token_deref(softc, it);
7543 RWLOCK_EXIT(&softc->ipf_tokens);
7547 /* ------------------------------------------------------------------------ */
7548 /* Function: ipf_token_flush */
7549 /* Returns: None. */
7550 /* Parameters: softc(I) - pointer to soft context main structure */
7552 /* Loop through all of the existing tokens and call deref to see if they */
7553 /* can be freed. Normally a function like this might just loop on */
7554 /* ipf_token_head but there is a chance that a token might have a ref count */
7555 /* of greater than one and in that case the the reference would drop twice */
7556 /* by code that is only entitled to drop it once. */
7557 /* ------------------------------------------------------------------------ */
7559 ipf_token_flush(softc)
7560 ipf_main_softc_t *softc;
7562 ipftoken_t *it, *next;
7564 WRITE_ENTER(&softc->ipf_tokens);
7565 for (it = softc->ipf_token_head; it != NULL; it = next) {
7566 next = it->ipt_next;
7567 (void) ipf_token_deref(softc, it);
7569 RWLOCK_EXIT(&softc->ipf_tokens);
7573 /* ------------------------------------------------------------------------ */
7574 /* Function: ipf_token_del */
7575 /* Returns: int - 0 = success, else error */
7576 /* Parameters: softc(I)- pointer to soft context main structure */
7577 /* type(I) - the token type to match */
7578 /* uid(I) - uid owning the token */
7579 /* ptr(I) - context pointer for the token */
7581 /* This function looks for a a token in the current list that matches up */
7582 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7583 /* call ipf_token_dewref() to remove it from the list. In the event that */
7584 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7585 /* enables debugging to distinguish between the two paths that ultimately */
7586 /* lead to a token to be deleted. */
7587 /* ------------------------------------------------------------------------ */
7589 ipf_token_del(softc, type, uid, ptr)
7590 ipf_main_softc_t *softc;
7600 WRITE_ENTER(&softc->ipf_tokens);
7601 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7602 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7603 uid == it->ipt_uid) {
7604 it->ipt_complete = 2;
7605 ipf_token_deref(softc, it);
7610 RWLOCK_EXIT(&softc->ipf_tokens);
7616 /* ------------------------------------------------------------------------ */
7617 /* Function: ipf_token_mark_complete */
7618 /* Returns: None. */
7619 /* Parameters: token(I) - pointer to token structure */
7621 /* Mark a token as being ineligable for being found with ipf_token_find. */
7622 /* ------------------------------------------------------------------------ */
7624 ipf_token_mark_complete(token)
7627 if (token->ipt_complete == 0)
7628 token->ipt_complete = 1;
7632 /* ------------------------------------------------------------------------ */
7633 /* Function: ipf_token_find */
7634 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7635 /* Parameters: softc(I)- pointer to soft context main structure */
7636 /* type(I) - the token type to match */
7637 /* uid(I) - uid owning the token */
7638 /* ptr(I) - context pointer for the token */
7640 /* This function looks for a live token in the list of current tokens that */
7641 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7642 /* allocated. If one is found then it is moved to the top of the list of */
7643 /* currently active tokens. */
7644 /* ------------------------------------------------------------------------ */
7646 ipf_token_find(softc, type, uid, ptr)
7647 ipf_main_softc_t *softc;
7651 ipftoken_t *it, *new;
7653 KMALLOC(new, ipftoken_t *);
7655 bzero((char *)new, sizeof(*new));
7657 WRITE_ENTER(&softc->ipf_tokens);
7658 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7659 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7660 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7668 RWLOCK_EXIT(&softc->ipf_tokens);
7673 it->ipt_type = type;
7681 if (it->ipt_complete > 0)
7684 ipf_token_unlink(softc, it);
7688 it->ipt_pnext = softc->ipf_token_tail;
7689 *softc->ipf_token_tail = it;
7690 softc->ipf_token_tail = &it->ipt_next;
7691 it->ipt_next = NULL;
7694 it->ipt_die = softc->ipf_ticks + 20;
7697 RWLOCK_EXIT(&softc->ipf_tokens);
7703 /* ------------------------------------------------------------------------ */
7704 /* Function: ipf_token_unlink */
7705 /* Returns: None. */
7706 /* Parameters: softc(I) - pointer to soft context main structure */
7707 /* token(I) - pointer to token structure */
7708 /* Write Locks: ipf_tokens */
7710 /* This function unlinks a token structure from the linked list of tokens */
7711 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7712 /* but the tail does due to the linked list implementation. */
7713 /* ------------------------------------------------------------------------ */
7715 ipf_token_unlink(softc, token)
7716 ipf_main_softc_t *softc;
7720 if (softc->ipf_token_tail == &token->ipt_next)
7721 softc->ipf_token_tail = token->ipt_pnext;
7723 *token->ipt_pnext = token->ipt_next;
7724 if (token->ipt_next != NULL)
7725 token->ipt_next->ipt_pnext = token->ipt_pnext;
7726 token->ipt_next = NULL;
7727 token->ipt_pnext = NULL;
7731 /* ------------------------------------------------------------------------ */
7732 /* Function: ipf_token_deref */
7733 /* Returns: int - 0 == token freed, else reference count */
7734 /* Parameters: softc(I) - pointer to soft context main structure */
7735 /* token(I) - pointer to token structure */
7736 /* Write Locks: ipf_tokens */
7738 /* Drop the reference count on the token structure and if it drops to zero, */
7739 /* call the dereference function for the token type because it is then */
7740 /* possible to free the token data structure. */
7741 /* ------------------------------------------------------------------------ */
7743 ipf_token_deref(softc, token)
7744 ipf_main_softc_t *softc;
7747 void *data, **datap;
7749 ASSERT(token->ipt_ref > 0);
7751 if (token->ipt_ref > 0)
7752 return token->ipt_ref;
7754 data = token->ipt_data;
7757 if ((data != NULL) && (data != (void *)-1)) {
7758 switch (token->ipt_type)
7760 case IPFGENITER_IPF :
7761 (void) ipf_derefrule(softc, (frentry_t **)datap);
7763 case IPFGENITER_IPNAT :
7764 WRITE_ENTER(&softc->ipf_nat);
7765 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7766 RWLOCK_EXIT(&softc->ipf_nat);
7768 case IPFGENITER_NAT :
7769 ipf_nat_deref(softc, (nat_t **)datap);
7771 case IPFGENITER_STATE :
7772 ipf_state_deref(softc, (ipstate_t **)datap);
7774 case IPFGENITER_FRAG :
7775 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7777 case IPFGENITER_NATFRAG :
7778 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7780 case IPFGENITER_HOSTMAP :
7781 WRITE_ENTER(&softc->ipf_nat);
7782 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7783 RWLOCK_EXIT(&softc->ipf_nat);
7786 ipf_lookup_iterderef(softc, token->ipt_type, data);
7791 ipf_token_unlink(softc, token);
7797 /* ------------------------------------------------------------------------ */
7798 /* Function: ipf_nextrule */
7799 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7800 /* Parameters: softc(I) - pointer to soft context main structure */
7801 /* fr(I) - pointer to filter rule */
7802 /* out(I) - 1 == out rules, 0 == input rules */
7804 /* Starting with "fr", find the next rule to visit. This includes visiting */
7805 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7806 /* last rule in the list. When walking rule lists, it is either input or */
7807 /* output rules that are returned, never both. */
7808 /* ------------------------------------------------------------------------ */
7810 ipf_nextrule(softc, active, unit, fr, out)
7811 ipf_main_softc_t *softc;
7819 if (fr != NULL && fr->fr_group != -1) {
7820 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7821 unit, active, NULL);
7825 fg = softc->ipf_groups[unit][active];
7828 while (fg != NULL) {
7829 next = fg->fg_start;
7830 while (next != NULL) {
7832 if (next->fr_flags & FR_OUTQUE)
7834 } else if (next->fr_flags & FR_INQUE) {
7837 next = next->fr_next;
7846 /* ------------------------------------------------------------------------ */
7847 /* Function: ipf_getnextrule */
7848 /* Returns: int - 0 = success, else error */
7849 /* Parameters: softc(I)- pointer to soft context main structure */
7850 /* t(I) - pointer to destination information to resolve */
7851 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7853 /* This function's first job is to bring in the ipfruleiter_t structure via */
7854 /* the ipfobj_t structure to determine what should be the next rule to */
7855 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7856 /* find the 'next rule'. This may include searching rule group lists or */
7857 /* just be as simple as looking at the 'next' field in the rule structure. */
7858 /* When we have found the rule to return, increase its reference count and */
7859 /* if we used an existing rule to get here, decrease its reference count. */
7860 /* ------------------------------------------------------------------------ */
7862 ipf_getnextrule(softc, t, ptr)
7863 ipf_main_softc_t *softc;
7867 frentry_t *fr, *next, zero;
7876 if (t == NULL || ptr == NULL) {
7881 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7885 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7889 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7893 if (it.iri_nrules == 0) {
7897 if (it.iri_rule == NULL) {
7904 if ((it.iri_inout & F_OUT) != 0)
7908 if ((it.iri_inout & F_ACIN) != 0)
7909 unit = IPL_LOGCOUNT;
7913 READ_ENTER(&softc->ipf_mutex);
7915 if (*it.iri_group == '\0') {
7916 if (unit == IPL_LOGCOUNT) {
7917 next = softc->ipf_acct[out][it.iri_active];
7919 next = softc->ipf_rules[out][it.iri_active];
7922 next = ipf_nextrule(softc, it.iri_active,
7925 fg = ipf_findgroup(softc, it.iri_group, unit,
7926 it.iri_active, NULL);
7928 next = fg->fg_start;
7935 next = ipf_nextrule(softc, it.iri_active, unit,
7939 if (next != NULL && next->fr_next != NULL)
7941 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7947 (void) ipf_derefrule(softc, &fr);
7949 obj.ipfo_type = IPFOBJ_FRENTRY;
7950 dst = (char *)it.iri_rule;
7953 obj.ipfo_size = next->fr_size;
7954 MUTEX_ENTER(&next->fr_lock);
7956 MUTEX_EXIT(&next->fr_lock);
7959 obj.ipfo_size = sizeof(frentry_t);
7960 bzero(&zero, sizeof(zero));
7964 it.iri_rule = predict ? next : NULL;
7966 ipf_token_mark_complete(t);
7968 RWLOCK_EXIT(&softc->ipf_mutex);
7971 error = ipf_outobjk(softc, &obj, next);
7972 if (error == 0 && t->ipt_data != NULL) {
7973 dst += obj.ipfo_size;
7974 if (next->fr_data != NULL) {
7977 if (next->fr_type == FR_T_IPFEXPR)
7978 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7980 dobj.ipfo_type = IPFOBJ_FRIPF;
7981 dobj.ipfo_size = next->fr_dsize;
7982 dobj.ipfo_rev = obj.ipfo_rev;
7983 dobj.ipfo_ptr = dst;
7984 error = ipf_outobjk(softc, &dobj, next->fr_data);
7988 if ((fr != NULL) && (next == &zero))
7989 (void) ipf_derefrule(softc, &fr);
7995 /* ------------------------------------------------------------------------ */
7996 /* Function: ipf_frruleiter */
7997 /* Returns: int - 0 = success, else error */
7998 /* Parameters: softc(I)- pointer to soft context main structure */
7999 /* data(I) - the token type to match */
8000 /* uid(I) - uid owning the token */
8001 /* ptr(I) - context pointer for the token */
8003 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
8004 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
8005 /* the process doing the ioctl and use that to ask for the next rule. */
8006 /* ------------------------------------------------------------------------ */
8008 ipf_frruleiter(softc, data, uid, ctx)
8009 ipf_main_softc_t *softc;
8018 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8019 if (token != NULL) {
8020 error = ipf_getnextrule(softc, token, data);
8021 WRITE_ENTER(&softc->ipf_tokens);
8022 ipf_token_deref(softc, token);
8023 RWLOCK_EXIT(&softc->ipf_tokens);
8025 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8029 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8036 /* ------------------------------------------------------------------------ */
8037 /* Function: ipf_geniter */
8038 /* Returns: int - 0 = success, else error */
8039 /* Parameters: softc(I) - pointer to soft context main structure */
8040 /* token(I) - pointer to ipftoken_t structure */
8041 /* itp(I) - pointer to iterator data */
8043 /* Decide which iterator function to call using information passed through */
8044 /* the ipfgeniter_t structure at itp. */
8045 /* ------------------------------------------------------------------------ */
8047 ipf_geniter(softc, token, itp)
8048 ipf_main_softc_t *softc;
8054 switch (itp->igi_type)
8056 case IPFGENITER_FRAG :
8057 error = ipf_frag_pkt_next(softc, token, itp);
8069 /* ------------------------------------------------------------------------ */
8070 /* Function: ipf_genericiter */
8071 /* Returns: int - 0 = success, else error */
8072 /* Parameters: softc(I)- pointer to soft context main structure */
8073 /* data(I) - the token type to match */
8074 /* uid(I) - uid owning the token */
8075 /* ptr(I) - context pointer for the token */
8077 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
8078 /* ------------------------------------------------------------------------ */
8080 ipf_genericiter(softc, data, uid, ctx)
8081 ipf_main_softc_t *softc;
8089 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8093 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8094 if (token != NULL) {
8095 token->ipt_subtype = iter.igi_type;
8096 error = ipf_geniter(softc, token, &iter);
8097 WRITE_ENTER(&softc->ipf_tokens);
8098 ipf_token_deref(softc, token);
8099 RWLOCK_EXIT(&softc->ipf_tokens);
8109 /* ------------------------------------------------------------------------ */
8110 /* Function: ipf_ipf_ioctl */
8111 /* Returns: int - 0 = success, else error */
8112 /* Parameters: softc(I)- pointer to soft context main structure */
8113 /* data(I) - the token type to match */
8114 /* cmd(I) - the ioctl command number */
8115 /* mode(I) - mode flags for the ioctl */
8116 /* uid(I) - uid owning the token */
8117 /* ptr(I) - context pointer for the token */
8119 /* This function handles all of the ioctl command that are actually isssued */
8120 /* to the /dev/ipl device. */
8121 /* ------------------------------------------------------------------------ */
8123 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8124 ipf_main_softc_t *softc;
8138 if (!(mode & FWRITE)) {
8142 error = BCOPYIN(data, &tmp, sizeof(tmp));
8149 WRITE_ENTER(&softc->ipf_global);
8151 if (softc->ipf_running > 0)
8154 error = ipfattach(softc);
8156 softc->ipf_running = 1;
8158 (void) ipfdetach(softc);
8160 if (softc->ipf_running == 1)
8161 error = ipfdetach(softc);
8165 softc->ipf_running = -1;
8167 RWLOCK_EXIT(&softc->ipf_global);
8172 if (!(mode & FWRITE)) {
8178 case SIOCIPFGETNEXT :
8180 error = ipf_ipftune(softc, cmd, (void *)data);
8184 if (!(mode & FWRITE)) {
8188 error = BCOPYIN(data, &softc->ipf_flags,
8189 sizeof(softc->ipf_flags));
8198 error = BCOPYOUT(&softc->ipf_flags, data,
8199 sizeof(softc->ipf_flags));
8207 error = ipf_resolvefunc(softc, (void *)data);
8214 if (!(mode & FWRITE)) {
8218 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8219 softc->ipf_active, 1);
8226 if (!(mode & FWRITE)) {
8230 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8231 1 - softc->ipf_active, 1);
8236 if (!(mode & FWRITE)) {
8240 WRITE_ENTER(&softc->ipf_mutex);
8241 error = BCOPYOUT(&softc->ipf_active, data,
8242 sizeof(softc->ipf_active));
8247 softc->ipf_active = 1 - softc->ipf_active;
8249 RWLOCK_EXIT(&softc->ipf_mutex);
8254 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8258 ipf_getstat(softc, &fio, obj.ipfo_rev);
8259 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8263 if (!(mode & FWRITE)) {
8267 error = ipf_zerostats(softc, (caddr_t)data);
8271 if (!(mode & FWRITE)) {
8275 error = BCOPYIN(data, &tmp, sizeof(tmp));
8277 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8278 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8292 if (!(mode & FWRITE)) {
8296 error = BCOPYIN(data, &tmp, sizeof(tmp));
8298 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8299 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8313 if (!(mode & FWRITE)) {
8317 error = BCOPYIN(data, &tmp, sizeof(tmp));
8319 ipf_state_setlock(softc->ipf_state_soft, tmp);
8320 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8321 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8322 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8332 if (!(mode & FWRITE)) {
8336 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8337 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8344 #endif /* IPFILTER_LOG */
8347 if (!(mode & FWRITE)) {
8351 WRITE_ENTER(&softc->ipf_global);
8352 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8355 ipf_sync(softc, NULL);
8358 RWLOCK_EXIT(&softc->ipf_global);
8364 error = ipf_outobj(softc, (void *)data,
8365 ipf_frag_stats(softc->ipf_frag_soft),
8371 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8372 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8378 error = ipf_frruleiter(softc, data, uid, ctx);
8384 error = ipf_genericiter(softc, data, uid, ctx);
8388 case SIOCIPFDELTOK :
8389 error = BCOPYIN(data, &tmp, sizeof(tmp));
8392 error = ipf_token_del(softc, tmp, uid, ctx);
8407 /* ------------------------------------------------------------------------ */
8408 /* Function: ipf_decaps */
8409 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8410 /* flags indicating packet filtering decision. */
8411 /* Parameters: fin(I) - pointer to packet information */
8412 /* pass(I) - IP protocol version to match */
8413 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8415 /* This function is called for packets that are wrapt up in other packets, */
8416 /* for example, an IP packet that is the entire data segment for another IP */
8417 /* packet. If the basic constraints for this are satisfied, change the */
8418 /* buffer to point to the start of the inner packet and start processing */
8419 /* rules belonging to the head group this rule specifies. */
8420 /* ------------------------------------------------------------------------ */
8422 ipf_decaps(fin, pass, l5proto)
8427 fr_info_t fin2, *fino = NULL;
8433 if ((fin->fin_flx & FI_COALESCE) == 0)
8434 if (ipf_coalesce(fin) == -1)
8438 hlen = fin->fin_hlen;
8444 * In this case, the specific protocol being decapsulated
8445 * inside UDP frames comes from the rule.
8447 nh = fin->fin_fr->fr_icode;
8450 case IPPROTO_GRE : /* 47 */
8451 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8452 hlen += sizeof(grehdr_t);
8453 if (gre.gr_R|gre.gr_s)
8465 * If the routing options flag is set, validate that it is
8466 * there and bounce over it.
8469 /* This is really heavy weight and lots of room for error, */
8470 /* so for now, put it off and get the simple stuff right. */
8472 u_char off, len, *s;
8479 aplen = fin->fin_plen - hlen;
8481 af = (s[0] << 8) | s[1];
8486 if (af == 0 && len == 0) {
8497 hlen = s - (u_char *)fin->fin_dp;
8503 case IPPROTO_IPIP : /* 4 */
8508 default : /* Includes ESP, AH is special for IPv4 */
8521 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8525 #if defined(MENTAT) && defined(_KERNEL)
8531 fin->fin_plen -= elen;
8533 ip = (ip_t *)((char *)fin->fin_ip + elen);
8536 * Make sure we have at least enough data for the network layer
8540 hlen = IP_HL(ip) << 2;
8542 else if (IP_V(ip) == 6)
8543 hlen = sizeof(ip6_t);
8548 if (fin->fin_plen < hlen)
8551 fin->fin_dp = (char *)ip + hlen;
8553 if (IP_V(ip) == 4) {
8555 * Perform IPv4 header checksum validation.
8557 if (ipf_cksum((u_short *)ip, hlen))
8561 if (ipf_makefrip(hlen, ip, fin) == -1) {
8564 #if defined(MENTAT) && defined(_KERNEL)
8572 DT1(frb_decapfrip, fr_info_t *, fin);
8573 pass &= ~FR_CMDMASK;
8574 pass |= FR_BLOCK|FR_QUICK;
8575 fin->fin_reason = FRB_DECAPFRIP;
8579 pass = ipf_scanlist(fin, pass);
8582 * Copy the packet filter "result" fields out of the fr_info_t struct
8583 * that is local to the decapsulation processing and back into the
8584 * one we were called with.
8586 fino->fin_flx = fin->fin_flx;
8587 fino->fin_rev = fin->fin_rev;
8588 fino->fin_icode = fin->fin_icode;
8589 fino->fin_rule = fin->fin_rule;
8590 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8591 fino->fin_fr = fin->fin_fr;
8592 fino->fin_error = fin->fin_error;
8593 fino->fin_mp = fin->fin_mp;
8594 fino->fin_m = fin->fin_m;
8597 #if defined(MENTAT) && defined(_KERNEL)
8608 /* ------------------------------------------------------------------------ */
8609 /* Function: ipf_matcharray_load */
8610 /* Returns: int - 0 = success, else error */
8611 /* Parameters: softc(I) - pointer to soft context main structure */
8612 /* data(I) - pointer to ioctl data */
8613 /* objp(I) - ipfobj_t structure to load data into */
8614 /* arrayptr(I) - pointer to location to store array pointer */
8616 /* This function loads in a mathing array through the ipfobj_t struct that */
8617 /* describes it. Sanity checking and array size limitations are enforced */
8618 /* in this function to prevent userspace from trying to load in something */
8619 /* that is insanely big. Once the size of the array is known, the memory */
8620 /* required is malloc'd and returned through changing *arrayptr. The */
8621 /* contents of the array are verified before returning. Only in the event */
8622 /* of a successful call is the caller required to free up the malloc area. */
8623 /* ------------------------------------------------------------------------ */
8625 ipf_matcharray_load(softc, data, objp, arrayptr)
8626 ipf_main_softc_t *softc;
8631 int arraysize, *array, error;
8635 error = BCOPYIN(data, objp, sizeof(*objp));
8641 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8646 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8647 (objp->ipfo_size > 1024)) {
8652 arraysize = objp->ipfo_size * sizeof(*array);
8653 KMALLOCS(array, int *, arraysize);
8654 if (array == NULL) {
8659 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8661 KFREES(array, arraysize);
8666 if (ipf_matcharray_verify(array, arraysize) != 0) {
8667 KFREES(array, arraysize);
8677 /* ------------------------------------------------------------------------ */
8678 /* Function: ipf_matcharray_verify */
8680 /* Parameters: array(I) - pointer to matching array */
8681 /* arraysize(I) - number of elements in the array */
8683 /* Verify the contents of a matching array by stepping through each element */
8684 /* in it. The actual commands in the array are not verified for */
8685 /* correctness, only that all of the sizes are correctly within limits. */
8686 /* ------------------------------------------------------------------------ */
8688 ipf_matcharray_verify(array, arraysize)
8689 int *array, arraysize;
8691 int i, nelem, maxidx;
8694 nelem = arraysize / sizeof(*array);
8697 * Currently, it makes no sense to have an array less than 6
8698 * elements long - the initial size at the from, a single operation
8699 * (minimum 4 in length) and a trailer, for a total of 6.
8701 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8706 * Verify the size of data pointed to by array with how long
8707 * the array claims to be itself.
8709 if (array[0] * sizeof(*array) != arraysize) {
8715 * The last opcode in this array should be an IPF_EXP_END.
8717 if (array[maxidx] != IPF_EXP_END) {
8721 for (i = 1; i < maxidx; ) {
8722 e = (ipfexp_t *)(array + i);
8725 * The length of the bits to check must be at least 1
8726 * (or else there is nothing to comapre with!) and it
8727 * cannot exceed the length of the data present.
8729 if ((e->ipfe_size < 1 ) ||
8730 (e->ipfe_size + i > maxidx)) {
8739 /* ------------------------------------------------------------------------ */
8740 /* Function: ipf_fr_matcharray */
8741 /* Returns: int - 0 = match failed, else positive match */
8742 /* Parameters: fin(I) - pointer to packet information */
8743 /* array(I) - pointer to matching array */
8745 /* This function is used to apply a matching array against a packet and */
8746 /* return an indication of whether or not the packet successfully matches */
8747 /* all of the commands in it. */
8748 /* ------------------------------------------------------------------------ */
8750 ipf_fr_matcharray(fin, array)
8754 int i, n, *x, rv, p;
8761 for (; n > 0; x += 3 + x[3], rv = 0) {
8763 if (e->ipfe_cmd == IPF_EXP_END)
8768 * The upper 16 bits currently store the protocol value.
8769 * This is currently used with TCP and UDP port compares and
8770 * allows "tcp.port = 80" without requiring an explicit
8771 " "ip.pr = tcp" first.
8773 p = e->ipfe_cmd >> 16;
8774 if ((p != 0) && (p != fin->fin_p))
8777 switch (e->ipfe_cmd)
8779 case IPF_EXP_IP_PR :
8780 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8781 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8785 case IPF_EXP_IP_SRCADDR :
8786 if (fin->fin_v != 4)
8788 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8789 rv |= ((fin->fin_saddr &
8790 e->ipfe_arg0[i * 2 + 1]) ==
8791 e->ipfe_arg0[i * 2]);
8795 case IPF_EXP_IP_DSTADDR :
8796 if (fin->fin_v != 4)
8798 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8799 rv |= ((fin->fin_daddr &
8800 e->ipfe_arg0[i * 2 + 1]) ==
8801 e->ipfe_arg0[i * 2]);
8805 case IPF_EXP_IP_ADDR :
8806 if (fin->fin_v != 4)
8808 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8809 rv |= ((fin->fin_saddr &
8810 e->ipfe_arg0[i * 2 + 1]) ==
8811 e->ipfe_arg0[i * 2]) ||
8813 e->ipfe_arg0[i * 2 + 1]) ==
8814 e->ipfe_arg0[i * 2]);
8819 case IPF_EXP_IP6_SRCADDR :
8820 if (fin->fin_v != 6)
8822 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8823 rv |= IP6_MASKEQ(&fin->fin_src6,
8824 &e->ipfe_arg0[i * 8 + 4],
8825 &e->ipfe_arg0[i * 8]);
8829 case IPF_EXP_IP6_DSTADDR :
8830 if (fin->fin_v != 6)
8832 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8833 rv |= IP6_MASKEQ(&fin->fin_dst6,
8834 &e->ipfe_arg0[i * 8 + 4],
8835 &e->ipfe_arg0[i * 8]);
8839 case IPF_EXP_IP6_ADDR :
8840 if (fin->fin_v != 6)
8842 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8843 rv |= IP6_MASKEQ(&fin->fin_src6,
8844 &e->ipfe_arg0[i * 8 + 4],
8845 &e->ipfe_arg0[i * 8]) ||
8846 IP6_MASKEQ(&fin->fin_dst6,
8847 &e->ipfe_arg0[i * 8 + 4],
8848 &e->ipfe_arg0[i * 8]);
8853 case IPF_EXP_UDP_PORT :
8854 case IPF_EXP_TCP_PORT :
8855 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8856 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8857 (fin->fin_dport == e->ipfe_arg0[i]);
8861 case IPF_EXP_UDP_SPORT :
8862 case IPF_EXP_TCP_SPORT :
8863 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8864 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8868 case IPF_EXP_UDP_DPORT :
8869 case IPF_EXP_TCP_DPORT :
8870 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8871 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8875 case IPF_EXP_TCP_FLAGS :
8876 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8877 rv |= ((fin->fin_tcpf &
8878 e->ipfe_arg0[i * 2 + 1]) ==
8879 e->ipfe_arg0[i * 2]);
8893 /* ------------------------------------------------------------------------ */
8894 /* Function: ipf_queueflush */
8895 /* Returns: int - number of entries flushed (0 = none) */
8896 /* Parameters: softc(I) - pointer to soft context main structure */
8897 /* deletefn(I) - function to call to delete entry */
8898 /* ipfqs(I) - top of the list of ipf internal queues */
8899 /* userqs(I) - top of the list of user defined timeouts */
8901 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8902 /* need to try a bit harder to free up some space. The algorithm used here */
8903 /* split into two parts but both halves have the same goal: to reduce the */
8904 /* number of connections considered to be "active" to the low watermark. */
8905 /* There are two steps in doing this: */
8906 /* 1) Remove any TCP connections that are already considered to be "closed" */
8907 /* but have not yet been removed from the state table. The two states */
8908 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8909 /* candidates for this style of removal. If freeing up entries in */
8910 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8911 /* we do not go on to step 2. */
8913 /* 2) Look for the oldest entries on each timeout queue and free them if */
8914 /* they are within the given window we are considering. Where the */
8915 /* window starts and the steps taken to increase its size depend upon */
8916 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8917 /* last 30 seconds is not touched. */
8919 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8921 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8922 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8924 /* Points to note: */
8925 /* - tqe_die is the time, in the future, when entries die. */
8926 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8928 /* - tqe_touched is when the entry was last used by NAT/state */
8929 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8930 /* ipf_ticks any given timeout queue and vice versa. */
8931 /* - both tqe_die and tqe_touched increase over time */
8932 /* - timeout queues are sorted with the highest value of tqe_die at the */
8933 /* bottom and therefore the smallest values of each are at the top */
8934 /* - the pointer passed in as ipfqs should point to an array of timeout */
8935 /* queues representing each of the TCP states */
8937 /* We start by setting up a maximum range to scan for things to move of */
8938 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8939 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8940 /* we start again with a new value for "iend" and "istart". This is */
8941 /* continued until we either finish the scan of 30 second intervals or the */
8942 /* low water mark is reached. */
8943 /* ------------------------------------------------------------------------ */
8945 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8946 ipf_main_softc_t *softc;
8947 ipftq_delete_fn_t deletefn;
8948 ipftq_t *ipfqs, *userqs;
8952 u_long interval, istart, iend;
8953 ipftq_t *ifq, *ifqnext;
8954 ipftqent_t *tqe, *tqn;
8957 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8958 tqn = tqe->tqe_next;
8959 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8962 if ((*activep * 100 / size) > low) {
8963 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8964 ((tqe = tqn) != NULL); ) {
8965 tqn = tqe->tqe_next;
8966 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8971 if ((*activep * 100 / size) <= low) {
8976 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8977 * used then the operations are upgraded to floating point
8978 * and kernels don't like floating point...
8980 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8981 istart = IPF_TTLVAL(86400 * 4);
8982 interval = IPF_TTLVAL(43200);
8983 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8984 istart = IPF_TTLVAL(43200);
8985 interval = IPF_TTLVAL(1800);
8986 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8987 istart = IPF_TTLVAL(1800);
8988 interval = IPF_TTLVAL(30);
8992 if (istart > softc->ipf_ticks) {
8993 if (softc->ipf_ticks - interval < interval)
8996 istart = (softc->ipf_ticks / interval) * interval;
8999 iend = softc->ipf_ticks - interval;
9001 while ((*activep * 100 / size) > low) {
9004 try = softc->ipf_ticks - istart;
9006 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9007 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9008 if (try < tqe->tqe_touched)
9010 tqn = tqe->tqe_next;
9011 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9016 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9017 ifqnext = ifq->ifq_next;
9019 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9020 if (try < tqe->tqe_touched)
9022 tqn = tqe->tqe_next;
9023 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9029 if (interval == IPF_TTLVAL(43200)) {
9030 interval = IPF_TTLVAL(1800);
9031 } else if (interval == IPF_TTLVAL(1800)) {
9032 interval = IPF_TTLVAL(30);
9036 if (interval >= softc->ipf_ticks)
9039 iend = softc->ipf_ticks - interval;
9048 /* ------------------------------------------------------------------------ */
9049 /* Function: ipf_deliverlocal */
9050 /* Returns: int - 1 = local address, 0 = non-local address */
9051 /* Parameters: softc(I) - pointer to soft context main structure */
9052 /* ipversion(I) - IP protocol version (4 or 6) */
9053 /* ifp(I) - network interface pointer */
9054 /* ipaddr(I) - IPv4/6 destination address */
9056 /* This fucntion is used to determine in the address "ipaddr" belongs to */
9057 /* the network interface represented by ifp. */
9058 /* ------------------------------------------------------------------------ */
9060 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9061 ipf_main_softc_t *softc;
9069 if (ipversion == 4) {
9070 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9071 if (addr.in4.s_addr == ipaddr->in4.s_addr)
9076 } else if (ipversion == 6) {
9077 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9078 if (IP6_EQ(&addr, ipaddr))
9088 /* ------------------------------------------------------------------------ */
9089 /* Function: ipf_settimeout */
9090 /* Returns: int - 0 = success, -1 = failure */
9091 /* Parameters: softc(I) - pointer to soft context main structure */
9092 /* t(I) - pointer to tuneable array entry */
9093 /* p(I) - pointer to values passed in to apply */
9095 /* This function is called to set the timeout values for each distinct */
9096 /* queue timeout that is available. When called, it calls into both the */
9097 /* state and NAT code, telling them to update their timeout queues. */
9098 /* ------------------------------------------------------------------------ */
9100 ipf_settimeout(softc, t, p)
9101 struct ipf_main_softc_s *softc;
9107 * ipf_interror should be set by the functions called here, not
9108 * by this function - it's just a middle man.
9110 if (ipf_state_settimeout(softc, t, p) == -1)
9112 if (ipf_nat_settimeout(softc, t, p) == -1)
9118 /* ------------------------------------------------------------------------ */
9119 /* Function: ipf_apply_timeout */
9120 /* Returns: int - 0 = success, -1 = failure */
9121 /* Parameters: head(I) - pointer to tuneable array entry */
9122 /* seconds(I) - pointer to values passed in to apply */
9124 /* This function applies a timeout of "seconds" to the timeout queue that */
9125 /* is pointed to by "head". All entries on this list have an expiration */
9126 /* set to be the current tick value of ipf plus the ttl. Given that this */
9127 /* function should only be called when the delta is non-zero, the task is */
9128 /* to walk the entire list and apply the change. The sort order will not */
9129 /* change. The only catch is that this is O(n) across the list, so if the */
9130 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
9131 /* could take a relatively long time to work through them all. */
9132 /* ------------------------------------------------------------------------ */
9134 ipf_apply_timeout(head, seconds)
9138 u_int oldtimeout, newtimeout;
9142 MUTEX_ENTER(&head->ifq_lock);
9143 oldtimeout = head->ifq_ttl;
9144 newtimeout = IPF_TTLVAL(seconds);
9145 delta = oldtimeout - newtimeout;
9147 head->ifq_ttl = newtimeout;
9149 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9150 tqe->tqe_die += delta;
9152 MUTEX_EXIT(&head->ifq_lock);
9156 /* ------------------------------------------------------------------------ */
9157 /* Function: ipf_settimeout_tcp */
9158 /* Returns: int - 0 = successfully applied, -1 = failed */
9159 /* Parameters: t(I) - pointer to tuneable to change */
9160 /* p(I) - pointer to new timeout information */
9161 /* tab(I) - pointer to table of TCP queues */
9163 /* This function applies the new timeout (p) to the TCP tunable (t) and */
9164 /* updates all of the entries on the relevant timeout queue by calling */
9165 /* ipf_apply_timeout(). */
9166 /* ------------------------------------------------------------------------ */
9168 ipf_settimeout_tcp(t, p, tab)
9173 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9174 !strcmp(t->ipft_name, "tcp_established")) {
9175 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9176 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9177 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9178 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9179 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9180 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9181 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9182 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9183 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9184 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9185 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9186 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9187 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9188 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9189 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9190 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9191 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9192 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9193 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9194 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9195 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9196 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9197 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9198 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9199 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9202 * ipf_interror isn't set here because it should be set
9203 * by whatever called this function.
9211 /* ------------------------------------------------------------------------ */
9212 /* Function: ipf_main_soft_create */
9213 /* Returns: NULL = failure, else success */
9214 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9216 /* Create the foundation soft context structure. In circumstances where it */
9217 /* is not required to dynamically allocate the context, a pointer can be */
9218 /* passed in (rather than NULL) to a structure to be initialised. */
9219 /* The main thing of interest is that a number of locks are initialised */
9220 /* here instead of in the where might be expected - in the relevant create */
9221 /* function elsewhere. This is done because the current locking design has */
9222 /* some areas where these locks are used outside of their module. */
9223 /* Possibly the most important exercise that is done here is setting of all */
9224 /* the timeout values, allowing them to be changed before init(). */
9225 /* ------------------------------------------------------------------------ */
9227 ipf_main_soft_create(arg)
9230 ipf_main_softc_t *softc;
9233 KMALLOC(softc, ipf_main_softc_t *);
9240 bzero((char *)softc, sizeof(*softc));
9243 * This serves as a flag as to whether or not the softc should be
9244 * free'd when _destroy is called.
9246 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9248 softc->ipf_tuners = ipf_tune_array_copy(softc,
9249 sizeof(ipf_main_tuneables),
9250 ipf_main_tuneables);
9251 if (softc->ipf_tuners == NULL) {
9252 ipf_main_soft_destroy(softc);
9256 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9257 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9258 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9259 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9260 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9261 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9262 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9263 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9264 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9266 softc->ipf_token_head = NULL;
9267 softc->ipf_token_tail = &softc->ipf_token_head;
9269 softc->ipf_tcpidletimeout = FIVE_DAYS;
9270 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9271 softc->ipf_tcplastack = IPF_TTLVAL(30);
9272 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9273 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9274 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9275 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9276 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9277 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9278 softc->ipf_udptimeout = IPF_TTLVAL(120);
9279 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9280 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9281 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9282 softc->ipf_iptimeout = IPF_TTLVAL(60);
9284 #if defined(IPFILTER_DEFAULT_BLOCK)
9285 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9287 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9289 softc->ipf_minttl = 4;
9290 softc->ipf_icmpminfragmtu = 68;
9291 softc->ipf_flags = IPF_LOGGING;
9296 /* ------------------------------------------------------------------------ */
9297 /* Function: ipf_main_soft_init */
9298 /* Returns: 0 = success, -1 = failure */
9299 /* Parameters: softc(I) - pointer to soft context main structure */
9301 /* A null-op function that exists as a placeholder so that the flow in */
9302 /* other functions is obvious. */
9303 /* ------------------------------------------------------------------------ */
9306 ipf_main_soft_init(softc)
9307 ipf_main_softc_t *softc;
9313 /* ------------------------------------------------------------------------ */
9314 /* Function: ipf_main_soft_destroy */
9316 /* Parameters: softc(I) - pointer to soft context main structure */
9318 /* Undo everything that we did in ipf_main_soft_create. */
9320 /* The most important check that needs to be made here is whether or not */
9321 /* the structure was allocated by ipf_main_soft_create() by checking what */
9322 /* value is stored in ipf_dynamic_main. */
9323 /* ------------------------------------------------------------------------ */
9326 ipf_main_soft_destroy(softc)
9327 ipf_main_softc_t *softc;
9330 RW_DESTROY(&softc->ipf_frag);
9331 RW_DESTROY(&softc->ipf_poolrw);
9332 RW_DESTROY(&softc->ipf_nat);
9333 RW_DESTROY(&softc->ipf_state);
9334 RW_DESTROY(&softc->ipf_tokens);
9335 RW_DESTROY(&softc->ipf_mutex);
9336 RW_DESTROY(&softc->ipf_global);
9337 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9338 MUTEX_DESTROY(&softc->ipf_rw);
9340 if (softc->ipf_tuners != NULL) {
9341 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9343 if (softc->ipf_dynamic_softc == 1) {
9349 /* ------------------------------------------------------------------------ */
9350 /* Function: ipf_main_soft_fini */
9351 /* Returns: 0 = success, -1 = failure */
9352 /* Parameters: softc(I) - pointer to soft context main structure */
9354 /* Clean out the rules which have been added since _init was last called, */
9355 /* the only dynamic part of the mainline. */
9356 /* ------------------------------------------------------------------------ */
9358 ipf_main_soft_fini(softc)
9359 ipf_main_softc_t *softc;
9361 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9362 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9363 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9364 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9370 /* ------------------------------------------------------------------------ */
9371 /* Function: ipf_main_load */
9372 /* Returns: 0 = success, -1 = failure */
9373 /* Parameters: none */
9375 /* Handle global initialisation that needs to be done for the base part of */
9376 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9377 /* arrays that get used by the state/NAT code. */
9378 /* ------------------------------------------------------------------------ */
9384 /* fill icmp reply type table */
9385 for (i = 0; i <= ICMP_MAXTYPE; i++)
9386 icmpreplytype4[i] = -1;
9387 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9388 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9389 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9390 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9393 /* fill icmp reply type table */
9394 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9395 icmpreplytype6[i] = -1;
9396 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9397 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9398 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9399 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9400 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9407 /* ------------------------------------------------------------------------ */
9408 /* Function: ipf_main_unload */
9409 /* Returns: 0 = success, -1 = failure */
9410 /* Parameters: none */
9412 /* A null-op function that exists as a placeholder so that the flow in */
9413 /* other functions is obvious. */
9414 /* ------------------------------------------------------------------------ */
9422 /* ------------------------------------------------------------------------ */
9423 /* Function: ipf_load_all */
9424 /* Returns: 0 = success, -1 = failure */
9425 /* Parameters: none */
9427 /* Work through all of the subsystems inside IPFilter and call the load */
9428 /* function for each in an order that won't lead to a crash :) */
9429 /* ------------------------------------------------------------------------ */
9433 if (ipf_main_load() == -1)
9436 if (ipf_state_main_load() == -1)
9439 if (ipf_nat_main_load() == -1)
9442 if (ipf_frag_main_load() == -1)
9445 if (ipf_auth_main_load() == -1)
9448 if (ipf_proxy_main_load() == -1)
9455 /* ------------------------------------------------------------------------ */
9456 /* Function: ipf_unload_all */
9457 /* Returns: 0 = success, -1 = failure */
9458 /* Parameters: none */
9460 /* Work through all of the subsystems inside IPFilter and call the unload */
9461 /* function for each in an order that won't lead to a crash :) */
9462 /* ------------------------------------------------------------------------ */
9466 if (ipf_proxy_main_unload() == -1)
9469 if (ipf_auth_main_unload() == -1)
9472 if (ipf_frag_main_unload() == -1)
9475 if (ipf_nat_main_unload() == -1)
9478 if (ipf_state_main_unload() == -1)
9481 if (ipf_main_unload() == -1)
9488 /* ------------------------------------------------------------------------ */
9489 /* Function: ipf_create_all */
9490 /* Returns: NULL = failure, else success */
9491 /* Parameters: arg(I) - pointer to soft context main structure */
9493 /* Work through all of the subsystems inside IPFilter and call the create */
9494 /* function for each in an order that won't lead to a crash :) */
9495 /* ------------------------------------------------------------------------ */
9500 ipf_main_softc_t *softc;
9502 softc = ipf_main_soft_create(arg);
9507 softc->ipf_log_soft = ipf_log_soft_create(softc);
9508 if (softc->ipf_log_soft == NULL) {
9509 ipf_destroy_all(softc);
9514 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9515 if (softc->ipf_lookup_soft == NULL) {
9516 ipf_destroy_all(softc);
9520 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9521 if (softc->ipf_sync_soft == NULL) {
9522 ipf_destroy_all(softc);
9526 softc->ipf_state_soft = ipf_state_soft_create(softc);
9527 if (softc->ipf_state_soft == NULL) {
9528 ipf_destroy_all(softc);
9532 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9533 if (softc->ipf_nat_soft == NULL) {
9534 ipf_destroy_all(softc);
9538 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9539 if (softc->ipf_frag_soft == NULL) {
9540 ipf_destroy_all(softc);
9544 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9545 if (softc->ipf_auth_soft == NULL) {
9546 ipf_destroy_all(softc);
9550 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9551 if (softc->ipf_proxy_soft == NULL) {
9552 ipf_destroy_all(softc);
9560 /* ------------------------------------------------------------------------ */
9561 /* Function: ipf_destroy_all */
9563 /* Parameters: softc(I) - pointer to soft context main structure */
9565 /* Work through all of the subsystems inside IPFilter and call the destroy */
9566 /* function for each in an order that won't lead to a crash :) */
9568 /* Every one of these functions is expected to succeed, so there is no */
9569 /* checking of return values. */
9570 /* ------------------------------------------------------------------------ */
9572 ipf_destroy_all(softc)
9573 ipf_main_softc_t *softc;
9576 if (softc->ipf_state_soft != NULL) {
9577 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9578 softc->ipf_state_soft = NULL;
9581 if (softc->ipf_nat_soft != NULL) {
9582 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9583 softc->ipf_nat_soft = NULL;
9586 if (softc->ipf_frag_soft != NULL) {
9587 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9588 softc->ipf_frag_soft = NULL;
9591 if (softc->ipf_auth_soft != NULL) {
9592 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9593 softc->ipf_auth_soft = NULL;
9596 if (softc->ipf_proxy_soft != NULL) {
9597 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9598 softc->ipf_proxy_soft = NULL;
9601 if (softc->ipf_sync_soft != NULL) {
9602 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9603 softc->ipf_sync_soft = NULL;
9606 if (softc->ipf_lookup_soft != NULL) {
9607 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9608 softc->ipf_lookup_soft = NULL;
9612 if (softc->ipf_log_soft != NULL) {
9613 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9614 softc->ipf_log_soft = NULL;
9618 ipf_main_soft_destroy(softc);
9622 /* ------------------------------------------------------------------------ */
9623 /* Function: ipf_init_all */
9624 /* Returns: 0 = success, -1 = failure */
9625 /* Parameters: softc(I) - pointer to soft context main structure */
9627 /* Work through all of the subsystems inside IPFilter and call the init */
9628 /* function for each in an order that won't lead to a crash :) */
9629 /* ------------------------------------------------------------------------ */
9632 ipf_main_softc_t *softc;
9635 if (ipf_main_soft_init(softc) == -1)
9639 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9643 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9646 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9649 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9652 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9655 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9658 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9661 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9668 /* ------------------------------------------------------------------------ */
9669 /* Function: ipf_fini_all */
9670 /* Returns: 0 = success, -1 = failure */
9671 /* Parameters: softc(I) - pointer to soft context main structure */
9673 /* Work through all of the subsystems inside IPFilter and call the fini */
9674 /* function for each in an order that won't lead to a crash :) */
9675 /* ------------------------------------------------------------------------ */
9678 ipf_main_softc_t *softc;
9681 ipf_token_flush(softc);
9683 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9686 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9689 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9692 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9695 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9698 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9701 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9705 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9709 if (ipf_main_soft_fini(softc) == -1)
9716 /* ------------------------------------------------------------------------ */
9717 /* Function: ipf_rule_expire */
9719 /* Parameters: softc(I) - pointer to soft context main structure */
9721 /* At present this function exists just to support temporary addition of */
9722 /* firewall rules. Both inactive and active lists are scanned for items to */
9723 /* purge, as by rights, the expiration is computed as soon as the rule is */
9725 /* ------------------------------------------------------------------------ */
9727 ipf_rule_expire(softc)
9728 ipf_main_softc_t *softc;
9732 if ((softc->ipf_rule_explist[0] == NULL) &&
9733 (softc->ipf_rule_explist[1] == NULL))
9736 WRITE_ENTER(&softc->ipf_mutex);
9738 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9740 * Because the list is kept sorted on insertion, the fist
9741 * one that dies in the future means no more work to do.
9743 if (fr->fr_die > softc->ipf_ticks)
9745 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9748 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9750 * Because the list is kept sorted on insertion, the fist
9751 * one that dies in the future means no more work to do.
9753 if (fr->fr_die > softc->ipf_ticks)
9755 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9758 RWLOCK_EXIT(&softc->ipf_mutex);
9762 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9763 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9766 host_node_t RBI_ZERO(ipf_rb);
9767 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9770 /* ------------------------------------------------------------------------ */
9771 /* Function: ipf_ht_node_cmp */
9772 /* Returns: int - 0 == nodes are the same, .. */
9773 /* Parameters: k1(I) - pointer to first key to compare */
9774 /* k2(I) - pointer to second key to compare */
9776 /* The "key" for the node is a combination of two fields: the address */
9777 /* family and the address itself. */
9779 /* Because we're not actually interpreting the address data, it isn't */
9780 /* necessary to convert them to/from network/host byte order. The mask is */
9781 /* just used to remove bits that aren't significant - it doesn't matter */
9782 /* where they are, as long as they're always in the same place. */
9784 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9785 /* this is where individual ones will differ the most - but not true for */
9786 /* for /48's, etc. */
9787 /* ------------------------------------------------------------------------ */
9789 ipf_ht_node_cmp(k1, k2)
9790 struct host_node_s *k1, *k2;
9794 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9798 if (k1->hn_addr.adf_family == AF_INET)
9799 return (k2->hn_addr.adf_addr.in4.s_addr -
9800 k1->hn_addr.adf_addr.in4.s_addr);
9802 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9805 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9808 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9811 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9816 /* ------------------------------------------------------------------------ */
9817 /* Function: ipf_ht_node_make_key */
9819 /* parameters: htp(I) - pointer to address tracking structure */
9820 /* key(I) - where to store masked address for lookup */
9821 /* family(I) - protocol family of address */
9822 /* addr(I) - pointer to network address */
9824 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9825 /* copy the address passed in into the key structure whilst masking out the */
9826 /* bits that we don't want. */
9828 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9829 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9830 /* have to be wary of that and not allow 32-128 to happen. */
9831 /* ------------------------------------------------------------------------ */
9833 ipf_ht_node_make_key(htp, key, family, addr)
9839 key->hn_addr.adf_family = family;
9840 if (family == AF_INET) {
9844 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9845 bits = htp->ht_netmask;
9849 mask = htonl(0xffffffff << (32 - bits));
9851 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9854 int bits = htp->ht_netmask;
9856 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9858 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9859 htonl(0xffffffff << (128 - bits));
9860 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9861 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9862 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9863 } else if (bits > 64) {
9864 key->hn_addr.adf_addr.i6[3] = 0;
9865 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9866 htonl(0xffffffff << (96 - bits));
9867 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9868 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9869 } else if (bits > 32) {
9870 key->hn_addr.adf_addr.i6[3] = 0;
9871 key->hn_addr.adf_addr.i6[2] = 0;
9872 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9873 htonl(0xffffffff << (64 - bits));
9874 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9876 key->hn_addr.adf_addr.i6[3] = 0;
9877 key->hn_addr.adf_addr.i6[2] = 0;
9878 key->hn_addr.adf_addr.i6[1] = 0;
9879 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9880 htonl(0xffffffff << (32 - bits));
9887 /* ------------------------------------------------------------------------ */
9888 /* Function: ipf_ht_node_add */
9889 /* Returns: int - 0 == success, -1 == failure */
9890 /* Parameters: softc(I) - pointer to soft context main structure */
9891 /* htp(I) - pointer to address tracking structure */
9892 /* family(I) - protocol family of address */
9893 /* addr(I) - pointer to network address */
9895 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9896 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9898 /* After preparing the key with the address information to find, look in */
9899 /* the red-black tree to see if the address is known. A successful call to */
9900 /* this function can mean one of two things: a new node was added to the */
9901 /* tree or a matching node exists and we're able to bump up its activity. */
9902 /* ------------------------------------------------------------------------ */
9904 ipf_ht_node_add(softc, htp, family, addr)
9905 ipf_main_softc_t *softc;
9913 ipf_ht_node_make_key(htp, &k, family, addr);
9915 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9917 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9919 KMALLOC(h, host_node_t *);
9922 LBUMP(ipf_rb_no_mem);
9927 * If there was a macro to initialise the RB node then that
9928 * would get used here, but there isn't...
9930 bzero((char *)h, sizeof(*h));
9931 h->hn_addr = k.hn_addr;
9932 h->hn_addr.adf_family = k.hn_addr.adf_family;
9933 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9934 htp->ht_cur_nodes++;
9936 if ((htp->ht_max_per_node != 0) &&
9937 (h->hn_active >= htp->ht_max_per_node)) {
9938 DT(ipf_rb_node_max);
9939 LBUMP(ipf_rb_node_max);
9950 /* ------------------------------------------------------------------------ */
9951 /* Function: ipf_ht_node_del */
9952 /* Returns: int - 0 == success, -1 == failure */
9953 /* parameters: htp(I) - pointer to address tracking structure */
9954 /* family(I) - protocol family of address */
9955 /* addr(I) - pointer to network address */
9957 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9958 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9960 /* Try and find the address passed in amongst the leavese on this tree to */
9961 /* be friend. If found then drop the active account for that node drops by */
9962 /* one. If that count reaches 0, it is time to free it all up. */
9963 /* ------------------------------------------------------------------------ */
9965 ipf_ht_node_del(htp, family, addr)
9973 ipf_ht_node_make_key(htp, &k, family, addr);
9975 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9980 if (h->hn_active == 0) {
9981 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9982 htp->ht_cur_nodes--;
9991 /* ------------------------------------------------------------------------ */
9992 /* Function: ipf_rb_ht_init */
9994 /* Parameters: head(I) - pointer to host tracking structure */
9996 /* Initialise the host tracking structure to be ready for use above. */
9997 /* ------------------------------------------------------------------------ */
9999 ipf_rb_ht_init(head)
10000 host_track_t *head;
10002 RBI_INIT(ipf_rb, &head->ht_root);
10006 /* ------------------------------------------------------------------------ */
10007 /* Function: ipf_rb_ht_freenode */
10009 /* Parameters: head(I) - pointer to host tracking structure */
10010 /* arg(I) - additional argument from walk caller */
10012 /* Free an actual host_node_t structure. */
10013 /* ------------------------------------------------------------------------ */
10015 ipf_rb_ht_freenode(node, arg)
10023 /* ------------------------------------------------------------------------ */
10024 /* Function: ipf_rb_ht_flush */
10026 /* Parameters: head(I) - pointer to host tracking structure */
10028 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
10029 /* and free'ing each one. */
10030 /* ------------------------------------------------------------------------ */
10032 ipf_rb_ht_flush(head)
10033 host_track_t *head;
10035 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10039 /* ------------------------------------------------------------------------ */
10040 /* Function: ipf_slowtimer */
10042 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
10044 /* Slowly expire held state for fragments. Timeouts are set * in */
10045 /* expectation of this being called twice per second. */
10046 /* ------------------------------------------------------------------------ */
10048 ipf_slowtimer(softc)
10049 ipf_main_softc_t *softc;
10052 ipf_token_expire(softc);
10053 ipf_frag_expire(softc);
10054 ipf_state_expire(softc);
10055 ipf_nat_expire(softc);
10056 ipf_auth_expire(softc);
10057 ipf_lookup_expire(softc);
10058 ipf_rule_expire(softc);
10059 ipf_sync_expire(softc);
10060 softc->ipf_ticks++;
10064 /* ------------------------------------------------------------------------ */
10065 /* Function: ipf_inet_mask_add */
10067 /* Parameters: bits(I) - pointer to nat context information */
10068 /* mtab(I) - pointer to mask hash table structure */
10070 /* When called, bits represents the mask of a new NAT rule that has just */
10071 /* been added. This function inserts a bitmask into the array of masks to */
10072 /* search when searching for a matching NAT rule for a packet. */
10073 /* Prevention of duplicate masks is achieved by checking the use count for */
10074 /* a given netmask. */
10075 /* ------------------------------------------------------------------------ */
10077 ipf_inet_mask_add(bits, mtab)
10079 ipf_v4_masktab_t *mtab;
10084 mtab->imt4_masks[bits]++;
10085 if (mtab->imt4_masks[bits] > 1)
10091 mask = 0xffffffff << (32 - bits);
10093 for (i = 0; i < 33; i++) {
10094 if (ntohl(mtab->imt4_active[i]) < mask) {
10095 for (j = 32; j > i; j--)
10096 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10097 mtab->imt4_active[i] = htonl(mask);
10105 /* ------------------------------------------------------------------------ */
10106 /* Function: ipf_inet_mask_del */
10108 /* Parameters: bits(I) - number of bits set in the netmask */
10109 /* mtab(I) - pointer to mask hash table structure */
10111 /* Remove the 32bit bitmask represented by "bits" from the collection of */
10112 /* netmasks stored inside of mtab. */
10113 /* ------------------------------------------------------------------------ */
10115 ipf_inet_mask_del(bits, mtab)
10117 ipf_v4_masktab_t *mtab;
10122 mtab->imt4_masks[bits]--;
10123 if (mtab->imt4_masks[bits] > 0)
10126 mask = htonl(0xffffffff << (32 - bits));
10127 for (i = 0; i < 33; i++) {
10128 if (mtab->imt4_active[i] == mask) {
10129 for (j = i + 1; j < 33; j++)
10130 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10135 ASSERT(mtab->imt4_max >= 0);
10140 /* ------------------------------------------------------------------------ */
10141 /* Function: ipf_inet6_mask_add */
10143 /* Parameters: bits(I) - number of bits set in mask */
10144 /* mask(I) - pointer to mask to add */
10145 /* mtab(I) - pointer to mask hash table structure */
10147 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
10148 /* has just been added. This function inserts a bitmask into the array of */
10149 /* masks to search when searching for a matching NAT rule for a packet. */
10150 /* Prevention of duplicate masks is achieved by checking the use count for */
10151 /* a given netmask. */
10152 /* ------------------------------------------------------------------------ */
10154 ipf_inet6_mask_add(bits, mask, mtab)
10157 ipf_v6_masktab_t *mtab;
10162 mtab->imt6_masks[bits]++;
10163 if (mtab->imt6_masks[bits] > 1)
10174 for (i = 0; i < 129; i++) {
10175 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10176 for (j = 128; j > i; j--)
10177 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10178 mtab->imt6_active[i] = *mask;
10186 /* ------------------------------------------------------------------------ */
10187 /* Function: ipf_inet6_mask_del */
10189 /* Parameters: bits(I) - number of bits set in mask */
10190 /* mask(I) - pointer to mask to remove */
10191 /* mtab(I) - pointer to mask hash table structure */
10193 /* Remove the 128bit bitmask represented by "bits" from the collection of */
10194 /* netmasks stored inside of mtab. */
10195 /* ------------------------------------------------------------------------ */
10197 ipf_inet6_mask_del(bits, mask, mtab)
10200 ipf_v6_masktab_t *mtab;
10205 mtab->imt6_masks[bits]--;
10206 if (mtab->imt6_masks[bits] > 0)
10216 for (i = 0; i < 129; i++) {
10217 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10218 for (j = i + 1; j < 129; j++) {
10219 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10220 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10227 ASSERT(mtab->imt6_max >= 0);