4 * Copyright (C) 1993-2003 by Darren Reed.
6 * See the IPFILTER.LICENCE file for details on licencing.
8 #if defined(KERNEL) || defined(_KERNEL)
14 #include <sys/errno.h>
15 #include <sys/types.h>
16 #include <sys/param.h>
18 #if defined(__NetBSD__)
19 # if (NetBSD >= 199905) && !defined(IPFILTER_LKM) && defined(_KERNEL)
20 # if (__NetBSD_Version__ < 399001400)
21 # include "opt_ipfilter_log.h"
23 # include "opt_ipfilter.h"
27 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
28 (__FreeBSD_version >= 220000)
29 # if (__FreeBSD_version >= 400000)
30 # if !defined(IPFILTER_LKM)
31 # include "opt_inet6.h"
33 # if (__FreeBSD_version == 400019)
34 # define CSUM_DELAY_DATA
37 # include <sys/filio.h>
39 # include <sys/ioctl.h>
41 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
42 # include <sys/filio.h>
45 # include <sys/fcntl.h>
48 # include <sys/systm.h>
49 # include <sys/file.h>
55 # include <sys/file.h>
63 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
65 # include <sys/mbuf.h>
68 # include <sys/byteorder.h>
70 # if (SOLARIS2 < 5) && defined(sun)
71 # include <sys/dditypes.h>
75 # define _NET_ROUTE_INCLUDED
78 # include <sys/protosw.h>
80 #include <sys/socket.h>
85 #if !defined(_KERNEL) && defined(__FreeBSD__)
86 # if (__FreeBSD_version >= 504000)
89 # include "radix_ipf.h"
92 # include "radix_ipf.h"
94 # include <net/route.h>
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
100 # include <netinet/ip_var.h>
102 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
103 # include <sys/hashing.h>
104 # include <netinet/in_var.h>
106 #include <netinet/tcp.h>
107 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
108 # include <netinet/udp.h>
109 # include <netinet/ip_icmp.h>
112 # undef _NET_ROUTE_INCLUDED
117 #include "netinet/ip_compat.h"
119 # include <netinet/icmp6.h>
120 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
121 # include <netinet6/in6_var.h>
124 #include <netinet/tcpip.h>
125 #include "netinet/ip_fil.h"
126 #include "netinet/ip_nat.h"
127 #include "netinet/ip_frag.h"
128 #include "netinet/ip_state.h"
129 #include "netinet/ip_proxy.h"
130 #include "netinet/ip_auth.h"
132 # include "netinet/ip_scan.h"
135 # include "netinet/ip_sync.h"
137 #include "netinet/ip_pool.h"
138 #include "netinet/ip_htable.h"
139 #ifdef IPFILTER_COMPILED
140 # include "netinet/ip_rules.h"
142 #if defined(IPFILTER_BPF) && defined(_KERNEL)
143 # include <net/bpf.h>
145 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
146 # include <sys/malloc.h>
147 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
148 # include "opt_ipfilter.h"
151 #include "netinet/ipl.h"
152 /* END OF INCLUDES */
154 #include <machine/in_cksum.h>
157 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
158 static const char rcsid[] = "@(#)$FreeBSD$";
159 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.78 2006/03/29 11:19:54 darrenr Exp $"; */
165 # include "bpf-ipf.h"
170 fr_info_t frcache[2][8];
171 struct filterstats frstats[2];
172 struct frentry *ipfilter[2][2] = { { NULL, NULL }, { NULL, NULL } },
173 *ipfilter6[2][2] = { { NULL, NULL }, { NULL, NULL } },
174 *ipacct6[2][2] = { { NULL, NULL }, { NULL, NULL } },
175 *ipacct[2][2] = { { NULL, NULL }, { NULL, NULL } },
176 *ipnatrules[2][2] = { { NULL, NULL }, { NULL, NULL } };
177 struct frgroup *ipfgroups[IPL_LOGSIZE][2];
178 char ipfilter_version[] = IPL_VERSION;
182 * 0 == loading, 1 = running, -1 = disabled, -2 = unloading
185 int fr_flags = IPF_LOGGING;
187 int fr_control_forwarding = 0;
188 int fr_update_ipid = 0;
189 u_short fr_ip_id = 0;
190 int fr_chksrc = 0; /* causes a system crash if enabled */
192 int fr_icmpminfragmtu = 68;
193 u_long fr_frouteok[2] = {0, 0};
194 u_long fr_userifqs = 0;
195 u_long fr_badcoalesces[2] = {0, 0};
196 u_char ipf_iss_secret[32];
197 #if defined(IPFILTER_DEFAULT_BLOCK)
198 int fr_pass = FR_BLOCK|FR_NOMATCH;
200 int fr_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
209 #ifdef IPFILTER_LOOKUP
215 #ifdef IPFILTER_COMPILED
218 #ifdef IPFILTER_CKSUM
232 static INLINE int fr_ipfcheck __P((fr_info_t *, frentry_t *, int));
233 static int fr_portcheck __P((frpcmp_t *, u_short *));
234 static int frflushlist __P((int, minor_t, int *, frentry_t **));
235 static ipfunc_t fr_findfunc __P((ipfunc_t));
236 static frentry_t *fr_firewall __P((fr_info_t *, u_32_t *));
237 static int fr_funcinit __P((frentry_t *fr));
238 static INLINE void frpr_ah __P((fr_info_t *));
239 static INLINE void frpr_esp __P((fr_info_t *));
240 static INLINE void frpr_gre __P((fr_info_t *));
241 static INLINE void frpr_udp __P((fr_info_t *));
242 static INLINE void frpr_tcp __P((fr_info_t *));
243 static INLINE void frpr_icmp __P((fr_info_t *));
244 static INLINE void frpr_ipv4hdr __P((fr_info_t *));
245 static INLINE int frpr_pullup __P((fr_info_t *, int));
246 static INLINE void frpr_short __P((fr_info_t *, int));
247 static INLINE int frpr_tcpcommon __P((fr_info_t *));
248 static INLINE int frpr_udpcommon __P((fr_info_t *));
249 static int fr_updateipid __P((fr_info_t *));
250 #ifdef IPFILTER_LOOKUP
251 static int fr_grpmapinit __P((frentry_t *fr));
252 static INLINE void *fr_resolvelookup __P((u_int, u_int, i6addr_t *, lookupfunc_t *));
254 static void frsynclist __P((frentry_t *, void *));
255 static ipftuneable_t *fr_findtunebyname __P((const char *));
256 static ipftuneable_t *fr_findtunebycookie __P((void *, void **));
257 static int ipf_geniter __P((ipftoken_t *, ipfgeniter_t *));
258 static int ipf_frruleiter __P((void *, int, void *));
259 static void ipf_unlinktoken __P((ipftoken_t *));
263 * bit values for identifying presence of individual IP options
264 * All of these tables should be ordered by increasing key value on the left
265 * hand side to allow for binary searching of the array and include a trailer
266 * with a 0 for the bitmask for linear searches to easily find the end with.
268 const struct optlist ipopts[20] = {
269 { IPOPT_NOP, 0x000001 },
270 { IPOPT_RR, 0x000002 },
271 { IPOPT_ZSU, 0x000004 },
272 { IPOPT_MTUP, 0x000008 },
273 { IPOPT_MTUR, 0x000010 },
274 { IPOPT_ENCODE, 0x000020 },
275 { IPOPT_TS, 0x000040 },
276 { IPOPT_TR, 0x000080 },
277 { IPOPT_SECURITY, 0x000100 },
278 { IPOPT_LSRR, 0x000200 },
279 { IPOPT_E_SEC, 0x000400 },
280 { IPOPT_CIPSO, 0x000800 },
281 { IPOPT_SATID, 0x001000 },
282 { IPOPT_SSRR, 0x002000 },
283 { IPOPT_ADDEXT, 0x004000 },
284 { IPOPT_VISA, 0x008000 },
285 { IPOPT_IMITD, 0x010000 },
286 { IPOPT_EIP, 0x020000 },
287 { IPOPT_FINN, 0x040000 },
292 struct optlist ip6exthdr[] = {
293 { IPPROTO_HOPOPTS, 0x000001 },
294 { IPPROTO_IPV6, 0x000002 },
295 { IPPROTO_ROUTING, 0x000004 },
296 { IPPROTO_FRAGMENT, 0x000008 },
297 { IPPROTO_ESP, 0x000010 },
298 { IPPROTO_AH, 0x000020 },
299 { IPPROTO_NONE, 0x000040 },
300 { IPPROTO_DSTOPTS, 0x000080 },
301 { IPPROTO_MOBILITY, 0x000100 },
306 struct optlist tcpopts[] = {
307 { TCPOPT_NOP, 0x000001 },
308 { TCPOPT_MAXSEG, 0x000002 },
309 { TCPOPT_WINDOW, 0x000004 },
310 { TCPOPT_SACK_PERMITTED, 0x000008 },
311 { TCPOPT_SACK, 0x000010 },
312 { TCPOPT_TIMESTAMP, 0x000020 },
317 * bit values for identifying presence of individual IP security options
319 const struct optlist secopt[8] = {
320 { IPSO_CLASS_RES4, 0x01 },
321 { IPSO_CLASS_TOPS, 0x02 },
322 { IPSO_CLASS_SECR, 0x04 },
323 { IPSO_CLASS_RES3, 0x08 },
324 { IPSO_CLASS_CONF, 0x10 },
325 { IPSO_CLASS_UNCL, 0x20 },
326 { IPSO_CLASS_RES2, 0x40 },
327 { IPSO_CLASS_RES1, 0x80 }
332 * Table of functions available for use with call rules.
334 static ipfunc_resolve_t fr_availfuncs[] = {
335 #ifdef IPFILTER_LOOKUP
336 { "fr_srcgrpmap", fr_srcgrpmap, fr_grpmapinit },
337 { "fr_dstgrpmap", fr_dstgrpmap, fr_grpmapinit },
344 * The next section of code is a a collection of small routines that set
345 * fields in the fr_info_t structure passed based on properties of the
346 * current packet. There are different routines for the same protocol
347 * for each of IPv4 and IPv6. Adding a new protocol, for which there
348 * will "special" inspection for setup, is now more easily done by adding
349 * a new routine and expanding the frpr_ipinit*() function rather than by
350 * adding more code to a growing switch statement.
353 static INLINE int frpr_ah6 __P((fr_info_t *));
354 static INLINE void frpr_esp6 __P((fr_info_t *));
355 static INLINE void frpr_gre6 __P((fr_info_t *));
356 static INLINE void frpr_udp6 __P((fr_info_t *));
357 static INLINE void frpr_tcp6 __P((fr_info_t *));
358 static INLINE void frpr_icmp6 __P((fr_info_t *));
359 static INLINE int frpr_ipv6hdr __P((fr_info_t *));
360 static INLINE void frpr_short6 __P((fr_info_t *, int));
361 static INLINE int frpr_hopopts6 __P((fr_info_t *));
362 static INLINE int frpr_mobility6 __P((fr_info_t *));
363 static INLINE int frpr_routing6 __P((fr_info_t *));
364 static INLINE int frpr_dstopts6 __P((fr_info_t *));
365 static INLINE void frpr_fragment6 __P((fr_info_t *));
366 static INLINE int frpr_ipv6exthdr __P((fr_info_t *, int, int));
369 /* ------------------------------------------------------------------------ */
370 /* Function: frpr_short6 */
372 /* Parameters: fin(I) - pointer to packet information */
375 /* This is function enforces the 'is a packet too short to be legit' rule */
376 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
377 /* for frpr_short() for more details. */
378 /* ------------------------------------------------------------------------ */
379 static INLINE void frpr_short6(fin, xmin)
384 if (fin->fin_dlen < xmin)
385 fin->fin_flx |= FI_SHORT;
389 /* ------------------------------------------------------------------------ */
390 /* Function: frpr_ipv6hdr */
391 /* Returns: int - 0 = IPv6 packet intact, -1 = packet lost */
392 /* Parameters: fin(I) - pointer to packet information */
395 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
396 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
397 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
398 /* of that possibility arising. */
399 /* ------------------------------------------------------------------------ */
400 static INLINE int frpr_ipv6hdr(fin)
403 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
404 int p, go = 1, i, hdrcount;
405 fr_ip_t *fi = &fin->fin_fi;
415 fi->fi_ttl = ip6->ip6_hlim;
416 fi->fi_src.in6 = ip6->ip6_src;
417 fi->fi_dst.in6 = ip6->ip6_dst;
418 fin->fin_id = (u_short)(ip6->ip6_flow & 0xffff);
421 while (go && !(fin->fin_flx & (FI_BAD|FI_SHORT))) {
434 case IPPROTO_ICMPV6 :
444 case IPPROTO_HOPOPTS :
445 p = frpr_hopopts6(fin);
448 case IPPROTO_MOBILITY :
449 p = frpr_mobility6(fin);
452 case IPPROTO_DSTOPTS :
453 p = frpr_dstopts6(fin);
456 case IPPROTO_ROUTING :
457 p = frpr_routing6(fin);
470 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
471 if (ip6exthdr[i].ol_val == p) {
472 fin->fin_flx |= ip6exthdr[i].ol_bit;
482 case IPPROTO_FRAGMENT :
494 * It is important to note that at this point, for the
495 * extension headers (go != 0), the entire header may not have
496 * been pulled up when the code gets to this point. This is
497 * only done for "go != 0" because the other header handlers
498 * will all pullup their complete header. The other indicator
499 * of an incomplete packet is that this was just an extension
502 if ((go != 0) && (p != IPPROTO_NONE) &&
503 (frpr_pullup(fin, 0) == -1)) {
511 * Some of the above functions, like frpr_esp6(), can call fr_pullup
512 * and destroy whatever packet was here. The caller of this function
513 * expects us to return -1 if there is a problem with fr_pullup.
515 if (fin->fin_m == NULL)
522 /* ------------------------------------------------------------------------ */
523 /* Function: frpr_ipv6exthdr */
524 /* Returns: int - value of the next header or IPPROTO_NONE if error */
525 /* Parameters: fin(I) - pointer to packet information */
526 /* multiple(I) - flag indicating yes/no if multiple occurances */
527 /* of this extension header are allowed. */
528 /* proto(I) - protocol number for this extension header */
531 /* ------------------------------------------------------------------------ */
532 static INLINE int frpr_ipv6exthdr(fin, multiple, proto)
540 fin->fin_flx |= FI_V6EXTHDR;
542 /* 8 is default length of extension hdr */
543 if ((fin->fin_dlen - 8) < 0) {
544 fin->fin_flx |= FI_SHORT;
548 if (frpr_pullup(fin, 8) == -1)
554 case IPPROTO_FRAGMENT :
558 shift = 8 + (hdr->ip6e_len << 3);
562 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
563 fin->fin_flx |= FI_BAD;
567 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
568 if (ip6exthdr[i].ol_val == proto) {
570 * Most IPv6 extension headers are only allowed once.
572 if ((multiple == 0) &&
573 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
574 fin->fin_flx |= FI_BAD;
576 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
580 fin->fin_exthdr = fin->fin_dp;
581 fin->fin_dp = (char *)fin->fin_dp + shift;
582 fin->fin_dlen -= shift;
584 return hdr->ip6e_nxt;
588 /* ------------------------------------------------------------------------ */
589 /* Function: frpr_hopopts6 */
590 /* Returns: int - value of the next header or IPPROTO_NONE if error */
591 /* Parameters: fin(I) - pointer to packet information */
594 /* This is function checks pending hop by hop options extension header */
595 /* ------------------------------------------------------------------------ */
596 static INLINE int frpr_hopopts6(fin)
599 return frpr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
603 /* ------------------------------------------------------------------------ */
604 /* Function: frpr_mobility6 */
605 /* Returns: int - value of the next header or IPPROTO_NONE if error */
606 /* Parameters: fin(I) - pointer to packet information */
609 /* This is function checks the IPv6 mobility extension header */
610 /* ------------------------------------------------------------------------ */
611 static INLINE int frpr_mobility6(fin)
614 return frpr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
618 /* ------------------------------------------------------------------------ */
619 /* Function: frpr_routing6 */
620 /* Returns: int - value of the next header or IPPROTO_NONE if error */
621 /* Parameters: fin(I) - pointer to packet information */
624 /* This is function checks pending routing extension header */
625 /* ------------------------------------------------------------------------ */
626 static INLINE int frpr_routing6(fin)
631 if (frpr_ipv6exthdr(fin, 0, IPPROTO_ROUTING) == IPPROTO_NONE)
633 hdr = fin->fin_exthdr;
635 if ((hdr->ip6e_len & 1) != 0) {
637 * The routing header data is made up of 128 bit IPv6 addresses
638 * which means it must be a multiple of 2 lots of 8 in length.
640 fin->fin_flx |= FI_BAD;
642 * Compensate for the changes made in frpr_ipv6exthdr()
644 fin->fin_dlen += 8 + (hdr->ip6e_len << 3);
649 return hdr->ip6e_nxt;
653 /* ------------------------------------------------------------------------ */
654 /* Function: frpr_fragment6 */
656 /* Parameters: fin(I) - pointer to packet information */
659 /* Examine the IPv6 fragment header and extract fragment offset information.*/
661 /* We don't know where the transport layer header (or whatever is next is), */
662 /* as it could be behind destination options (amongst others). Because */
663 /* there is no fragment cache, there is no knowledge about whether or not an*/
664 /* upper layer header has been seen (or where it ends) and thus we are not */
665 /* able to continue processing beyond this header with any confidence. */
666 /* ------------------------------------------------------------------------ */
667 static INLINE void frpr_fragment6(fin)
670 struct ip6_frag *frag;
673 fin->fin_flx |= FI_FRAG;
675 if (frpr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT) == IPPROTO_NONE)
678 extoff = (char *)fin->fin_exthdr - (char *)fin->fin_dp;
680 if (frpr_pullup(fin, sizeof(*frag)) == -1)
683 fin->fin_exthdr = (char *)fin->fin_dp + extoff;
684 frag = fin->fin_exthdr;
686 * Fragment but no fragmentation info set? Bad packet...
688 if (frag->ip6f_offlg == 0) {
689 fin->fin_flx |= FI_BAD;
693 fin->fin_off = frag->ip6f_offlg & IP6F_OFF_MASK;
695 if (fin->fin_off != 0)
696 fin->fin_flx |= FI_FRAGBODY;
698 fin->fin_dp = (char *)fin->fin_dp + sizeof(*frag);
699 fin->fin_dlen -= sizeof(*frag);
703 /* ------------------------------------------------------------------------ */
704 /* Function: frpr_dstopts6 */
705 /* Returns: int - value of the next header or IPPROTO_NONE if error */
706 /* Parameters: fin(I) - pointer to packet information */
707 /* nextheader(I) - stores next header value */
710 /* This is function checks pending destination options extension header */
711 /* ------------------------------------------------------------------------ */
712 static INLINE int frpr_dstopts6(fin)
715 return frpr_ipv6exthdr(fin, 1, IPPROTO_DSTOPTS);
719 /* ------------------------------------------------------------------------ */
720 /* Function: frpr_icmp6 */
722 /* Parameters: fin(I) - pointer to packet information */
725 /* This routine is mainly concerned with determining the minimum valid size */
726 /* for an ICMPv6 packet. */
727 /* ------------------------------------------------------------------------ */
728 static INLINE void frpr_icmp6(fin)
731 int minicmpsz = sizeof(struct icmp6_hdr);
732 struct icmp6_hdr *icmp6;
734 if (frpr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1)
737 if (fin->fin_dlen > 1) {
742 fin->fin_data[0] = *(u_short *)icmp6;
744 switch (icmp6->icmp6_type)
746 case ICMP6_ECHO_REPLY :
747 case ICMP6_ECHO_REQUEST :
748 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
750 case ICMP6_DST_UNREACH :
751 case ICMP6_PACKET_TOO_BIG :
752 case ICMP6_TIME_EXCEEDED :
753 case ICMP6_PARAM_PROB :
754 fin->fin_flx |= FI_ICMPERR;
755 if ((fin->fin_m != NULL) &&
756 (M_LEN(fin->fin_m) < fin->fin_plen)) {
757 if (fr_coalesce(fin) != 1)
761 if (frpr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
765 * If the destination of this packet doesn't match the
766 * source of the original packet then this packet is
770 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
771 if (IP6_NEQ(&fin->fin_fi.fi_dst,
772 (i6addr_t *)&ip6->ip6_src))
773 fin->fin_flx |= FI_BAD;
775 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
782 frpr_short6(fin, minicmpsz);
786 /* ------------------------------------------------------------------------ */
787 /* Function: frpr_udp6 */
789 /* Parameters: fin(I) - pointer to packet information */
792 /* Analyse the packet for IPv6/UDP properties. */
793 /* Is not expected to be called for fragmented packets. */
794 /* ------------------------------------------------------------------------ */
795 static INLINE void frpr_udp6(fin)
799 frpr_short6(fin, sizeof(struct udphdr));
801 if (frpr_udpcommon(fin) == 0) {
802 u_char p = fin->fin_p;
804 fin->fin_p = IPPROTO_UDP;
811 /* ------------------------------------------------------------------------ */
812 /* Function: frpr_tcp6 */
814 /* Parameters: fin(I) - pointer to packet information */
817 /* Analyse the packet for IPv6/TCP properties. */
818 /* Is not expected to be called for fragmented packets. */
819 /* ------------------------------------------------------------------------ */
820 static INLINE void frpr_tcp6(fin)
824 frpr_short6(fin, sizeof(struct tcphdr));
826 if (frpr_tcpcommon(fin) == 0) {
827 u_char p = fin->fin_p;
829 fin->fin_p = IPPROTO_TCP;
836 /* ------------------------------------------------------------------------ */
837 /* Function: frpr_esp6 */
839 /* Parameters: fin(I) - pointer to packet information */
842 /* Analyse the packet for ESP properties. */
843 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
844 /* even though the newer ESP packets must also have a sequence number that */
845 /* is 32bits as well, it is not possible(?) to determine the version from a */
846 /* simple packet header. */
847 /* ------------------------------------------------------------------------ */
848 static INLINE void frpr_esp6(fin)
852 frpr_short6(fin, sizeof(grehdr_t));
854 (void) frpr_pullup(fin, 8);
858 /* ------------------------------------------------------------------------ */
859 /* Function: frpr_ah6 */
861 /* Parameters: fin(I) - pointer to packet information */
864 /* Analyse the packet for AH properties. */
865 /* The minimum length is taken to be the combination of all fields in the */
866 /* header being present and no authentication data (null algorithm used.) */
867 /* ------------------------------------------------------------------------ */
868 static INLINE int frpr_ah6(fin)
873 frpr_short6(fin, 12);
875 if (frpr_pullup(fin, sizeof(*ah)) == -1)
878 ah = (authhdr_t *)fin->fin_dp;
883 /* ------------------------------------------------------------------------ */
884 /* Function: frpr_gre6 */
886 /* Parameters: fin(I) - pointer to packet information */
888 /* Analyse the packet for GRE properties. */
889 /* ------------------------------------------------------------------------ */
890 static INLINE void frpr_gre6(fin)
895 frpr_short6(fin, sizeof(grehdr_t));
897 if (frpr_pullup(fin, sizeof(grehdr_t)) == -1)
901 if (GRE_REV(gre->gr_flags) == 1)
902 fin->fin_data[0] = gre->gr_call;
904 #endif /* USE_INET6 */
907 /* ------------------------------------------------------------------------ */
908 /* Function: frpr_pullup */
909 /* Returns: int - 0 == pullup succeeded, -1 == failure */
910 /* Parameters: fin(I) - pointer to packet information */
911 /* plen(I) - length (excluding L3 header) to pullup */
913 /* Short inline function to cut down on code duplication to perform a call */
914 /* to fr_pullup to ensure there is the required amount of data, */
915 /* consecutively in the packet buffer. */
916 /* ------------------------------------------------------------------------ */
917 static INLINE int frpr_pullup(fin, plen)
921 if (fin->fin_m != NULL) {
922 if (fin->fin_dp != NULL)
923 plen += (char *)fin->fin_dp -
924 ((char *)fin->fin_ip + fin->fin_hlen);
925 plen += fin->fin_hlen;
926 if (M_LEN(fin->fin_m) < plen) {
928 if (fr_pullup(fin->fin_m, fin, plen) == NULL)
932 * Fake fr_pullup failing
945 /* ------------------------------------------------------------------------ */
946 /* Function: frpr_short */
948 /* Parameters: fin(I) - pointer to packet information */
949 /* xmin(I) - minimum header size */
951 /* Check if a packet is "short" as defined by xmin. The rule we are */
952 /* applying here is that the packet must not be fragmented within the layer */
953 /* 4 header. That is, it must not be a fragment that has its offset set to */
954 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
955 /* entire layer 4 header must be present (min). */
956 /* ------------------------------------------------------------------------ */
957 static INLINE void frpr_short(fin, xmin)
962 if (fin->fin_off == 0) {
963 if (fin->fin_dlen < xmin)
964 fin->fin_flx |= FI_SHORT;
965 } else if (fin->fin_off < xmin) {
966 fin->fin_flx |= FI_SHORT;
971 /* ------------------------------------------------------------------------ */
972 /* Function: frpr_icmp */
974 /* Parameters: fin(I) - pointer to packet information */
977 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
978 /* except extrememly bad packets, both type and code will be present. */
979 /* The expected minimum size of an ICMP packet is very much dependent on */
980 /* the type of it. */
982 /* XXX - other ICMP sanity checks? */
983 /* ------------------------------------------------------------------------ */
984 static INLINE void frpr_icmp(fin)
987 int minicmpsz = sizeof(struct icmp);
991 if (fin->fin_off != 0) {
992 frpr_short(fin, ICMPERR_ICMPHLEN);
996 if (frpr_pullup(fin, ICMPERR_ICMPHLEN) == -1)
999 if (fin->fin_dlen > 1) {
1002 fin->fin_data[0] = *(u_short *)icmp;
1004 switch (icmp->icmp_type)
1006 case ICMP_ECHOREPLY :
1008 /* Router discovery messaes - RFC 1256 */
1009 case ICMP_ROUTERADVERT :
1010 case ICMP_ROUTERSOLICIT :
1011 minicmpsz = ICMP_MINLEN;
1014 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1015 * 3 * timestamp(3 * 4)
1018 case ICMP_TSTAMPREPLY :
1022 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1026 case ICMP_MASKREPLY :
1030 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1034 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1035 if (icmp->icmp_nextmtu < fr_icmpminfragmtu)
1036 fin->fin_flx |= FI_BAD;
1039 case ICMP_SOURCEQUENCH :
1040 case ICMP_REDIRECT :
1041 case ICMP_TIMXCEED :
1042 case ICMP_PARAMPROB :
1043 fin->fin_flx |= FI_ICMPERR;
1044 if (fr_coalesce(fin) != 1)
1047 * ICMP error packets should not be generated for IP
1048 * packets that are a fragment that isn't the first
1051 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1052 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1053 fin->fin_flx |= FI_BAD;
1056 * If the destination of this packet doesn't match the
1057 * source of the original packet then this packet is
1060 if (oip->ip_src.s_addr != fin->fin_daddr)
1061 fin->fin_flx |= FI_BAD;
1064 * If the destination of this packet doesn't match the
1065 * source of the original packet then this packet is
1068 if (oip->ip_src.s_addr != fin->fin_daddr)
1069 fin->fin_flx |= FI_BAD;
1075 if (fin->fin_dlen >= 6) /* ID field */
1076 fin->fin_data[1] = icmp->icmp_id;
1079 frpr_short(fin, minicmpsz);
1085 /* ------------------------------------------------------------------------ */
1086 /* Function: frpr_tcpcommon */
1087 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1088 /* Parameters: fin(I) - pointer to packet information */
1090 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1091 /* and make some checks with how they interact with other fields. */
1092 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1093 /* valid and mark the packet as bad if not. */
1094 /* ------------------------------------------------------------------------ */
1095 static INLINE int frpr_tcpcommon(fin)
1101 fin->fin_flx |= FI_TCPUDP;
1102 if (fin->fin_off != 0)
1105 if (frpr_pullup(fin, sizeof(*tcp)) == -1)
1109 if (fin->fin_dlen > 3) {
1110 fin->fin_sport = ntohs(tcp->th_sport);
1111 fin->fin_dport = ntohs(tcp->th_dport);
1114 if ((fin->fin_flx & FI_SHORT) != 0)
1118 * Use of the TCP data offset *must* result in a value that is at
1119 * least the same size as the TCP header.
1121 tlen = TCP_OFF(tcp) << 2;
1122 if (tlen < sizeof(tcphdr_t)) {
1123 fin->fin_flx |= FI_BAD;
1127 flags = tcp->th_flags;
1128 fin->fin_tcpf = tcp->th_flags;
1131 * If the urgent flag is set, then the urgent pointer must
1132 * also be set and vice versa. Good TCP packets do not have
1133 * just one of these set.
1135 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1136 fin->fin_flx |= FI_BAD;
1138 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1140 * Ignore this case (#if 0) as it shows up in "real"
1141 * traffic with bogus values in the urgent pointer field.
1143 fin->fin_flx |= FI_BAD;
1145 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1146 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1147 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1148 fin->fin_flx |= FI_BAD;
1150 } else if (((flags & TH_SYN) != 0) &&
1151 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1153 * SYN with URG and PUSH set is not for normal TCP but it is
1154 * possible(?) with T/TCP...but who uses T/TCP?
1156 fin->fin_flx |= FI_BAD;
1158 } else if (!(flags & TH_ACK)) {
1160 * If the ack bit isn't set, then either the SYN or
1161 * RST bit must be set. If the SYN bit is set, then
1162 * we expect the ACK field to be 0. If the ACK is
1163 * not set and if URG, PSH or FIN are set, consdier
1164 * that to indicate a bad TCP packet.
1166 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1168 * Cisco PIX sets the ACK field to a random value.
1169 * In light of this, do not set FI_BAD until a patch
1170 * is available from Cisco to ensure that
1171 * interoperability between existing systems is
1174 /*fin->fin_flx |= FI_BAD*/;
1175 } else if (!(flags & (TH_RST|TH_SYN))) {
1176 fin->fin_flx |= FI_BAD;
1177 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1178 fin->fin_flx |= FI_BAD;
1183 * At this point, it's not exactly clear what is to be gained by
1184 * marking up which TCP options are and are not present. The one we
1185 * are most interested in is the TCP window scale. This is only in
1186 * a SYN packet [RFC1323] so we don't need this here...?
1187 * Now if we were to analyse the header for passive fingerprinting,
1188 * then that might add some weight to adding this...
1190 if (tlen == sizeof(tcphdr_t))
1193 if (frpr_pullup(fin, tlen) == -1)
1198 s = (u_char *)(tcp + 1);
1199 off = IP_HL(ip) << 2;
1201 if (fin->fin_mp != NULL) {
1202 mb_t *m = *fin->fin_mp;
1204 if (off + tlen > M_LEN(m))
1208 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1212 else if (opt == TCPOPT_NOP)
1218 if (ol < 2 || ol > tlen)
1222 for (i = 9, mv = 4; mv >= 0; ) {
1224 if (opt == (u_char)op->ol_val) {
1225 optmsk |= op->ol_bit;
1239 /* ------------------------------------------------------------------------ */
1240 /* Function: frpr_udpcommon */
1241 /* Returns: int - 0 = header ok, 1 = bad packet */
1242 /* Parameters: fin(I) - pointer to packet information */
1244 /* Extract the UDP source and destination ports, if present. If compiled */
1245 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1246 /* ------------------------------------------------------------------------ */
1247 static INLINE int frpr_udpcommon(fin)
1252 fin->fin_flx |= FI_TCPUDP;
1254 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1255 if (frpr_pullup(fin, sizeof(*udp)) == -1) {
1256 fin->fin_flx |= FI_SHORT;
1262 fin->fin_sport = ntohs(udp->uh_sport);
1263 fin->fin_dport = ntohs(udp->uh_dport);
1270 /* ------------------------------------------------------------------------ */
1271 /* Function: frpr_tcp */
1273 /* Parameters: fin(I) - pointer to packet information */
1276 /* Analyse the packet for IPv4/TCP properties. */
1277 /* ------------------------------------------------------------------------ */
1278 static INLINE void frpr_tcp(fin)
1282 frpr_short(fin, sizeof(tcphdr_t));
1284 if (frpr_tcpcommon(fin) == 0)
1289 /* ------------------------------------------------------------------------ */
1290 /* Function: frpr_udp */
1292 /* Parameters: fin(I) - pointer to packet information */
1295 /* Analyse the packet for IPv4/UDP properties. */
1296 /* ------------------------------------------------------------------------ */
1297 static INLINE void frpr_udp(fin)
1301 frpr_short(fin, sizeof(udphdr_t));
1303 if (frpr_udpcommon(fin) == 0)
1308 /* ------------------------------------------------------------------------ */
1309 /* Function: frpr_esp */
1311 /* Parameters: fin(I) - pointer to packet information */
1313 /* Analyse the packet for ESP properties. */
1314 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1315 /* even though the newer ESP packets must also have a sequence number that */
1316 /* is 32bits as well, it is not possible(?) to determine the version from a */
1317 /* simple packet header. */
1318 /* ------------------------------------------------------------------------ */
1319 static INLINE void frpr_esp(fin)
1323 if (fin->fin_off == 0) {
1325 (void) frpr_pullup(fin, 8);
1331 /* ------------------------------------------------------------------------ */
1332 /* Function: frpr_ah */
1334 /* Parameters: fin(I) - pointer to packet information */
1336 /* Analyse the packet for AH properties. */
1337 /* The minimum length is taken to be the combination of all fields in the */
1338 /* header being present and no authentication data (null algorithm used.) */
1339 /* ------------------------------------------------------------------------ */
1340 static INLINE void frpr_ah(fin)
1346 frpr_short(fin, sizeof(*ah));
1348 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0))
1351 if (frpr_pullup(fin, sizeof(*ah)) == -1)
1354 ah = (authhdr_t *)fin->fin_dp;
1356 len = (ah->ah_plen + 2) << 2;
1357 frpr_short(fin, len);
1361 /* ------------------------------------------------------------------------ */
1362 /* Function: frpr_gre */
1364 /* Parameters: fin(I) - pointer to packet information */
1366 /* Analyse the packet for GRE properties. */
1367 /* ------------------------------------------------------------------------ */
1368 static INLINE void frpr_gre(fin)
1373 frpr_short(fin, sizeof(*gre));
1375 if (fin->fin_off != 0)
1378 if (frpr_pullup(fin, sizeof(*gre)) == -1)
1381 if (fin->fin_off == 0) {
1383 if (GRE_REV(gre->gr_flags) == 1)
1384 fin->fin_data[0] = gre->gr_call;
1389 /* ------------------------------------------------------------------------ */
1390 /* Function: frpr_ipv4hdr */
1392 /* Parameters: fin(I) - pointer to packet information */
1395 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1396 /* Check all options present and flag their presence if any exist. */
1397 /* ------------------------------------------------------------------------ */
1398 static INLINE void frpr_ipv4hdr(fin)
1401 u_short optmsk = 0, secmsk = 0, auth = 0;
1402 int hlen, ol, mv, p, i;
1403 const struct optlist *op;
1410 hlen = fin->fin_hlen;
1415 fi->fi_tos = ip->ip_tos;
1416 fin->fin_id = ip->ip_id;
1419 /* Get both TTL and protocol */
1420 fi->fi_p = ip->ip_p;
1421 fi->fi_ttl = ip->ip_ttl;
1423 (*(((u_short *)fi) + 1)) = (*(((u_short *)ip) + 4));
1426 /* Zero out bits not used in IPv6 address */
1427 fi->fi_src.i6[1] = 0;
1428 fi->fi_src.i6[2] = 0;
1429 fi->fi_src.i6[3] = 0;
1430 fi->fi_dst.i6[1] = 0;
1431 fi->fi_dst.i6[2] = 0;
1432 fi->fi_dst.i6[3] = 0;
1434 fi->fi_saddr = ip->ip_src.s_addr;
1435 fi->fi_daddr = ip->ip_dst.s_addr;
1438 * set packet attribute flags based on the offset and
1439 * calculate the byte offset that it represents.
1441 off &= IP_MF|IP_OFFMASK;
1443 int morefrag = off & IP_MF;
1445 fi->fi_flx |= FI_FRAG;
1448 fin->fin_flx |= FI_FRAGBODY;
1450 if ((off + fin->fin_dlen > 65535) ||
1451 (fin->fin_dlen == 0) ||
1452 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1454 * The length of the packet, starting at its
1455 * offset cannot exceed 65535 (0xffff) as the
1456 * length of an IP packet is only 16 bits.
1458 * Any fragment that isn't the last fragment
1459 * must have a length greater than 0 and it
1460 * must be an even multiple of 8.
1462 fi->fi_flx |= FI_BAD;
1469 * Call per-protocol setup and checking
1498 * If it is a standard IP header (no options), set the flag fields
1499 * which relate to options to 0.
1501 if (hlen == sizeof(*ip)) {
1509 * So the IP header has some IP options attached. Walk the entire
1510 * list of options present with this packet and set flags to indicate
1511 * which ones are here and which ones are not. For the somewhat out
1512 * of date and obscure security classification options, set a flag to
1513 * represent which classification is present.
1515 fi->fi_flx |= FI_OPTIONS;
1517 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1521 else if (opt == IPOPT_NOP)
1527 if (ol < 2 || ol > hlen)
1530 for (i = 9, mv = 4; mv >= 0; ) {
1532 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1533 optmsk |= op->ol_bit;
1534 if (opt == IPOPT_SECURITY) {
1535 const struct optlist *sp;
1539 sec = *(s + 2); /* classification */
1540 for (j = 3, m = 2; m >= 0; ) {
1542 if (sec == sp->ol_val) {
1543 secmsk |= sp->ol_bit;
1549 if (sec < sp->ol_val)
1558 if (opt < op->ol_val)
1571 if (auth && !(auth & 0x0100))
1573 fi->fi_optmsk = optmsk;
1574 fi->fi_secmsk = secmsk;
1579 /* ------------------------------------------------------------------------ */
1580 /* Function: fr_makefrip */
1582 /* Parameters: hlen(I) - length of IP packet header */
1583 /* ip(I) - pointer to the IP header */
1584 /* fin(IO) - pointer to packet information */
1586 /* Compact the IP header into a structure which contains just the info. */
1587 /* which is useful for comparing IP headers with and store this information */
1588 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
1589 /* this function will be called with either an IPv4 or IPv6 packet. */
1590 /* ------------------------------------------------------------------------ */
1591 int fr_makefrip(hlen, ip, fin)
1598 fin->fin_nat = NULL;
1599 fin->fin_state = NULL;
1601 fin->fin_hlen = (u_short)hlen;
1603 fin->fin_rule = 0xffffffff;
1604 fin->fin_group[0] = -1;
1605 fin->fin_group[1] = '\0';
1606 fin->fin_dp = (char *)ip + hlen;
1610 fin->fin_plen = ip->ip_len;
1611 fin->fin_dlen = fin->fin_plen - hlen;
1615 } else if (v == 6) {
1616 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
1617 fin->fin_dlen = fin->fin_plen;
1618 fin->fin_plen += hlen;
1620 if (frpr_ipv6hdr(fin) == -1)
1624 if (fin->fin_ip == NULL)
1630 /* ------------------------------------------------------------------------ */
1631 /* Function: fr_portcheck */
1632 /* Returns: int - 1 == port matched, 0 == port match failed */
1633 /* Parameters: frp(I) - pointer to port check `expression' */
1634 /* pop(I) - pointer to port number to evaluate */
1636 /* Perform a comparison of a port number against some other(s), using a */
1637 /* structure with compare information stored in it. */
1638 /* ------------------------------------------------------------------------ */
1639 static INLINE int fr_portcheck(frp, pop)
1650 * Do opposite test to that required and continue if that succeeds.
1652 switch (frp->frp_cmp)
1655 if (tup != po) /* EQUAL */
1659 if (tup == po) /* NOTEQUAL */
1663 if (tup >= po) /* LESSTHAN */
1667 if (tup <= po) /* GREATERTHAN */
1671 if (tup > po) /* LT or EQ */
1675 if (tup < po) /* GT or EQ */
1679 if (tup >= po && tup <= frp->frp_top) /* Out of range */
1683 if (tup <= po || tup >= frp->frp_top) /* In range */
1687 if (tup < po || tup > frp->frp_top) /* Inclusive range */
1697 /* ------------------------------------------------------------------------ */
1698 /* Function: fr_tcpudpchk */
1699 /* Returns: int - 1 == protocol matched, 0 == check failed */
1700 /* Parameters: fin(I) - pointer to packet information */
1701 /* ft(I) - pointer to structure with comparison data */
1703 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
1704 /* structure containing information that we want to match against. */
1705 /* ------------------------------------------------------------------------ */
1706 int fr_tcpudpchk(fin, ft)
1713 * Both ports should *always* be in the first fragment.
1714 * So far, I cannot find any cases where they can not be.
1716 * compare destination ports
1719 err = fr_portcheck(&ft->ftu_dst, &fin->fin_dport);
1722 * compare source ports
1724 if (err && ft->ftu_scmp)
1725 err = fr_portcheck(&ft->ftu_src, &fin->fin_sport);
1728 * If we don't have all the TCP/UDP header, then how can we
1729 * expect to do any sort of match on it ? If we were looking for
1730 * TCP flags, then NO match. If not, then match (which should
1731 * satisfy the "short" class too).
1733 if (err && (fin->fin_p == IPPROTO_TCP)) {
1734 if (fin->fin_flx & FI_SHORT)
1735 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
1737 * Match the flags ? If not, abort this match.
1739 if (ft->ftu_tcpfm &&
1740 ft->ftu_tcpf != (fin->fin_tcpf & ft->ftu_tcpfm)) {
1741 FR_DEBUG(("f. %#x & %#x != %#x\n", fin->fin_tcpf,
1742 ft->ftu_tcpfm, ft->ftu_tcpf));
1751 /* ------------------------------------------------------------------------ */
1752 /* Function: fr_ipfcheck */
1753 /* Returns: int - 0 == match, 1 == no match */
1754 /* Parameters: fin(I) - pointer to packet information */
1755 /* fr(I) - pointer to filter rule */
1756 /* portcmp(I) - flag indicating whether to attempt matching on */
1757 /* TCP/UDP port data. */
1759 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
1760 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
1761 /* this function. */
1762 /* ------------------------------------------------------------------------ */
1763 static INLINE int fr_ipfcheck(fin, fr, portcmp)
1768 u_32_t *ld, *lm, *lip;
1776 lm = (u_32_t *)&fri->fri_mip;
1777 ld = (u_32_t *)&fri->fri_ip;
1780 * first 32 bits to check coversion:
1781 * IP version, TOS, TTL, protocol
1783 i = ((*lip & *lm) != *ld);
1784 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
1785 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1790 * Next 32 bits is a constructed bitmask indicating which IP options
1791 * are present (if any) in this packet.
1794 i |= ((*lip & *lm) != *ld);
1795 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
1796 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1802 * Unrolled loops (4 each, for 32 bits) for address checks.
1805 * Check the source address.
1807 #ifdef IPFILTER_LOOKUP
1808 if (fr->fr_satype == FRI_LOOKUP) {
1809 i = (*fr->fr_srcfunc)(fr->fr_srcptr, fi->fi_v, lip);
1817 i = ((*lip & *lm) != *ld);
1818 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
1819 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1820 if (fi->fi_v == 6) {
1822 i |= ((*lip & *lm) != *ld);
1823 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
1824 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1826 i |= ((*lip & *lm) != *ld);
1827 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
1828 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1830 i |= ((*lip & *lm) != *ld);
1831 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
1832 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1838 #ifdef IPFILTER_LOOKUP
1841 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
1846 * Check the destination address.
1849 #ifdef IPFILTER_LOOKUP
1850 if (fr->fr_datype == FRI_LOOKUP) {
1851 i = (*fr->fr_dstfunc)(fr->fr_dstptr, fi->fi_v, lip);
1859 i = ((*lip & *lm) != *ld);
1860 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
1861 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1862 if (fi->fi_v == 6) {
1864 i |= ((*lip & *lm) != *ld);
1865 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
1866 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1868 i |= ((*lip & *lm) != *ld);
1869 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
1870 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1872 i |= ((*lip & *lm) != *ld);
1873 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
1874 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
1880 #ifdef IPFILTER_LOOKUP
1883 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
1887 * IP addresses matched. The next 32bits contains:
1888 * mast of old IP header security & authentication bits.
1891 i |= ((*lip & *lm) != *ld);
1892 FR_DEBUG(("4. %#08x & %#08x != %#08x\n",
1896 * Next we have 32 bits of packet flags.
1899 i |= ((*lip & *lm) != *ld);
1900 FR_DEBUG(("5. %#08x & %#08x != %#08x\n",
1905 * If a fragment, then only the first has what we're
1906 * looking for here...
1909 if (!fr_tcpudpchk(fin, &fr->fr_tuc))
1912 if (fr->fr_dcmp || fr->fr_scmp ||
1913 fr->fr_tcpf || fr->fr_tcpfm)
1915 if (fr->fr_icmpm || fr->fr_icmp) {
1916 if (((fi->fi_p != IPPROTO_ICMP) &&
1917 (fi->fi_p != IPPROTO_ICMPV6)) ||
1918 fin->fin_off || (fin->fin_dlen < 2))
1920 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
1922 FR_DEBUG(("i. %#x & %#x != %#x\n",
1924 fr->fr_icmpm, fr->fr_icmp));
1934 /* ------------------------------------------------------------------------ */
1935 /* Function: fr_scanlist */
1936 /* Returns: int - result flags of scanning filter list */
1937 /* Parameters: fin(I) - pointer to packet information */
1938 /* pass(I) - default result to return for filtering */
1940 /* Check the input/output list of rules for a match to the current packet. */
1941 /* If a match is found, the value of fr_flags from the rule becomes the */
1942 /* return value and fin->fin_fr points to the matched rule. */
1944 /* This function may be called recusively upto 16 times (limit inbuilt.) */
1945 /* When unwinding, it should finish up with fin_depth as 0. */
1947 /* Could be per interface, but this gets real nasty when you don't have, */
1948 /* or can't easily change, the kernel source code to . */
1949 /* ------------------------------------------------------------------------ */
1950 int fr_scanlist(fin, pass)
1954 int rulen, portcmp, off, logged, skip;
1955 struct frentry *fr, *fnext;
1956 u_32_t passt, passo;
1959 * Do not allow nesting deeper than 16 levels.
1961 if (fin->fin_depth >= 16)
1967 * If there are no rules in this list, return now.
1979 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
1982 for (rulen = 0; fr; fr = fnext, rulen++) {
1983 fnext = fr->fr_next;
1985 FR_VERBOSE(("%d (%#x)\n", skip, fr->fr_flags));
1991 * In all checks below, a null (zero) value in the
1992 * filter struture is taken to mean a wildcard.
1994 * check that we are working for the right interface
1997 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2000 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2002 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2003 FR_ISPASS(pass) ? 'p' :
2004 FR_ISACCOUNT(pass) ? 'A' :
2005 FR_ISAUTH(pass) ? 'a' :
2006 (pass & FR_NOMATCH) ? 'n' :'b'));
2007 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2012 switch (fr->fr_type)
2015 case FR_T_IPF|FR_T_BUILTIN :
2016 if (fr_ipfcheck(fin, fr, portcmp))
2019 #if defined(IPFILTER_BPF)
2021 case FR_T_BPFOPC|FR_T_BUILTIN :
2025 if (*fin->fin_mp == NULL)
2027 if (fin->fin_v != fr->fr_v)
2029 mc = (u_char *)fin->fin_m;
2030 if (!bpf_filter(fr->fr_data, mc, fin->fin_plen, 0))
2035 case FR_T_CALLFUNC|FR_T_BUILTIN :
2039 f = (*fr->fr_func)(fin, &pass);
2050 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2051 if (fin->fin_nattag == NULL)
2053 if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2056 FR_VERBOSE(("=%s.%d *", fr->fr_group, rulen));
2058 passt = fr->fr_flags;
2061 * Allowing a rule with the "keep state" flag set to match
2062 * packets that have been tagged "out of window" by the TCP
2063 * state tracking is foolish as the attempt to add a new
2064 * state entry to the table will fail.
2066 if ((passt & FR_KEEPSTATE) && (fin->fin_flx & FI_OOW))
2070 * If the rule is a "call now" rule, then call the function
2071 * in the rule, if it exists and use the results from that.
2072 * If the function pointer is bad, just make like we ignore
2073 * it, except for increasing the hit counter.
2075 if ((passt & FR_CALLNOW) != 0) {
2078 ATOMIC_INC64(fr->fr_hits);
2079 if ((fr->fr_func != NULL) &&
2080 (fr->fr_func == (ipfunc_t)-1))
2085 fr = (*fr->fr_func)(fin, &passt);
2090 passt = fr->fr_flags;
2096 * Just log this packet...
2098 if ((passt & FR_LOGMASK) == FR_LOG) {
2099 if (ipflog(fin, passt) == -1) {
2100 if (passt & FR_LOGORBLOCK) {
2101 passt &= ~FR_CMDMASK;
2102 passt |= FR_BLOCK|FR_QUICK;
2104 ATOMIC_INCL(frstats[fin->fin_out].fr_skip);
2106 ATOMIC_INCL(frstats[fin->fin_out].fr_pkl);
2109 #endif /* IPFILTER_LOG */
2110 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2112 if (FR_ISSKIP(passt))
2114 else if ((passt & FR_LOGMASK) != FR_LOG)
2116 if (passt & (FR_RETICMP|FR_FAKEICMP))
2117 fin->fin_icode = fr->fr_icode;
2118 FR_DEBUG(("pass %#x\n", pass));
2119 ATOMIC_INC64(fr->fr_hits);
2120 fin->fin_rule = rulen;
2121 (void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
2122 if (fr->fr_grp != NULL) {
2123 fin->fin_fr = *fr->fr_grp;
2124 passt = fr_scanlist(fin, pass);
2125 if (fin->fin_fr == NULL) {
2126 fin->fin_rule = rulen;
2127 (void) strncpy(fin->fin_group, fr->fr_group,
2132 if (fin->fin_flx & FI_DONTCACHE)
2137 if (passt & FR_QUICK) {
2139 * Finally, if we've asked to track state for this
2140 * packet, set it up. Add state for "quick" rules
2141 * here so that if the action fails we can consider
2142 * the rule to "not match" and keep on processing
2145 if ((pass & FR_KEEPSTATE) &&
2146 !(fin->fin_flx & FI_STATE)) {
2147 int out = fin->fin_out;
2150 if (fr_addstate(fin, NULL, 0) != NULL) {
2151 ATOMIC_INCL(frstats[out].fr_ads);
2153 ATOMIC_INCL(frstats[out].fr_bads);
2162 fin->fin_flx |= FI_DONTCACHE;
2168 /* ------------------------------------------------------------------------ */
2169 /* Function: fr_acctpkt */
2170 /* Returns: frentry_t* - always returns NULL */
2171 /* Parameters: fin(I) - pointer to packet information */
2172 /* passp(IO) - pointer to current/new filter decision (unused) */
2174 /* Checks a packet against accounting rules, if there are any for the given */
2175 /* IP protocol version. */
2177 /* N.B.: this function returns NULL to match the prototype used by other */
2178 /* functions called from the IPFilter "mainline" in fr_check(). */
2179 /* ------------------------------------------------------------------------ */
2180 frentry_t *fr_acctpkt(fin, passp)
2184 char group[FR_GROUPLEN];
2185 frentry_t *fr, *frsave;
2190 if (fin->fin_v == 6)
2191 fr = ipacct6[fin->fin_out][fr_active];
2194 fr = ipacct[fin->fin_out][fr_active];
2197 frsave = fin->fin_fr;
2198 bcopy(fin->fin_group, group, FR_GROUPLEN);
2199 rulen = fin->fin_rule;
2201 pass = fr_scanlist(fin, FR_NOMATCH);
2202 if (FR_ISACCOUNT(pass)) {
2203 ATOMIC_INCL(frstats[0].fr_acct);
2205 fin->fin_fr = frsave;
2206 bcopy(group, fin->fin_group, FR_GROUPLEN);
2207 fin->fin_rule = rulen;
2213 /* ------------------------------------------------------------------------ */
2214 /* Function: fr_firewall */
2215 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2216 /* were found, returns NULL. */
2217 /* Parameters: fin(I) - pointer to packet information */
2218 /* passp(IO) - pointer to current/new filter decision (unused) */
2220 /* Applies an appropriate set of firewall rules to the packet, to see if */
2221 /* there are any matches. The first check is to see if a match can be seen */
2222 /* in the cache. If not, then search an appropriate list of rules. Once a */
2223 /* matching rule is found, take any appropriate actions as defined by the */
2224 /* rule - except logging. */
2225 /* ------------------------------------------------------------------------ */
2226 static frentry_t *fr_firewall(fin, passp)
2239 * If a packet is found in the auth table, then skip checking
2240 * the access lists for permission but we do need to consider
2241 * the result as if it were from the ACL's.
2243 fc = &frcache[out][CACHE_HASH(fin)];
2244 READ_ENTER(&ipf_frcache);
2245 if (!bcmp((char *)fin, (char *)fc, FI_CSIZE)) {
2247 * copy cached data so we can unlock the mutexes earlier.
2249 bcopy((char *)fc, (char *)fin, FI_COPYSIZE);
2250 RWLOCK_EXIT(&ipf_frcache);
2251 ATOMIC_INCL(frstats[out].fr_chit);
2253 if ((fr = fin->fin_fr) != NULL) {
2254 ATOMIC_INC64(fr->fr_hits);
2255 pass = fr->fr_flags;
2258 RWLOCK_EXIT(&ipf_frcache);
2261 if (fin->fin_v == 6)
2262 fin->fin_fr = ipfilter6[out][fr_active];
2265 fin->fin_fr = ipfilter[out][fr_active];
2266 if (fin->fin_fr != NULL)
2267 pass = fr_scanlist(fin, fr_pass);
2269 if (((pass & FR_KEEPSTATE) == 0) &&
2270 ((fin->fin_flx & FI_DONTCACHE) == 0)) {
2271 WRITE_ENTER(&ipf_frcache);
2272 bcopy((char *)fin, (char *)fc, FI_COPYSIZE);
2273 RWLOCK_EXIT(&ipf_frcache);
2275 if ((pass & FR_NOMATCH)) {
2276 ATOMIC_INCL(frstats[out].fr_nom);
2282 * Apply packets per second rate-limiting to a rule as required.
2284 if ((fr != NULL) && (fr->fr_pps != 0) &&
2285 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2286 pass &= ~(FR_CMDMASK|FR_DUP|FR_RETICMP|FR_RETRST);
2288 ATOMIC_INCL(frstats[out].fr_ppshit);
2292 * If we fail to add a packet to the authorization queue, then we
2293 * drop the packet later. However, if it was added then pretend
2294 * we've dropped it already.
2296 if (FR_ISAUTH(pass)) {
2297 if (fr_newauth(fin->fin_m, fin) != 0) {
2299 if ((pass & FR_RETMASK) == 0)
2300 fin->fin_m = *fin->fin_mp = NULL;
2306 fin->fin_error = ENOSPC;
2309 if ((fr != NULL) && (fr->fr_func != NULL) &&
2310 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2311 (void) (*fr->fr_func)(fin, &pass);
2314 * If a rule is a pre-auth rule, check again in the list of rules
2315 * loaded for authenticated use. It does not particulary matter
2316 * if this search fails because a "preauth" result, from a rule,
2317 * is treated as "not a pass", hence the packet is blocked.
2319 if (FR_ISPREAUTH(pass)) {
2320 if ((fin->fin_fr = ipauth) != NULL)
2321 pass = fr_scanlist(fin, fr_pass);
2325 * If the rule has "keep frag" and the packet is actually a fragment,
2326 * then create a fragment state entry.
2328 if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2329 if (fin->fin_flx & FI_FRAG) {
2330 if (fr_newfrag(fin, pass) == -1) {
2331 ATOMIC_INCL(frstats[out].fr_bnfr);
2333 ATOMIC_INCL(frstats[out].fr_nfr);
2336 ATOMIC_INCL(frstats[out].fr_cfr);
2349 /* ------------------------------------------------------------------------ */
2350 /* Function: fr_check */
2351 /* Returns: int - 0 == packet allowed through, */
2353 /* -1 == packet blocked */
2354 /* 1 == packet not matched */
2355 /* -2 == requires authentication */
2357 /* > 0 == filter error # for packet */
2358 /* Parameters: ip(I) - pointer to start of IPv4/6 packet */
2359 /* hlen(I) - length of header */
2360 /* ifp(I) - pointer to interface this packet is on */
2361 /* out(I) - 0 == packet going in, 1 == packet going out */
2362 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2364 /* Solaris & HP-UX ONLY : */
2365 /* qpi(I) - pointer to STREAMS queue information for this */
2366 /* interface & direction. */
2368 /* fr_check() is the master function for all IPFilter packet processing. */
2369 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2370 /* authorisation (or pre-authorisation), presence of related state info., */
2371 /* generating log entries, IP packet accounting, routing of packets as */
2372 /* directed by firewall rules and of course whether or not to allow the */
2373 /* packet to be further processed by the kernel. */
2375 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2376 /* freed. Packets passed may be returned with the pointer pointed to by */
2377 /* by "mp" changed to a new buffer. */
2378 /* ------------------------------------------------------------------------ */
2379 int fr_check(ip, hlen, ifp, out
2380 #if defined(_KERNEL) && defined(MENTAT)
2393 * The above really sucks, but short of writing a diff
2396 fr_info_t *fin = &frinfo;
2397 u_32_t pass = fr_pass;
2398 frentry_t *fr = NULL;
2403 * The first part of fr_check() deals with making sure that what goes
2404 * into the filtering engine makes some sense. Information about the
2405 * the packet is distilled, collected into a fr_info_t structure and
2406 * the an attempt to ensure the buffer the packet is in is big enough
2407 * to hold all the required packet headers.
2411 qpktinfo_t *qpi = qif;
2413 if ((u_int)ip & 0x3)
2419 READ_ENTER(&ipf_global);
2421 if (fr_running <= 0) {
2422 RWLOCK_EXIT(&ipf_global);
2426 bzero((char *)fin, sizeof(*fin));
2429 if (qpi->qpi_flags & QF_GROUP)
2430 fin->fin_flx |= FI_MBCAST;
2438 # if defined(M_MCAST)
2439 if ((m->m_flags & M_MCAST) != 0)
2440 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2442 # if defined(M_MLOOP)
2443 if ((m->m_flags & M_MLOOP) != 0)
2444 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2446 # if defined(M_BCAST)
2447 if ((m->m_flags & M_BCAST) != 0)
2448 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2450 # ifdef M_CANFASTFWD
2452 * XXX For now, IP Filter and fast-forwarding of cached flows
2453 * XXX are mutually exclusive. Eventually, IP Filter should
2454 * XXX get a "can-fast-forward" filter rule.
2456 m->m_flags &= ~M_CANFASTFWD;
2457 # endif /* M_CANFASTFWD */
2458 # ifdef CSUM_DELAY_DATA
2460 * disable delayed checksums.
2462 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2463 in_delayed_cksum(m);
2464 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2466 # endif /* CSUM_DELAY_DATA */
2467 # endif /* MENTAT */
2469 READ_ENTER(&ipf_global);
2471 bzero((char *)fin, sizeof(*fin));
2473 #endif /* _KERNEL */
2481 fin->fin_error = ENETUNREACH;
2482 fin->fin_hlen = (u_short)hlen;
2483 fin->fin_dp = (char *)ip + hlen;
2485 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2491 ATOMIC_INCL(frstats[out].fr_ipv6);
2493 * Jumbo grams are quite likely too big for internal buffer
2494 * structures to handle comfortably, for now, so just drop
2497 if (((ip6_t *)ip)->ip6_plen == 0) {
2498 pass = FR_BLOCK|FR_NOMATCH;
2504 #if (defined(OpenBSD) && OpenBSD >= 200311) && defined(_KERNEL)
2505 ip->ip_len = ntohs(ip->ip_len);
2506 ip->ip_off = ntohs(ip->ip_off);
2510 if (fr_makefrip(hlen, ip, fin) == -1) {
2511 pass = FR_BLOCK|FR_NOMATCH;
2516 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2517 * becomes NULL and so we have no packet to free.
2519 if (*fin->fin_mp == NULL)
2525 if (fr_chksrc && !fr_verifysrc(fin)) {
2526 ATOMIC_INCL(frstats[0].fr_badsrc);
2527 fin->fin_flx |= FI_BADSRC;
2530 if (fin->fin_ip->ip_ttl < fr_minttl) {
2531 ATOMIC_INCL(frstats[0].fr_badttl);
2532 fin->fin_flx |= FI_LOWTTL;
2537 if (((ip6_t *)ip)->ip6_hlim < fr_minttl) {
2538 ATOMIC_INCL(frstats[0].fr_badttl);
2539 fin->fin_flx |= FI_LOWTTL;
2545 if (fin->fin_flx & FI_SHORT) {
2546 ATOMIC_INCL(frstats[out].fr_short);
2549 READ_ENTER(&ipf_mutex);
2552 * Check auth now. This, combined with the check below to see if apass
2553 * is 0 is to ensure that we don't count the packet twice, which can
2554 * otherwise occur when we reprocess it. As it is, we only count it
2555 * after it has no auth. table matchup. This also stops NAT from
2556 * occuring until after the packet has been auth'd.
2558 fr = fr_checkauth(fin, &pass);
2560 if (fr_checknatin(fin, &pass) == -1) {
2565 (void) fr_acctpkt(fin, NULL);
2568 if ((fin->fin_flx & (FI_FRAG|FI_BAD)) == FI_FRAG)
2569 fr = fr_knownfrag(fin, &pass);
2571 fr = fr_checkstate(fin, &pass);
2573 if ((pass & FR_NOMATCH) || (fr == NULL))
2574 fr = fr_firewall(fin, &pass);
2577 * If we've asked to track state for this packet, set it up.
2578 * Here rather than fr_firewall because fr_checkauth may decide
2579 * to return a packet for "keep state"
2581 if ((pass & FR_KEEPSTATE) && !(fin->fin_flx & FI_STATE)) {
2582 if (fr_addstate(fin, NULL, 0) != NULL) {
2583 ATOMIC_INCL(frstats[out].fr_ads);
2585 ATOMIC_INCL(frstats[out].fr_bads);
2586 if (FR_ISPASS(pass)) {
2587 pass &= ~FR_CMDMASK;
2596 * Only count/translate packets which will be passed on, out the
2599 if (out && FR_ISPASS(pass)) {
2600 (void) fr_acctpkt(fin, NULL);
2602 if (fr_checknatout(fin, &pass) == -1) {
2604 } else if ((fr_update_ipid != 0) && (v == 4)) {
2605 if (fr_updateipid(fin) == -1) {
2606 ATOMIC_INCL(frstats[1].fr_ipud);
2607 pass &= ~FR_CMDMASK;
2610 ATOMIC_INCL(frstats[0].fr_ipud);
2617 if ((fr_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
2618 (void) fr_dolog(fin, &pass);
2623 * The FI_STATE flag is cleared here so that calling fr_checkstate
2624 * will work when called from inside of fr_fastroute. Although
2625 * there is a similar flag, FI_NATED, for NAT, it does have the same
2626 * impact on code execution.
2628 if (fin->fin_state != NULL) {
2629 fr_statederef((ipstate_t **)&fin->fin_state);
2630 fin->fin_flx ^= FI_STATE;
2633 if (fin->fin_nat != NULL) {
2634 fr_natderef((nat_t **)&fin->fin_nat);
2638 * Up the reference on fr_lock and exit ipf_mutex. fr_fastroute
2639 * only frees up the lock on ipf_global and the generation of a
2640 * packet below could cause a recursive call into IPFilter.
2641 * Hang onto the filter rule just in case someone decides to remove
2642 * or flush it in the meantime.
2645 MUTEX_ENTER(&fr->fr_lock);
2647 MUTEX_EXIT(&fr->fr_lock);
2650 RWLOCK_EXIT(&ipf_mutex);
2652 if ((pass & FR_RETMASK) != 0) {
2654 * Should we return an ICMP packet to indicate error
2655 * status passing through the packet filter ?
2656 * WARNING: ICMP error packets AND TCP RST packets should
2657 * ONLY be sent in repsonse to incoming packets. Sending them
2658 * in response to outbound packets can result in a panic on
2659 * some operating systems.
2662 if (pass & FR_RETICMP) {
2665 if ((pass & FR_RETMASK) == FR_FAKEICMP)
2669 (void) fr_send_icmp_err(ICMP_UNREACH, fin, dst);
2670 ATOMIC_INCL(frstats[0].fr_ret);
2671 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
2672 !(fin->fin_flx & FI_SHORT)) {
2673 if (((fin->fin_flx & FI_OOW) != 0) ||
2674 (fr_send_reset(fin) == 0)) {
2675 ATOMIC_INCL(frstats[1].fr_ret);
2680 * When using return-* with auth rules, the auth code
2681 * takes over disposing of this packet.
2683 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
2684 fin->fin_m = *fin->fin_mp = NULL;
2687 if (pass & FR_RETRST)
2688 fin->fin_error = ECONNRESET;
2693 * If we didn't drop off the bottom of the list of rules (and thus
2694 * the 'current' rule fr is not NULL), then we may have some extra
2695 * instructions about what to do with a packet.
2696 * Once we're finished return to our caller, freeing the packet if
2697 * we are dropping it (* BSD ONLY *).
2702 fdp = &fr->fr_tifs[fin->fin_rev];
2704 if (!out && (pass & FR_FASTROUTE)) {
2706 * For fastroute rule, no destioation interface defined
2707 * so pass NULL as the frdest_t parameter
2709 (void) fr_fastroute(fin->fin_m, mp, fin, NULL);
2711 } else if ((fdp->fd_ifp != NULL) &&
2712 (fdp->fd_ifp != (struct ifnet *)-1)) {
2713 /* this is for to rules: */
2714 (void) fr_fastroute(fin->fin_m, mp, fin, fdp);
2719 * Generate a duplicated packet.
2721 if ((pass & FR_DUP) != 0) {
2722 mc = M_DUPLICATE(fin->fin_m);
2724 (void) fr_fastroute(mc, &mc, fin, &fr->fr_dif);
2727 (void) fr_derefrule(&fr);
2731 if (!FR_ISPASS(pass)) {
2732 ATOMIC_INCL(frstats[out].fr_block);
2738 ATOMIC_INCL(frstats[out].fr_pass);
2739 #if defined(_KERNEL) && defined(__sgi)
2740 if ((fin->fin_hbuf != NULL) &&
2741 (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
2742 COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
2748 RWLOCK_EXIT(&ipf_global);
2751 # if defined(OpenBSD) && OpenBSD >= 200311
2752 if (FR_ISPASS(pass) && (v == 4)) {
2754 ip->ip_len = ntohs(ip->ip_len);
2755 ip->ip_off = ntohs(ip->ip_off);
2758 return (FR_ISPASS(pass)) ? 0 : fin->fin_error;
2760 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
2761 if ((pass & FR_NOMATCH) != 0)
2764 if ((pass & FR_RETMASK) != 0)
2765 switch (pass & FR_RETMASK)
2775 switch (pass & FR_CMDMASK)
2789 #endif /* _KERNEL */
2794 /* ------------------------------------------------------------------------ */
2795 /* Function: fr_dolog */
2796 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
2797 /* Parameters: fin(I) - pointer to packet information */
2798 /* passp(IO) - pointer to current/new filter decision (unused) */
2800 /* Checks flags set to see how a packet should be logged, if it is to be */
2801 /* logged. Adjust statistics based on its success or not. */
2802 /* ------------------------------------------------------------------------ */
2803 frentry_t *fr_dolog(fin, passp)
2813 if ((fr_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
2814 pass |= FF_LOGNOMATCH;
2815 ATOMIC_INCL(frstats[out].fr_npkl);
2817 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
2818 (FR_ISPASS(pass) && (fr_flags & FF_LOGPASS))) {
2819 if ((pass & FR_LOGMASK) != FR_LOGP)
2821 ATOMIC_INCL(frstats[out].fr_ppkl);
2823 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
2824 (FR_ISBLOCK(pass) && (fr_flags & FF_LOGBLOCK))) {
2825 if ((pass & FR_LOGMASK) != FR_LOGB)
2826 pass |= FF_LOGBLOCK;
2827 ATOMIC_INCL(frstats[out].fr_bpkl);
2829 if (ipflog(fin, pass) == -1) {
2830 ATOMIC_INCL(frstats[out].fr_skip);
2833 * If the "or-block" option has been used then
2834 * block the packet if we failed to log it.
2836 if ((pass & FR_LOGORBLOCK) &&
2838 pass &= ~FR_CMDMASK;
2847 #endif /* IPFILTER_LOG */
2850 /* ------------------------------------------------------------------------ */
2851 /* Function: ipf_cksum */
2852 /* Returns: u_short - IP header checksum */
2853 /* Parameters: addr(I) - pointer to start of buffer to checksum */
2854 /* len(I) - length of buffer in bytes */
2856 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
2858 /* N.B.: addr should be 16bit aligned. */
2859 /* ------------------------------------------------------------------------ */
2860 u_short ipf_cksum(addr, len)
2866 for (sum = 0; len > 1; len -= 2)
2869 /* mop up an odd byte, if necessary */
2871 sum += *(u_char *)addr;
2874 * add back carry outs from top 16 bits to low 16 bits
2876 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
2877 sum += (sum >> 16); /* add carry */
2878 return (u_short)(~sum);
2882 /* ------------------------------------------------------------------------ */
2883 /* Function: fr_cksum */
2884 /* Returns: u_short - layer 4 checksum */
2885 /* Parameters: m(I ) - pointer to buffer holding packet */
2886 /* ip(I) - pointer to IP header */
2887 /* l4proto(I) - protocol to caclulate checksum for */
2888 /* l4hdr(I) - pointer to layer 4 header */
2889 /* l3len(I) - length of layer 4 data plus layer 3 header */
2891 /* Calculates the TCP checksum for the packet held in "m", using the data */
2892 /* in the IP header "ip" to seed it. */
2894 /* NB: This function assumes we've pullup'd enough for all of the IP header */
2895 /* and the TCP header. We also assume that data blocks aren't allocated in */
2898 /* For IPv6, l3len excludes extension header size. */
2900 /* Expects ip_len to be in host byte order when called. */
2901 /* ------------------------------------------------------------------------ */
2902 u_short fr_cksum(m, ip, l4proto, l4hdr, l3len)
2908 u_short *sp, slen, sumsave, l4hlen, *csump;
2924 * Add up IP Header portion
2927 if (IP_V(ip) == 4) {
2929 hlen = IP_HL(ip) << 2;
2930 slen = l3len - hlen;
2931 sum = htons((u_short)l4proto);
2933 sp = (u_short *)&ip->ip_src;
2934 sum += *sp++; /* ip_src */
2936 sum += *sp++; /* ip_dst */
2939 } else if (IP_V(ip) == 6) {
2941 hlen = sizeof(*ip6);
2942 slen = l3len - hlen;
2943 sum = htons((u_short)l4proto);
2945 sp = (u_short *)&ip6->ip6_src;
2946 sum += *sp++; /* ip6_src */
2954 sum += *sp++; /* ip6_dst */
2968 csump = &((udphdr_t *)l4hdr)->uh_sum;
2969 l4hlen = sizeof(udphdr_t);
2973 csump = &((tcphdr_t *)l4hdr)->th_sum;
2974 l4hlen = sizeof(tcphdr_t);
2977 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
2985 if (csump != NULL) {
2990 l4hlen = l4hlen; /* LINT */
2995 void *rp = m->b_rptr;
2997 if ((unsigned char *)ip > m->b_rptr && (unsigned char *)ip < m->b_wptr)
2998 m->b_rptr = (u_char *)ip;
2999 sum2 = ip_cksum(m, hlen, sum); /* hlen == offset */
3001 sum2 = (u_short)(~sum2 & 0xffff);
3004 # if defined(BSD) || defined(sun)
3011 sum2 = in_cksum(m, slen);
3019 * Both sum and sum2 are partial sums, so combine them together.
3021 sum += ~sum2 & 0xffff;
3022 while (sum > 0xffff)
3023 sum = (sum & 0xffff) + (sum >> 16);
3024 sum2 = ~sum & 0xffff;
3025 # else /* defined(BSD) || defined(sun) */
3031 u_short len = ip->ip_len;
3037 * Add up IP Header portion
3039 if (sp != (u_short *)l4hdr)
3040 sp = (u_short *)l4hdr;
3045 sum += *sp++; /* sport */
3046 sum += *sp++; /* dport */
3047 sum += *sp++; /* udp length */
3048 sum += *sp++; /* checksum */
3052 sum += *sp++; /* sport */
3053 sum += *sp++; /* dport */
3054 sum += *sp++; /* seq */
3056 sum += *sp++; /* ack */
3058 sum += *sp++; /* off */
3059 sum += *sp++; /* win */
3060 sum += *sp++; /* checksum */
3061 sum += *sp++; /* urp */
3064 sum = *sp++; /* type/code */
3065 sum += *sp++; /* checksum */
3071 * In case we had to copy the IP & TCP header out of mbufs,
3072 * skip over the mbuf bits which are the header
3074 if ((caddr_t)ip != mtod(m, caddr_t)) {
3075 hlen = (caddr_t)sp - (caddr_t)ip;
3077 add = MIN(hlen, m->m_len);
3078 sp = (u_short *)(mtod(m, caddr_t) + add);
3080 if (add == m->m_len) {
3085 sp = mtod(m, u_short *);
3087 PANIC((!m),("fr_cksum(1): not enough data"));
3093 len -= (l4hlen + hlen);
3098 if (((caddr_t)sp - mtod(m, caddr_t)) >= m->m_len) {
3100 PANIC((!m),("fr_cksum(2): not enough data"));
3101 sp = mtod(m, u_short *);
3103 if (((caddr_t)(sp + 1) - mtod(m, caddr_t)) > m->m_len) {
3104 bytes.c[0] = *(u_char *)sp;
3106 PANIC((!m),("fr_cksum(3): not enough data"));
3107 sp = mtod(m, u_short *);
3108 bytes.c[1] = *(u_char *)sp;
3110 sp = (u_short *)((u_char *)sp + 1);
3112 if ((u_long)sp & 1) {
3113 bcopy((char *)sp++, (char *)&bytes.s, sizeof(bytes.s));
3121 sum += ntohs(*(u_char *)sp << 8);
3123 while (sum > 0xffff)
3124 sum = (sum & 0xffff) + (sum >> 16);
3125 sum2 = (u_short)(~sum & 0xffff);
3127 # endif /* defined(BSD) || defined(sun) */
3128 # endif /* MENTAT */
3131 * Add up IP Header portion
3133 if (sp != (u_short *)l4hdr)
3134 sp = (u_short *)l4hdr;
3136 for (; slen > 1; slen -= 2)
3139 sum += ntohs(*(u_char *)sp << 8);
3140 while (sum > 0xffff)
3141 sum = (sum & 0xffff) + (sum >> 16);
3142 sum2 = (u_short)(~sum & 0xffff);
3143 #endif /* _KERNEL */
3150 #if defined(_KERNEL) && ( ((BSD < 199103) && !defined(MENTAT)) || \
3151 defined(__sgi) ) && !defined(linux) && !defined(_AIX51)
3153 * Copyright (c) 1982, 1986, 1988, 1991, 1993
3154 * The Regents of the University of California. All rights reserved.
3156 * Redistribution and use in source and binary forms, with or without
3157 * modification, are permitted provided that the following conditions
3159 * 1. Redistributions of source code must retain the above copyright
3160 * notice, this list of conditions and the following disclaimer.
3161 * 2. Redistributions in binary form must reproduce the above copyright
3162 * notice, this list of conditions and the following disclaimer in the
3163 * documentation and/or other materials provided with the distribution.
3164 * 3. Neither the name of the University nor the names of its contributors
3165 * may be used to endorse or promote products derived from this software
3166 * without specific prior written permission.
3168 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3169 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3170 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3171 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3172 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3173 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3174 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3175 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3176 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3177 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3180 * @(#)uipc_mbuf.c 8.2 (Berkeley) 1/4/94
3181 * $Id: fil.c,v 2.243.2.109 2007/05/31 12:27:33 darrenr Exp $
3184 * Copy data from an mbuf chain starting "off" bytes from the beginning,
3185 * continuing for "len" bytes, into the indicated buffer.
3188 m_copydata(m, off, len, cp)
3196 if (off < 0 || len < 0)
3197 panic("m_copydata");
3200 panic("m_copydata");
3208 panic("m_copydata");
3209 count = MIN(m->m_len - off, len);
3210 bcopy(mtod(m, caddr_t) + off, cp, count);
3220 * Copy data from a buffer back into the indicated mbuf chain,
3221 * starting "off" bytes from the beginning, extending the mbuf
3222 * chain if necessary.
3225 m_copyback(m0, off, len, cp)
3232 struct mbuf *m = m0, *n;
3237 while (off > (mlen = m->m_len)) {
3240 if (m->m_next == 0) {
3241 n = m_getclr(M_DONTWAIT, m->m_type);
3244 n->m_len = min(MLEN, len + off);
3250 mlen = min(m->m_len - off, len);
3251 bcopy(cp, off + mtod(m, caddr_t), (unsigned)mlen);
3259 if (m->m_next == 0) {
3260 n = m_get(M_DONTWAIT, m->m_type);
3263 n->m_len = min(MLEN, len);
3270 if (((m = m0)->m_flags & M_PKTHDR) && (m->m_pkthdr.len < totlen))
3271 m->m_pkthdr.len = totlen;
3275 #endif /* (_KERNEL) && ( ((BSD < 199103) && !MENTAT) || __sgi) */
3278 /* ------------------------------------------------------------------------ */
3279 /* Function: fr_findgroup */
3280 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3281 /* Parameters: group(I) - group name to search for */
3282 /* unit(I) - device to which this group belongs */
3283 /* set(I) - which set of rules (inactive/inactive) this is */
3284 /* fgpp(O) - pointer to place to store pointer to the pointer */
3285 /* to where to add the next (last) group or where */
3286 /* to delete group from. */
3288 /* Search amongst the defined groups for a particular group number. */
3289 /* ------------------------------------------------------------------------ */
3290 frgroup_t *fr_findgroup(group, unit, set, fgpp)
3296 frgroup_t *fg, **fgp;
3299 * Which list of groups to search in is dependent on which list of
3300 * rules are being operated on.
3302 fgp = &ipfgroups[unit][set];
3304 while ((fg = *fgp) != NULL) {
3305 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3316 /* ------------------------------------------------------------------------ */
3317 /* Function: fr_addgroup */
3318 /* Returns: frgroup_t * - NULL == did not create group, */
3319 /* != NULL == pointer to the group */
3320 /* Parameters: num(I) - group number to add */
3321 /* head(I) - rule pointer that is using this as the head */
3322 /* flags(I) - rule flags which describe the type of rule it is */
3323 /* unit(I) - device to which this group will belong to */
3324 /* set(I) - which set of rules (inactive/inactive) this is */
3325 /* Write Locks: ipf_mutex */
3327 /* Add a new group head, or if it already exists, increase the reference */
3329 /* ------------------------------------------------------------------------ */
3330 frgroup_t *fr_addgroup(group, head, flags, unit, set)
3337 frgroup_t *fg, **fgp;
3343 if (unit == IPL_LOGIPF && *group == '\0')
3347 gflags = flags & FR_INOUT;
3349 fg = fr_findgroup(group, unit, set, &fgp);
3351 if (fg->fg_flags == 0)
3352 fg->fg_flags = gflags;
3353 else if (gflags != fg->fg_flags)
3358 KMALLOC(fg, frgroup_t *);
3361 fg->fg_start = NULL;
3363 bcopy(group, fg->fg_name, FR_GROUPLEN);
3364 fg->fg_flags = gflags;
3372 /* ------------------------------------------------------------------------ */
3373 /* Function: fr_delgroup */
3375 /* Parameters: group(I) - group name to delete */
3376 /* unit(I) - device to which this group belongs */
3377 /* set(I) - which set of rules (inactive/inactive) this is */
3378 /* Write Locks: ipf_mutex */
3380 /* Attempt to delete a group head. */
3381 /* Only do this when its reference count reaches 0. */
3382 /* ------------------------------------------------------------------------ */
3383 void fr_delgroup(group, unit, set)
3388 frgroup_t *fg, **fgp;
3390 fg = fr_findgroup(group, unit, set, &fgp);
3395 if (fg->fg_ref == 0) {
3402 /* ------------------------------------------------------------------------ */
3403 /* Function: fr_getrulen */
3404 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3405 /* Parameters: unit(I) - device for which to count the rule's number */
3406 /* flags(I) - which set of rules to find the rule in */
3407 /* group(I) - group name */
3408 /* n(I) - rule number to find */
3410 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3411 /* group # g doesn't exist or there are less than n rules in the group. */
3412 /* ------------------------------------------------------------------------ */
3413 frentry_t *fr_getrulen(unit, group, n)
3421 fg = fr_findgroup(group, unit, fr_active, NULL);
3424 for (fr = fg->fg_head; fr && n; fr = fr->fr_next, n--)
3432 /* ------------------------------------------------------------------------ */
3433 /* Function: fr_rulen */
3434 /* Returns: int - >= 0 - rule number, -1 == search failed */
3435 /* Parameters: unit(I) - device for which to count the rule's number */
3436 /* fr(I) - pointer to rule to match */
3438 /* Return the number for a rule on a specific filtering device. */
3439 /* ------------------------------------------------------------------------ */
3440 int fr_rulen(unit, fr)
3450 fg = fr_findgroup(fr->fr_group, unit, fr_active, NULL);
3453 for (fh = fg->fg_head; fh; n++, fh = fh->fr_next)
3462 /* ------------------------------------------------------------------------ */
3463 /* Function: frflushlist */
3464 /* Returns: int - >= 0 - number of flushed rules */
3465 /* Parameters: set(I) - which set of rules (inactive/inactive) this is */
3466 /* unit(I) - device for which to flush rules */
3467 /* flags(I) - which set of rules to flush */
3468 /* nfreedp(O) - pointer to int where flush count is stored */
3469 /* listp(I) - pointer to list to flush pointer */
3470 /* Write Locks: ipf_mutex */
3472 /* Recursively flush rules from the list, descending groups as they are */
3473 /* encountered. if a rule is the head of a group and it has lost all its */
3474 /* group members, then also delete the group reference. nfreedp is needed */
3475 /* to store the accumulating count of rules removed, whereas the returned */
3476 /* value is just the number removed from the current list. The latter is */
3477 /* needed to correctly adjust reference counts on rules that define groups. */
3479 /* NOTE: Rules not loaded from user space cannot be flushed. */
3480 /* ------------------------------------------------------------------------ */
3481 static int frflushlist(set, unit, nfreedp, listp)
3490 while ((fp = *listp) != NULL) {
3491 if ((fp->fr_type & FR_T_BUILTIN) ||
3492 !(fp->fr_flags & FR_COPIED)) {
3493 listp = &fp->fr_next;
3496 *listp = fp->fr_next;
3497 if (fp->fr_grp != NULL) {
3498 i = frflushlist(set, unit, nfreedp, fp->fr_grp);
3502 if (fp->fr_grhead != NULL) {
3503 fr_delgroup(fp->fr_grhead, unit, set);
3504 *fp->fr_grhead = '\0';
3507 ASSERT(fp->fr_ref > 0);
3509 if (fr_derefrule(&fp) == 0)
3517 /* ------------------------------------------------------------------------ */
3518 /* Function: frflush */
3519 /* Returns: int - >= 0 - number of flushed rules */
3520 /* Parameters: unit(I) - device for which to flush rules */
3521 /* flags(I) - which set of rules to flush */
3523 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3524 /* and IPv6) as defined by the value of flags. */
3525 /* ------------------------------------------------------------------------ */
3526 int frflush(unit, proto, flags)
3530 int flushed = 0, set;
3532 WRITE_ENTER(&ipf_mutex);
3533 bzero((char *)frcache, sizeof(frcache));
3536 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3539 if (flags & FR_OUTQUE) {
3540 if (proto == 0 || proto == 6) {
3541 (void) frflushlist(set, unit,
3542 &flushed, &ipfilter6[1][set]);
3543 (void) frflushlist(set, unit,
3544 &flushed, &ipacct6[1][set]);
3546 if (proto == 0 || proto == 4) {
3547 (void) frflushlist(set, unit,
3548 &flushed, &ipfilter[1][set]);
3549 (void) frflushlist(set, unit,
3550 &flushed, &ipacct[1][set]);
3553 if (flags & FR_INQUE) {
3554 if (proto == 0 || proto == 6) {
3555 (void) frflushlist(set, unit,
3556 &flushed, &ipfilter6[0][set]);
3557 (void) frflushlist(set, unit,
3558 &flushed, &ipacct6[0][set]);
3560 if (proto == 0 || proto == 4) {
3561 (void) frflushlist(set, unit,
3562 &flushed, &ipfilter[0][set]);
3563 (void) frflushlist(set, unit,
3564 &flushed, &ipacct[0][set]);
3567 RWLOCK_EXIT(&ipf_mutex);
3569 if (unit == IPL_LOGIPF) {
3572 tmp = frflush(IPL_LOGCOUNT, proto, flags);
3580 /* ------------------------------------------------------------------------ */
3581 /* Function: memstr */
3582 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3583 /* Parameters: src(I) - pointer to byte sequence to match */
3584 /* dst(I) - pointer to byte sequence to search */
3585 /* slen(I) - match length */
3586 /* dlen(I) - length available to search in */
3588 /* Search dst for a sequence of bytes matching those at src and extend for */
3590 /* ------------------------------------------------------------------------ */
3591 char *memstr(src, dst, slen, dlen)
3598 while (dlen >= slen) {
3599 if (bcmp(src, dst, slen) == 0) {
3608 /* ------------------------------------------------------------------------ */
3609 /* Function: fr_fixskip */
3611 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3612 /* rp(I) - rule added/removed with skip in it. */
3613 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3614 /* depending on whether a rule was just added */
3617 /* Adjust all the rules in a list which would have skip'd past the position */
3618 /* where we are inserting to skip to the right place given the change. */
3619 /* ------------------------------------------------------------------------ */
3620 void fr_fixskip(listp, rp, addremove)
3621 frentry_t **listp, *rp;
3628 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3634 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3635 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3636 fp->fr_arg += addremove;
3641 /* ------------------------------------------------------------------------ */
3642 /* Function: count4bits */
3643 /* Returns: int - >= 0 - number of consecutive bits in input */
3644 /* Parameters: ip(I) - 32bit IP address */
3647 /* count consecutive 1's in bit mask. If the mask generated by counting */
3648 /* consecutive 1's is different to that passed, return -1, else return # */
3650 /* ------------------------------------------------------------------------ */
3657 ip = ipn = ntohl(ip);
3658 for (i = 32; i; i--, ipn *= 2)
3659 if (ipn & 0x80000000)
3664 for (i = 32, j = cnt; i; i--, j--) {
3676 /* ------------------------------------------------------------------------ */
3677 /* Function: count6bits */
3678 /* Returns: int - >= 0 - number of consecutive bits in input */
3679 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3682 /* count consecutive 1's in bit mask. */
3683 /* ------------------------------------------------------------------------ */
3690 for (k = 3; k >= 0; k--)
3691 if (msk[k] == 0xffffffff)
3694 for (j = msk[k]; j; j <<= 1)
3701 #endif /* _KERNEL */
3704 /* ------------------------------------------------------------------------ */
3705 /* Function: frsynclist */
3707 /* Parameters: fr(I) - start of filter list to sync interface names for */
3708 /* ifp(I) - interface pointer for limiting sync lookups */
3709 /* Write Locks: ipf_mutex */
3711 /* Walk through a list of filter rules and resolve any interface names into */
3712 /* pointers. Where dynamic addresses are used, also update the IP address */
3713 /* used in the rule. The interface pointer is used to limit the lookups to */
3714 /* a specific set of matching names if it is non-NULL. */
3715 /* ------------------------------------------------------------------------ */
3716 static void frsynclist(fr, ifp)
3723 for (; fr; fr = fr->fr_next) {
3727 * Lookup all the interface names that are part of the rule.
3729 for (i = 0; i < 4; i++) {
3730 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3732 fr->fr_ifas[i] = fr_resolvenic(fr->fr_ifnames[i], v);
3735 if (fr->fr_type == FR_T_IPF) {
3736 if (fr->fr_satype != FRI_NORMAL &&
3737 fr->fr_satype != FRI_LOOKUP) {
3738 (void)fr_ifpaddr(v, fr->fr_satype,
3739 fr->fr_ifas[fr->fr_sifpidx],
3740 &fr->fr_src, &fr->fr_smsk);
3742 if (fr->fr_datype != FRI_NORMAL &&
3743 fr->fr_datype != FRI_LOOKUP) {
3744 (void)fr_ifpaddr(v, fr->fr_datype,
3745 fr->fr_ifas[fr->fr_difpidx],
3746 &fr->fr_dst, &fr->fr_dmsk);
3750 fdp = &fr->fr_tifs[0];
3751 if ((ifp == NULL) || (fdp->fd_ifp == ifp))
3752 fr_resolvedest(fdp, v);
3754 fdp = &fr->fr_tifs[1];
3755 if ((ifp == NULL) || (fdp->fd_ifp == ifp))
3756 fr_resolvedest(fdp, v);
3759 if ((ifp == NULL) || (fdp->fd_ifp == ifp)) {
3760 fr_resolvedest(fdp, v);
3762 fr->fr_flags &= ~FR_DUP;
3763 if ((fdp->fd_ifp != (void *)-1) &&
3764 (fdp->fd_ifp != NULL))
3765 fr->fr_flags |= FR_DUP;
3768 #ifdef IPFILTER_LOOKUP
3769 if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP &&
3770 fr->fr_srcptr == NULL) {
3771 fr->fr_srcptr = fr_resolvelookup(fr->fr_srctype,
3776 if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP &&
3777 fr->fr_dstptr == NULL) {
3778 fr->fr_dstptr = fr_resolvelookup(fr->fr_dsttype,
3789 /* ------------------------------------------------------------------------ */
3790 /* Function: frsync */
3792 /* Parameters: Nil */
3794 /* frsync() is called when we suspect that the interface list or */
3795 /* information about interfaces (like IP#) has changed. Go through all */
3796 /* filter rules, NAT entries and the state table and check if anything */
3797 /* needs to be changed/updated. */
3798 /* ------------------------------------------------------------------------ */
3809 WRITE_ENTER(&ipf_mutex);
3810 frsynclist(ipacct[0][fr_active], ifp);
3811 frsynclist(ipacct[1][fr_active], ifp);
3812 frsynclist(ipfilter[0][fr_active], ifp);
3813 frsynclist(ipfilter[1][fr_active], ifp);
3814 frsynclist(ipacct6[0][fr_active], ifp);
3815 frsynclist(ipacct6[1][fr_active], ifp);
3816 frsynclist(ipfilter6[0][fr_active], ifp);
3817 frsynclist(ipfilter6[1][fr_active], ifp);
3819 for (i = 0; i < IPL_LOGSIZE; i++) {
3822 for (g = ipfgroups[i][0]; g != NULL; g = g->fg_next)
3823 frsynclist(g->fg_start, ifp);
3824 for (g = ipfgroups[i][1]; g != NULL; g = g->fg_next)
3825 frsynclist(g->fg_start, ifp);
3827 RWLOCK_EXIT(&ipf_mutex);
3832 * In the functions below, bcopy() is called because the pointer being
3833 * copied _from_ in this instance is a pointer to a char buf (which could
3834 * end up being unaligned) and on the kernel's local stack.
3836 /* ------------------------------------------------------------------------ */
3837 /* Function: copyinptr */
3838 /* Returns: int - 0 = success, else failure */
3839 /* Parameters: src(I) - pointer to the source address */
3840 /* dst(I) - destination address */
3841 /* size(I) - number of bytes to copy */
3843 /* Copy a block of data in from user space, given a pointer to the pointer */
3844 /* to start copying from (src) and a pointer to where to store it (dst). */
3845 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
3846 /* ------------------------------------------------------------------------ */
3847 int copyinptr(src, dst, size)
3855 error = COPYIN(src, (caddr_t)&ca, sizeof(ca));
3859 bcopy(src, (caddr_t)&ca, sizeof(ca));
3861 error = COPYIN(ca, dst, size);
3868 /* ------------------------------------------------------------------------ */
3869 /* Function: copyoutptr */
3870 /* Returns: int - 0 = success, else failure */
3871 /* Parameters: src(I) - pointer to the source address */
3872 /* dst(I) - destination address */
3873 /* size(I) - number of bytes to copy */
3875 /* Copy a block of data out to user space, given a pointer to the pointer */
3876 /* to start copying from (src) and a pointer to where to store it (dst). */
3877 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
3878 /* ------------------------------------------------------------------------ */
3879 int copyoutptr(src, dst, size)
3886 bcopy(dst, (caddr_t)&ca, sizeof(ca));
3887 error = COPYOUT(src, ca, size);
3895 /* ------------------------------------------------------------------------ */
3896 /* Function: fr_lock */
3897 /* Returns: (void) */
3898 /* Parameters: data(I) - pointer to lock value to set */
3899 /* lockp(O) - pointer to location to store old lock value */
3901 /* Get the new value for the lock integer, set it and return the old value */
3903 /* ------------------------------------------------------------------------ */
3904 void fr_lock(data, lockp)
3910 BCOPYIN(data, (caddr_t)&arg, sizeof(arg));
3911 BCOPYOUT((caddr_t)lockp, data, sizeof(*lockp));
3916 /* ------------------------------------------------------------------------ */
3917 /* Function: fr_getstat */
3919 /* Parameters: fiop(I) - pointer to ipfilter stats structure */
3921 /* Stores a copy of current pointers, counters, etc, in the friostat */
3923 /* ------------------------------------------------------------------------ */
3924 void fr_getstat(fiop)
3929 bcopy((char *)frstats, (char *)fiop->f_st, sizeof(filterstats_t) * 2);
3930 fiop->f_locks[IPL_LOGSTATE] = fr_state_lock;
3931 fiop->f_locks[IPL_LOGNAT] = fr_nat_lock;
3932 fiop->f_locks[IPL_LOGIPF] = fr_frag_lock;
3933 fiop->f_locks[IPL_LOGAUTH] = fr_auth_lock;
3935 for (i = 0; i < 2; i++)
3936 for (j = 0; j < 2; j++) {
3937 fiop->f_ipf[i][j] = ipfilter[i][j];
3938 fiop->f_acct[i][j] = ipacct[i][j];
3939 fiop->f_ipf6[i][j] = ipfilter6[i][j];
3940 fiop->f_acct6[i][j] = ipacct6[i][j];
3943 fiop->f_ticks = fr_ticks;
3944 fiop->f_active = fr_active;
3945 fiop->f_froute[0] = fr_frouteok[0];
3946 fiop->f_froute[1] = fr_frouteok[1];
3948 fiop->f_running = fr_running;
3949 for (i = 0; i < IPL_LOGSIZE; i++) {
3950 fiop->f_groups[i][0] = ipfgroups[i][0];
3951 fiop->f_groups[i][1] = ipfgroups[i][1];
3954 fiop->f_logging = 1;
3956 fiop->f_logging = 0;
3958 fiop->f_defpass = fr_pass;
3959 fiop->f_features = fr_features;
3960 (void) strncpy(fiop->f_version, ipfilter_version,
3961 sizeof(fiop->f_version));
3966 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
3967 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
3970 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
3971 -1, /* 4: ICMP_SOURCEQUENCH */
3972 ND_REDIRECT, /* 5: ICMP_REDIRECT */
3975 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
3977 -1, /* 10: UNUSED */
3978 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
3979 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
3980 -1, /* 13: ICMP_TSTAMP */
3981 -1, /* 14: ICMP_TSTAMPREPLY */
3982 -1, /* 15: ICMP_IREQ */
3983 -1, /* 16: ICMP_IREQREPLY */
3984 -1, /* 17: ICMP_MASKREQ */
3985 -1, /* 18: ICMP_MASKREPLY */
3989 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
3990 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
3991 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
3992 -1, /* 2: ICMP_UNREACH_PROTOCOL */
3993 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
3994 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
3995 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
3996 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
3997 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
3998 -1, /* 8: ICMP_UNREACH_ISOLATED */
3999 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4000 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4001 -1, /* 11: ICMP_UNREACH_TOSNET */
4002 -1, /* 12: ICMP_UNREACH_TOSHOST */
4003 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4005 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4008 int icmpreplytype4[ICMP_MAXTYPE + 1];
4011 /* ------------------------------------------------------------------------ */
4012 /* Function: fr_matchicmpqueryreply */
4013 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4014 /* Parameters: v(I) - IP protocol version (4 or 6) */
4015 /* ic(I) - ICMP information */
4016 /* icmp(I) - ICMP packet header */
4017 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4019 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4020 /* reply to one as described by what's in ic. If it is a match, return 1, */
4021 /* else return 0 for no match. */
4022 /* ------------------------------------------------------------------------ */
4023 int fr_matchicmpqueryreply(v, ic, icmp, rev)
4031 ictype = ic->ici_type;
4035 * If we matched its type on the way in, then when going out
4036 * it will still be the same type.
4038 if ((!rev && (icmp->icmp_type == ictype)) ||
4039 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4040 if (icmp->icmp_type != ICMP_ECHOREPLY)
4042 if (icmp->icmp_id == ic->ici_id)
4048 if ((!rev && (icmp->icmp_type == ictype)) ||
4049 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4050 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4052 if (icmp->icmp_id == ic->ici_id)
4061 #ifdef IPFILTER_LOOKUP
4062 /* ------------------------------------------------------------------------ */
4063 /* Function: fr_resolvelookup */
4064 /* Returns: void * - NULL = failure, else success. */
4065 /* Parameters: type(I) - type of lookup these parameters are for. */
4066 /* subtype(I) - whether the info below contains number/name */
4067 /* info(I) - pointer to name/number of the lookup data */
4068 /* funcptr(IO) - pointer to pointer for storing IP address */
4069 /* searching function. */
4071 /* Search for the "table" number passed in amongst those configured for */
4072 /* that particular type. If the type is recognised then the function to */
4073 /* call to do the IP address search will be change, regardless of whether */
4074 /* or not the "table" number exists. */
4075 /* ------------------------------------------------------------------------ */
4076 static void *fr_resolvelookup(type, subtype, info, funcptr)
4077 u_int type, subtype;
4079 lookupfunc_t *funcptr;
4081 char label[FR_GROUPLEN], *name;
4087 #if defined(SNPRINTF) && defined(_KERNEL)
4088 SNPRINTF(label, sizeof(label), "%u", info->iplookupnum);
4090 (void) sprintf(label, "%u", info->iplookupnum);
4093 } else if (subtype == 1) {
4095 * Because iplookupname is currently only a 12 character
4096 * string and FR_GROUPLEN is 16, copy all of it into the
4097 * label buffer and add on a NULL at the end.
4099 strncpy(label, info->iplookupname, sizeof(info->iplookupname));
4100 label[sizeof(info->iplookupname)] = '\0';
4106 READ_ENTER(&ip_poolrw);
4111 # if (defined(__osf__) && defined(_KERNEL))
4115 ipo = ip_pool_find(IPL_LOGIPF, name);
4118 ATOMIC_INC32(ipo->ipo_ref);
4120 *funcptr = ip_pool_search;
4124 iph = fr_findhtable(IPL_LOGIPF, name);
4127 ATOMIC_INC32(iph->iph_ref);
4129 *funcptr = fr_iphmfindip;
4136 RWLOCK_EXIT(&ip_poolrw);
4143 /* ------------------------------------------------------------------------ */
4144 /* Function: frrequest */
4145 /* Returns: int - 0 == success, > 0 == errno value */
4146 /* Parameters: unit(I) - device for which this is for */
4147 /* req(I) - ioctl command (SIOC*) */
4148 /* data(I) - pointr to ioctl data */
4149 /* set(I) - 1 or 0 (filter set) */
4150 /* makecopy(I) - flag indicating whether data points to a rule */
4151 /* in kernel space & hence doesn't need copying. */
4153 /* This function handles all the requests which operate on the list of */
4154 /* filter rules. This includes adding, deleting, insertion. It is also */
4155 /* responsible for creating groups when a "head" rule is loaded. Interface */
4156 /* names are resolved here and other sanity checks are made on the content */
4157 /* of the rule structure being loaded. If a rule has user defined timeouts */
4158 /* then make sure they are created and initialised before exiting. */
4159 /* ------------------------------------------------------------------------ */
4160 int frrequest(unit, req, data, set, makecopy)
4166 frentry_t frd, *fp, *f, **fprev, **ftail;
4167 int error = 0, in, v;
4175 if (makecopy != 0) {
4176 error = fr_inobj(data, fp, IPFOBJ_FRENTRY);
4179 if ((fp->fr_flags & FR_T_BUILTIN) != 0)
4182 fp->fr_flags |= FR_COPIED;
4184 fp = (frentry_t *)data;
4185 if ((fp->fr_type & FR_T_BUILTIN) == 0)
4187 fp->fr_flags &= ~FR_COPIED;
4190 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4191 ((fp->fr_dsize != 0) && (fp->fr_data == NULL)))
4198 * Only filter rules for IPv4 or IPv6 are accepted.
4211 * If the rule is being loaded from user space, i.e. we had to copy it
4212 * into kernel space, then do not trust the function pointer in the
4215 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4216 if (fr_findfunc(fp->fr_func) == NULL)
4218 error = fr_funcinit(fp);
4225 * Check that the group number does exist and that its use (in/out)
4226 * matches what the rule is.
4228 if (!strncmp(fp->fr_grhead, "0", FR_GROUPLEN))
4229 *fp->fr_grhead = '\0';
4230 group = fp->fr_group;
4231 if (!strncmp(group, "0", FR_GROUPLEN))
4234 if (FR_ISACCOUNT(fp->fr_flags))
4235 unit = IPL_LOGCOUNT;
4237 if ((req != (int)SIOCZRLST) && (*group != '\0')) {
4238 fg = fr_findgroup(group, unit, set, NULL);
4241 if (fg->fg_flags == 0)
4242 fg->fg_flags = fp->fr_flags & FR_INOUT;
4243 else if (fg->fg_flags != (fp->fr_flags & FR_INOUT))
4247 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4250 * Work out which rule list this change is being applied to.
4254 if (unit == IPL_LOGAUTH)
4257 if (FR_ISACCOUNT(fp->fr_flags))
4258 fprev = &ipacct[in][set];
4259 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4260 fprev = &ipfilter[in][set];
4261 } else if (v == 6) {
4262 if (FR_ISACCOUNT(fp->fr_flags))
4263 fprev = &ipacct6[in][set];
4264 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4265 fprev = &ipfilter6[in][set];
4270 if (*group != '\0') {
4271 if (!fg && !(fg = fr_findgroup(group, unit, set, NULL)))
4273 fprev = &fg->fg_start;
4277 * Copy in extra data for the rule.
4279 if (fp->fr_dsize != 0) {
4280 if (makecopy != 0) {
4281 KMALLOCS(ptr, void *, fp->fr_dsize);
4284 error = COPYIN(uptr, ptr, fp->fr_dsize);
4292 KFREES(ptr, fp->fr_dsize);
4300 * Perform per-rule type sanity checks of their members.
4302 switch (fp->fr_type & ~FR_T_BUILTIN)
4304 #if defined(IPFILTER_BPF)
4306 if (fp->fr_dsize == 0)
4308 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4309 if (makecopy && fp->fr_data != NULL) {
4310 KFREES(fp->fr_data, fp->fr_dsize);
4317 if (fp->fr_dsize != sizeof(fripf_t))
4321 * Allowing a rule with both "keep state" and "with oow" is
4322 * pointless because adding a state entry to the table will
4323 * fail with the out of window (oow) flag set.
4325 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW))
4328 switch (fp->fr_satype)
4330 case FRI_BROADCAST :
4333 case FRI_NETMASKED :
4335 if (fp->fr_sifpidx < 0 || fp->fr_sifpidx > 3) {
4336 if (makecopy && fp->fr_data != NULL) {
4337 KFREES(fp->fr_data, fp->fr_dsize);
4342 #ifdef IPFILTER_LOOKUP
4344 fp->fr_srcptr = fr_resolvelookup(fp->fr_srctype,
4348 if (fp->fr_srcptr == NULL)
4356 switch (fp->fr_datype)
4358 case FRI_BROADCAST :
4361 case FRI_NETMASKED :
4363 if (fp->fr_difpidx < 0 || fp->fr_difpidx > 3) {
4364 if (makecopy && fp->fr_data != NULL) {
4365 KFREES(fp->fr_data, fp->fr_dsize);
4370 #ifdef IPFILTER_LOOKUP
4372 fp->fr_dstptr = fr_resolvelookup(fp->fr_dsttype,
4376 if (fp->fr_dstptr == NULL)
4386 case FR_T_CALLFUNC :
4391 if (makecopy && fp->fr_data != NULL) {
4392 KFREES(fp->fr_data, fp->fr_dsize);
4398 * Lookup all the interface names that are part of the rule.
4400 frsynclist(fp, NULL);
4401 fp->fr_statecnt = 0;
4404 * Look for an existing matching filter rule, but don't include the
4405 * next or interface pointer in the comparison (fr_next, fr_ifa).
4406 * This elminates rules which are indentical being loaded. Checksum
4407 * the constant part of the filter rule to make comparisons quicker
4408 * (this meaning no pointers are included).
4410 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4413 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4414 for (p = (u_int *)fp->fr_data; p < pp; p++)
4417 WRITE_ENTER(&ipf_mutex);
4420 * Now that the filter rule lists are locked, we can walk the
4421 * chain of them without fear.
4424 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4425 if (fp->fr_collect <= f->fr_collect) {
4432 bzero((char *)frcache, sizeof(frcache));
4434 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4435 if ((fp->fr_cksum != f->fr_cksum) ||
4436 (f->fr_dsize != fp->fr_dsize))
4438 if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func, FR_CMPSIZ))
4440 if ((!ptr && !f->fr_data) ||
4441 (ptr && f->fr_data &&
4442 !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4447 * If zero'ing statistics, copy current to caller and zero.
4449 if (req == (ioctlcmd_t)SIOCZRLST) {
4454 * Copy and reduce lock because of impending copyout.
4455 * Well we should, but if we do then the atomicity of
4456 * this call and the correctness of fr_hits and
4457 * fr_bytes cannot be guaranteed. As it is, this code
4458 * only resets them to 0 if they are successfully
4459 * copied out into user space.
4461 bcopy((char *)f, (char *)fp, sizeof(*f));
4462 /* MUTEX_DOWNGRADE(&ipf_mutex); */
4465 * When we copy this rule back out, set the data
4466 * pointer to be what it was in user space.
4469 error = fr_outobj(data, fp, IPFOBJ_FRENTRY);
4472 if ((f->fr_dsize != 0) && (uptr != NULL))
4473 error = COPYOUT(f->fr_data, uptr,
4484 if ((ptr != NULL) && (makecopy != 0)) {
4485 KFREES(ptr, fp->fr_dsize);
4487 RWLOCK_EXIT(&ipf_mutex);
4493 * At the end of this, ftail must point to the place where the
4494 * new rule is to be saved/inserted/added.
4495 * For SIOCAD*FR, this should be the last rule in the group of
4496 * rules that have equal fr_collect fields.
4497 * For SIOCIN*FR, ...
4499 if (req == (ioctlcmd_t)SIOCADAFR ||
4500 req == (ioctlcmd_t)SIOCADIFR) {
4502 for (ftail = fprev; (f = *ftail) != NULL; ) {
4503 if (f->fr_collect > fp->fr_collect)
4505 ftail = &f->fr_next;
4510 } else if (req == (ioctlcmd_t)SIOCINAFR ||
4511 req == (ioctlcmd_t)SIOCINIFR) {
4512 while ((f = *fprev) != NULL) {
4513 if (f->fr_collect >= fp->fr_collect)
4515 fprev = &f->fr_next;
4518 if (fp->fr_hits != 0) {
4519 while (fp->fr_hits && (f = *ftail)) {
4520 if (f->fr_collect != fp->fr_collect)
4523 ftail = &f->fr_next;
4534 * Request to remove a rule.
4536 if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR) {
4541 * Do not allow activity from user space to interfere
4542 * with rules not loaded that way.
4544 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4550 * Return EBUSY if the rule is being reference by
4551 * something else (eg state information.
4553 if (f->fr_ref > 1) {
4557 #ifdef IPFILTER_SCAN
4558 if (f->fr_isctag[0] != '\0' &&
4559 (f->fr_isc != (struct ipscan *)-1))
4562 if ((fg != NULL) && (fg->fg_head != NULL))
4563 fg->fg_head->fr_ref--;
4564 if (unit == IPL_LOGAUTH) {
4565 error = fr_preauthcmd(req, f, ftail);
4568 if (*f->fr_grhead != '\0')
4569 fr_delgroup(f->fr_grhead, unit, set);
4570 fr_fixskip(ftail, f, -1);
4571 *ftail = f->fr_next;
4573 (void) fr_derefrule(&f);
4577 * Not removing, so we must be adding/inserting a rule.
4582 if (unit == IPL_LOGAUTH) {
4583 error = fr_preauthcmd(req, fp, ftail);
4587 KMALLOC(f, frentry_t *);
4591 if (fg != NULL && fg->fg_head != NULL)
4592 fg->fg_head->fr_ref++;
4594 bcopy((char *)fp, (char *)f,
4596 MUTEX_NUKE(&f->fr_lock);
4597 MUTEX_INIT(&f->fr_lock, "filter rule lock");
4598 #ifdef IPFILTER_SCAN
4599 if (f->fr_isctag[0] != '\0' &&
4601 f->fr_isc = (struct ipscan *)-1;
4606 f->fr_next = *ftail;
4608 if (req == (ioctlcmd_t)SIOCINIFR ||
4609 req == (ioctlcmd_t)SIOCINAFR)
4610 fr_fixskip(ftail, f, 1);
4612 group = f->fr_grhead;
4613 if (*group != '\0') {
4614 fg = fr_addgroup(group, f, f->fr_flags,
4617 f->fr_grp = &fg->fg_start;
4624 RWLOCK_EXIT(&ipf_mutex);
4625 if ((ptr != NULL) && (error != 0) && (makecopy != 0)) {
4626 KFREES(ptr, fp->fr_dsize);
4632 /* ------------------------------------------------------------------------ */
4633 /* Function: fr_funcinit */
4634 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
4635 /* Parameters: fr(I) - pointer to filter rule */
4637 /* If a rule is a call rule, then check if the function it points to needs */
4638 /* an init function to be called now the rule has been loaded. */
4639 /* ------------------------------------------------------------------------ */
4640 static int fr_funcinit(fr)
4643 ipfunc_resolve_t *ft;
4648 for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4649 if (ft->ipfu_addr == fr->fr_func) {
4651 if (ft->ipfu_init != NULL)
4652 err = (*ft->ipfu_init)(fr);
4659 /* ------------------------------------------------------------------------ */
4660 /* Function: fr_findfunc */
4661 /* Returns: ipfunc_t - pointer to function if found, else NULL */
4662 /* Parameters: funcptr(I) - function pointer to lookup */
4664 /* Look for a function in the table of known functions. */
4665 /* ------------------------------------------------------------------------ */
4666 static ipfunc_t fr_findfunc(funcptr)
4669 ipfunc_resolve_t *ft;
4671 for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4672 if (ft->ipfu_addr == funcptr)
4678 /* ------------------------------------------------------------------------ */
4679 /* Function: fr_resolvefunc */
4680 /* Returns: int - 0 == success, else error */
4681 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
4683 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
4684 /* This will either be the function name (if the pointer is set) or the */
4685 /* function pointer if the name is set. When found, fill in the other one */
4686 /* so that the entire, complete, structure can be copied back to user space.*/
4687 /* ------------------------------------------------------------------------ */
4688 int fr_resolvefunc(data)
4691 ipfunc_resolve_t res, *ft;
4693 BCOPYIN(data, &res, sizeof(res));
4695 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
4696 for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4697 if (strncmp(res.ipfu_name, ft->ipfu_name,
4698 sizeof(res.ipfu_name)) == 0) {
4699 res.ipfu_addr = ft->ipfu_addr;
4700 res.ipfu_init = ft->ipfu_init;
4701 if (COPYOUT(&res, data, sizeof(res)) != 0)
4706 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
4707 for (ft = fr_availfuncs; ft->ipfu_addr != NULL; ft++)
4708 if (ft->ipfu_addr == res.ipfu_addr) {
4709 (void) strncpy(res.ipfu_name, ft->ipfu_name,
4710 sizeof(res.ipfu_name));
4711 res.ipfu_init = ft->ipfu_init;
4712 if (COPYOUT(&res, data, sizeof(res)) != 0)
4721 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__FreeBSD__)) || \
4722 (defined(__FreeBSD__) && (__FreeBSD_version < 501000)) || \
4723 (defined(__NetBSD__) && (__NetBSD_Version__ < 105000000)) || \
4724 (defined(__OpenBSD__) && (OpenBSD < 200006))
4727 * ppsratecheck(): packets (or events) per second limitation.
4730 ppsratecheck(lasttime, curpps, maxpps)
4731 struct timeval *lasttime;
4733 int maxpps; /* maximum pps allowed */
4735 struct timeval tv, delta;
4740 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
4741 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
4742 if (delta.tv_usec < 0) {
4744 delta.tv_usec += 1000000;
4748 * check for 0,0 is so that the message will be seen at least once.
4749 * if more than one second have passed since the last update of
4750 * lasttime, reset the counter.
4752 * we do increment *curpps even in *curpps < maxpps case, as some may
4753 * try to use *curpps for stat purposes as well.
4755 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
4756 delta.tv_sec >= 1) {
4760 } else if (maxpps < 0)
4762 else if (*curpps < maxpps)
4766 *curpps = *curpps + 1;
4773 /* ------------------------------------------------------------------------ */
4774 /* Function: fr_derefrule */
4775 /* Returns: int - 0 == rule freed up, else rule not freed */
4776 /* Parameters: fr(I) - pointer to filter rule */
4778 /* Decrement the reference counter to a rule by one. If it reaches zero, */
4779 /* free it and any associated storage space being used by it. */
4780 /* ------------------------------------------------------------------------ */
4781 int fr_derefrule(frp)
4789 MUTEX_ENTER(&fr->fr_lock);
4791 if (fr->fr_ref == 0) {
4792 MUTEX_EXIT(&fr->fr_lock);
4793 MUTEX_DESTROY(&fr->fr_lock);
4795 #ifdef IPFILTER_LOOKUP
4796 if (fr->fr_type == FR_T_IPF && fr->fr_satype == FRI_LOOKUP)
4797 ip_lookup_deref(fr->fr_srctype, fr->fr_srcptr);
4798 if (fr->fr_type == FR_T_IPF && fr->fr_datype == FRI_LOOKUP)
4799 ip_lookup_deref(fr->fr_dsttype, fr->fr_dstptr);
4803 KFREES(fr->fr_data, fr->fr_dsize);
4805 if ((fr->fr_flags & FR_COPIED) != 0) {
4811 MUTEX_EXIT(&fr->fr_lock);
4817 #ifdef IPFILTER_LOOKUP
4818 /* ------------------------------------------------------------------------ */
4819 /* Function: fr_grpmapinit */
4820 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
4821 /* Parameters: fr(I) - pointer to rule to find hash table for */
4823 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
4824 /* fr_ptr is later used by fr_srcgrpmap and fr_dstgrpmap. */
4825 /* ------------------------------------------------------------------------ */
4826 static int fr_grpmapinit(fr)
4829 char name[FR_GROUPLEN];
4832 #if defined(SNPRINTF) && defined(_KERNEL)
4833 SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
4835 (void) sprintf(name, "%d", fr->fr_arg);
4837 iph = fr_findhtable(IPL_LOGIPF, name);
4840 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT))
4847 /* ------------------------------------------------------------------------ */
4848 /* Function: fr_srcgrpmap */
4849 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
4850 /* Parameters: fin(I) - pointer to packet information */
4851 /* passp(IO) - pointer to current/new filter decision (unused) */
4853 /* Look for a rule group head in a hash table, using the source address as */
4854 /* the key, and descend into that group and continue matching rules against */
4856 /* ------------------------------------------------------------------------ */
4857 frentry_t *fr_srcgrpmap(fin, passp)
4864 rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, &fin->fin_src);
4869 fin->fin_fr = fg->fg_start;
4870 (void) fr_scanlist(fin, *passp);
4875 /* ------------------------------------------------------------------------ */
4876 /* Function: fr_dstgrpmap */
4877 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
4878 /* Parameters: fin(I) - pointer to packet information */
4879 /* passp(IO) - pointer to current/new filter decision (unused) */
4881 /* Look for a rule group head in a hash table, using the destination */
4882 /* address as the key, and descend into that group and continue matching */
4883 /* rules against the packet. */
4884 /* ------------------------------------------------------------------------ */
4885 frentry_t *fr_dstgrpmap(fin, passp)
4892 rval = fr_iphmfindgroup(fin->fin_fr->fr_ptr, &fin->fin_dst);
4897 fin->fin_fr = fg->fg_start;
4898 (void) fr_scanlist(fin, *passp);
4901 #endif /* IPFILTER_LOOKUP */
4906 * These functions manage objects on queues for efficient timeouts. There are
4907 * a number of system defined queues as well as user defined timeouts. It is
4908 * expected that a lock is held in the domain in which the queue belongs
4909 * (i.e. either state or NAT) when calling any of these functions that prevents
4910 * fr_freetimeoutqueue() from being called at the same time as any other.
4914 /* ------------------------------------------------------------------------ */
4915 /* Function: fr_addtimeoutqueue */
4916 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
4917 /* timeout queue with given interval. */
4918 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
4919 /* of interface queues. */
4920 /* seconds(I) - timeout value in seconds for this queue. */
4922 /* This routine first looks for a timeout queue that matches the interval */
4923 /* being requested. If it finds one, increments the reference counter and */
4924 /* returns a pointer to it. If none are found, it allocates a new one and */
4925 /* inserts it at the top of the list. */
4928 /* It is assumed that the caller of this function has an appropriate lock */
4929 /* held (exclusively) in the domain that encompases 'parent'. */
4930 /* ------------------------------------------------------------------------ */
4931 ipftq_t *fr_addtimeoutqueue(parent, seconds)
4938 period = seconds * IPF_HZ_DIVIDE;
4940 MUTEX_ENTER(&ipf_timeoutlock);
4941 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
4942 if (ifq->ifq_ttl == period) {
4944 * Reset the delete flag, if set, so the structure
4945 * gets reused rather than freed and reallocated.
4947 MUTEX_ENTER(&ifq->ifq_lock);
4948 ifq->ifq_flags &= ~IFQF_DELETE;
4950 MUTEX_EXIT(&ifq->ifq_lock);
4951 MUTEX_EXIT(&ipf_timeoutlock);
4957 KMALLOC(ifq, ipftq_t *);
4959 ifq->ifq_ttl = period;
4960 ifq->ifq_head = NULL;
4961 ifq->ifq_tail = &ifq->ifq_head;
4962 ifq->ifq_next = *parent;
4963 ifq->ifq_pnext = parent;
4965 ifq->ifq_flags = IFQF_USER;
4968 MUTEX_NUKE(&ifq->ifq_lock);
4969 MUTEX_INIT(&ifq->ifq_lock, "ipftq mutex");
4971 MUTEX_EXIT(&ipf_timeoutlock);
4976 /* ------------------------------------------------------------------------ */
4977 /* Function: fr_deletetimeoutqueue */
4978 /* Returns: int - new reference count value of the timeout queue */
4979 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
4980 /* Locks: ifq->ifq_lock */
4982 /* This routine must be called when we're discarding a pointer to a timeout */
4983 /* queue object, taking care of the reference counter. */
4985 /* Now that this just sets a DELETE flag, it requires the expire code to */
4986 /* check the list of user defined timeout queues and call the free function */
4987 /* below (currently commented out) to stop memory leaking. It is done this */
4988 /* way because the locking may not be sufficient to safely do a free when */
4989 /* this function is called. */
4990 /* ------------------------------------------------------------------------ */
4991 int fr_deletetimeoutqueue(ifq)
4996 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
4997 ifq->ifq_flags |= IFQF_DELETE;
5000 return ifq->ifq_ref;
5004 /* ------------------------------------------------------------------------ */
5005 /* Function: fr_freetimeoutqueue */
5006 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5010 /* It is assumed that the caller of this function has an appropriate lock */
5011 /* held (exclusively) in the domain that encompases the callers "domain". */
5012 /* The ifq_lock for this structure should not be held. */
5014 /* Remove a user definde timeout queue from the list of queues it is in and */
5015 /* tidy up after this is done. */
5016 /* ------------------------------------------------------------------------ */
5017 void fr_freetimeoutqueue(ifq)
5022 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5023 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5024 printf("fr_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5025 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5031 * Remove from its position in the list.
5033 *ifq->ifq_pnext = ifq->ifq_next;
5034 if (ifq->ifq_next != NULL)
5035 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5037 MUTEX_DESTROY(&ifq->ifq_lock);
5038 ATOMIC_DEC(fr_userifqs);
5043 /* ------------------------------------------------------------------------ */
5044 /* Function: fr_deletequeueentry */
5046 /* Parameters: tqe(I) - timeout queue entry to delete */
5047 /* ifq(I) - timeout queue to remove entry from */
5049 /* Remove a tail queue entry from its queue and make it an orphan. */
5050 /* fr_deletetimeoutqueue is called to make sure the reference count on the */
5051 /* queue is correct. We can't, however, call fr_freetimeoutqueue because */
5052 /* the correct lock(s) may not be held that would make it safe to do so. */
5053 /* ------------------------------------------------------------------------ */
5054 void fr_deletequeueentry(tqe)
5061 MUTEX_ENTER(&ifq->ifq_lock);
5063 if (tqe->tqe_pnext != NULL) {
5064 *tqe->tqe_pnext = tqe->tqe_next;
5065 if (tqe->tqe_next != NULL)
5066 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5067 else /* we must be the tail anyway */
5068 ifq->ifq_tail = tqe->tqe_pnext;
5070 tqe->tqe_pnext = NULL;
5071 tqe->tqe_ifq = NULL;
5074 (void) fr_deletetimeoutqueue(ifq);
5076 MUTEX_EXIT(&ifq->ifq_lock);
5080 /* ------------------------------------------------------------------------ */
5081 /* Function: fr_queuefront */
5083 /* Parameters: tqe(I) - pointer to timeout queue entry */
5085 /* Move a queue entry to the front of the queue, if it isn't already there. */
5086 /* ------------------------------------------------------------------------ */
5087 void fr_queuefront(tqe)
5096 MUTEX_ENTER(&ifq->ifq_lock);
5097 if (ifq->ifq_head != tqe) {
5098 *tqe->tqe_pnext = tqe->tqe_next;
5100 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5102 ifq->ifq_tail = tqe->tqe_pnext;
5104 tqe->tqe_next = ifq->ifq_head;
5105 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5106 ifq->ifq_head = tqe;
5107 tqe->tqe_pnext = &ifq->ifq_head;
5109 MUTEX_EXIT(&ifq->ifq_lock);
5113 /* ------------------------------------------------------------------------ */
5114 /* Function: fr_queueback */
5116 /* Parameters: tqe(I) - pointer to timeout queue entry */
5118 /* Move a queue entry to the back of the queue, if it isn't already there. */
5119 /* ------------------------------------------------------------------------ */
5120 void fr_queueback(tqe)
5128 tqe->tqe_die = fr_ticks + ifq->ifq_ttl;
5130 MUTEX_ENTER(&ifq->ifq_lock);
5131 if (tqe->tqe_next != NULL) { /* at the end already ? */
5135 *tqe->tqe_pnext = tqe->tqe_next;
5136 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5139 * Make it the last entry.
5141 tqe->tqe_next = NULL;
5142 tqe->tqe_pnext = ifq->ifq_tail;
5143 *ifq->ifq_tail = tqe;
5144 ifq->ifq_tail = &tqe->tqe_next;
5146 MUTEX_EXIT(&ifq->ifq_lock);
5150 /* ------------------------------------------------------------------------ */
5151 /* Function: fr_queueappend */
5153 /* Parameters: tqe(I) - pointer to timeout queue entry */
5154 /* ifq(I) - pointer to timeout queue */
5155 /* parent(I) - owing object pointer */
5157 /* Add a new item to this queue and put it on the very end. */
5158 /* ------------------------------------------------------------------------ */
5159 void fr_queueappend(tqe, ifq, parent)
5165 MUTEX_ENTER(&ifq->ifq_lock);
5166 tqe->tqe_parent = parent;
5167 tqe->tqe_pnext = ifq->ifq_tail;
5168 *ifq->ifq_tail = tqe;
5169 ifq->ifq_tail = &tqe->tqe_next;
5170 tqe->tqe_next = NULL;
5172 tqe->tqe_die = fr_ticks + ifq->ifq_ttl;
5174 MUTEX_EXIT(&ifq->ifq_lock);
5178 /* ------------------------------------------------------------------------ */
5179 /* Function: fr_movequeue */
5181 /* Parameters: tq(I) - pointer to timeout queue information */
5182 /* oifp(I) - old timeout queue entry was on */
5183 /* nifp(I) - new timeout queue to put entry on */
5185 /* Move a queue entry from one timeout queue to another timeout queue. */
5186 /* If it notices that the current entry is already last and does not need */
5187 /* to move queue, the return. */
5188 /* ------------------------------------------------------------------------ */
5189 void fr_movequeue(tqe, oifq, nifq)
5191 ipftq_t *oifq, *nifq;
5194 * Is the operation here going to be a no-op ?
5196 MUTEX_ENTER(&oifq->ifq_lock);
5197 if ((oifq != nifq) || (*oifq->ifq_tail != tqe)) {
5199 * Remove from the old queue
5201 *tqe->tqe_pnext = tqe->tqe_next;
5203 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5205 oifq->ifq_tail = tqe->tqe_pnext;
5206 tqe->tqe_next = NULL;
5209 * If we're moving from one queue to another, release the
5210 * lock on the old queue and get a lock on the new queue.
5211 * For user defined queues, if we're moving off it, call
5212 * delete in case it can now be freed.
5215 tqe->tqe_ifq = NULL;
5217 (void) fr_deletetimeoutqueue(oifq);
5219 MUTEX_EXIT(&oifq->ifq_lock);
5221 MUTEX_ENTER(&nifq->ifq_lock);
5223 tqe->tqe_ifq = nifq;
5228 * Add to the bottom of the new queue
5230 tqe->tqe_die = fr_ticks + nifq->ifq_ttl;
5231 tqe->tqe_pnext = nifq->ifq_tail;
5232 *nifq->ifq_tail = tqe;
5233 nifq->ifq_tail = &tqe->tqe_next;
5235 MUTEX_EXIT(&nifq->ifq_lock);
5239 /* ------------------------------------------------------------------------ */
5240 /* Function: fr_updateipid */
5241 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
5242 /* Parameters: fin(I) - pointer to packet information */
5244 /* When we are doing NAT, change the IP of every packet to represent a */
5245 /* single sequence of packets coming from the host, hiding any host */
5246 /* specific sequencing that might otherwise be revealed. If the packet is */
5247 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
5248 /* the fragment cache for non-leading fragments. If a non-leading fragment */
5249 /* has no match in the cache, return an error. */
5250 /* ------------------------------------------------------------------------ */
5251 static int fr_updateipid(fin)
5254 u_short id, ido, sums;
5258 if (fin->fin_off != 0) {
5259 sum = fr_ipid_knownfrag(fin);
5260 if (sum == 0xffffffff)
5265 id = fr_nextipid(fin);
5266 if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5267 (void) fr_ipid_newfrag(fin, (u_32_t)id);
5271 ido = ntohs(ip->ip_id);
5274 ip->ip_id = htons(id);
5275 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
5276 sum = (~ntohs(ip->ip_sum)) & 0xffff;
5278 sum = (sum >> 16) + (sum & 0xffff);
5279 sum = (sum >> 16) + (sum & 0xffff);
5280 sums = ~(u_short)sum;
5281 ip->ip_sum = htons(sums);
5286 #ifdef NEED_FRGETIFNAME
5287 /* ------------------------------------------------------------------------ */
5288 /* Function: fr_getifname */
5289 /* Returns: char * - pointer to interface name */
5290 /* Parameters: ifp(I) - pointer to network interface */
5291 /* buffer(O) - pointer to where to store interface name */
5293 /* Constructs an interface name in the buffer passed. The buffer passed is */
5294 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
5295 /* as a NULL pointer then return a pointer to a static array. */
5296 /* ------------------------------------------------------------------------ */
5297 char *fr_getifname(ifp, buffer)
5301 static char namebuf[LIFNAMSIZ];
5302 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5303 defined(__sgi) || defined(linux) || defined(_AIX51) || \
5304 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5312 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5313 buffer[LIFNAMSIZ - 1] = '\0';
5314 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5315 defined(__sgi) || defined(_AIX51) || \
5316 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5317 for (s = buffer; *s; s++)
5319 unit = ifp->if_unit;
5320 space = LIFNAMSIZ - (s - buffer);
5322 # if defined(SNPRINTF) && defined(_KERNEL)
5323 SNPRINTF(temp, sizeof(temp), "%d", unit);
5325 (void) sprintf(temp, "%d", unit);
5327 (void) strncpy(s, temp, space);
5335 /* ------------------------------------------------------------------------ */
5336 /* Function: fr_ioctlswitch */
5337 /* Returns: int - -1 continue processing, else ioctl return value */
5338 /* Parameters: unit(I) - device unit opened */
5339 /* data(I) - pointer to ioctl data */
5340 /* cmd(I) - ioctl command */
5341 /* mode(I) - mode value */
5342 /* uid(I) - uid making the ioctl call */
5343 /* ctx(I) - pointer to context data */
5345 /* Based on the value of unit, call the appropriate ioctl handler or return */
5346 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
5347 /* for the device in order to execute the ioctl. */
5348 /* ------------------------------------------------------------------------ */
5349 int fr_ioctlswitch(unit, data, cmd, mode, uid, ctx)
5350 int unit, mode, uid;
5359 error = fr_ipf_ioctl(data, cmd, mode, uid, ctx);
5363 error = fr_nat_ioctl(data, cmd, mode, uid, ctx);
5369 error = fr_state_ioctl(data, cmd, mode, uid, ctx);
5375 error = fr_auth_ioctl(data, cmd, mode, uid, ctx);
5380 #ifdef IPFILTER_SYNC
5382 error = fr_sync_ioctl(data, cmd, mode, uid, ctx);
5388 #ifdef IPFILTER_SCAN
5390 error = fr_scan_ioctl(data, cmd, mode, uid, ctx);
5395 case IPL_LOGLOOKUP :
5396 #ifdef IPFILTER_LOOKUP
5398 error = ip_lookup_ioctl(data, cmd, mode, uid, ctx);
5413 * This array defines the expected size of objects coming into the kernel
5414 * for the various recognised object types.
5416 static int fr_objbytes[IPFOBJ_COUNT][2] = {
5417 { 1, sizeof(struct frentry) }, /* frentry */
5418 { 0, sizeof(struct friostat) },
5419 { 0, sizeof(struct fr_info) },
5420 { 0, sizeof(struct fr_authstat) },
5421 { 0, sizeof(struct ipfrstat) },
5422 { 0, sizeof(struct ipnat) },
5423 { 0, sizeof(struct natstat) },
5424 { 0, sizeof(struct ipstate_save) },
5425 { 1, sizeof(struct nat_save) }, /* nat_save */
5426 { 0, sizeof(struct natlookup) },
5427 { 1, sizeof(struct ipstate) }, /* ipstate */
5428 { 0, sizeof(struct ips_stat) },
5429 { 0, sizeof(struct frauth) },
5430 { 0, sizeof(struct ipftune) },
5431 { 0, sizeof(struct nat) }, /* nat_t */
5432 { 0, sizeof(struct ipfruleiter) },
5433 { 0, sizeof(struct ipfgeniter) },
5434 { 0, sizeof(struct ipftable) },
5435 { 0, sizeof(struct ipflookupiter) },
5436 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
5440 /* ------------------------------------------------------------------------ */
5441 /* Function: fr_inobj */
5442 /* Returns: int - 0 = success, else failure */
5443 /* Parameters: data(I) - pointer to ioctl data */
5444 /* ptr(I) - pointer to store real data in */
5445 /* type(I) - type of structure being moved */
5447 /* Copy in the contents of what the ipfobj_t points to. In future, we */
5448 /* add things to check for version numbers, sizes, etc, to make it backward */
5449 /* compatible at the ABI for user land. */
5450 /* ------------------------------------------------------------------------ */
5451 int fr_inobj(data, ptr, type)
5459 if ((type < 0) || (type >= IPFOBJ_COUNT))
5462 BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5464 if (obj.ipfo_type != type)
5467 #ifndef IPFILTER_COMPAT
5468 if ((fr_objbytes[type][0] & 1) != 0) {
5469 if (obj.ipfo_size < fr_objbytes[type][1])
5471 } else if (obj.ipfo_size != fr_objbytes[type][1]) {
5475 if (obj.ipfo_rev != IPFILTER_VERSION)
5476 /* XXX compatibility hook here */
5478 if ((fr_objbytes[type][0] & 1) != 0) {
5479 if (obj.ipfo_size < fr_objbytes[type][1])
5480 /* XXX compatibility hook here */
5482 } else if (obj.ipfo_size != fr_objbytes[type][1])
5483 /* XXX compatibility hook here */
5487 if ((fr_objbytes[type][0] & 1) != 0) {
5488 error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5489 fr_objbytes[type][1]);
5491 error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr,
5500 /* ------------------------------------------------------------------------ */
5501 /* Function: fr_inobjsz */
5502 /* Returns: int - 0 = success, else failure */
5503 /* Parameters: data(I) - pointer to ioctl data */
5504 /* ptr(I) - pointer to store real data in */
5505 /* type(I) - type of structure being moved */
5506 /* sz(I) - size of data to copy */
5508 /* As per fr_inobj, except the size of the object to copy in is passed in */
5509 /* but it must not be smaller than the size defined for the type and the */
5510 /* type must allow for varied sized objects. The extra requirement here is */
5511 /* that sz must match the size of the object being passed in - this is not */
5512 /* not possible nor required in fr_inobj(). */
5513 /* ------------------------------------------------------------------------ */
5514 int fr_inobjsz(data, ptr, type, sz)
5522 if ((type < 0) || (type >= IPFOBJ_COUNT))
5524 if (((fr_objbytes[type][0] & 1) == 0) || (sz < fr_objbytes[type][1]))
5527 BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5529 if (obj.ipfo_type != type)
5532 #ifndef IPFILTER_COMPAT
5533 if (obj.ipfo_size != sz)
5536 if (obj.ipfo_rev != IPFILTER_VERSION)
5537 /* XXX compatibility hook here */
5539 if (obj.ipfo_size != sz)
5540 /* XXX compatibility hook here */
5544 error = COPYIN((caddr_t)obj.ipfo_ptr, (caddr_t)ptr, sz);
5551 /* ------------------------------------------------------------------------ */
5552 /* Function: fr_outobjsz */
5553 /* Returns: int - 0 = success, else failure */
5554 /* Parameters: data(I) - pointer to ioctl data */
5555 /* ptr(I) - pointer to store real data in */
5556 /* type(I) - type of structure being moved */
5557 /* sz(I) - size of data to copy */
5559 /* As per fr_outobj, except the size of the object to copy out is passed in */
5560 /* but it must not be smaller than the size defined for the type and the */
5561 /* type must allow for varied sized objects. The extra requirement here is */
5562 /* that sz must match the size of the object being passed in - this is not */
5563 /* not possible nor required in fr_outobj(). */
5564 /* ------------------------------------------------------------------------ */
5565 int fr_outobjsz(data, ptr, type, sz)
5573 if ((type < 0) || (type > IPFOBJ_COUNT) ||
5574 ((fr_objbytes[type][0] & 1) == 0) ||
5575 (sz < fr_objbytes[type][1]))
5578 BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5580 if (obj.ipfo_type != type)
5583 #ifndef IPFILTER_COMPAT
5584 if (obj.ipfo_size != sz)
5587 if (obj.ipfo_rev != IPFILTER_VERSION)
5588 /* XXX compatibility hook here */
5590 if (obj.ipfo_size != sz)
5591 /* XXX compatibility hook here */
5595 error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, sz);
5602 /* ------------------------------------------------------------------------ */
5603 /* Function: fr_outobj */
5604 /* Returns: int - 0 = success, else failure */
5605 /* Parameters: data(I) - pointer to ioctl data */
5606 /* ptr(I) - pointer to store real data in */
5607 /* type(I) - type of structure being moved */
5609 /* Copy out the contents of what ptr is to where ipfobj points to. In */
5610 /* future, we add things to check for version numbers, sizes, etc, to make */
5611 /* it backward compatible at the ABI for user land. */
5612 /* ------------------------------------------------------------------------ */
5613 int fr_outobj(data, ptr, type)
5621 if ((type < 0) || (type > IPFOBJ_COUNT))
5624 BCOPYIN((caddr_t)data, (caddr_t)&obj, sizeof(obj));
5626 if (obj.ipfo_type != type)
5629 #ifndef IPFILTER_COMPAT
5630 if ((fr_objbytes[type][0] & 1) != 0) {
5631 if (obj.ipfo_size < fr_objbytes[type][1])
5633 } else if (obj.ipfo_size != fr_objbytes[type][1])
5636 if (obj.ipfo_rev != IPFILTER_VERSION)
5637 /* XXX compatibility hook here */
5639 if ((fr_objbytes[type][0] & 1) != 0) {
5640 if (obj.ipfo_size < fr_objbytes[type][1])
5641 /* XXX compatibility hook here */
5643 } else if (obj.ipfo_size != fr_objbytes[type][1])
5644 /* XXX compatibility hook here */
5648 error = COPYOUT((caddr_t)ptr, (caddr_t)obj.ipfo_ptr, obj.ipfo_size);
5655 /* ------------------------------------------------------------------------ */
5656 /* Function: fr_checkl4sum */
5657 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
5658 /* Parameters: fin(I) - pointer to packet information */
5660 /* If possible, calculate the layer 4 checksum for the packet. If this is */
5661 /* not possible, return without indicating a failure or success but in a */
5662 /* way that is ditinguishable. */
5663 /* ------------------------------------------------------------------------ */
5664 int fr_checkl4sum(fin)
5667 u_short sum, hdrsum, *csump;
5671 if ((fin->fin_flx & FI_NOCKSUM) != 0)
5675 * If the TCP packet isn't a fragment, isn't too short and otherwise
5676 * isn't already considered "bad", then validate the checksum. If
5677 * this check fails then considered the packet to be "bad".
5679 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
5687 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_VALID)
5688 if (dohwcksum && ((*fin->fin_mp)->b_ick_flag == ICK_VALID)) {
5696 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
5702 if (udp->uh_sum != 0) {
5703 csump = &udp->uh_sum;
5709 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
5722 sum = fr_cksum(fin->fin_m, fin->fin_ip,
5723 fin->fin_p, fin->fin_dp,
5724 fin->fin_dlen + fin->fin_hlen);
5726 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_VALID)
5729 #if !defined(_KERNEL)
5730 if (sum == hdrsum) {
5731 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
5733 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
5742 /* ------------------------------------------------------------------------ */
5743 /* Function: fr_ifpfillv4addr */
5744 /* Returns: int - 0 = address update, -1 = address not updated */
5745 /* Parameters: atype(I) - type of network address update to perform */
5746 /* sin(I) - pointer to source of address information */
5747 /* mask(I) - pointer to source of netmask information */
5748 /* inp(I) - pointer to destination address store */
5749 /* inpmask(I) - pointer to destination netmask store */
5751 /* Given a type of network address update (atype) to perform, copy */
5752 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
5753 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
5754 /* which case the operation fails. For all values of atype other than */
5755 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
5757 /* ------------------------------------------------------------------------ */
5758 int fr_ifpfillv4addr(atype, sin, mask, inp, inpmask)
5760 struct sockaddr_in *sin, *mask;
5761 struct in_addr *inp, *inpmask;
5763 if (inpmask != NULL && atype != FRI_NETMASKED)
5764 inpmask->s_addr = 0xffffffff;
5766 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5767 if (atype == FRI_NETMASKED) {
5768 if (inpmask == NULL)
5770 inpmask->s_addr = mask->sin_addr.s_addr;
5772 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
5774 inp->s_addr = sin->sin_addr.s_addr;
5781 /* ------------------------------------------------------------------------ */
5782 /* Function: fr_ifpfillv6addr */
5783 /* Returns: int - 0 = address update, -1 = address not updated */
5784 /* Parameters: atype(I) - type of network address update to perform */
5785 /* sin(I) - pointer to source of address information */
5786 /* mask(I) - pointer to source of netmask information */
5787 /* inp(I) - pointer to destination address store */
5788 /* inpmask(I) - pointer to destination netmask store */
5790 /* Given a type of network address update (atype) to perform, copy */
5791 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
5792 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
5793 /* which case the operation fails. For all values of atype other than */
5794 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
5796 /* ------------------------------------------------------------------------ */
5797 int fr_ifpfillv6addr(atype, sin, mask, inp, inpmask)
5799 struct sockaddr_in6 *sin, *mask;
5800 struct in_addr *inp, *inpmask;
5802 i6addr_t *src, *dst, *and, *dmask;
5804 src = (i6addr_t *)&sin->sin6_addr;
5805 and = (i6addr_t *)&mask->sin6_addr;
5806 dst = (i6addr_t *)inp;
5807 dmask = (i6addr_t *)inpmask;
5809 if (inpmask != NULL && atype != FRI_NETMASKED) {
5810 dmask->i6[0] = 0xffffffff;
5811 dmask->i6[1] = 0xffffffff;
5812 dmask->i6[2] = 0xffffffff;
5813 dmask->i6[3] = 0xffffffff;
5816 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
5817 if (atype == FRI_NETMASKED) {
5818 if (inpmask == NULL)
5820 dmask->i6[0] = and->i6[0];
5821 dmask->i6[1] = and->i6[1];
5822 dmask->i6[2] = and->i6[2];
5823 dmask->i6[3] = and->i6[3];
5826 dst->i6[0] = src->i6[0] & and->i6[0];
5827 dst->i6[1] = src->i6[1] & and->i6[1];
5828 dst->i6[2] = src->i6[2] & and->i6[2];
5829 dst->i6[3] = src->i6[3] & and->i6[3];
5831 dst->i6[0] = src->i6[0];
5832 dst->i6[1] = src->i6[1];
5833 dst->i6[2] = src->i6[2];
5834 dst->i6[3] = src->i6[3];
5841 /* ------------------------------------------------------------------------ */
5842 /* Function: fr_matchtag */
5843 /* Returns: 0 == mismatch, 1 == match. */
5844 /* Parameters: tag1(I) - pointer to first tag to compare */
5845 /* tag2(I) - pointer to second tag to compare */
5847 /* Returns true (non-zero) or false(0) if the two tag structures can be */
5848 /* considered to be a match or not match, respectively. The tag is 16 */
5849 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
5850 /* compare the ints instead, for speed. tag1 is the master of the */
5851 /* comparison. This function should only be called with both tag1 and tag2 */
5852 /* as non-NULL pointers. */
5853 /* ------------------------------------------------------------------------ */
5854 int fr_matchtag(tag1, tag2)
5855 ipftag_t *tag1, *tag2;
5860 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
5863 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
5864 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
5865 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
5866 (tag1->ipt_num[3] == tag2->ipt_num[3]))
5872 /* ------------------------------------------------------------------------ */
5873 /* Function: fr_coalesce */
5874 /* Returns: 1 == success, -1 == failure, 0 == no change */
5875 /* Parameters: fin(I) - pointer to packet information */
5877 /* Attempt to get all of the packet data into a single, contiguous buffer. */
5878 /* If this call returns a failure then the buffers have also been freed. */
5879 /* ------------------------------------------------------------------------ */
5880 int fr_coalesce(fin)
5883 if ((fin->fin_flx & FI_COALESCE) != 0)
5887 * If the mbuf pointers indicate that there is no mbuf to work with,
5888 * return but do not indicate success or failure.
5890 if (fin->fin_m == NULL || fin->fin_mp == NULL)
5893 #if defined(_KERNEL)
5894 if (fr_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
5895 ATOMIC_INCL(fr_badcoalesces[fin->fin_out]);
5897 FREE_MB_T(*fin->fin_mp);
5899 *fin->fin_mp = NULL;
5904 fin = fin; /* LINT */
5911 * The following table lists all of the tunable variables that can be
5912 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
5913 * in the table below is as follows:
5915 * pointer to value, name of value, minimum, maximum, size of the value's
5916 * container, value attribute flags
5918 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
5919 * means the value can only be written to when IPFilter is loaded but disabled.
5920 * The obvious implication is if neither of these are set then the value can be
5921 * changed at any time without harm.
5923 ipftuneable_t ipf_tuneables[] = {
5925 { { &fr_flags }, "fr_flags", 0, 0xffffffff,
5926 sizeof(fr_flags), 0, NULL },
5927 { { &fr_active }, "fr_active", 0, 0,
5928 sizeof(fr_active), IPFT_RDONLY, NULL },
5929 { { &fr_control_forwarding }, "fr_control_forwarding", 0, 1,
5930 sizeof(fr_control_forwarding), 0, NULL },
5931 { { &fr_update_ipid }, "fr_update_ipid", 0, 1,
5932 sizeof(fr_update_ipid), 0, NULL },
5933 { { &fr_chksrc }, "fr_chksrc", 0, 1,
5934 sizeof(fr_chksrc), 0, NULL },
5935 { { &fr_minttl }, "fr_minttl", 0, 1,
5936 sizeof(fr_minttl), 0, NULL },
5937 { { &fr_icmpminfragmtu }, "fr_icmpminfragmtu", 0, 1,
5938 sizeof(fr_icmpminfragmtu), 0, NULL },
5939 { { &fr_pass }, "fr_pass", 0, 0xffffffff,
5940 sizeof(fr_pass), 0, NULL },
5942 { { &fr_tcpidletimeout }, "fr_tcpidletimeout", 1, 0x7fffffff,
5943 sizeof(fr_tcpidletimeout), IPFT_WRDISABLED, NULL },
5944 { { &fr_tcpclosewait }, "fr_tcpclosewait", 1, 0x7fffffff,
5945 sizeof(fr_tcpclosewait), IPFT_WRDISABLED, NULL },
5946 { { &fr_tcplastack }, "fr_tcplastack", 1, 0x7fffffff,
5947 sizeof(fr_tcplastack), IPFT_WRDISABLED, NULL },
5948 { { &fr_tcptimeout }, "fr_tcptimeout", 1, 0x7fffffff,
5949 sizeof(fr_tcptimeout), IPFT_WRDISABLED, NULL },
5950 { { &fr_tcpclosed }, "fr_tcpclosed", 1, 0x7fffffff,
5951 sizeof(fr_tcpclosed), IPFT_WRDISABLED, NULL },
5952 { { &fr_tcphalfclosed }, "fr_tcphalfclosed", 1, 0x7fffffff,
5953 sizeof(fr_tcphalfclosed), IPFT_WRDISABLED, NULL },
5954 { { &fr_udptimeout }, "fr_udptimeout", 1, 0x7fffffff,
5955 sizeof(fr_udptimeout), IPFT_WRDISABLED, NULL },
5956 { { &fr_udpacktimeout }, "fr_udpacktimeout", 1, 0x7fffffff,
5957 sizeof(fr_udpacktimeout), IPFT_WRDISABLED, NULL },
5958 { { &fr_icmptimeout }, "fr_icmptimeout", 1, 0x7fffffff,
5959 sizeof(fr_icmptimeout), IPFT_WRDISABLED, NULL },
5960 { { &fr_icmpacktimeout }, "fr_icmpacktimeout", 1, 0x7fffffff,
5961 sizeof(fr_icmpacktimeout), IPFT_WRDISABLED, NULL },
5962 { { &fr_iptimeout }, "fr_iptimeout", 1, 0x7fffffff,
5963 sizeof(fr_iptimeout), IPFT_WRDISABLED, NULL },
5964 { { &fr_statemax }, "fr_statemax", 1, 0x7fffffff,
5965 sizeof(fr_statemax), 0, NULL },
5966 { { &fr_statesize }, "fr_statesize", 1, 0x7fffffff,
5967 sizeof(fr_statesize), IPFT_WRDISABLED, NULL },
5968 { { &fr_state_lock }, "fr_state_lock", 0, 1,
5969 sizeof(fr_state_lock), IPFT_RDONLY, NULL },
5970 { { &fr_state_maxbucket }, "fr_state_maxbucket", 1, 0x7fffffff,
5971 sizeof(fr_state_maxbucket), IPFT_WRDISABLED, NULL },
5972 { { &fr_state_maxbucket_reset }, "fr_state_maxbucket_reset", 0, 1,
5973 sizeof(fr_state_maxbucket_reset), IPFT_WRDISABLED, NULL },
5974 { { &ipstate_logging }, "ipstate_logging", 0, 1,
5975 sizeof(ipstate_logging), 0, NULL },
5977 { { &fr_nat_lock }, "fr_nat_lock", 0, 1,
5978 sizeof(fr_nat_lock), IPFT_RDONLY, NULL },
5979 { { &ipf_nattable_sz }, "ipf_nattable_sz", 1, 0x7fffffff,
5980 sizeof(ipf_nattable_sz), IPFT_WRDISABLED, NULL },
5981 { { &ipf_nattable_max }, "ipf_nattable_max", 1, 0x7fffffff,
5982 sizeof(ipf_nattable_max), 0, NULL },
5983 { { &ipf_natrules_sz }, "ipf_natrules_sz", 1, 0x7fffffff,
5984 sizeof(ipf_natrules_sz), IPFT_WRDISABLED, NULL },
5985 { { &ipf_rdrrules_sz }, "ipf_rdrrules_sz", 1, 0x7fffffff,
5986 sizeof(ipf_rdrrules_sz), IPFT_WRDISABLED, NULL },
5987 { { &ipf_hostmap_sz }, "ipf_hostmap_sz", 1, 0x7fffffff,
5988 sizeof(ipf_hostmap_sz), IPFT_WRDISABLED, NULL },
5989 { { &fr_nat_maxbucket }, "fr_nat_maxbucket", 1, 0x7fffffff,
5990 sizeof(fr_nat_maxbucket), IPFT_WRDISABLED, NULL },
5991 { { &fr_nat_maxbucket_reset }, "fr_nat_maxbucket_reset", 0, 1,
5992 sizeof(fr_nat_maxbucket_reset), IPFT_WRDISABLED, NULL },
5993 { { &nat_logging }, "nat_logging", 0, 1,
5994 sizeof(nat_logging), 0, NULL },
5995 { { &fr_defnatage }, "fr_defnatage", 1, 0x7fffffff,
5996 sizeof(fr_defnatage), IPFT_WRDISABLED, NULL },
5997 { { &fr_defnatipage }, "fr_defnatipage", 1, 0x7fffffff,
5998 sizeof(fr_defnatipage), IPFT_WRDISABLED, NULL },
5999 { { &fr_defnaticmpage }, "fr_defnaticmpage", 1, 0x7fffffff,
6000 sizeof(fr_defnaticmpage), IPFT_WRDISABLED, NULL },
6001 { { &fr_nat_doflush }, "fr_nat_doflush", 0, 1,
6002 sizeof(fr_nat_doflush), 0, NULL },
6004 { { &ipf_proxy_debug }, "ipf_proxy_debug", 0, 10,
6005 sizeof(ipf_proxy_debug), 0, 0 },
6007 { { &ipfr_size }, "ipfr_size", 1, 0x7fffffff,
6008 sizeof(ipfr_size), IPFT_WRDISABLED, NULL },
6009 { { &fr_ipfrttl }, "fr_ipfrttl", 1, 0x7fffffff,
6010 sizeof(fr_ipfrttl), IPFT_WRDISABLED, NULL },
6013 { { &ipl_suppress }, "ipl_suppress", 0, 1,
6014 sizeof(ipl_suppress), 0, NULL },
6015 { { &ipl_logmax }, "ipl_logmax", 0, 0x7fffffff,
6016 sizeof(ipl_logmax), IPFT_WRDISABLED, NULL },
6017 { { &ipl_logall }, "ipl_logall", 0, 1,
6018 sizeof(ipl_logall), 0, NULL },
6019 { { &ipl_logsize }, "ipl_logsize", 0, 0x80000,
6020 sizeof(ipl_logsize), 0, NULL },
6022 { { NULL }, NULL, 0, 0,
6026 static ipftuneable_t *ipf_tunelist = NULL;
6029 /* ------------------------------------------------------------------------ */
6030 /* Function: fr_findtunebycookie */
6031 /* Returns: NULL = search failed, else pointer to tune struct */
6032 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6033 /* next(O) - pointer to place to store the cookie for the */
6034 /* "next" tuneable, if it is desired. */
6036 /* This function is used to walk through all of the existing tunables with */
6037 /* successive calls. It searches the known tunables for the one which has */
6038 /* a matching value for "cookie" - ie its address. When returning a match, */
6039 /* the next one to be found may be returned inside next. */
6040 /* ------------------------------------------------------------------------ */
6041 static ipftuneable_t *fr_findtunebycookie(cookie, next)
6042 void *cookie, **next;
6044 ipftuneable_t *ta, **tap;
6046 for (ta = ipf_tuneables; ta->ipft_name != NULL; ta++)
6050 * If the next entry in the array has a name
6051 * present, then return a pointer to it for
6052 * where to go next, else return a pointer to
6053 * the dynaminc list as a key to search there
6054 * next. This facilitates a weak linking of
6055 * the two "lists" together.
6057 if ((ta + 1)->ipft_name != NULL)
6060 *next = &ipf_tunelist;
6065 for (tap = &ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6066 if (tap == cookie) {
6068 *next = &ta->ipft_next;
6078 /* ------------------------------------------------------------------------ */
6079 /* Function: fr_findtunebyname */
6080 /* Returns: NULL = search failed, else pointer to tune struct */
6081 /* Parameters: name(I) - name of the tuneable entry to find. */
6083 /* Search the static array of tuneables and the list of dynamic tuneables */
6084 /* for an entry with a matching name. If we can find one, return a pointer */
6085 /* to the matching structure. */
6086 /* ------------------------------------------------------------------------ */
6087 static ipftuneable_t *fr_findtunebyname(name)
6092 for (ta = ipf_tuneables; ta->ipft_name != NULL; ta++)
6093 if (!strcmp(ta->ipft_name, name)) {
6097 for (ta = ipf_tunelist; ta != NULL; ta = ta->ipft_next)
6098 if (!strcmp(ta->ipft_name, name)) {
6106 /* ------------------------------------------------------------------------ */
6107 /* Function: fr_addipftune */
6108 /* Returns: int - 0 == success, else failure */
6109 /* Parameters: newtune - pointer to new tune struct to add to tuneables */
6111 /* Appends the tune structure pointer to by "newtune" to the end of the */
6112 /* current list of "dynamic" tuneable parameters. Once added, the owner */
6113 /* of the object is not expected to ever change "ipft_next". */
6114 /* ------------------------------------------------------------------------ */
6115 int fr_addipftune(newtune)
6116 ipftuneable_t *newtune;
6118 ipftuneable_t *ta, **tap;
6120 ta = fr_findtunebyname(newtune->ipft_name);
6124 for (tap = &ipf_tunelist; *tap != NULL; tap = &(*tap)->ipft_next)
6127 newtune->ipft_next = NULL;
6133 /* ------------------------------------------------------------------------ */
6134 /* Function: fr_delipftune */
6135 /* Returns: int - 0 == success, else failure */
6136 /* Parameters: oldtune - pointer to tune struct to remove from the list of */
6137 /* current dynamic tuneables */
6139 /* Search for the tune structure, by pointer, in the list of those that are */
6140 /* dynamically added at run time. If found, adjust the list so that this */
6141 /* structure is no longer part of it. */
6142 /* ------------------------------------------------------------------------ */
6143 int fr_delipftune(oldtune)
6144 ipftuneable_t *oldtune;
6146 ipftuneable_t *ta, **tap;
6148 for (tap = &ipf_tunelist; (ta = *tap) != NULL; tap = &ta->ipft_next)
6149 if (ta == oldtune) {
6150 *tap = oldtune->ipft_next;
6151 oldtune->ipft_next = NULL;
6159 /* ------------------------------------------------------------------------ */
6160 /* Function: fr_ipftune */
6161 /* Returns: int - 0 == success, else failure */
6162 /* Parameters: cmd(I) - ioctl command number */
6163 /* data(I) - pointer to ioctl data structure */
6165 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
6166 /* three ioctls provide the means to access and control global variables */
6167 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
6168 /* changed without rebooting, reloading or recompiling. The initialisation */
6169 /* and 'destruction' routines of the various components of ipfilter are all */
6170 /* each responsible for handling their own values being too big. */
6171 /* ------------------------------------------------------------------------ */
6172 int fr_ipftune(cmd, data)
6181 error = fr_inobj(data, &tu, IPFOBJ_TUNEABLE);
6185 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
6186 cookie = tu.ipft_cookie;
6191 case SIOCIPFGETNEXT :
6193 * If cookie is non-NULL, assume it to be a pointer to the last
6194 * entry we looked at, so find it (if possible) and return a
6195 * pointer to the next one after it. The last entry in the
6196 * the table is a NULL entry, so when we get to it, set cookie
6197 * to NULL and return that, indicating end of list, erstwhile
6198 * if we come in with cookie set to NULL, we are starting anew
6199 * at the front of the list.
6201 if (cookie != NULL) {
6202 ta = fr_findtunebycookie(cookie, &tu.ipft_cookie);
6205 tu.ipft_cookie = ta + 1;
6209 * Entry found, but does the data pointed to by that
6210 * row fit in what we can return?
6212 if (ta->ipft_sz > sizeof(tu.ipft_un))
6216 if (ta->ipft_sz == sizeof(u_long))
6217 tu.ipft_vlong = *ta->ipft_plong;
6218 else if (ta->ipft_sz == sizeof(u_int))
6219 tu.ipft_vint = *ta->ipft_pint;
6220 else if (ta->ipft_sz == sizeof(u_short))
6221 tu.ipft_vshort = *ta->ipft_pshort;
6222 else if (ta->ipft_sz == sizeof(u_char))
6223 tu.ipft_vchar = *ta->ipft_pchar;
6225 tu.ipft_sz = ta->ipft_sz;
6226 tu.ipft_min = ta->ipft_min;
6227 tu.ipft_max = ta->ipft_max;
6228 tu.ipft_flags = ta->ipft_flags;
6229 bcopy(ta->ipft_name, tu.ipft_name,
6230 MIN(sizeof(tu.ipft_name),
6231 strlen(ta->ipft_name) + 1));
6233 error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6239 * Search by name or by cookie value for a particular entry
6240 * in the tuning paramter table.
6243 if (cookie != NULL) {
6244 ta = fr_findtunebycookie(cookie, NULL);
6247 } else if (tu.ipft_name[0] != '\0') {
6248 ta = fr_findtunebyname(tu.ipft_name);
6255 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
6257 * Fetch the tuning parameters for a particular value
6260 if (ta->ipft_sz == sizeof(u_long))
6261 tu.ipft_vlong = *ta->ipft_plong;
6262 else if (ta->ipft_sz == sizeof(u_int))
6263 tu.ipft_vint = *ta->ipft_pint;
6264 else if (ta->ipft_sz == sizeof(u_short))
6265 tu.ipft_vshort = *ta->ipft_pshort;
6266 else if (ta->ipft_sz == sizeof(u_char))
6267 tu.ipft_vchar = *ta->ipft_pchar;
6268 tu.ipft_cookie = ta;
6269 tu.ipft_sz = ta->ipft_sz;
6270 tu.ipft_min = ta->ipft_min;
6271 tu.ipft_max = ta->ipft_max;
6272 tu.ipft_flags = ta->ipft_flags;
6273 error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6275 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
6277 * Set an internal parameter. The hard part here is
6278 * getting the new value safely and correctly out of
6279 * the kernel (given we only know its size, not type.)
6283 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
6290 if (in < ta->ipft_min || in > ta->ipft_max) {
6295 if (ta->ipft_sz == sizeof(u_long)) {
6296 tu.ipft_vlong = *ta->ipft_plong;
6297 *ta->ipft_plong = in;
6298 } else if (ta->ipft_sz == sizeof(u_int)) {
6299 tu.ipft_vint = *ta->ipft_pint;
6300 *ta->ipft_pint = (u_int)(in & 0xffffffff);
6301 } else if (ta->ipft_sz == sizeof(u_short)) {
6302 tu.ipft_vshort = *ta->ipft_pshort;
6303 *ta->ipft_pshort = (u_short)(in & 0xffff);
6304 } else if (ta->ipft_sz == sizeof(u_char)) {
6305 tu.ipft_vchar = *ta->ipft_pchar;
6306 *ta->ipft_pchar = (u_char)(in & 0xff);
6308 error = fr_outobj(data, &tu, IPFOBJ_TUNEABLE);
6321 /* ------------------------------------------------------------------------ */
6322 /* Function: fr_initialise */
6323 /* Returns: int - 0 == success, < 0 == failure */
6324 /* Parameters: None. */
6326 /* Call of the initialise functions for all the various subsystems inside */
6327 /* of IPFilter. If any of them should fail, return immeadiately a failure */
6328 /* BUT do not try to recover from the error here. */
6329 /* ------------------------------------------------------------------------ */
6334 bzero(&frstats, sizeof(frstats));
6361 #ifdef IPFILTER_SYNC
6366 #ifdef IPFILTER_SCAN
6371 #ifdef IPFILTER_LOOKUP
6372 i = ip_lookup_init();
6376 #ifdef IPFILTER_COMPILED
6383 /* ------------------------------------------------------------------------ */
6384 /* Function: fr_deinitialise */
6385 /* Returns: None. */
6386 /* Parameters: None. */
6388 /* Call all the various subsystem cleanup routines to deallocate memory or */
6389 /* destroy locks or whatever they've done that they need to now undo. */
6390 /* The order here IS important as there are some cross references of */
6391 /* internal data structures. */
6392 /* ------------------------------------------------------------------------ */
6393 void fr_deinitialise()
6399 #ifdef IPFILTER_SCAN
6404 #ifdef IPFILTER_COMPILED
6408 (void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
6409 (void) frflush(IPL_LOGIPF, 0, FR_INQUE|FR_OUTQUE);
6410 (void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
6411 (void) frflush(IPL_LOGCOUNT, 0, FR_INQUE|FR_OUTQUE);
6413 #ifdef IPFILTER_LOOKUP
6423 /* ------------------------------------------------------------------------ */
6424 /* Function: fr_zerostats */
6425 /* Returns: int - 0 = success, else failure */
6426 /* Parameters: data(O) - pointer to pointer for copying data back to */
6428 /* Copies the current statistics out to userspace and then zero's the */
6429 /* current ones in the kernel. The lock is only held across the bzero() as */
6430 /* the copyout may result in paging (ie network activity.) */
6431 /* ------------------------------------------------------------------------ */
6432 int fr_zerostats(data)
6439 error = fr_outobj(data, &fio, IPFOBJ_IPFSTAT);
6443 WRITE_ENTER(&ipf_mutex);
6444 bzero(&frstats, sizeof(frstats));
6445 RWLOCK_EXIT(&ipf_mutex);
6451 /* ------------------------------------------------------------------------ */
6452 /* Function: fr_resolvedest */
6454 /* Parameters: fdp(IO) - pointer to destination information to resolve */
6455 /* v(I) - IP protocol version to match */
6457 /* Looks up an interface name in the frdest structure pointed to by fdp and */
6458 /* if a matching name can be found for the particular IP protocol version */
6459 /* then store the interface pointer in the frdest struct. If no match is */
6460 /* found, then set the interface pointer to be -1 as NULL is considered to */
6461 /* indicate there is no information at all in the structure. */
6462 /* ------------------------------------------------------------------------ */
6463 void fr_resolvedest(fdp, v)
6472 if (*fdp->fd_ifname != '\0') {
6473 ifp = GETIFP(fdp->fd_ifname, v);
6481 /* ------------------------------------------------------------------------ */
6482 /* Function: fr_resolvenic */
6483 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
6484 /* pointer to interface structure for NIC */
6485 /* Parameters: name(I) - complete interface name */
6486 /* v(I) - IP protocol version */
6488 /* Look for a network interface structure that firstly has a matching name */
6489 /* to that passed in and that is also being used for that IP protocol */
6490 /* version (necessary on some platforms where there are separate listings */
6491 /* for both IPv4 and IPv6 on the same physical NIC. */
6493 /* One might wonder why name gets terminated with a \0 byte in here. The */
6494 /* reason is an interface name could get into the kernel structures of ipf */
6495 /* in any number of ways and so long as they all use the same sized array */
6496 /* to put the name in, it makes sense to ensure it gets null terminated */
6497 /* before it is used for its intended purpose - finding its match in the */
6498 /* kernel's list of configured interfaces. */
6500 /* NOTE: This SHOULD ONLY be used with IPFilter structures that have an */
6501 /* array for the name that is LIFNAMSIZ bytes (at least) in length. */
6502 /* ------------------------------------------------------------------------ */
6503 void *fr_resolvenic(name, v)
6509 if (name[0] == '\0')
6512 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
6516 name[LIFNAMSIZ - 1] = '\0';
6518 nic = GETIFP(name, v);
6525 ipftoken_t *ipftokenhead = NULL, **ipftokentail = &ipftokenhead;
6528 /* ------------------------------------------------------------------------ */
6529 /* Function: ipf_expiretokens */
6530 /* Returns: None. */
6531 /* Parameters: None. */
6533 /* This function is run every ipf tick to see if there are any tokens that */
6534 /* have been held for too long and need to be freed up. */
6535 /* ------------------------------------------------------------------------ */
6536 void ipf_expiretokens()
6541 WRITE_ENTER(&ipf_tokens);
6542 while ((it = ipftokenhead) != NULL) {
6543 if (it->ipt_die > fr_ticks)
6546 data = it->ipt_data;
6550 RWLOCK_EXIT(&ipf_tokens);
6554 /* ------------------------------------------------------------------------ */
6555 /* Function: ipf_deltoken */
6556 /* Returns: int - 0 = success, else error */
6557 /* Parameters: type(I) - the token type to match */
6558 /* uid(I) - uid owning the token */
6559 /* ptr(I) - context pointer for the token */
6561 /* This function looks for a a token in the current list that matches up */
6562 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
6563 /* call ipf_freetoken() to remove it from the list. */
6564 /* ------------------------------------------------------------------------ */
6565 int ipf_deltoken(type, uid, ptr)
6572 WRITE_ENTER(&ipf_tokens);
6573 for (it = ipftokenhead; it != NULL; it = it->ipt_next)
6574 if (ptr == it->ipt_ctx && type == it->ipt_type &&
6575 uid == it->ipt_uid) {
6580 RWLOCK_EXIT(&ipf_tokens);
6586 /* ------------------------------------------------------------------------ */
6587 /* Function: ipf_findtoken */
6588 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
6589 /* Parameters: type(I) - the token type to match */
6590 /* uid(I) - uid owning the token */
6591 /* ptr(I) - context pointer for the token */
6593 /* This function looks for a live token in the list of current tokens that */
6594 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
6595 /* allocated. If one is found then it is moved to the top of the list of */
6596 /* currently active tokens. */
6598 /* NOTE: It is by design that this function returns holding a read lock on */
6599 /* ipf_tokens. Callers must make sure they release it! */
6600 /* ------------------------------------------------------------------------ */
6601 ipftoken_t *ipf_findtoken(type, uid, ptr)
6605 ipftoken_t *it, *new;
6607 KMALLOC(new, ipftoken_t *);
6609 WRITE_ENTER(&ipf_tokens);
6610 for (it = ipftokenhead; it != NULL; it = it->ipt_next) {
6611 if (it->ipt_alive == 0)
6613 if (ptr == it->ipt_ctx && type == it->ipt_type &&
6623 it->ipt_data = NULL;
6626 it->ipt_type = type;
6627 it->ipt_next = NULL;
6635 ipf_unlinktoken(it);
6637 it->ipt_pnext = ipftokentail;
6639 ipftokentail = &it->ipt_next;
6640 it->ipt_next = NULL;
6642 it->ipt_die = fr_ticks + 2;
6644 MUTEX_DOWNGRADE(&ipf_tokens);
6650 /* ------------------------------------------------------------------------ */
6651 /* Function: ipf_unlinktoken */
6652 /* Returns: None. */
6653 /* Parameters: token(I) - pointer to token structure */
6655 /* This function unlinks a token structure from the linked list of tokens */
6656 /* that "own" it. The head pointer never needs to be explicitly adjusted */
6657 /* but the tail does due to the linked list implementation. */
6658 /* ------------------------------------------------------------------------ */
6659 static void ipf_unlinktoken(token)
6663 if (ipftokentail == &token->ipt_next)
6664 ipftokentail = token->ipt_pnext;
6666 *token->ipt_pnext = token->ipt_next;
6667 if (token->ipt_next != NULL)
6668 token->ipt_next->ipt_pnext = token->ipt_pnext;
6672 /* ------------------------------------------------------------------------ */
6673 /* Function: ipf_freetoken */
6674 /* Returns: None. */
6675 /* Parameters: token(I) - pointer to token structure */
6677 /* This function unlinks a token from the linked list and on the path to */
6678 /* free'ing the data, it calls the dereference function that is associated */
6679 /* with the type of data pointed to by the token as it is considered to */
6680 /* hold a reference to it. */
6681 /* ------------------------------------------------------------------------ */
6682 void ipf_freetoken(token)
6685 void *data, **datap;
6687 ipf_unlinktoken(token);
6689 data = token->ipt_data;
6692 if ((data != NULL) && (data != (void *)-1)) {
6693 switch (token->ipt_type)
6695 case IPFGENITER_IPF :
6696 (void) fr_derefrule((frentry_t **)datap);
6698 case IPFGENITER_IPNAT :
6699 WRITE_ENTER(&ipf_nat);
6700 fr_ipnatderef((ipnat_t **)datap);
6701 RWLOCK_EXIT(&ipf_nat);
6703 case IPFGENITER_NAT :
6704 fr_natderef((nat_t **)datap);
6706 case IPFGENITER_STATE :
6707 fr_statederef((ipstate_t **)datap);
6709 case IPFGENITER_FRAG :
6711 fr_fragderef((ipfr_t **)datap, &ipf_frag);
6713 fr_fragderef((ipfr_t **)datap);
6716 case IPFGENITER_NATFRAG :
6718 fr_fragderef((ipfr_t **)datap, &ipf_natfrag);
6720 fr_fragderef((ipfr_t **)datap);
6723 case IPFGENITER_HOSTMAP :
6724 fr_hostmapdel((hostmap_t **)datap);
6727 #ifdef IPFILTER_LOOKUP
6728 ip_lookup_iterderef(token->ipt_type, data);
6738 /* ------------------------------------------------------------------------ */
6739 /* Function: ipf_getnextrule */
6740 /* Returns: int - 0 = success, else error */
6741 /* Parameters: t(I) - pointer to destination information to resolve */
6742 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
6744 /* This function's first job is to bring in the ipfruleiter_t structure via */
6745 /* the ipfobj_t structure to determine what should be the next rule to */
6746 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
6747 /* find the 'next rule'. This may include searching rule group lists or */
6748 /* just be as simple as looking at the 'next' field in the rule structure. */
6749 /* When we have found the rule to return, increase its reference count and */
6750 /* if we used an existing rule to get here, decrease its reference count. */
6751 /* ------------------------------------------------------------------------ */
6752 int ipf_getnextrule(ipftoken_t *t, void *ptr)
6754 frentry_t *fr, *next, zero;
6755 int error, count, out;
6760 if (t == NULL || ptr == NULL)
6762 error = fr_inobj(ptr, &it, IPFOBJ_IPFITER);
6765 if ((it.iri_inout < 0) || (it.iri_inout > 3))
6767 if ((it.iri_active != 0) && (it.iri_active != 1))
6769 if (it.iri_nrules == 0)
6771 if (it.iri_rule == NULL)
6774 out = it.iri_inout & F_OUT;
6776 READ_ENTER(&ipf_mutex);
6778 if (*it.iri_group == '\0') {
6779 if ((it.iri_inout & F_ACIN) != 0) {
6781 next = ipacct[out][it.iri_active];
6783 next = ipacct6[out][it.iri_active];
6786 next = ipfilter[out][it.iri_active];
6788 next = ipfilter6[out][it.iri_active];
6791 fg = fr_findgroup(it.iri_group, IPL_LOGIPF,
6792 it.iri_active, NULL);
6794 next = fg->fg_start;
6802 dst = (char *)it.iri_rule;
6804 * The ipfruleiter may ask for more than 1 rule at a time to be
6805 * copied out, so long as that many exist in the list to start with!
6807 for (count = it.iri_nrules; count > 0; count--) {
6809 MUTEX_ENTER(&next->fr_lock);
6811 MUTEX_EXIT(&next->fr_lock);
6814 bzero(&zero, sizeof(zero));
6821 RWLOCK_EXIT(&ipf_mutex);
6824 (void) fr_derefrule(&fr);
6827 error = COPYOUT(next, dst, sizeof(*next));
6831 if (next->fr_data != NULL) {
6832 dst += sizeof(*next);
6833 error = COPYOUT(next->fr_data, dst, next->fr_dsize);
6837 dst += next->fr_dsize;
6840 if ((count == 1) || (next->fr_next == NULL) || (error != 0))
6843 READ_ENTER(&ipf_mutex);
6852 /* ------------------------------------------------------------------------ */
6853 /* Function: fr_frruleiter */
6854 /* Returns: int - 0 = success, else error */
6855 /* Parameters: data(I) - the token type to match */
6856 /* uid(I) - uid owning the token */
6857 /* ptr(I) - context pointer for the token */
6859 /* This function serves as a stepping stone between fr_ipf_ioctl and */
6860 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
6861 /* the process doing the ioctl and use that to ask for the next rule. */
6862 /* ------------------------------------------------------------------------ */
6863 static int ipf_frruleiter(data, uid, ctx)
6870 token = ipf_findtoken(IPFGENITER_IPF, uid, ctx);
6872 error = ipf_getnextrule(token, data);
6875 RWLOCK_EXIT(&ipf_tokens);
6881 /* ------------------------------------------------------------------------ */
6882 /* Function: fr_geniter */
6883 /* Returns: int - 0 = success, else error */
6884 /* Parameters: token(I) - pointer to ipftoken_t structure */
6887 /* ------------------------------------------------------------------------ */
6888 static int ipf_geniter(token, itp)
6894 switch (itp->igi_type)
6896 case IPFGENITER_FRAG :
6898 error = fr_nextfrag(token, itp,
6899 &ipfr_list, &ipfr_tail, &ipf_frag);
6901 error = fr_nextfrag(token, itp, &ipfr_list, &ipfr_tail);
6913 /* ------------------------------------------------------------------------ */
6914 /* Function: fr_genericiter */
6915 /* Returns: int - 0 = success, else error */
6916 /* Parameters: data(I) - the token type to match */
6917 /* uid(I) - uid owning the token */
6918 /* ptr(I) - context pointer for the token */
6920 /* ------------------------------------------------------------------------ */
6921 int ipf_genericiter(data, uid, ctx)
6929 error = fr_inobj(data, &iter, IPFOBJ_GENITER);
6933 token = ipf_findtoken(iter.igi_type, uid, ctx);
6934 if (token != NULL) {
6935 token->ipt_subtype = iter.igi_type;
6936 error = ipf_geniter(token, &iter);
6939 RWLOCK_EXIT(&ipf_tokens);
6945 /* ------------------------------------------------------------------------ */
6946 /* Function: fr_ipf_ioctl */
6947 /* Returns: int - 0 = success, else error */
6948 /* Parameters: data(I) - the token type to match */
6949 /* cmd(I) - the ioctl command number */
6950 /* mode(I) - mode flags for the ioctl */
6951 /* uid(I) - uid owning the token */
6952 /* ptr(I) - context pointer for the token */
6954 /* This function handles all of the ioctl command that are actually isssued */
6955 /* to the /dev/ipl device. */
6956 /* ------------------------------------------------------------------------ */
6957 int fr_ipf_ioctl(data, cmd, mode, uid, ctx)
6970 if (!(mode & FWRITE))
6973 error = BCOPYIN((caddr_t)data, (caddr_t)&tmp,
6980 RWLOCK_EXIT(&ipf_global);
6981 WRITE_ENTER(&ipf_global);
6986 error = ipfattach();
6992 error = ipfdetach();
7000 if (!(mode & FWRITE)) {
7005 case SIOCIPFGETNEXT :
7007 error = fr_ipftune(cmd, (void *)data);
7011 if (!(mode & FWRITE))
7014 error = BCOPYIN((caddr_t)data, (caddr_t)&fr_flags,
7022 error = BCOPYOUT((caddr_t)&fr_flags, (caddr_t)data,
7029 error = fr_resolvefunc((void *)data);
7036 if (!(mode & FWRITE))
7039 error = frrequest(IPL_LOGIPF, cmd, (caddr_t)data,
7046 if (!(mode & FWRITE))
7049 error = frrequest(IPL_LOGIPF, cmd, (caddr_t)data,
7054 if (!(mode & FWRITE))
7057 WRITE_ENTER(&ipf_mutex);
7058 bzero((char *)frcache, sizeof(frcache[0]) * 2);
7059 error = BCOPYOUT((caddr_t)&fr_active, (caddr_t)data,
7064 fr_active = 1 - fr_active;
7065 RWLOCK_EXIT(&ipf_mutex);
7071 error = fr_outobj((void *)data, &fio, IPFOBJ_IPFSTAT);
7075 if (!(mode & FWRITE))
7078 error = fr_zerostats((caddr_t)data);
7082 if (!(mode & FWRITE))
7085 error = BCOPYIN((caddr_t)data, (caddr_t)&tmp,
7088 tmp = frflush(IPL_LOGIPF, 4, tmp);
7089 error = BCOPYOUT((caddr_t)&tmp, (caddr_t)data,
7100 if (!(mode & FWRITE))
7103 error = BCOPYIN((caddr_t)data, (caddr_t)&tmp,
7106 tmp = frflush(IPL_LOGIPF, 6, tmp);
7107 error = BCOPYOUT((caddr_t)&tmp, (caddr_t)data,
7118 error = BCOPYIN((caddr_t)data, (caddr_t)&tmp, sizeof(tmp));
7120 fr_state_lock = tmp;
7130 if (!(mode & FWRITE))
7133 tmp = ipflog_clear(IPL_LOGIPF);
7134 error = BCOPYOUT((caddr_t)&tmp, (caddr_t)data,
7140 #endif /* IPFILTER_LOG */
7143 if (!(mode & FWRITE))
7146 RWLOCK_EXIT(&ipf_global);
7147 WRITE_ENTER(&ipf_global);
7159 error = fr_outobj((void *)data, fr_fragstats(),
7165 tmp = (int)iplused[IPL_LOGIPF];
7167 error = BCOPYOUT((caddr_t)&tmp, (caddr_t)data, sizeof(tmp));
7173 error = ipf_frruleiter(data, uid, ctx);
7179 error = ipf_genericiter(data, uid, ctx);
7184 case SIOCIPFDELTOK :
7186 error = BCOPYIN((caddr_t)data, (caddr_t)&tmp, sizeof(tmp));
7188 error = ipf_deltoken(tmp, uid, ctx);
7202 /* ------------------------------------------------------------------------ */
7203 /* Function: ipf_queueflush */
7204 /* Returns: int - number of entries flushed (0 = none) */
7205 /* Parameters: deletefn(I) - function to call to delete entry */
7206 /* ipfqs(I) - top of the list of ipf internal queues */
7207 /* userqs(I) - top of the list of user defined timeouts */
7209 /* This fucntion gets called when the state/NAT hash tables fill up and we */
7210 /* need to try a bit harder to free up some space. The algorithm used is */
7211 /* to look for the oldest entries on each timeout queue and free them if */
7212 /* they are within the given window we are considering. Where the window */
7213 /* starts and the steps taken to increase its size depend upon how long ipf */
7214 /* has been running (fr_ticks.) Anything modified in the last 30 seconds */
7215 /* is not touched. */
7217 /* die fr_ticks 30*1.5 1800*1.5 | 43200*1.5 */
7219 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
7220 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
7222 /* Points to note: */
7223 /* - tqe_die is the time, in the future, when entries die. */
7224 /* - tqe_die - fr_ticks is how long left the connection has to live in ipf */
7226 /* - tqe_touched is when the entry was last used by NAT/state */
7227 /* - the closer tqe_touched is to fr_ticks, the further tqe_die will be for */
7228 /* any given timeout queue and vice versa. */
7229 /* - both tqe_die and tqe_touched increase over time */
7230 /* - timeout queues are sorted with the highest value of tqe_die at the */
7231 /* bottom and therefore the smallest values of each are at the top */
7233 /* We start by setting up a maximum range to scan for things to move of */
7234 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
7235 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
7236 /* we start again with a new value for "iend" and "istart". The downside */
7237 /* of the current implementation is that it may return removing just 1 entry*/
7238 /* every time (pathological case) where it could remove more. */
7239 /* ------------------------------------------------------------------------ */
7240 int ipf_queueflush(deletefn, ipfqs, userqs)
7241 ipftq_delete_fn_t deletefn;
7242 ipftq_t *ipfqs, *userqs;
7244 u_long interval, istart, iend;
7245 ipftq_t *ifq, *ifqnext;
7246 ipftqent_t *tqe, *tqn;
7250 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
7251 * used then the operations are upgraded to floating point
7252 * and kernels don't like floating point...
7254 if (fr_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
7255 istart = IPF_TTLVAL(86400 * 4);
7256 interval = IPF_TTLVAL(43200);
7257 } else if (fr_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
7258 istart = IPF_TTLVAL(43200);
7259 interval = IPF_TTLVAL(1800);
7260 } else if (fr_ticks > IPF_TTLVAL(30 * 15 / 10)) {
7261 istart = IPF_TTLVAL(1800);
7262 interval = IPF_TTLVAL(30);
7266 if (istart > fr_ticks) {
7267 istart = (fr_ticks / interval) * interval;
7270 iend = fr_ticks - interval;
7272 istart = iend - interval;
7275 while (removed == 0) {
7278 try = fr_ticks - istart;
7280 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
7281 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
7282 if (try < tqe->tqe_touched)
7284 tqn = tqe->tqe_next;
7285 if ((*deletefn)(tqe->tqe_parent) == 0)
7290 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
7291 ifqnext = ifq->ifq_next;
7293 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
7294 if (try < tqe->tqe_touched)
7296 tqn = tqe->tqe_next;
7297 if ((*deletefn)(tqe->tqe_parent) == 0)
7304 if (interval == IPF_TTLVAL(43200)) {
7305 interval = IPF_TTLVAL(1800);
7306 } else if (interval == IPF_TTLVAL(1800)) {
7307 interval = IPF_TTLVAL(30);
7311 if (interval >= fr_ticks)
7314 iend = fr_ticks - interval;