]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/ipfilter/netinet/fil.c
While working on PR/238796 I discovered an unused variable in frdest,
[FreeBSD/FreeBSD.git] / sys / contrib / ipfilter / netinet / fil.c
1 /*      $FreeBSD$       */
2
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Copyright 2008 Sun Microsystems.
9  *
10  * $Id$
11  *
12  */
13 #if defined(KERNEL) || defined(_KERNEL)
14 # undef KERNEL
15 # undef _KERNEL
16 # define        KERNEL  1
17 # define        _KERNEL 1
18 #endif
19 #include <sys/errno.h>
20 #include <sys/types.h>
21 #include <sys/param.h>
22 #include <sys/time.h>
23 #if defined(_KERNEL) && defined(__FreeBSD_version)
24 #  if !defined(IPFILTER_LKM)
25 #   include "opt_inet6.h"
26 #  endif
27 # include <sys/filio.h>
28 #else
29 # include <sys/ioctl.h>
30 #endif
31 #if defined(__SVR4) || defined(sun) /* SOLARIS */
32 # include <sys/filio.h>
33 #endif
34 # include <sys/fcntl.h>
35 #if defined(_KERNEL)
36 # include <sys/systm.h>
37 # include <sys/file.h>
38 #else
39 # include <stdio.h>
40 # include <string.h>
41 # include <stdlib.h>
42 # include <stddef.h>
43 # include <sys/file.h>
44 # define _KERNEL
45 # include <sys/uio.h>
46 # undef _KERNEL
47 #endif
48 #if !defined(__SVR4)
49 # include <sys/mbuf.h>
50 #else
51 #  include <sys/byteorder.h>
52 # if (SOLARIS2 < 5) && defined(sun)
53 #  include <sys/dditypes.h>
54 # endif
55 #endif
56 # include <sys/protosw.h>
57 #include <sys/socket.h>
58 #include <net/if.h>
59 #ifdef sun
60 # include <net/af.h>
61 #endif
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66 # include <netinet/udp.h>
67 # include <netinet/ip_icmp.h>
68 #include "netinet/ip_compat.h"
69 #ifdef  USE_INET6
70 # include <netinet/icmp6.h>
71 # if !SOLARIS && defined(_KERNEL)
72 #  include <netinet6/in6_var.h>
73 # endif
74 #endif
75 #include "netinet/ip_fil.h"
76 #include "netinet/ip_nat.h"
77 #include "netinet/ip_frag.h"
78 #include "netinet/ip_state.h"
79 #include "netinet/ip_proxy.h"
80 #include "netinet/ip_auth.h"
81 #ifdef IPFILTER_SCAN
82 # include "netinet/ip_scan.h"
83 #endif
84 #include "netinet/ip_sync.h"
85 #include "netinet/ip_lookup.h"
86 #include "netinet/ip_pool.h"
87 #include "netinet/ip_htable.h"
88 #ifdef IPFILTER_COMPILED
89 # include "netinet/ip_rules.h"
90 #endif
91 #if defined(IPFILTER_BPF) && defined(_KERNEL)
92 # include <net/bpf.h>
93 #endif
94 #if defined(__FreeBSD_version)
95 # include <sys/malloc.h>
96 #endif
97 #include "netinet/ipl.h"
98
99 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
100 # include <sys/callout.h>
101 extern struct callout ipf_slowtimer_ch;
102 #endif
103 /* END OF INCLUDES */
104
105 #if !defined(lint)
106 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
107 static const char rcsid[] = "@(#)$FreeBSD$";
108 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
109 #endif
110
111 #ifndef _KERNEL
112 # include "ipf.h"
113 # include "ipt.h"
114 extern  int     opts;
115 extern  int     blockreason;
116 #endif /* _KERNEL */
117
118 #define LBUMP(x)        softc->x++
119 #define LBUMPD(x, y)    do { softc->x.y++; DT(y); } while (0)
120
121 static  INLINE int      ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
122 static  u_32_t          ipf_checkcipso __P((fr_info_t *, u_char *, int));
123 static  u_32_t          ipf_checkripso __P((u_char *));
124 static  u_32_t          ipf_decaps __P((fr_info_t *, u_32_t, int));
125 #ifdef IPFILTER_LOG
126 static  frentry_t       *ipf_dolog __P((fr_info_t *, u_32_t *));
127 #endif
128 static  int             ipf_flushlist __P((ipf_main_softc_t *, int *,
129                                            frentry_t **));
130 static  int             ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
131                                               int));
132 static  ipfunc_t        ipf_findfunc __P((ipfunc_t));
133 static  void            *ipf_findlookup __P((ipf_main_softc_t *, int,
134                                              frentry_t *,
135                                              i6addr_t *, i6addr_t *));
136 static  frentry_t       *ipf_firewall __P((fr_info_t *, u_32_t *));
137 static  int             ipf_fr_matcharray __P((fr_info_t *, int *));
138 static  int             ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
139                                             void *));
140 static  void            ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
141 static  int             ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
142 static  int             ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
143                                          ipfgeniter_t *));
144 static  void            ipf_getstat __P((ipf_main_softc_t *,
145                                          struct friostat *, int));
146 static  int             ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
147 static  void            ipf_group_free __P((frgroup_t *));
148 static  int             ipf_grpmapfini __P((struct ipf_main_softc_s *,
149                                             frentry_t *));
150 static  int             ipf_grpmapinit __P((struct ipf_main_softc_s *,
151                                             frentry_t *));
152 static  frentry_t       *ipf_nextrule __P((ipf_main_softc_t *, int, int,
153                                            frentry_t *, int));
154 static  int             ipf_portcheck __P((frpcmp_t *, u_32_t));
155 static  INLINE int      ipf_pr_ah __P((fr_info_t *));
156 static  INLINE void     ipf_pr_esp __P((fr_info_t *));
157 static  INLINE void     ipf_pr_gre __P((fr_info_t *));
158 static  INLINE void     ipf_pr_udp __P((fr_info_t *));
159 static  INLINE void     ipf_pr_tcp __P((fr_info_t *));
160 static  INLINE void     ipf_pr_icmp __P((fr_info_t *));
161 static  INLINE void     ipf_pr_ipv4hdr __P((fr_info_t *));
162 static  INLINE void     ipf_pr_short __P((fr_info_t *, int));
163 static  INLINE int      ipf_pr_tcpcommon __P((fr_info_t *));
164 static  INLINE int      ipf_pr_udpcommon __P((fr_info_t *));
165 static  void            ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
166                                              int, int));
167 static  void            ipf_rule_expire_insert __P((ipf_main_softc_t *,
168                                                     frentry_t *, int));
169 static  int             ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
170                                           void *));
171 static  void            ipf_token_flush __P((ipf_main_softc_t *));
172 static  void            ipf_token_unlink __P((ipf_main_softc_t *,
173                                               ipftoken_t *));
174 static  ipftuneable_t   *ipf_tune_findbyname __P((ipftuneable_t *,
175                                                   const char *));
176 static  ipftuneable_t   *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
177                                                     void **));
178 static  int             ipf_updateipid __P((fr_info_t *));
179 static  int             ipf_settimeout __P((struct ipf_main_softc_s *,
180                                             struct ipftuneable *,
181                                             ipftuneval_t *));
182 #if !defined(_KERNEL) || SOLARIS
183 static  int             ppsratecheck(struct timeval *, int *, int);
184 #endif
185
186
187 /*
188  * bit values for identifying presence of individual IP options
189  * All of these tables should be ordered by increasing key value on the left
190  * hand side to allow for binary searching of the array and include a trailer
191  * with a 0 for the bitmask for linear searches to easily find the end with.
192  */
193 static const    struct  optlist ipopts[20] = {
194         { IPOPT_NOP,    0x000001 },
195         { IPOPT_RR,     0x000002 },
196         { IPOPT_ZSU,    0x000004 },
197         { IPOPT_MTUP,   0x000008 },
198         { IPOPT_MTUR,   0x000010 },
199         { IPOPT_ENCODE, 0x000020 },
200         { IPOPT_TS,     0x000040 },
201         { IPOPT_TR,     0x000080 },
202         { IPOPT_SECURITY, 0x000100 },
203         { IPOPT_LSRR,   0x000200 },
204         { IPOPT_E_SEC,  0x000400 },
205         { IPOPT_CIPSO,  0x000800 },
206         { IPOPT_SATID,  0x001000 },
207         { IPOPT_SSRR,   0x002000 },
208         { IPOPT_ADDEXT, 0x004000 },
209         { IPOPT_VISA,   0x008000 },
210         { IPOPT_IMITD,  0x010000 },
211         { IPOPT_EIP,    0x020000 },
212         { IPOPT_FINN,   0x040000 },
213         { 0,            0x000000 }
214 };
215
216 #ifdef USE_INET6
217 static const struct optlist ip6exthdr[] = {
218         { IPPROTO_HOPOPTS,              0x000001 },
219         { IPPROTO_IPV6,                 0x000002 },
220         { IPPROTO_ROUTING,              0x000004 },
221         { IPPROTO_FRAGMENT,             0x000008 },
222         { IPPROTO_ESP,                  0x000010 },
223         { IPPROTO_AH,                   0x000020 },
224         { IPPROTO_NONE,                 0x000040 },
225         { IPPROTO_DSTOPTS,              0x000080 },
226         { IPPROTO_MOBILITY,             0x000100 },
227         { 0,                            0 }
228 };
229 #endif
230
231 /*
232  * bit values for identifying presence of individual IP security options
233  */
234 static const    struct  optlist secopt[8] = {
235         { IPSO_CLASS_RES4,      0x01 },
236         { IPSO_CLASS_TOPS,      0x02 },
237         { IPSO_CLASS_SECR,      0x04 },
238         { IPSO_CLASS_RES3,      0x08 },
239         { IPSO_CLASS_CONF,      0x10 },
240         { IPSO_CLASS_UNCL,      0x20 },
241         { IPSO_CLASS_RES2,      0x40 },
242         { IPSO_CLASS_RES1,      0x80 }
243 };
244
245 char    ipfilter_version[] = IPL_VERSION;
246
247 int     ipf_features = 0
248 #ifdef  IPFILTER_LKM
249                 | IPF_FEAT_LKM
250 #endif
251 #ifdef  IPFILTER_LOG
252                 | IPF_FEAT_LOG
253 #endif
254                 | IPF_FEAT_LOOKUP
255 #ifdef  IPFILTER_BPF
256                 | IPF_FEAT_BPF
257 #endif
258 #ifdef  IPFILTER_COMPILED
259                 | IPF_FEAT_COMPILED
260 #endif
261 #ifdef  IPFILTER_CKSUM
262                 | IPF_FEAT_CKSUM
263 #endif
264                 | IPF_FEAT_SYNC
265 #ifdef  IPFILTER_SCAN
266                 | IPF_FEAT_SCAN
267 #endif
268 #ifdef  USE_INET6
269                 | IPF_FEAT_IPV6
270 #endif
271         ;
272
273
274 /*
275  * Table of functions available for use with call rules.
276  */
277 static ipfunc_resolve_t ipf_availfuncs[] = {
278         { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
279         { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
280         { "",         NULL,           NULL,           NULL }
281 };
282
283 static ipftuneable_t ipf_main_tuneables[] = {
284         { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
285                 "ipf_flags",            0,      0xffffffff,
286                 stsizeof(ipf_main_softc_t, ipf_flags),
287                 0,                      NULL,   NULL },
288         { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
289                 "active",               0,      0,
290                 stsizeof(ipf_main_softc_t, ipf_active),
291                 IPFT_RDONLY,            NULL,   NULL },
292         { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
293                 "control_forwarding",   0, 1,
294                 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
295                 0,                      NULL,   NULL },
296         { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
297                 "update_ipid",          0,      1,
298                 stsizeof(ipf_main_softc_t, ipf_update_ipid),
299                 0,                      NULL,   NULL },
300         { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
301                 "chksrc",               0,      1,
302                 stsizeof(ipf_main_softc_t, ipf_chksrc),
303                 0,                      NULL,   NULL },
304         { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
305                 "min_ttl",              0,      1,
306                 stsizeof(ipf_main_softc_t, ipf_minttl),
307                 0,                      NULL,   NULL },
308         { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
309                 "icmp_minfragmtu",      0,      1,
310                 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
311                 0,                      NULL,   NULL },
312         { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
313                 "default_pass",         0,      0xffffffff,
314                 stsizeof(ipf_main_softc_t, ipf_pass),
315                 0,                      NULL,   NULL },
316         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
317                 "tcp_idle_timeout",     1,      0x7fffffff,
318                 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
319                 0,                      NULL,   ipf_settimeout },
320         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
321                 "tcp_close_wait",       1,      0x7fffffff,
322                 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
323                 0,                      NULL,   ipf_settimeout },
324         { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
325                 "tcp_last_ack",         1,      0x7fffffff,
326                 stsizeof(ipf_main_softc_t, ipf_tcplastack),
327                 0,                      NULL,   ipf_settimeout },
328         { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
329                 "tcp_timeout",          1,      0x7fffffff,
330                 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
331                 0,                      NULL,   ipf_settimeout },
332         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
333                 "tcp_syn_sent",         1,      0x7fffffff,
334                 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
335                 0,                      NULL,   ipf_settimeout },
336         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
337                 "tcp_syn_received",     1,      0x7fffffff,
338                 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
339                 0,                      NULL,   ipf_settimeout },
340         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
341                 "tcp_closed",           1,      0x7fffffff,
342                 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
343                 0,                      NULL,   ipf_settimeout },
344         { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
345                 "tcp_half_closed",      1,      0x7fffffff,
346                 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
347                 0,                      NULL,   ipf_settimeout },
348         { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
349                 "tcp_time_wait",        1,      0x7fffffff,
350                 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
351                 0,                      NULL,   ipf_settimeout },
352         { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
353                 "udp_timeout",          1,      0x7fffffff,
354                 stsizeof(ipf_main_softc_t, ipf_udptimeout),
355                 0,                      NULL,   ipf_settimeout },
356         { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
357                 "udp_ack_timeout",      1,      0x7fffffff,
358                 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
359                 0,                      NULL,   ipf_settimeout },
360         { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
361                 "icmp_timeout",         1,      0x7fffffff,
362                 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
363                 0,                      NULL,   ipf_settimeout },
364         { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
365                 "icmp_ack_timeout",     1,      0x7fffffff,
366                 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
367                 0,                      NULL,   ipf_settimeout },
368         { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
369                 "ip_timeout",           1,      0x7fffffff,
370                 stsizeof(ipf_main_softc_t, ipf_iptimeout),
371                 0,                      NULL,   ipf_settimeout },
372 #if defined(INSTANCES) && defined(_KERNEL)
373         { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
374                 "intercept_loopback",   0,      1,
375                 stsizeof(ipf_main_softc_t, ipf_get_loopback),
376                 0,                      NULL,   ipf_set_loopback },
377 #endif
378         { { 0 },
379                 NULL,                   0,      0,
380                 0,
381                 0,                      NULL,   NULL }
382 };
383
384
385 /*
386  * The next section of code is a collection of small routines that set
387  * fields in the fr_info_t structure passed based on properties of the
388  * current packet.  There are different routines for the same protocol
389  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
390  * will "special" inspection for setup, is now more easily done by adding
391  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
392  * adding more code to a growing switch statement.
393  */
394 #ifdef USE_INET6
395 static  INLINE int      ipf_pr_ah6 __P((fr_info_t *));
396 static  INLINE void     ipf_pr_esp6 __P((fr_info_t *));
397 static  INLINE void     ipf_pr_gre6 __P((fr_info_t *));
398 static  INLINE void     ipf_pr_udp6 __P((fr_info_t *));
399 static  INLINE void     ipf_pr_tcp6 __P((fr_info_t *));
400 static  INLINE void     ipf_pr_icmp6 __P((fr_info_t *));
401 static  INLINE void     ipf_pr_ipv6hdr __P((fr_info_t *));
402 static  INLINE void     ipf_pr_short6 __P((fr_info_t *, int));
403 static  INLINE int      ipf_pr_hopopts6 __P((fr_info_t *));
404 static  INLINE int      ipf_pr_mobility6 __P((fr_info_t *));
405 static  INLINE int      ipf_pr_routing6 __P((fr_info_t *));
406 static  INLINE int      ipf_pr_dstopts6 __P((fr_info_t *));
407 static  INLINE int      ipf_pr_fragment6 __P((fr_info_t *));
408 static  INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
409
410
411 /* ------------------------------------------------------------------------ */
412 /* Function:    ipf_pr_short6                                               */
413 /* Returns:     void                                                        */
414 /* Parameters:  fin(I)  - pointer to packet information                     */
415 /*              xmin(I) - minimum header size                               */
416 /*                                                                          */
417 /* IPv6 Only                                                                */
418 /* This is function enforces the 'is a packet too short to be legit' rule   */
419 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
420 /* for ipf_pr_short() for more details.                                     */
421 /* ------------------------------------------------------------------------ */
422 static INLINE void
423 ipf_pr_short6(fin, xmin)
424         fr_info_t *fin;
425         int xmin;
426 {
427
428         if (fin->fin_dlen < xmin)
429                 fin->fin_flx |= FI_SHORT;
430 }
431
432
433 /* ------------------------------------------------------------------------ */
434 /* Function:    ipf_pr_ipv6hdr                                              */
435 /* Returns:     void                                                        */
436 /* Parameters:  fin(I) - pointer to packet information                      */
437 /*                                                                          */
438 /* IPv6 Only                                                                */
439 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
440 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
441 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
442 /* of that possibility arising.                                             */
443 /* ------------------------------------------------------------------------ */
444 static INLINE void
445 ipf_pr_ipv6hdr(fin)
446         fr_info_t *fin;
447 {
448         ip6_t *ip6 = (ip6_t *)fin->fin_ip;
449         int p, go = 1, i, hdrcount;
450         fr_ip_t *fi = &fin->fin_fi;
451
452         fin->fin_off = 0;
453
454         fi->fi_tos = 0;
455         fi->fi_optmsk = 0;
456         fi->fi_secmsk = 0;
457         fi->fi_auth = 0;
458
459         p = ip6->ip6_nxt;
460         fin->fin_crc = p;
461         fi->fi_ttl = ip6->ip6_hlim;
462         fi->fi_src.in6 = ip6->ip6_src;
463         fin->fin_crc += fi->fi_src.i6[0];
464         fin->fin_crc += fi->fi_src.i6[1];
465         fin->fin_crc += fi->fi_src.i6[2];
466         fin->fin_crc += fi->fi_src.i6[3];
467         fi->fi_dst.in6 = ip6->ip6_dst;
468         fin->fin_crc += fi->fi_dst.i6[0];
469         fin->fin_crc += fi->fi_dst.i6[1];
470         fin->fin_crc += fi->fi_dst.i6[2];
471         fin->fin_crc += fi->fi_dst.i6[3];
472         fin->fin_id = 0;
473         if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
474                 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
475
476         hdrcount = 0;
477         while (go && !(fin->fin_flx & FI_SHORT)) {
478                 switch (p)
479                 {
480                 case IPPROTO_UDP :
481                         ipf_pr_udp6(fin);
482                         go = 0;
483                         break;
484
485                 case IPPROTO_TCP :
486                         ipf_pr_tcp6(fin);
487                         go = 0;
488                         break;
489
490                 case IPPROTO_ICMPV6 :
491                         ipf_pr_icmp6(fin);
492                         go = 0;
493                         break;
494
495                 case IPPROTO_GRE :
496                         ipf_pr_gre6(fin);
497                         go = 0;
498                         break;
499
500                 case IPPROTO_HOPOPTS :
501                         p = ipf_pr_hopopts6(fin);
502                         break;
503
504                 case IPPROTO_MOBILITY :
505                         p = ipf_pr_mobility6(fin);
506                         break;
507
508                 case IPPROTO_DSTOPTS :
509                         p = ipf_pr_dstopts6(fin);
510                         break;
511
512                 case IPPROTO_ROUTING :
513                         p = ipf_pr_routing6(fin);
514                         break;
515
516                 case IPPROTO_AH :
517                         p = ipf_pr_ah6(fin);
518                         break;
519
520                 case IPPROTO_ESP :
521                         ipf_pr_esp6(fin);
522                         go = 0;
523                         break;
524
525                 case IPPROTO_IPV6 :
526                         for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
527                                 if (ip6exthdr[i].ol_val == p) {
528                                         fin->fin_flx |= ip6exthdr[i].ol_bit;
529                                         break;
530                                 }
531                         go = 0;
532                         break;
533
534                 case IPPROTO_NONE :
535                         go = 0;
536                         break;
537
538                 case IPPROTO_FRAGMENT :
539                         p = ipf_pr_fragment6(fin);
540                         /*
541                          * Given that the only fragments we want to let through
542                          * (where fin_off != 0) are those where the non-first
543                          * fragments only have data, we can safely stop looking
544                          * at headers if this is a non-leading fragment.
545                          */
546                         if (fin->fin_off != 0)
547                                 go = 0;
548                         break;
549
550                 default :
551                         go = 0;
552                         break;
553                 }
554                 hdrcount++;
555
556                 /*
557                  * It is important to note that at this point, for the
558                  * extension headers (go != 0), the entire header may not have
559                  * been pulled up when the code gets to this point.  This is
560                  * only done for "go != 0" because the other header handlers
561                  * will all pullup their complete header.  The other indicator
562                  * of an incomplete packet is that this was just an extension
563                  * header.
564                  */
565                 if ((go != 0) && (p != IPPROTO_NONE) &&
566                     (ipf_pr_pullup(fin, 0) == -1)) {
567                         p = IPPROTO_NONE;
568                         break;
569                 }
570         }
571
572         /*
573          * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
574          * and destroy whatever packet was here.  The caller of this function
575          * expects us to return if there is a problem with ipf_pullup.
576          */
577         if (fin->fin_m == NULL) {
578                 ipf_main_softc_t *softc = fin->fin_main_soft;
579
580                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
581                 return;
582         }
583
584         fi->fi_p = p;
585
586         /*
587          * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
588          * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
589          */
590         if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
591                 ipf_main_softc_t *softc = fin->fin_main_soft;
592
593                 fin->fin_flx |= FI_BAD;
594                 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
595                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
596                 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
597         }
598 }
599
600
601 /* ------------------------------------------------------------------------ */
602 /* Function:    ipf_pr_ipv6exthdr                                           */
603 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
604 /*                                 or NULL if there is a prolblem.          */
605 /* Parameters:  fin(I)      - pointer to packet information                 */
606 /*              multiple(I) - flag indicating yes/no if multiple occurances */
607 /*                            of this extension header are allowed.         */
608 /*              proto(I)    - protocol number for this extension header     */
609 /*                                                                          */
610 /* IPv6 Only                                                                */
611 /* This function embodies a number of common checks that all IPv6 extension */
612 /* headers must be subjected to.  For example, making sure the packet is    */
613 /* big enough for it to be in, checking if it is repeated and setting a     */
614 /* flag to indicate its presence.                                           */
615 /* ------------------------------------------------------------------------ */
616 static INLINE struct ip6_ext *
617 ipf_pr_ipv6exthdr(fin, multiple, proto)
618         fr_info_t *fin;
619         int multiple, proto;
620 {
621         ipf_main_softc_t *softc = fin->fin_main_soft;
622         struct ip6_ext *hdr;
623         u_short shift;
624         int i;
625
626         fin->fin_flx |= FI_V6EXTHDR;
627
628                                 /* 8 is default length of extension hdr */
629         if ((fin->fin_dlen - 8) < 0) {
630                 fin->fin_flx |= FI_SHORT;
631                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
632                 return NULL;
633         }
634
635         if (ipf_pr_pullup(fin, 8) == -1) {
636                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
637                 return NULL;
638         }
639
640         hdr = fin->fin_dp;
641         switch (proto)
642         {
643         case IPPROTO_FRAGMENT :
644                 shift = 8;
645                 break;
646         default :
647                 shift = 8 + (hdr->ip6e_len << 3);
648                 break;
649         }
650
651         if (shift > fin->fin_dlen) {    /* Nasty extension header length? */
652                 fin->fin_flx |= FI_BAD;
653                 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
654                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
655                 return NULL;
656         }
657
658         fin->fin_dp = (char *)fin->fin_dp + shift;
659         fin->fin_dlen -= shift;
660
661         /*
662          * If we have seen a fragment header, do not set any flags to indicate
663          * the presence of this extension header as it has no impact on the
664          * end result until after it has been defragmented.
665          */
666         if (fin->fin_flx & FI_FRAG)
667                 return hdr;
668
669         for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
670                 if (ip6exthdr[i].ol_val == proto) {
671                         /*
672                          * Most IPv6 extension headers are only allowed once.
673                          */
674                         if ((multiple == 0) &&
675                             ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
676                                 fin->fin_flx |= FI_BAD;
677                                 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
678                         } else
679                                 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
680                         break;
681                 }
682
683         return hdr;
684 }
685
686
687 /* ------------------------------------------------------------------------ */
688 /* Function:    ipf_pr_hopopts6                                             */
689 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
690 /* Parameters:  fin(I) - pointer to packet information                      */
691 /*                                                                          */
692 /* IPv6 Only                                                                */
693 /* This is function checks pending hop by hop options extension header      */
694 /* ------------------------------------------------------------------------ */
695 static INLINE int
696 ipf_pr_hopopts6(fin)
697         fr_info_t *fin;
698 {
699         struct ip6_ext *hdr;
700
701         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
702         if (hdr == NULL)
703                 return IPPROTO_NONE;
704         return hdr->ip6e_nxt;
705 }
706
707
708 /* ------------------------------------------------------------------------ */
709 /* Function:    ipf_pr_mobility6                                            */
710 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
711 /* Parameters:  fin(I) - pointer to packet information                      */
712 /*                                                                          */
713 /* IPv6 Only                                                                */
714 /* This is function checks the IPv6 mobility extension header               */
715 /* ------------------------------------------------------------------------ */
716 static INLINE int
717 ipf_pr_mobility6(fin)
718         fr_info_t *fin;
719 {
720         struct ip6_ext *hdr;
721
722         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
723         if (hdr == NULL)
724                 return IPPROTO_NONE;
725         return hdr->ip6e_nxt;
726 }
727
728
729 /* ------------------------------------------------------------------------ */
730 /* Function:    ipf_pr_routing6                                             */
731 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
732 /* Parameters:  fin(I) - pointer to packet information                      */
733 /*                                                                          */
734 /* IPv6 Only                                                                */
735 /* This is function checks pending routing extension header                 */
736 /* ------------------------------------------------------------------------ */
737 static INLINE int
738 ipf_pr_routing6(fin)
739         fr_info_t *fin;
740 {
741         struct ip6_routing *hdr;
742
743         hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
744         if (hdr == NULL)
745                 return IPPROTO_NONE;
746
747         switch (hdr->ip6r_type)
748         {
749         case 0 :
750                 /*
751                  * Nasty extension header length?
752                  */
753                 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
754                     (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
755                         ipf_main_softc_t *softc = fin->fin_main_soft;
756
757                         fin->fin_flx |= FI_BAD;
758                         DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
759                         LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
760                         return IPPROTO_NONE;
761                 }
762                 break;
763
764         default :
765                 break;
766         }
767
768         return hdr->ip6r_nxt;
769 }
770
771
772 /* ------------------------------------------------------------------------ */
773 /* Function:    ipf_pr_fragment6                                            */
774 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
775 /* Parameters:  fin(I) - pointer to packet information                      */
776 /*                                                                          */
777 /* IPv6 Only                                                                */
778 /* Examine the IPv6 fragment header and extract fragment offset information.*/
779 /*                                                                          */
780 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
781 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
782 /* packets with a fragment header can fit into.  They are as follows:       */
783 /*                                                                          */
784 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
785 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
786 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
787 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
788 /* 5.  [IPV6][0-n EH][FH][data]                                             */
789 /*                                                                          */
790 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
791 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
792 /*                                                                          */
793 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
794 /* scenario in which they happen is in extreme circumstances that are most  */
795 /* likely to be an indication of an attack rather than normal traffic.      */
796 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
797 /* are two rules that can be used to guard against type 3 packets: L4       */
798 /* headers must always be in a packet that has the offset field set to 0    */
799 /* and no packet is allowed to overlay that where offset = 0.               */
800 /* ------------------------------------------------------------------------ */
801 static INLINE int
802 ipf_pr_fragment6(fin)
803         fr_info_t *fin;
804 {
805         ipf_main_softc_t *softc = fin->fin_main_soft;
806         struct ip6_frag *frag;
807
808         fin->fin_flx |= FI_FRAG;
809
810         frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
811         if (frag == NULL) {
812                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
813                 return IPPROTO_NONE;
814         }
815
816         if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
817                 /*
818                  * Any fragment that isn't the last fragment must have its
819                  * length as a multiple of 8.
820                  */
821                 if ((fin->fin_plen & 7) != 0) {
822                         fin->fin_flx |= FI_BAD;
823                         DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
824                 }
825         }
826
827         fin->fin_fraghdr = frag;
828         fin->fin_id = frag->ip6f_ident;
829         fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
830         if (fin->fin_off != 0)
831                 fin->fin_flx |= FI_FRAGBODY;
832
833         /*
834          * Jumbograms aren't handled, so the max. length is 64k
835          */
836         if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
837                   fin->fin_flx |= FI_BAD;
838                   DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
839         }
840
841         /*
842          * We don't know where the transport layer header (or whatever is next
843          * is), as it could be behind destination options (amongst others) so
844          * return the fragment header as the type of packet this is.  Note that
845          * this effectively disables the fragment cache for > 1 protocol at a
846          * time.
847          */
848         return frag->ip6f_nxt;
849 }
850
851
852 /* ------------------------------------------------------------------------ */
853 /* Function:    ipf_pr_dstopts6                                             */
854 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
855 /* Parameters:  fin(I) - pointer to packet information                      */
856 /*                                                                          */
857 /* IPv6 Only                                                                */
858 /* This is function checks pending destination options extension header     */
859 /* ------------------------------------------------------------------------ */
860 static INLINE int
861 ipf_pr_dstopts6(fin)
862         fr_info_t *fin;
863 {
864         ipf_main_softc_t *softc = fin->fin_main_soft;
865         struct ip6_ext *hdr;
866
867         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
868         if (hdr == NULL) {
869                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
870                 return IPPROTO_NONE;
871         }
872         return hdr->ip6e_nxt;
873 }
874
875
876 /* ------------------------------------------------------------------------ */
877 /* Function:    ipf_pr_icmp6                                                */
878 /* Returns:     void                                                        */
879 /* Parameters:  fin(I) - pointer to packet information                      */
880 /*                                                                          */
881 /* IPv6 Only                                                                */
882 /* This routine is mainly concerned with determining the minimum valid size */
883 /* for an ICMPv6 packet.                                                    */
884 /* ------------------------------------------------------------------------ */
885 static INLINE void
886 ipf_pr_icmp6(fin)
887         fr_info_t *fin;
888 {
889         int minicmpsz = sizeof(struct icmp6_hdr);
890         struct icmp6_hdr *icmp6;
891
892         if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
893                 ipf_main_softc_t *softc = fin->fin_main_soft;
894
895                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
896                 return;
897         }
898
899         if (fin->fin_dlen > 1) {
900                 ip6_t *ip6;
901
902                 icmp6 = fin->fin_dp;
903
904                 fin->fin_data[0] = *(u_short *)icmp6;
905
906                 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
907                         fin->fin_flx |= FI_ICMPQUERY;
908
909                 switch (icmp6->icmp6_type)
910                 {
911                 case ICMP6_ECHO_REPLY :
912                 case ICMP6_ECHO_REQUEST :
913                         if (fin->fin_dlen >= 6)
914                                 fin->fin_data[1] = icmp6->icmp6_id;
915                         minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
916                         break;
917
918                 case ICMP6_DST_UNREACH :
919                 case ICMP6_PACKET_TOO_BIG :
920                 case ICMP6_TIME_EXCEEDED :
921                 case ICMP6_PARAM_PROB :
922                         fin->fin_flx |= FI_ICMPERR;
923                         minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
924                         if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
925                                 break;
926
927                         if (M_LEN(fin->fin_m) < fin->fin_plen) {
928                                 if (ipf_coalesce(fin) != 1)
929                                         return;
930                         }
931
932                         if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
933                                 return;
934
935                         /*
936                          * If the destination of this packet doesn't match the
937                          * source of the original packet then this packet is
938                          * not correct.
939                          */
940                         icmp6 = fin->fin_dp;
941                         ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
942                         if (IP6_NEQ(&fin->fin_fi.fi_dst,
943                                     (i6addr_t *)&ip6->ip6_src)) {
944                                 fin->fin_flx |= FI_BAD;
945                                 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
946                         }
947                         break;
948                 default :
949                         break;
950                 }
951         }
952
953         ipf_pr_short6(fin, minicmpsz);
954         if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
955                 u_char p = fin->fin_p;
956
957                 fin->fin_p = IPPROTO_ICMPV6;
958                 ipf_checkv6sum(fin);
959                 fin->fin_p = p;
960         }
961 }
962
963
964 /* ------------------------------------------------------------------------ */
965 /* Function:    ipf_pr_udp6                                                 */
966 /* Returns:     void                                                        */
967 /* Parameters:  fin(I) - pointer to packet information                      */
968 /*                                                                          */
969 /* IPv6 Only                                                                */
970 /* Analyse the packet for IPv6/UDP properties.                              */
971 /* Is not expected to be called for fragmented packets.                     */
972 /* ------------------------------------------------------------------------ */
973 static INLINE void
974 ipf_pr_udp6(fin)
975         fr_info_t *fin;
976 {
977
978         if (ipf_pr_udpcommon(fin) == 0) {
979                 u_char p = fin->fin_p;
980
981                 fin->fin_p = IPPROTO_UDP;
982                 ipf_checkv6sum(fin);
983                 fin->fin_p = p;
984         }
985 }
986
987
988 /* ------------------------------------------------------------------------ */
989 /* Function:    ipf_pr_tcp6                                                 */
990 /* Returns:     void                                                        */
991 /* Parameters:  fin(I) - pointer to packet information                      */
992 /*                                                                          */
993 /* IPv6 Only                                                                */
994 /* Analyse the packet for IPv6/TCP properties.                              */
995 /* Is not expected to be called for fragmented packets.                     */
996 /* ------------------------------------------------------------------------ */
997 static INLINE void
998 ipf_pr_tcp6(fin)
999         fr_info_t *fin;
1000 {
1001
1002         if (ipf_pr_tcpcommon(fin) == 0) {
1003                 u_char p = fin->fin_p;
1004
1005                 fin->fin_p = IPPROTO_TCP;
1006                 ipf_checkv6sum(fin);
1007                 fin->fin_p = p;
1008         }
1009 }
1010
1011
1012 /* ------------------------------------------------------------------------ */
1013 /* Function:    ipf_pr_esp6                                                 */
1014 /* Returns:     void                                                        */
1015 /* Parameters:  fin(I) - pointer to packet information                      */
1016 /*                                                                          */
1017 /* IPv6 Only                                                                */
1018 /* Analyse the packet for ESP properties.                                   */
1019 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1020 /* even though the newer ESP packets must also have a sequence number that  */
1021 /* is 32bits as well, it is not possible(?) to determine the version from a */
1022 /* simple packet header.                                                    */
1023 /* ------------------------------------------------------------------------ */
1024 static INLINE void
1025 ipf_pr_esp6(fin)
1026         fr_info_t *fin;
1027 {
1028
1029         if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030                 ipf_main_softc_t *softc = fin->fin_main_soft;
1031
1032                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033                 return;
1034         }
1035 }
1036
1037
1038 /* ------------------------------------------------------------------------ */
1039 /* Function:    ipf_pr_ah6                                                  */
1040 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1041 /* Parameters:  fin(I) - pointer to packet information                      */
1042 /*                                                                          */
1043 /* IPv6 Only                                                                */
1044 /* Analyse the packet for AH properties.                                    */
1045 /* The minimum length is taken to be the combination of all fields in the   */
1046 /* header being present and no authentication data (null algorithm used.)   */
1047 /* ------------------------------------------------------------------------ */
1048 static INLINE int
1049 ipf_pr_ah6(fin)
1050         fr_info_t *fin;
1051 {
1052         authhdr_t *ah;
1053
1054         fin->fin_flx |= FI_AH;
1055
1056         ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1057         if (ah == NULL) {
1058                 ipf_main_softc_t *softc = fin->fin_main_soft;
1059
1060                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1061                 return IPPROTO_NONE;
1062         }
1063
1064         ipf_pr_short6(fin, sizeof(*ah));
1065
1066         /*
1067          * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1068          * enough data to satisfy ah_next (the very first one.)
1069          */
1070         return ah->ah_next;
1071 }
1072
1073
1074 /* ------------------------------------------------------------------------ */
1075 /* Function:    ipf_pr_gre6                                                 */
1076 /* Returns:     void                                                        */
1077 /* Parameters:  fin(I) - pointer to packet information                      */
1078 /*                                                                          */
1079 /* Analyse the packet for GRE properties.                                   */
1080 /* ------------------------------------------------------------------------ */
1081 static INLINE void
1082 ipf_pr_gre6(fin)
1083         fr_info_t *fin;
1084 {
1085         grehdr_t *gre;
1086
1087         if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1088                 ipf_main_softc_t *softc = fin->fin_main_soft;
1089
1090                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1091                 return;
1092         }
1093
1094         gre = fin->fin_dp;
1095         if (GRE_REV(gre->gr_flags) == 1)
1096                 fin->fin_data[0] = gre->gr_call;
1097 }
1098 #endif  /* USE_INET6 */
1099
1100
1101 /* ------------------------------------------------------------------------ */
1102 /* Function:    ipf_pr_pullup                                               */
1103 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1104 /* Parameters:  fin(I)  - pointer to packet information                     */
1105 /*              plen(I) - length (excluding L3 header) to pullup            */
1106 /*                                                                          */
1107 /* Short inline function to cut down on code duplication to perform a call  */
1108 /* to ipf_pullup to ensure there is the required amount of data,            */
1109 /* consecutively in the packet buffer.                                      */
1110 /*                                                                          */
1111 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1112 /* points to the first byte after the complete layer 3 header, which will   */
1113 /* include all of the known extension headers for IPv6 or options for IPv4. */
1114 /*                                                                          */
1115 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1116 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1117 /* - fin_ip) to what is passed through.                                     */
1118 /* ------------------------------------------------------------------------ */
1119 int
1120 ipf_pr_pullup(fin, plen)
1121         fr_info_t *fin;
1122         int plen;
1123 {
1124         ipf_main_softc_t *softc = fin->fin_main_soft;
1125
1126         if (fin->fin_m != NULL) {
1127                 if (fin->fin_dp != NULL)
1128                         plen += (char *)fin->fin_dp -
1129                                 ((char *)fin->fin_ip + fin->fin_hlen);
1130                 plen += fin->fin_hlen;
1131                 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1132 #if defined(_KERNEL)
1133                         if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1134                                 DT(ipf_pullup_fail);
1135                                 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1136                                 return -1;
1137                         }
1138                         LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1139 #else
1140                         LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1141                         /*
1142                          * Fake ipf_pullup failing
1143                          */
1144                         fin->fin_reason = FRB_PULLUP;
1145                         *fin->fin_mp = NULL;
1146                         fin->fin_m = NULL;
1147                         fin->fin_ip = NULL;
1148                         return -1;
1149 #endif
1150                 }
1151         }
1152         return 0;
1153 }
1154
1155
1156 /* ------------------------------------------------------------------------ */
1157 /* Function:    ipf_pr_short                                                */
1158 /* Returns:     void                                                        */
1159 /* Parameters:  fin(I)  - pointer to packet information                     */
1160 /*              xmin(I) - minimum header size                               */
1161 /*                                                                          */
1162 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1163 /* applying here is that the packet must not be fragmented within the layer */
1164 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1165 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1166 /* entire layer 4 header must be present (min).                             */
1167 /* ------------------------------------------------------------------------ */
1168 static INLINE void
1169 ipf_pr_short(fin, xmin)
1170         fr_info_t *fin;
1171         int xmin;
1172 {
1173
1174         if (fin->fin_off == 0) {
1175                 if (fin->fin_dlen < xmin)
1176                         fin->fin_flx |= FI_SHORT;
1177         } else if (fin->fin_off < xmin) {
1178                 fin->fin_flx |= FI_SHORT;
1179         }
1180 }
1181
1182
1183 /* ------------------------------------------------------------------------ */
1184 /* Function:    ipf_pr_icmp                                                 */
1185 /* Returns:     void                                                        */
1186 /* Parameters:  fin(I) - pointer to packet information                      */
1187 /*                                                                          */
1188 /* IPv4 Only                                                                */
1189 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1190 /* except extrememly bad packets, both type and code will be present.       */
1191 /* The expected minimum size of an ICMP packet is very much dependent on    */
1192 /* the type of it.                                                          */
1193 /*                                                                          */
1194 /* XXX - other ICMP sanity checks?                                          */
1195 /* ------------------------------------------------------------------------ */
1196 static INLINE void
1197 ipf_pr_icmp(fin)
1198         fr_info_t *fin;
1199 {
1200         ipf_main_softc_t *softc = fin->fin_main_soft;
1201         int minicmpsz = sizeof(struct icmp);
1202         icmphdr_t *icmp;
1203         ip_t *oip;
1204
1205         ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1206
1207         if (fin->fin_off != 0) {
1208                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1209                 return;
1210         }
1211
1212         if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1213                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1214                 return;
1215         }
1216
1217         icmp = fin->fin_dp;
1218
1219         fin->fin_data[0] = *(u_short *)icmp;
1220         fin->fin_data[1] = icmp->icmp_id;
1221
1222         switch (icmp->icmp_type)
1223         {
1224         case ICMP_ECHOREPLY :
1225         case ICMP_ECHO :
1226         /* Router discovery messaes - RFC 1256 */
1227         case ICMP_ROUTERADVERT :
1228         case ICMP_ROUTERSOLICIT :
1229                 fin->fin_flx |= FI_ICMPQUERY;
1230                 minicmpsz = ICMP_MINLEN;
1231                 break;
1232         /*
1233          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1234          * 3 * timestamp(3 * 4)
1235          */
1236         case ICMP_TSTAMP :
1237         case ICMP_TSTAMPREPLY :
1238                 fin->fin_flx |= FI_ICMPQUERY;
1239                 minicmpsz = 20;
1240                 break;
1241         /*
1242          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1243          * mask(4)
1244          */
1245         case ICMP_IREQ :
1246         case ICMP_IREQREPLY :
1247         case ICMP_MASKREQ :
1248         case ICMP_MASKREPLY :
1249                 fin->fin_flx |= FI_ICMPQUERY;
1250                 minicmpsz = 12;
1251                 break;
1252         /*
1253          * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1254          */
1255         case ICMP_UNREACH :
1256 #ifdef icmp_nextmtu
1257                 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1258                         if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1259                                 fin->fin_flx |= FI_BAD;
1260                                 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1261                         }
1262                 }
1263 #endif
1264                 /* FALLTHROUGH */
1265         case ICMP_SOURCEQUENCH :
1266         case ICMP_REDIRECT :
1267         case ICMP_TIMXCEED :
1268         case ICMP_PARAMPROB :
1269                 fin->fin_flx |= FI_ICMPERR;
1270                 if (ipf_coalesce(fin) != 1) {
1271                         LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1272                         return;
1273                 }
1274
1275                 /*
1276                  * ICMP error packets should not be generated for IP
1277                  * packets that are a fragment that isn't the first
1278                  * fragment.
1279                  */
1280                 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1281                 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1282                         fin->fin_flx |= FI_BAD;
1283                         DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1284                 }
1285
1286                 /*
1287                  * If the destination of this packet doesn't match the
1288                  * source of the original packet then this packet is
1289                  * not correct.
1290                  */
1291                 if (oip->ip_src.s_addr != fin->fin_daddr) {
1292                         fin->fin_flx |= FI_BAD;
1293                         DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1294                 }
1295                 break;
1296         default :
1297                 break;
1298         }
1299
1300         ipf_pr_short(fin, minicmpsz);
1301
1302         ipf_checkv4sum(fin);
1303 }
1304
1305
1306 /* ------------------------------------------------------------------------ */
1307 /* Function:    ipf_pr_tcpcommon                                            */
1308 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1309 /* Parameters:  fin(I) - pointer to packet information                      */
1310 /*                                                                          */
1311 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1312 /* and make some checks with how they interact with other fields.           */
1313 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1314 /* valid and mark the packet as bad if not.                                 */
1315 /* ------------------------------------------------------------------------ */
1316 static INLINE int
1317 ipf_pr_tcpcommon(fin)
1318         fr_info_t *fin;
1319 {
1320         ipf_main_softc_t *softc = fin->fin_main_soft;
1321         int flags, tlen;
1322         tcphdr_t *tcp;
1323
1324         fin->fin_flx |= FI_TCPUDP;
1325         if (fin->fin_off != 0) {
1326                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1327                 return 0;
1328         }
1329
1330         if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1331                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1332                 return -1;
1333         }
1334
1335         tcp = fin->fin_dp;
1336         if (fin->fin_dlen > 3) {
1337                 fin->fin_sport = ntohs(tcp->th_sport);
1338                 fin->fin_dport = ntohs(tcp->th_dport);
1339         }
1340
1341         if ((fin->fin_flx & FI_SHORT) != 0) {
1342                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1343                 return 1;
1344         }
1345
1346         /*
1347          * Use of the TCP data offset *must* result in a value that is at
1348          * least the same size as the TCP header.
1349          */
1350         tlen = TCP_OFF(tcp) << 2;
1351         if (tlen < sizeof(tcphdr_t)) {
1352                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1353                 fin->fin_flx |= FI_BAD;
1354                 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1355                 return 1;
1356         }
1357
1358         flags = tcp->th_flags;
1359         fin->fin_tcpf = tcp->th_flags;
1360
1361         /*
1362          * If the urgent flag is set, then the urgent pointer must
1363          * also be set and vice versa.  Good TCP packets do not have
1364          * just one of these set.
1365          */
1366         if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1367                 fin->fin_flx |= FI_BAD;
1368                 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1369 #if 0
1370         } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1371                 /*
1372                  * Ignore this case (#if 0) as it shows up in "real"
1373                  * traffic with bogus values in the urgent pointer field.
1374                  */
1375                 fin->fin_flx |= FI_BAD;
1376                 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1377 #endif
1378         } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1379                    ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1380                 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1381                 fin->fin_flx |= FI_BAD;
1382                 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1383 #if 1
1384         } else if (((flags & TH_SYN) != 0) &&
1385                    ((flags & (TH_URG|TH_PUSH)) != 0)) {
1386                 /*
1387                  * SYN with URG and PUSH set is not for normal TCP but it is
1388                  * possible(?) with T/TCP...but who uses T/TCP?
1389                  */
1390                 fin->fin_flx |= FI_BAD;
1391                 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1392 #endif
1393         } else if (!(flags & TH_ACK)) {
1394                 /*
1395                  * If the ack bit isn't set, then either the SYN or
1396                  * RST bit must be set.  If the SYN bit is set, then
1397                  * we expect the ACK field to be 0.  If the ACK is
1398                  * not set and if URG, PSH or FIN are set, consdier
1399                  * that to indicate a bad TCP packet.
1400                  */
1401                 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1402                         /*
1403                          * Cisco PIX sets the ACK field to a random value.
1404                          * In light of this, do not set FI_BAD until a patch
1405                          * is available from Cisco to ensure that
1406                          * interoperability between existing systems is
1407                          * achieved.
1408                          */
1409                         /*fin->fin_flx |= FI_BAD*/;
1410                         /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1411                 } else if (!(flags & (TH_RST|TH_SYN))) {
1412                         fin->fin_flx |= FI_BAD;
1413                         DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1414                 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1415                         fin->fin_flx |= FI_BAD;
1416                         DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1417                 }
1418         }
1419         if (fin->fin_flx & FI_BAD) {
1420                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1421                 return 1;
1422         }
1423
1424         /*
1425          * At this point, it's not exactly clear what is to be gained by
1426          * marking up which TCP options are and are not present.  The one we
1427          * are most interested in is the TCP window scale.  This is only in
1428          * a SYN packet [RFC1323] so we don't need this here...?
1429          * Now if we were to analyse the header for passive fingerprinting,
1430          * then that might add some weight to adding this...
1431          */
1432         if (tlen == sizeof(tcphdr_t)) {
1433                 return 0;
1434         }
1435
1436         if (ipf_pr_pullup(fin, tlen) == -1) {
1437                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1438                 return -1;
1439         }
1440
1441 #if 0
1442         tcp = fin->fin_dp;
1443         ip = fin->fin_ip;
1444         s = (u_char *)(tcp + 1);
1445         off = IP_HL(ip) << 2;
1446 # ifdef _KERNEL
1447         if (fin->fin_mp != NULL) {
1448                 mb_t *m = *fin->fin_mp;
1449
1450                 if (off + tlen > M_LEN(m))
1451                         return;
1452         }
1453 # endif
1454         for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1455                 opt = *s;
1456                 if (opt == '\0')
1457                         break;
1458                 else if (opt == TCPOPT_NOP)
1459                         ol = 1;
1460                 else {
1461                         if (tlen < 2)
1462                                 break;
1463                         ol = (int)*(s + 1);
1464                         if (ol < 2 || ol > tlen)
1465                                 break;
1466                 }
1467
1468                 for (i = 9, mv = 4; mv >= 0; ) {
1469                         op = ipopts + i;
1470                         if (opt == (u_char)op->ol_val) {
1471                                 optmsk |= op->ol_bit;
1472                                 break;
1473                         }
1474                 }
1475                 tlen -= ol;
1476                 s += ol;
1477         }
1478 #endif /* 0 */
1479
1480         return 0;
1481 }
1482
1483
1484
1485 /* ------------------------------------------------------------------------ */
1486 /* Function:    ipf_pr_udpcommon                                            */
1487 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1488 /* Parameters:  fin(I) - pointer to packet information                      */
1489 /*                                                                          */
1490 /* Extract the UDP source and destination ports, if present.  If compiled   */
1491 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1492 /* ------------------------------------------------------------------------ */
1493 static INLINE int
1494 ipf_pr_udpcommon(fin)
1495         fr_info_t *fin;
1496 {
1497         udphdr_t *udp;
1498
1499         fin->fin_flx |= FI_TCPUDP;
1500
1501         if (!fin->fin_off && (fin->fin_dlen > 3)) {
1502                 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1503                         ipf_main_softc_t *softc = fin->fin_main_soft;
1504
1505                         fin->fin_flx |= FI_SHORT;
1506                         LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1507                         return 1;
1508                 }
1509
1510                 udp = fin->fin_dp;
1511
1512                 fin->fin_sport = ntohs(udp->uh_sport);
1513                 fin->fin_dport = ntohs(udp->uh_dport);
1514         }
1515
1516         return 0;
1517 }
1518
1519
1520 /* ------------------------------------------------------------------------ */
1521 /* Function:    ipf_pr_tcp                                                  */
1522 /* Returns:     void                                                        */
1523 /* Parameters:  fin(I) - pointer to packet information                      */
1524 /*                                                                          */
1525 /* IPv4 Only                                                                */
1526 /* Analyse the packet for IPv4/TCP properties.                              */
1527 /* ------------------------------------------------------------------------ */
1528 static INLINE void
1529 ipf_pr_tcp(fin)
1530         fr_info_t *fin;
1531 {
1532
1533         ipf_pr_short(fin, sizeof(tcphdr_t));
1534
1535         if (ipf_pr_tcpcommon(fin) == 0)
1536                 ipf_checkv4sum(fin);
1537 }
1538
1539
1540 /* ------------------------------------------------------------------------ */
1541 /* Function:    ipf_pr_udp                                                  */
1542 /* Returns:     void                                                        */
1543 /* Parameters:  fin(I) - pointer to packet information                      */
1544 /*                                                                          */
1545 /* IPv4 Only                                                                */
1546 /* Analyse the packet for IPv4/UDP properties.                              */
1547 /* ------------------------------------------------------------------------ */
1548 static INLINE void
1549 ipf_pr_udp(fin)
1550         fr_info_t *fin;
1551 {
1552
1553         ipf_pr_short(fin, sizeof(udphdr_t));
1554
1555         if (ipf_pr_udpcommon(fin) == 0)
1556                 ipf_checkv4sum(fin);
1557 }
1558
1559
1560 /* ------------------------------------------------------------------------ */
1561 /* Function:    ipf_pr_esp                                                  */
1562 /* Returns:     void                                                        */
1563 /* Parameters:  fin(I) - pointer to packet information                      */
1564 /*                                                                          */
1565 /* Analyse the packet for ESP properties.                                   */
1566 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1567 /* even though the newer ESP packets must also have a sequence number that  */
1568 /* is 32bits as well, it is not possible(?) to determine the version from a */
1569 /* simple packet header.                                                    */
1570 /* ------------------------------------------------------------------------ */
1571 static INLINE void
1572 ipf_pr_esp(fin)
1573         fr_info_t *fin;
1574 {
1575
1576         if (fin->fin_off == 0) {
1577                 ipf_pr_short(fin, 8);
1578                 if (ipf_pr_pullup(fin, 8) == -1) {
1579                         ipf_main_softc_t *softc = fin->fin_main_soft;
1580
1581                         LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1582                 }
1583         }
1584 }
1585
1586
1587 /* ------------------------------------------------------------------------ */
1588 /* Function:    ipf_pr_ah                                                   */
1589 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1590 /* Parameters:  fin(I) - pointer to packet information                      */
1591 /*                                                                          */
1592 /* Analyse the packet for AH properties.                                    */
1593 /* The minimum length is taken to be the combination of all fields in the   */
1594 /* header being present and no authentication data (null algorithm used.)   */
1595 /* ------------------------------------------------------------------------ */
1596 static INLINE int
1597 ipf_pr_ah(fin)
1598         fr_info_t *fin;
1599 {
1600         ipf_main_softc_t *softc = fin->fin_main_soft;
1601         authhdr_t *ah;
1602         int len;
1603
1604         fin->fin_flx |= FI_AH;
1605         ipf_pr_short(fin, sizeof(*ah));
1606
1607         if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1608                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1609                 return IPPROTO_NONE;
1610         }
1611
1612         if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1613                 DT(fr_v4_ah_pullup_1);
1614                 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1615                 return IPPROTO_NONE;
1616         }
1617
1618         ah = (authhdr_t *)fin->fin_dp;
1619
1620         len = (ah->ah_plen + 2) << 2;
1621         ipf_pr_short(fin, len);
1622         if (ipf_pr_pullup(fin, len) == -1) {
1623                 DT(fr_v4_ah_pullup_2);
1624                 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1625                 return IPPROTO_NONE;
1626         }
1627
1628         /*
1629          * Adjust fin_dp and fin_dlen for skipping over the authentication
1630          * header.
1631          */
1632         fin->fin_dp = (char *)fin->fin_dp + len;
1633         fin->fin_dlen -= len;
1634         return ah->ah_next;
1635 }
1636
1637
1638 /* ------------------------------------------------------------------------ */
1639 /* Function:    ipf_pr_gre                                                  */
1640 /* Returns:     void                                                        */
1641 /* Parameters:  fin(I) - pointer to packet information                      */
1642 /*                                                                          */
1643 /* Analyse the packet for GRE properties.                                   */
1644 /* ------------------------------------------------------------------------ */
1645 static INLINE void
1646 ipf_pr_gre(fin)
1647         fr_info_t *fin;
1648 {
1649         ipf_main_softc_t *softc = fin->fin_main_soft;
1650         grehdr_t *gre;
1651
1652         ipf_pr_short(fin, sizeof(grehdr_t));
1653
1654         if (fin->fin_off != 0) {
1655                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1656                 return;
1657         }
1658
1659         if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1660                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1661                 return;
1662         }
1663
1664         gre = fin->fin_dp;
1665         if (GRE_REV(gre->gr_flags) == 1)
1666                 fin->fin_data[0] = gre->gr_call;
1667 }
1668
1669
1670 /* ------------------------------------------------------------------------ */
1671 /* Function:    ipf_pr_ipv4hdr                                              */
1672 /* Returns:     void                                                        */
1673 /* Parameters:  fin(I) - pointer to packet information                      */
1674 /*                                                                          */
1675 /* IPv4 Only                                                                */
1676 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1677 /* Check all options present and flag their presence if any exist.          */
1678 /* ------------------------------------------------------------------------ */
1679 static INLINE void
1680 ipf_pr_ipv4hdr(fin)
1681         fr_info_t *fin;
1682 {
1683         u_short optmsk = 0, secmsk = 0, auth = 0;
1684         int hlen, ol, mv, p, i;
1685         const struct optlist *op;
1686         u_char *s, opt;
1687         u_short off;
1688         fr_ip_t *fi;
1689         ip_t *ip;
1690
1691         fi = &fin->fin_fi;
1692         hlen = fin->fin_hlen;
1693
1694         ip = fin->fin_ip;
1695         p = ip->ip_p;
1696         fi->fi_p = p;
1697         fin->fin_crc = p;
1698         fi->fi_tos = ip->ip_tos;
1699         fin->fin_id = ip->ip_id;
1700         off = ntohs(ip->ip_off);
1701
1702         /* Get both TTL and protocol */
1703         fi->fi_p = ip->ip_p;
1704         fi->fi_ttl = ip->ip_ttl;
1705
1706         /* Zero out bits not used in IPv6 address */
1707         fi->fi_src.i6[1] = 0;
1708         fi->fi_src.i6[2] = 0;
1709         fi->fi_src.i6[3] = 0;
1710         fi->fi_dst.i6[1] = 0;
1711         fi->fi_dst.i6[2] = 0;
1712         fi->fi_dst.i6[3] = 0;
1713
1714         fi->fi_saddr = ip->ip_src.s_addr;
1715         fin->fin_crc += fi->fi_saddr;
1716         fi->fi_daddr = ip->ip_dst.s_addr;
1717         fin->fin_crc += fi->fi_daddr;
1718         if (IN_CLASSD(ntohl(fi->fi_daddr)))
1719                 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1720
1721         /*
1722          * set packet attribute flags based on the offset and
1723          * calculate the byte offset that it represents.
1724          */
1725         off &= IP_MF|IP_OFFMASK;
1726         if (off == 1 && p == IPPROTO_TCP) {
1727                 fin->fin_flx |= FI_SHORT;       /* RFC 3128 */
1728                 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1729         }
1730         if (off != 0) {
1731                 int morefrag = off & IP_MF;
1732
1733                 fi->fi_flx |= FI_FRAG;
1734                 off &= IP_OFFMASK;
1735                 fin->fin_flx |= FI_FRAGBODY;
1736                 off <<= 3;
1737                 if ((off + fin->fin_dlen > 65535) ||
1738                     (fin->fin_dlen == 0) ||
1739                     ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1740                         /*
1741                          * The length of the packet, starting at its
1742                          * offset cannot exceed 65535 (0xffff) as the
1743                          * length of an IP packet is only 16 bits.
1744                          *
1745                          * Any fragment that isn't the last fragment
1746                          * must have a length greater than 0 and it
1747                          * must be an even multiple of 8.
1748                          */
1749                         fi->fi_flx |= FI_BAD;
1750                         DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1751                 }
1752         }
1753         fin->fin_off = off;
1754
1755         /*
1756          * Call per-protocol setup and checking
1757          */
1758         if (p == IPPROTO_AH) {
1759                 /*
1760                  * Treat AH differently because we expect there to be another
1761                  * layer 4 header after it.
1762                  */
1763                 p = ipf_pr_ah(fin);
1764         }
1765
1766         switch (p)
1767         {
1768         case IPPROTO_UDP :
1769                 ipf_pr_udp(fin);
1770                 break;
1771         case IPPROTO_TCP :
1772                 ipf_pr_tcp(fin);
1773                 break;
1774         case IPPROTO_ICMP :
1775                 ipf_pr_icmp(fin);
1776                 break;
1777         case IPPROTO_ESP :
1778                 ipf_pr_esp(fin);
1779                 break;
1780         case IPPROTO_GRE :
1781                 ipf_pr_gre(fin);
1782                 break;
1783         }
1784
1785         ip = fin->fin_ip;
1786         if (ip == NULL)
1787                 return;
1788
1789         /*
1790          * If it is a standard IP header (no options), set the flag fields
1791          * which relate to options to 0.
1792          */
1793         if (hlen == sizeof(*ip)) {
1794                 fi->fi_optmsk = 0;
1795                 fi->fi_secmsk = 0;
1796                 fi->fi_auth = 0;
1797                 return;
1798         }
1799
1800         /*
1801          * So the IP header has some IP options attached.  Walk the entire
1802          * list of options present with this packet and set flags to indicate
1803          * which ones are here and which ones are not.  For the somewhat out
1804          * of date and obscure security classification options, set a flag to
1805          * represent which classification is present.
1806          */
1807         fi->fi_flx |= FI_OPTIONS;
1808
1809         for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1810                 opt = *s;
1811                 if (opt == '\0')
1812                         break;
1813                 else if (opt == IPOPT_NOP)
1814                         ol = 1;
1815                 else {
1816                         if (hlen < 2)
1817                                 break;
1818                         ol = (int)*(s + 1);
1819                         if (ol < 2 || ol > hlen)
1820                                 break;
1821                 }
1822                 for (i = 9, mv = 4; mv >= 0; ) {
1823                         op = ipopts + i;
1824
1825                         if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1826                                 u_32_t doi;
1827
1828                                 switch (opt)
1829                                 {
1830                                 case IPOPT_SECURITY :
1831                                         if (optmsk & op->ol_bit) {
1832                                                 fin->fin_flx |= FI_BAD;
1833                                                 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1834                                         } else {
1835                                                 doi = ipf_checkripso(s);
1836                                                 secmsk = doi >> 16;
1837                                                 auth = doi & 0xffff;
1838                                         }
1839                                         break;
1840
1841                                 case IPOPT_CIPSO :
1842
1843                                         if (optmsk & op->ol_bit) {
1844                                                 fin->fin_flx |= FI_BAD;
1845                                                 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1846                                         } else {
1847                                                 doi = ipf_checkcipso(fin,
1848                                                                      s, ol);
1849                                                 secmsk = doi >> 16;
1850                                                 auth = doi & 0xffff;
1851                                         }
1852                                         break;
1853                                 }
1854                                 optmsk |= op->ol_bit;
1855                         }
1856
1857                         if (opt < op->ol_val)
1858                                 i -= mv;
1859                         else
1860                                 i += mv;
1861                         mv--;
1862                 }
1863                 hlen -= ol;
1864                 s += ol;
1865         }
1866
1867         /*
1868          *
1869          */
1870         if (auth && !(auth & 0x0100))
1871                 auth &= 0xff00;
1872         fi->fi_optmsk = optmsk;
1873         fi->fi_secmsk = secmsk;
1874         fi->fi_auth = auth;
1875 }
1876
1877
1878 /* ------------------------------------------------------------------------ */
1879 /* Function:    ipf_checkripso                                              */
1880 /* Returns:     void                                                        */
1881 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1882 /*                                                                          */
1883 /* ------------------------------------------------------------------------ */
1884 static u_32_t
1885 ipf_checkripso(s)
1886         u_char *s;
1887 {
1888         const struct optlist *sp;
1889         u_short secmsk = 0, auth = 0;
1890         u_char sec;
1891         int j, m;
1892
1893         sec = *(s + 2); /* classification */
1894         for (j = 3, m = 2; m >= 0; ) {
1895                 sp = secopt + j;
1896                 if (sec == sp->ol_val) {
1897                         secmsk |= sp->ol_bit;
1898                         auth = *(s + 3);
1899                         auth *= 256;
1900                         auth += *(s + 4);
1901                         break;
1902                 }
1903                 if (sec < sp->ol_val)
1904                         j -= m;
1905                 else
1906                         j += m;
1907                 m--;
1908         }
1909
1910         return (secmsk << 16) | auth;
1911 }
1912
1913
1914 /* ------------------------------------------------------------------------ */
1915 /* Function:    ipf_checkcipso                                              */
1916 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1917 /* Parameters:  fin(IO) - pointer to packet information                     */
1918 /*              s(I)    - pointer to start of CIPSO option                  */
1919 /*              ol(I)   - length of CIPSO option field                      */
1920 /*                                                                          */
1921 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1922 /* header and returns that whilst also storing the highest sensitivity      */
1923 /* value found in the fr_info_t structure.                                  */
1924 /*                                                                          */
1925 /* No attempt is made to extract the category bitmaps as these are defined  */
1926 /* by the user (rather than the protocol) and can be rather numerous on the */
1927 /* end nodes.                                                               */
1928 /* ------------------------------------------------------------------------ */
1929 static u_32_t
1930 ipf_checkcipso(fin, s, ol)
1931         fr_info_t *fin;
1932         u_char *s;
1933         int ol;
1934 {
1935         ipf_main_softc_t *softc = fin->fin_main_soft;
1936         fr_ip_t *fi;
1937         u_32_t doi;
1938         u_char *t, tag, tlen, sensitivity;
1939         int len;
1940
1941         if (ol < 6 || ol > 40) {
1942                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1943                 fin->fin_flx |= FI_BAD;
1944                 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1945                 return 0;
1946         }
1947
1948         fi = &fin->fin_fi;
1949         fi->fi_sensitivity = 0;
1950         /*
1951          * The DOI field MUST be there.
1952          */
1953         bcopy(s + 2, &doi, sizeof(doi));
1954
1955         t = (u_char *)s + 6;
1956         for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1957                 tag = *t;
1958                 tlen = *(t + 1);
1959                 if (tlen > len || tlen < 4 || tlen > 34) {
1960                         LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1961                         fin->fin_flx |= FI_BAD;
1962                         DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1963                         return 0;
1964                 }
1965
1966                 sensitivity = 0;
1967                 /*
1968                  * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1969                  * draft (16 July 1992) that has expired.
1970                  */
1971                 if (tag == 0) {
1972                         fin->fin_flx |= FI_BAD;
1973                         DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1974                         continue;
1975                 } else if (tag == 1) {
1976                         if (*(t + 2) != 0) {
1977                                 fin->fin_flx |= FI_BAD;
1978                                 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1979                                 continue;
1980                         }
1981                         sensitivity = *(t + 3);
1982                         /* Category bitmap for categories 0-239 */
1983
1984                 } else if (tag == 4) {
1985                         if (*(t + 2) != 0) {
1986                                 fin->fin_flx |= FI_BAD;
1987                                 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1988                                 continue;
1989                         }
1990                         sensitivity = *(t + 3);
1991                         /* Enumerated categories, 16bits each, upto 15 */
1992
1993                 } else if (tag == 5) {
1994                         if (*(t + 2) != 0) {
1995                                 fin->fin_flx |= FI_BAD;
1996                                 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1997                                 continue;
1998                         }
1999                         sensitivity = *(t + 3);
2000                         /* Range of categories (2*16bits), up to 7 pairs */
2001
2002                 } else if (tag > 127) {
2003                         /* Custom defined DOI */
2004                         ;
2005                 } else {
2006                         fin->fin_flx |= FI_BAD;
2007                         DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2008                         continue;
2009                 }
2010
2011                 if (sensitivity > fi->fi_sensitivity)
2012                         fi->fi_sensitivity = sensitivity;
2013         }
2014
2015         return doi;
2016 }
2017
2018
2019 /* ------------------------------------------------------------------------ */
2020 /* Function:    ipf_makefrip                                                */
2021 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2022 /* Parameters:  hlen(I) - length of IP packet header                        */
2023 /*              ip(I)   - pointer to the IP header                          */
2024 /*              fin(IO) - pointer to packet information                     */
2025 /*                                                                          */
2026 /* Compact the IP header into a structure which contains just the info.     */
2027 /* which is useful for comparing IP headers with and store this information */
2028 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2029 /* this function will be called with either an IPv4 or IPv6 packet.         */
2030 /* ------------------------------------------------------------------------ */
2031 int
2032 ipf_makefrip(hlen, ip, fin)
2033         int hlen;
2034         ip_t *ip;
2035         fr_info_t *fin;
2036 {
2037         ipf_main_softc_t *softc = fin->fin_main_soft;
2038         int v;
2039
2040         fin->fin_depth = 0;
2041         fin->fin_hlen = (u_short)hlen;
2042         fin->fin_ip = ip;
2043         fin->fin_rule = 0xffffffff;
2044         fin->fin_group[0] = -1;
2045         fin->fin_group[1] = '\0';
2046         fin->fin_dp = (char *)ip + hlen;
2047
2048         v = fin->fin_v;
2049         if (v == 4) {
2050                 fin->fin_plen = ntohs(ip->ip_len);
2051                 fin->fin_dlen = fin->fin_plen - hlen;
2052                 ipf_pr_ipv4hdr(fin);
2053 #ifdef  USE_INET6
2054         } else if (v == 6) {
2055                 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2056                 fin->fin_dlen = fin->fin_plen;
2057                 fin->fin_plen += hlen;
2058
2059                 ipf_pr_ipv6hdr(fin);
2060 #endif
2061         }
2062         if (fin->fin_ip == NULL) {
2063                 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2064                 return -1;
2065         }
2066         return 0;
2067 }
2068
2069
2070 /* ------------------------------------------------------------------------ */
2071 /* Function:    ipf_portcheck                                               */
2072 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2073 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2074 /*              pop(I) - port number to evaluate                            */
2075 /*                                                                          */
2076 /* Perform a comparison of a port number against some other(s), using a     */
2077 /* structure with compare information stored in it.                         */
2078 /* ------------------------------------------------------------------------ */
2079 static INLINE int
2080 ipf_portcheck(frp, pop)
2081         frpcmp_t *frp;
2082         u_32_t pop;
2083 {
2084         int err = 1;
2085         u_32_t po;
2086
2087         po = frp->frp_port;
2088
2089         /*
2090          * Do opposite test to that required and continue if that succeeds.
2091          */
2092         switch (frp->frp_cmp)
2093         {
2094         case FR_EQUAL :
2095                 if (pop != po) /* EQUAL */
2096                         err = 0;
2097                 break;
2098         case FR_NEQUAL :
2099                 if (pop == po) /* NOTEQUAL */
2100                         err = 0;
2101                 break;
2102         case FR_LESST :
2103                 if (pop >= po) /* LESSTHAN */
2104                         err = 0;
2105                 break;
2106         case FR_GREATERT :
2107                 if (pop <= po) /* GREATERTHAN */
2108                         err = 0;
2109                 break;
2110         case FR_LESSTE :
2111                 if (pop > po) /* LT or EQ */
2112                         err = 0;
2113                 break;
2114         case FR_GREATERTE :
2115                 if (pop < po) /* GT or EQ */
2116                         err = 0;
2117                 break;
2118         case FR_OUTRANGE :
2119                 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2120                         err = 0;
2121                 break;
2122         case FR_INRANGE :
2123                 if (pop <= po || pop >= frp->frp_top) /* In range */
2124                         err = 0;
2125                 break;
2126         case FR_INCRANGE :
2127                 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2128                         err = 0;
2129                 break;
2130         default :
2131                 break;
2132         }
2133         return err;
2134 }
2135
2136
2137 /* ------------------------------------------------------------------------ */
2138 /* Function:    ipf_tcpudpchk                                               */
2139 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2140 /* Parameters:  fda(I) - pointer to packet information                      */
2141 /*              ft(I)  - pointer to structure with comparison data          */
2142 /*                                                                          */
2143 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2144 /* structure containing information that we want to match against.          */
2145 /* ------------------------------------------------------------------------ */
2146 int
2147 ipf_tcpudpchk(fi, ft)
2148         fr_ip_t *fi;
2149         frtuc_t *ft;
2150 {
2151         int err = 1;
2152
2153         /*
2154          * Both ports should *always* be in the first fragment.
2155          * So far, I cannot find any cases where they can not be.
2156          *
2157          * compare destination ports
2158          */
2159         if (ft->ftu_dcmp)
2160                 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2161
2162         /*
2163          * compare source ports
2164          */
2165         if (err && ft->ftu_scmp)
2166                 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2167
2168         /*
2169          * If we don't have all the TCP/UDP header, then how can we
2170          * expect to do any sort of match on it ?  If we were looking for
2171          * TCP flags, then NO match.  If not, then match (which should
2172          * satisfy the "short" class too).
2173          */
2174         if (err && (fi->fi_p == IPPROTO_TCP)) {
2175                 if (fi->fi_flx & FI_SHORT)
2176                         return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2177                 /*
2178                  * Match the flags ?  If not, abort this match.
2179                  */
2180                 if (ft->ftu_tcpfm &&
2181                     ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2182                         FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2183                                  ft->ftu_tcpfm, ft->ftu_tcpf));
2184                         err = 0;
2185                 }
2186         }
2187         return err;
2188 }
2189
2190
2191 /* ------------------------------------------------------------------------ */
2192 /* Function:    ipf_check_ipf                                               */
2193 /* Returns:     int - 0 == match, else no match                             */
2194 /* Parameters:  fin(I)     - pointer to packet information                  */
2195 /*              fr(I)      - pointer to filter rule                         */
2196 /*              portcmp(I) - flag indicating whether to attempt matching on */
2197 /*                           TCP/UDP port data.                             */
2198 /*                                                                          */
2199 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2200 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2201 /* this function.                                                           */
2202 /* ------------------------------------------------------------------------ */
2203 static INLINE int
2204 ipf_check_ipf(fin, fr, portcmp)
2205         fr_info_t *fin;
2206         frentry_t *fr;
2207         int portcmp;
2208 {
2209         u_32_t  *ld, *lm, *lip;
2210         fripf_t *fri;
2211         fr_ip_t *fi;
2212         int i;
2213
2214         fi = &fin->fin_fi;
2215         fri = fr->fr_ipf;
2216         lip = (u_32_t *)fi;
2217         lm = (u_32_t *)&fri->fri_mip;
2218         ld = (u_32_t *)&fri->fri_ip;
2219
2220         /*
2221          * first 32 bits to check coversion:
2222          * IP version, TOS, TTL, protocol
2223          */
2224         i = ((*lip & *lm) != *ld);
2225         FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2226                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2227         if (i)
2228                 return 1;
2229
2230         /*
2231          * Next 32 bits is a constructed bitmask indicating which IP options
2232          * are present (if any) in this packet.
2233          */
2234         lip++, lm++, ld++;
2235         i = ((*lip & *lm) != *ld);
2236         FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2237                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2238         if (i != 0)
2239                 return 1;
2240
2241         lip++, lm++, ld++;
2242         /*
2243          * Unrolled loops (4 each, for 32 bits) for address checks.
2244          */
2245         /*
2246          * Check the source address.
2247          */
2248         if (fr->fr_satype == FRI_LOOKUP) {
2249                 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2250                                       fi->fi_v, lip, fin->fin_plen);
2251                 if (i == -1)
2252                         return 1;
2253                 lip += 3;
2254                 lm += 3;
2255                 ld += 3;
2256         } else {
2257                 i = ((*lip & *lm) != *ld);
2258                 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2259                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2260                 if (fi->fi_v == 6) {
2261                         lip++, lm++, ld++;
2262                         i |= ((*lip & *lm) != *ld);
2263                         FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2264                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2265                         lip++, lm++, ld++;
2266                         i |= ((*lip & *lm) != *ld);
2267                         FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2268                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2269                         lip++, lm++, ld++;
2270                         i |= ((*lip & *lm) != *ld);
2271                         FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2272                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2273                 } else {
2274                         lip += 3;
2275                         lm += 3;
2276                         ld += 3;
2277                 }
2278         }
2279         i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2280         if (i != 0)
2281                 return 1;
2282
2283         /*
2284          * Check the destination address.
2285          */
2286         lip++, lm++, ld++;
2287         if (fr->fr_datype == FRI_LOOKUP) {
2288                 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2289                                       fi->fi_v, lip, fin->fin_plen);
2290                 if (i == -1)
2291                         return 1;
2292                 lip += 3;
2293                 lm += 3;
2294                 ld += 3;
2295         } else {
2296                 i = ((*lip & *lm) != *ld);
2297                 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2298                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2299                 if (fi->fi_v == 6) {
2300                         lip++, lm++, ld++;
2301                         i |= ((*lip & *lm) != *ld);
2302                         FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2303                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2304                         lip++, lm++, ld++;
2305                         i |= ((*lip & *lm) != *ld);
2306                         FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2307                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2308                         lip++, lm++, ld++;
2309                         i |= ((*lip & *lm) != *ld);
2310                         FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2311                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2312                 } else {
2313                         lip += 3;
2314                         lm += 3;
2315                         ld += 3;
2316                 }
2317         }
2318         i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2319         if (i != 0)
2320                 return 1;
2321         /*
2322          * IP addresses matched.  The next 32bits contains:
2323          * mast of old IP header security & authentication bits.
2324          */
2325         lip++, lm++, ld++;
2326         i = (*ld - (*lip & *lm));
2327         FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2328
2329         /*
2330          * Next we have 32 bits of packet flags.
2331          */
2332         lip++, lm++, ld++;
2333         i |= (*ld - (*lip & *lm));
2334         FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2335
2336         if (i == 0) {
2337                 /*
2338                  * If a fragment, then only the first has what we're
2339                  * looking for here...
2340                  */
2341                 if (portcmp) {
2342                         if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2343                                 i = 1;
2344                 } else {
2345                         if (fr->fr_dcmp || fr->fr_scmp ||
2346                             fr->fr_tcpf || fr->fr_tcpfm)
2347                                 i = 1;
2348                         if (fr->fr_icmpm || fr->fr_icmp) {
2349                                 if (((fi->fi_p != IPPROTO_ICMP) &&
2350                                      (fi->fi_p != IPPROTO_ICMPV6)) ||
2351                                     fin->fin_off || (fin->fin_dlen < 2))
2352                                         i = 1;
2353                                 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2354                                          fr->fr_icmp) {
2355                                         FR_DEBUG(("i. %#x & %#x != %#x\n",
2356                                                  fin->fin_data[0],
2357                                                  fr->fr_icmpm, fr->fr_icmp));
2358                                         i = 1;
2359                                 }
2360                         }
2361                 }
2362         }
2363         return i;
2364 }
2365
2366
2367 /* ------------------------------------------------------------------------ */
2368 /* Function:    ipf_scanlist                                                */
2369 /* Returns:     int - result flags of scanning filter list                  */
2370 /* Parameters:  fin(I) - pointer to packet information                      */
2371 /*              pass(I) - default result to return for filtering            */
2372 /*                                                                          */
2373 /* Check the input/output list of rules for a match to the current packet.  */
2374 /* If a match is found, the value of fr_flags from the rule becomes the     */
2375 /* return value and fin->fin_fr points to the matched rule.                 */
2376 /*                                                                          */
2377 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2378 /* When unwinding, it should finish up with fin_depth as 0.                 */
2379 /*                                                                          */
2380 /* Could be per interface, but this gets real nasty when you don't have,    */
2381 /* or can't easily change, the kernel source code to .                      */
2382 /* ------------------------------------------------------------------------ */
2383 int
2384 ipf_scanlist(fin, pass)
2385         fr_info_t *fin;
2386         u_32_t pass;
2387 {
2388         ipf_main_softc_t *softc = fin->fin_main_soft;
2389         int rulen, portcmp, off, skip;
2390         struct frentry *fr, *fnext;
2391         u_32_t passt, passo;
2392
2393         /*
2394          * Do not allow nesting deeper than 16 levels.
2395          */
2396         if (fin->fin_depth >= 16)
2397                 return pass;
2398
2399         fr = fin->fin_fr;
2400
2401         /*
2402          * If there are no rules in this list, return now.
2403          */
2404         if (fr == NULL)
2405                 return pass;
2406
2407         skip = 0;
2408         portcmp = 0;
2409         fin->fin_depth++;
2410         fin->fin_fr = NULL;
2411         off = fin->fin_off;
2412
2413         if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2414                 portcmp = 1;
2415
2416         for (rulen = 0; fr; fr = fnext, rulen++) {
2417                 fnext = fr->fr_next;
2418                 if (skip != 0) {
2419                         FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2420                         skip--;
2421                         continue;
2422                 }
2423
2424                 /*
2425                  * In all checks below, a null (zero) value in the
2426                  * filter struture is taken to mean a wildcard.
2427                  *
2428                  * check that we are working for the right interface
2429                  */
2430 #ifdef  _KERNEL
2431                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2432                         continue;
2433 #else
2434                 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2435                         printf("\n");
2436                 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2437                                   FR_ISPASS(pass) ? 'p' :
2438                                   FR_ISACCOUNT(pass) ? 'A' :
2439                                   FR_ISAUTH(pass) ? 'a' :
2440                                   (pass & FR_NOMATCH) ? 'n' :'b'));
2441                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2442                         continue;
2443                 FR_VERBOSE((":i"));
2444 #endif
2445
2446                 switch (fr->fr_type)
2447                 {
2448                 case FR_T_IPF :
2449                 case FR_T_IPF_BUILTIN :
2450                         if (ipf_check_ipf(fin, fr, portcmp))
2451                                 continue;
2452                         break;
2453 #if defined(IPFILTER_BPF)
2454                 case FR_T_BPFOPC :
2455                 case FR_T_BPFOPC_BUILTIN :
2456                     {
2457                         u_char *mc;
2458                         int wlen;
2459
2460                         if (*fin->fin_mp == NULL)
2461                                 continue;
2462                         if (fin->fin_family != fr->fr_family)
2463                                 continue;
2464                         mc = (u_char *)fin->fin_m;
2465                         wlen = fin->fin_dlen + fin->fin_hlen;
2466                         if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2467                                 continue;
2468                         break;
2469                     }
2470 #endif
2471                 case FR_T_CALLFUNC_BUILTIN :
2472                     {
2473                         frentry_t *f;
2474
2475                         f = (*fr->fr_func)(fin, &pass);
2476                         if (f != NULL)
2477                                 fr = f;
2478                         else
2479                                 continue;
2480                         break;
2481                     }
2482
2483                 case FR_T_IPFEXPR :
2484                 case FR_T_IPFEXPR_BUILTIN :
2485                         if (fin->fin_family != fr->fr_family)
2486                                 continue;
2487                         if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2488                                 continue;
2489                         break;
2490
2491                 default :
2492                         break;
2493                 }
2494
2495                 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2496                         if (fin->fin_nattag == NULL)
2497                                 continue;
2498                         if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2499                                 continue;
2500                 }
2501                 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2502
2503                 passt = fr->fr_flags;
2504
2505                 /*
2506                  * If the rule is a "call now" rule, then call the function
2507                  * in the rule, if it exists and use the results from that.
2508                  * If the function pointer is bad, just make like we ignore
2509                  * it, except for increasing the hit counter.
2510                  */
2511                 if ((passt & FR_CALLNOW) != 0) {
2512                         frentry_t *frs;
2513
2514                         ATOMIC_INC64(fr->fr_hits);
2515                         if ((fr->fr_func == NULL) ||
2516                             (fr->fr_func == (ipfunc_t)-1))
2517                                 continue;
2518
2519                         frs = fin->fin_fr;
2520                         fin->fin_fr = fr;
2521                         fr = (*fr->fr_func)(fin, &passt);
2522                         if (fr == NULL) {
2523                                 fin->fin_fr = frs;
2524                                 continue;
2525                         }
2526                         passt = fr->fr_flags;
2527                 }
2528                 fin->fin_fr = fr;
2529
2530 #ifdef  IPFILTER_LOG
2531                 /*
2532                  * Just log this packet...
2533                  */
2534                 if ((passt & FR_LOGMASK) == FR_LOG) {
2535                         if (ipf_log_pkt(fin, passt) == -1) {
2536                                 if (passt & FR_LOGORBLOCK) {
2537                                         DT(frb_logfail);
2538                                         passt &= ~FR_CMDMASK;
2539                                         passt |= FR_BLOCK|FR_QUICK;
2540                                         fin->fin_reason = FRB_LOGFAIL;
2541                                 }
2542                         }
2543                 }
2544 #endif /* IPFILTER_LOG */
2545
2546                 MUTEX_ENTER(&fr->fr_lock);
2547                 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2548                 fr->fr_hits++;
2549                 MUTEX_EXIT(&fr->fr_lock);
2550                 fin->fin_rule = rulen;
2551
2552                 passo = pass;
2553                 if (FR_ISSKIP(passt)) {
2554                         skip = fr->fr_arg;
2555                         continue;
2556                 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2557                            ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2558                         pass = passt;
2559                 }
2560
2561                 if (passt & (FR_RETICMP|FR_FAKEICMP))
2562                         fin->fin_icode = fr->fr_icode;
2563
2564                 if (fr->fr_group != -1) {
2565                         (void) strncpy(fin->fin_group,
2566                                        FR_NAME(fr, fr_group),
2567                                        strlen(FR_NAME(fr, fr_group)));
2568                 } else {
2569                         fin->fin_group[0] = '\0';
2570                 }
2571
2572                 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2573
2574                 if (fr->fr_grphead != NULL) {
2575                         fin->fin_fr = fr->fr_grphead->fg_start;
2576                         FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2577
2578                         if (FR_ISDECAPS(passt))
2579                                 passt = ipf_decaps(fin, pass, fr->fr_icode);
2580                         else
2581                                 passt = ipf_scanlist(fin, pass);
2582
2583                         if (fin->fin_fr == NULL) {
2584                                 fin->fin_rule = rulen;
2585                                 if (fr->fr_group != -1)
2586                                         (void) strncpy(fin->fin_group,
2587                                                        fr->fr_names +
2588                                                        fr->fr_group,
2589                                                        strlen(fr->fr_names +
2590                                                               fr->fr_group));
2591                                 fin->fin_fr = fr;
2592                                 passt = pass;
2593                         }
2594                         pass = passt;
2595                 }
2596
2597                 if (pass & FR_QUICK) {
2598                         /*
2599                          * Finally, if we've asked to track state for this
2600                          * packet, set it up.  Add state for "quick" rules
2601                          * here so that if the action fails we can consider
2602                          * the rule to "not match" and keep on processing
2603                          * filter rules.
2604                          */
2605                         if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2606                             !(fin->fin_flx & FI_STATE)) {
2607                                 int out = fin->fin_out;
2608
2609                                 fin->fin_fr = fr;
2610                                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2611                                         LBUMPD(ipf_stats[out], fr_ads);
2612                                 } else {
2613                                         LBUMPD(ipf_stats[out], fr_bads);
2614                                         pass = passo;
2615                                         continue;
2616                                 }
2617                         }
2618                         break;
2619                 }
2620         }
2621         fin->fin_depth--;
2622         return pass;
2623 }
2624
2625
2626 /* ------------------------------------------------------------------------ */
2627 /* Function:    ipf_acctpkt                                                 */
2628 /* Returns:     frentry_t* - always returns NULL                            */
2629 /* Parameters:  fin(I) - pointer to packet information                      */
2630 /*              passp(IO) - pointer to current/new filter decision (unused) */
2631 /*                                                                          */
2632 /* Checks a packet against accounting rules, if there are any for the given */
2633 /* IP protocol version.                                                     */
2634 /*                                                                          */
2635 /* N.B.: this function returns NULL to match the prototype used by other    */
2636 /* functions called from the IPFilter "mainline" in ipf_check().            */
2637 /* ------------------------------------------------------------------------ */
2638 frentry_t *
2639 ipf_acctpkt(fin, passp)
2640         fr_info_t *fin;
2641         u_32_t *passp;
2642 {
2643         ipf_main_softc_t *softc = fin->fin_main_soft;
2644         char group[FR_GROUPLEN];
2645         frentry_t *fr, *frsave;
2646         u_32_t pass, rulen;
2647
2648         passp = passp;
2649         fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2650
2651         if (fr != NULL) {
2652                 frsave = fin->fin_fr;
2653                 bcopy(fin->fin_group, group, FR_GROUPLEN);
2654                 rulen = fin->fin_rule;
2655                 fin->fin_fr = fr;
2656                 pass = ipf_scanlist(fin, FR_NOMATCH);
2657                 if (FR_ISACCOUNT(pass)) {
2658                         LBUMPD(ipf_stats[0], fr_acct);
2659                 }
2660                 fin->fin_fr = frsave;
2661                 bcopy(group, fin->fin_group, FR_GROUPLEN);
2662                 fin->fin_rule = rulen;
2663         }
2664         return NULL;
2665 }
2666
2667
2668 /* ------------------------------------------------------------------------ */
2669 /* Function:    ipf_firewall                                                */
2670 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2671 /*                           were found, returns NULL.                      */
2672 /* Parameters:  fin(I) - pointer to packet information                      */
2673 /*              passp(IO) - pointer to current/new filter decision (unused) */
2674 /*                                                                          */
2675 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2676 /* there are any matches.  The first check is to see if a match can be seen */
2677 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2678 /* matching rule is found, take any appropriate actions as defined by the   */
2679 /* rule - except logging.                                                   */
2680 /* ------------------------------------------------------------------------ */
2681 static frentry_t *
2682 ipf_firewall(fin, passp)
2683         fr_info_t *fin;
2684         u_32_t *passp;
2685 {
2686         ipf_main_softc_t *softc = fin->fin_main_soft;
2687         frentry_t *fr;
2688         u_32_t pass;
2689         int out;
2690
2691         out = fin->fin_out;
2692         pass = *passp;
2693
2694         /*
2695          * This rule cache will only affect packets that are not being
2696          * statefully filtered.
2697          */
2698         fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2699         if (fin->fin_fr != NULL)
2700                 pass = ipf_scanlist(fin, softc->ipf_pass);
2701
2702         if ((pass & FR_NOMATCH)) {
2703                 LBUMPD(ipf_stats[out], fr_nom);
2704         }
2705         fr = fin->fin_fr;
2706
2707         /*
2708          * Apply packets per second rate-limiting to a rule as required.
2709          */
2710         if ((fr != NULL) && (fr->fr_pps != 0) &&
2711             !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2712                 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2713                 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2714                 pass |= FR_BLOCK;
2715                 LBUMPD(ipf_stats[out], fr_ppshit);
2716                 fin->fin_reason = FRB_PPSRATE;
2717         }
2718
2719         /*
2720          * If we fail to add a packet to the authorization queue, then we
2721          * drop the packet later.  However, if it was added then pretend
2722          * we've dropped it already.
2723          */
2724         if (FR_ISAUTH(pass)) {
2725                 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2726                         DT1(frb_authnew, fr_info_t *, fin);
2727                         fin->fin_m = *fin->fin_mp = NULL;
2728                         fin->fin_reason = FRB_AUTHNEW;
2729                         fin->fin_error = 0;
2730                 } else {
2731                         IPFERROR(1);
2732                         fin->fin_error = ENOSPC;
2733                 }
2734         }
2735
2736         if ((fr != NULL) && (fr->fr_func != NULL) &&
2737             (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2738                 (void) (*fr->fr_func)(fin, &pass);
2739
2740         /*
2741          * If a rule is a pre-auth rule, check again in the list of rules
2742          * loaded for authenticated use.  It does not particulary matter
2743          * if this search fails because a "preauth" result, from a rule,
2744          * is treated as "not a pass", hence the packet is blocked.
2745          */
2746         if (FR_ISPREAUTH(pass)) {
2747                 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2748         }
2749
2750         /*
2751          * If the rule has "keep frag" and the packet is actually a fragment,
2752          * then create a fragment state entry.
2753          */
2754         if (pass & FR_KEEPFRAG) {
2755                 if (fin->fin_flx & FI_FRAG) {
2756                         if (ipf_frag_new(softc, fin, pass) == -1) {
2757                                 LBUMP(ipf_stats[out].fr_bnfr);
2758                         } else {
2759                                 LBUMP(ipf_stats[out].fr_nfr);
2760                         }
2761                 } else {
2762                         LBUMP(ipf_stats[out].fr_cfr);
2763                 }
2764         }
2765
2766         fr = fin->fin_fr;
2767         *passp = pass;
2768
2769         return fr;
2770 }
2771
2772
2773 /* ------------------------------------------------------------------------ */
2774 /* Function:    ipf_check                                                   */
2775 /* Returns:     int -  0 == packet allowed through,                         */
2776 /*              User space:                                                 */
2777 /*                    -1 == packet blocked                                  */
2778 /*                     1 == packet not matched                              */
2779 /*                    -2 == requires authentication                         */
2780 /*              Kernel:                                                     */
2781 /*                   > 0 == filter error # for packet                       */
2782 /* Parameters: ctx(I)  - pointer to the instance context                    */
2783 /*             ip(I)   - pointer to start of IPv4/6 packet                  */
2784 /*             hlen(I) - length of header                                   */
2785 /*             ifp(I)  - pointer to interface this packet is on             */
2786 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2787 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2788 /*                       IP packet.                                         */
2789 /* Solaris:                                                                 */
2790 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2791 /*                       interface & direction.                             */
2792 /*                                                                          */
2793 /* ipf_check() is the master function for all IPFilter packet processing.   */
2794 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2795 /* authorisation (or pre-authorisation), presence of related state info.,   */
2796 /* generating log entries, IP packet accounting, routing of packets as      */
2797 /* directed by firewall rules and of course whether or not to allow the     */
2798 /* packet to be further processed by the kernel.                            */
2799 /*                                                                          */
2800 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2801 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2802 /* by "mp" changed to a new buffer.                                         */
2803 /* ------------------------------------------------------------------------ */
2804 int
2805 ipf_check(ctx, ip, hlen, ifp, out
2806 #if defined(_KERNEL) && defined(MENTAT)
2807         , qif, mp)
2808         void *qif;
2809 #else
2810         , mp)
2811 #endif
2812         mb_t **mp;
2813         ip_t *ip;
2814         int hlen;
2815         struct ifnet *ifp;
2816         int out;
2817         void *ctx;
2818 {
2819         /*
2820          * The above really sucks, but short of writing a diff
2821          */
2822         ipf_main_softc_t *softc = ctx;
2823         fr_info_t frinfo;
2824         fr_info_t *fin = &frinfo;
2825         u_32_t pass = softc->ipf_pass;
2826         frentry_t *fr = NULL;
2827         int v = IP_V(ip);
2828         mb_t *mc = NULL;
2829         mb_t *m;
2830         /*
2831          * The first part of ipf_check() deals with making sure that what goes
2832          * into the filtering engine makes some sense.  Information about the
2833          * the packet is distilled, collected into a fr_info_t structure and
2834          * the an attempt to ensure the buffer the packet is in is big enough
2835          * to hold all the required packet headers.
2836          */
2837 #ifdef  _KERNEL
2838 # ifdef MENTAT
2839         qpktinfo_t *qpi = qif;
2840
2841 #  ifdef __sparc
2842         if ((u_int)ip & 0x3)
2843                 return 2;
2844 #  endif
2845 # else
2846         SPL_INT(s);
2847 # endif
2848
2849         if (softc->ipf_running <= 0) {
2850                 return 0;
2851         }
2852
2853         bzero((char *)fin, sizeof(*fin));
2854
2855 # ifdef MENTAT
2856         if (qpi->qpi_flags & QF_BROADCAST)
2857                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2858         if (qpi->qpi_flags & QF_MULTICAST)
2859                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2860         m = qpi->qpi_m;
2861         fin->fin_qfm = m;
2862         fin->fin_qpi = qpi;
2863 # else /* MENTAT */
2864
2865         m = *mp;
2866
2867 #  if defined(M_MCAST)
2868         if ((m->m_flags & M_MCAST) != 0)
2869                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2870 #  endif
2871 #  if defined(M_MLOOP)
2872         if ((m->m_flags & M_MLOOP) != 0)
2873                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2874 #  endif
2875 #  if defined(M_BCAST)
2876         if ((m->m_flags & M_BCAST) != 0)
2877                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2878 #  endif
2879 #  ifdef M_CANFASTFWD
2880         /*
2881          * XXX For now, IP Filter and fast-forwarding of cached flows
2882          * XXX are mutually exclusive.  Eventually, IP Filter should
2883          * XXX get a "can-fast-forward" filter rule.
2884          */
2885         m->m_flags &= ~M_CANFASTFWD;
2886 #  endif /* M_CANFASTFWD */
2887 #  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2888         /*
2889          * disable delayed checksums.
2890          */
2891         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2892                 in_delayed_cksum(m);
2893                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2894         }
2895 #  endif /* CSUM_DELAY_DATA */
2896 # endif /* MENTAT */
2897 #else
2898         bzero((char *)fin, sizeof(*fin));
2899         m = *mp;
2900 # if defined(M_MCAST)
2901         if ((m->m_flags & M_MCAST) != 0)
2902                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2903 # endif
2904 # if defined(M_MLOOP)
2905         if ((m->m_flags & M_MLOOP) != 0)
2906                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2907 # endif
2908 # if defined(M_BCAST)
2909         if ((m->m_flags & M_BCAST) != 0)
2910                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2911 # endif
2912 #endif /* _KERNEL */
2913
2914         fin->fin_v = v;
2915         fin->fin_m = m;
2916         fin->fin_ip = ip;
2917         fin->fin_mp = mp;
2918         fin->fin_out = out;
2919         fin->fin_ifp = ifp;
2920         fin->fin_error = ENETUNREACH;
2921         fin->fin_hlen = (u_short)hlen;
2922         fin->fin_dp = (char *)ip + hlen;
2923         fin->fin_main_soft = softc;
2924
2925         fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2926
2927         SPL_NET(s);
2928
2929 #ifdef  USE_INET6
2930         if (v == 6) {
2931                 LBUMP(ipf_stats[out].fr_ipv6);
2932                 /*
2933                  * Jumbo grams are quite likely too big for internal buffer
2934                  * structures to handle comfortably, for now, so just drop
2935                  * them.
2936                  */
2937                 if (((ip6_t *)ip)->ip6_plen == 0) {
2938                         DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2939                         pass = FR_BLOCK|FR_NOMATCH;
2940                         fin->fin_reason = FRB_JUMBO;
2941                         goto finished;
2942                 }
2943                 fin->fin_family = AF_INET6;
2944         } else
2945 #endif
2946         {
2947                 fin->fin_family = AF_INET;
2948         }
2949
2950         if (ipf_makefrip(hlen, ip, fin) == -1) {
2951                 DT1(frb_makefrip, fr_info_t *, fin);
2952                 pass = FR_BLOCK|FR_NOMATCH;
2953                 fin->fin_reason = FRB_MAKEFRIP;
2954                 goto finished;
2955         }
2956
2957         /*
2958          * For at least IPv6 packets, if a m_pullup() fails then this pointer
2959          * becomes NULL and so we have no packet to free.
2960          */
2961         if (*fin->fin_mp == NULL)
2962                 goto finished;
2963
2964         if (!out) {
2965                 if (v == 4) {
2966                         if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2967                                 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2968                                 fin->fin_flx |= FI_BADSRC;
2969                         }
2970                         if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2971                                 LBUMPD(ipf_stats[0], fr_v4_badttl);
2972                                 fin->fin_flx |= FI_LOWTTL;
2973                         }
2974                 }
2975 #ifdef USE_INET6
2976                 else  if (v == 6) {
2977                         if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2978                                 LBUMPD(ipf_stats[0], fr_v6_badttl);
2979                                 fin->fin_flx |= FI_LOWTTL;
2980                         }
2981                 }
2982 #endif
2983         }
2984
2985         if (fin->fin_flx & FI_SHORT) {
2986                 LBUMPD(ipf_stats[out], fr_short);
2987         }
2988
2989         READ_ENTER(&softc->ipf_mutex);
2990
2991         if (!out) {
2992                 switch (fin->fin_v)
2993                 {
2994                 case 4 :
2995                         if (ipf_nat_checkin(fin, &pass) == -1) {
2996                                 goto filterdone;
2997                         }
2998                         break;
2999 #ifdef USE_INET6
3000                 case 6 :
3001                         if (ipf_nat6_checkin(fin, &pass) == -1) {
3002                                 goto filterdone;
3003                         }
3004                         break;
3005 #endif
3006                 default :
3007                         break;
3008                 }
3009         }
3010         /*
3011          * Check auth now.
3012          * If a packet is found in the auth table, then skip checking
3013          * the access lists for permission but we do need to consider
3014          * the result as if it were from the ACL's.  In addition, being
3015          * found in the auth table means it has been seen before, so do
3016          * not pass it through accounting (again), lest it be counted twice.
3017          */
3018         fr = ipf_auth_check(fin, &pass);
3019         if (!out && (fr == NULL))
3020                 (void) ipf_acctpkt(fin, NULL);
3021
3022         if (fr == NULL) {
3023                 if ((fin->fin_flx & FI_FRAG) != 0)
3024                         fr = ipf_frag_known(fin, &pass);
3025
3026                 if (fr == NULL)
3027                         fr = ipf_state_check(fin, &pass);
3028         }
3029
3030         if ((pass & FR_NOMATCH) || (fr == NULL))
3031                 fr = ipf_firewall(fin, &pass);
3032
3033         /*
3034          * If we've asked to track state for this packet, set it up.
3035          * Here rather than ipf_firewall because ipf_checkauth may decide
3036          * to return a packet for "keep state"
3037          */
3038         if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3039             !(fin->fin_flx & FI_STATE)) {
3040                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3041                         LBUMP(ipf_stats[out].fr_ads);
3042                 } else {
3043                         LBUMP(ipf_stats[out].fr_bads);
3044                         if (FR_ISPASS(pass)) {
3045                                 DT(frb_stateadd);
3046                                 pass &= ~FR_CMDMASK;
3047                                 pass |= FR_BLOCK;
3048                                 fin->fin_reason = FRB_STATEADD;
3049                         }
3050                 }
3051         }
3052
3053         fin->fin_fr = fr;
3054         if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3055                 fin->fin_dif = &fr->fr_dif;
3056                 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3057         }
3058
3059         /*
3060          * Only count/translate packets which will be passed on, out the
3061          * interface.
3062          */
3063         if (out && FR_ISPASS(pass)) {
3064                 (void) ipf_acctpkt(fin, NULL);
3065
3066                 switch (fin->fin_v)
3067                 {
3068                 case 4 :
3069                         if (ipf_nat_checkout(fin, &pass) == -1) {
3070                                 ;
3071                         } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3072                                 if (ipf_updateipid(fin) == -1) {
3073                                         DT(frb_updateipid);
3074                                         LBUMP(ipf_stats[1].fr_ipud);
3075                                         pass &= ~FR_CMDMASK;
3076                                         pass |= FR_BLOCK;
3077                                         fin->fin_reason = FRB_UPDATEIPID;
3078                                 } else {
3079                                         LBUMP(ipf_stats[0].fr_ipud);
3080                                 }
3081                         }
3082                         break;
3083 #ifdef USE_INET6
3084                 case 6 :
3085                         (void) ipf_nat6_checkout(fin, &pass);
3086                         break;
3087 #endif
3088                 default :
3089                         break;
3090                 }
3091         }
3092
3093 filterdone:
3094 #ifdef  IPFILTER_LOG
3095         if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3096                 (void) ipf_dolog(fin, &pass);
3097         }
3098 #endif
3099
3100         /*
3101          * The FI_STATE flag is cleared here so that calling ipf_state_check
3102          * will work when called from inside of fr_fastroute.  Although
3103          * there is a similar flag, FI_NATED, for NAT, it does have the same
3104          * impact on code execution.
3105          */
3106         fin->fin_flx &= ~FI_STATE;
3107
3108 #if defined(FASTROUTE_RECURSION)
3109         /*
3110          * Up the reference on fr_lock and exit ipf_mutex. The generation of
3111          * a packet below can sometimes cause a recursive call into IPFilter.
3112          * On those platforms where that does happen, we need to hang onto
3113          * the filter rule just in case someone decides to remove or flush it
3114          * in the meantime.
3115          */
3116         if (fr != NULL) {
3117                 MUTEX_ENTER(&fr->fr_lock);
3118                 fr->fr_ref++;
3119                 MUTEX_EXIT(&fr->fr_lock);
3120         }
3121
3122         RWLOCK_EXIT(&softc->ipf_mutex);
3123 #endif
3124
3125         if ((pass & FR_RETMASK) != 0) {
3126                 /*
3127                  * Should we return an ICMP packet to indicate error
3128                  * status passing through the packet filter ?
3129                  * WARNING: ICMP error packets AND TCP RST packets should
3130                  * ONLY be sent in repsonse to incoming packets.  Sending
3131                  * them in response to outbound packets can result in a
3132                  * panic on some operating systems.
3133                  */
3134                 if (!out) {
3135                         if (pass & FR_RETICMP) {
3136                                 int dst;
3137
3138                                 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3139                                         dst = 1;
3140                                 else
3141                                         dst = 0;
3142                                 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3143                                                          dst);
3144                                 LBUMP(ipf_stats[0].fr_ret);
3145                         } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3146                                    !(fin->fin_flx & FI_SHORT)) {
3147                                 if (((fin->fin_flx & FI_OOW) != 0) ||
3148                                     (ipf_send_reset(fin) == 0)) {
3149                                         LBUMP(ipf_stats[1].fr_ret);
3150                                 }
3151                         }
3152
3153                         /*
3154                          * When using return-* with auth rules, the auth code
3155                          * takes over disposing of this packet.
3156                          */
3157                         if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3158                                 DT1(frb_authcapture, fr_info_t *, fin);
3159                                 fin->fin_m = *fin->fin_mp = NULL;
3160                                 fin->fin_reason = FRB_AUTHCAPTURE;
3161                                 m = NULL;
3162                         }
3163                 } else {
3164                         if (pass & FR_RETRST) {
3165                                 fin->fin_error = ECONNRESET;
3166                         }
3167                 }
3168         }
3169
3170         /*
3171          * After the above so that ICMP unreachables and TCP RSTs get
3172          * created properly.
3173          */
3174         if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3175                 ipf_nat_uncreate(fin);
3176
3177         /*
3178          * If we didn't drop off the bottom of the list of rules (and thus
3179          * the 'current' rule fr is not NULL), then we may have some extra
3180          * instructions about what to do with a packet.
3181          * Once we're finished return to our caller, freeing the packet if
3182          * we are dropping it.
3183          */
3184         if (fr != NULL) {
3185                 frdest_t *fdp;
3186
3187                 /*
3188                  * Generate a duplicated packet first because ipf_fastroute
3189                  * can lead to fin_m being free'd... not good.
3190                  */
3191                 fdp = fin->fin_dif;
3192                 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3193                     (fdp->fd_ptr != (void *)-1)) {
3194                         mc = M_COPY(fin->fin_m);
3195                         if (mc != NULL)
3196                                 ipf_fastroute(mc, &mc, fin, fdp);
3197                 }
3198
3199                 fdp = fin->fin_tif;
3200                 if (!out && (pass & FR_FASTROUTE)) {
3201                         /*
3202                          * For fastroute rule, no destination interface defined
3203                          * so pass NULL as the frdest_t parameter
3204                          */
3205                         (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3206                         m = *mp = NULL;
3207                 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3208                            (fdp->fd_ptr != (struct ifnet *)-1)) {
3209                         /* this is for to rules: */
3210                         ipf_fastroute(fin->fin_m, mp, fin, fdp);
3211                         m = *mp = NULL;
3212                 }
3213
3214 #if defined(FASTROUTE_RECURSION)
3215                 (void) ipf_derefrule(softc, &fr);
3216 #endif
3217         }
3218 #if !defined(FASTROUTE_RECURSION)
3219         RWLOCK_EXIT(&softc->ipf_mutex);
3220 #endif
3221
3222 finished:
3223         if (!FR_ISPASS(pass)) {
3224                 LBUMP(ipf_stats[out].fr_block);
3225                 if (*mp != NULL) {
3226 #ifdef _KERNEL
3227                         FREE_MB_T(*mp);
3228 #endif
3229                         m = *mp = NULL;
3230                 }
3231         } else {
3232                 LBUMP(ipf_stats[out].fr_pass);
3233         }
3234
3235         SPL_X(s);
3236
3237 #ifdef _KERNEL
3238         if (FR_ISPASS(pass))
3239                 return 0;
3240         LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3241         return fin->fin_error;
3242 #else /* _KERNEL */
3243         if (*mp != NULL)
3244                 (*mp)->mb_ifp = fin->fin_ifp;
3245         blockreason = fin->fin_reason;
3246         FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3247         /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3248                 if ((pass & FR_NOMATCH) != 0)
3249                         return 1;
3250
3251         if ((pass & FR_RETMASK) != 0)
3252                 switch (pass & FR_RETMASK)
3253                 {
3254                 case FR_RETRST :
3255                         return 3;
3256                 case FR_RETICMP :
3257                         return 4;
3258                 case FR_FAKEICMP :
3259                         return 5;
3260                 }
3261
3262         switch (pass & FR_CMDMASK)
3263         {
3264         case FR_PASS :
3265                 return 0;
3266         case FR_BLOCK :
3267                 return -1;
3268         case FR_AUTH :
3269                 return -2;
3270         case FR_ACCOUNT :
3271                 return -3;
3272         case FR_PREAUTH :
3273                 return -4;
3274         }
3275         return 2;
3276 #endif /* _KERNEL */
3277 }
3278
3279
3280 #ifdef  IPFILTER_LOG
3281 /* ------------------------------------------------------------------------ */
3282 /* Function:    ipf_dolog                                                   */
3283 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3284 /* Parameters:  fin(I) - pointer to packet information                      */
3285 /*              passp(IO) - pointer to current/new filter decision (unused) */
3286 /*                                                                          */
3287 /* Checks flags set to see how a packet should be logged, if it is to be    */
3288 /* logged.  Adjust statistics based on its success or not.                  */
3289 /* ------------------------------------------------------------------------ */
3290 frentry_t *
3291 ipf_dolog(fin, passp)
3292         fr_info_t *fin;
3293         u_32_t *passp;
3294 {
3295         ipf_main_softc_t *softc = fin->fin_main_soft;
3296         u_32_t pass;
3297         int out;
3298
3299         out = fin->fin_out;
3300         pass = *passp;
3301
3302         if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3303                 pass |= FF_LOGNOMATCH;
3304                 LBUMPD(ipf_stats[out], fr_npkl);
3305                 goto logit;
3306
3307         } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3308             (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3309                 if ((pass & FR_LOGMASK) != FR_LOGP)
3310                         pass |= FF_LOGPASS;
3311                 LBUMPD(ipf_stats[out], fr_ppkl);
3312                 goto logit;
3313
3314         } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3315                    (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3316                 if ((pass & FR_LOGMASK) != FR_LOGB)
3317                         pass |= FF_LOGBLOCK;
3318                 LBUMPD(ipf_stats[out], fr_bpkl);
3319
3320 logit:
3321                 if (ipf_log_pkt(fin, pass) == -1) {
3322                         /*
3323                          * If the "or-block" option has been used then
3324                          * block the packet if we failed to log it.
3325                          */
3326                         if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3327                                 DT1(frb_logfail2, u_int, pass);
3328                                 pass &= ~FR_CMDMASK;
3329                                 pass |= FR_BLOCK;
3330                                 fin->fin_reason = FRB_LOGFAIL2;
3331                         }
3332                 }
3333                 *passp = pass;
3334         }
3335
3336         return fin->fin_fr;
3337 }
3338 #endif /* IPFILTER_LOG */
3339
3340
3341 /* ------------------------------------------------------------------------ */
3342 /* Function:    ipf_cksum                                                   */
3343 /* Returns:     u_short - IP header checksum                                */
3344 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3345 /*              len(I)  - length of buffer in bytes                         */
3346 /*                                                                          */
3347 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3348 /*                                                                          */
3349 /* N.B.: addr should be 16bit aligned.                                      */
3350 /* ------------------------------------------------------------------------ */
3351 u_short
3352 ipf_cksum(addr, len)
3353         u_short *addr;
3354         int len;
3355 {
3356         u_32_t sum = 0;
3357
3358         for (sum = 0; len > 1; len -= 2)
3359                 sum += *addr++;
3360
3361         /* mop up an odd byte, if necessary */
3362         if (len == 1)
3363                 sum += *(u_char *)addr;
3364
3365         /*
3366          * add back carry outs from top 16 bits to low 16 bits
3367          */
3368         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
3369         sum += (sum >> 16);                     /* add carry */
3370         return (u_short)(~sum);
3371 }
3372
3373
3374 /* ------------------------------------------------------------------------ */
3375 /* Function:    fr_cksum                                                    */
3376 /* Returns:     u_short - layer 4 checksum                                  */
3377 /* Parameters:  fin(I)     - pointer to packet information                  */
3378 /*              ip(I)      - pointer to IP header                           */
3379 /*              l4proto(I) - protocol to caclulate checksum for             */
3380 /*              l4hdr(I)   - pointer to layer 4 header                      */
3381 /*                                                                          */
3382 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3383 /* in the IP header "ip" to seed it.                                        */
3384 /*                                                                          */
3385 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3386 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3387 /* odd sizes.                                                               */
3388 /*                                                                          */
3389 /* Expects ip_len and ip_off to be in network byte order when called.       */
3390 /* ------------------------------------------------------------------------ */
3391 u_short
3392 fr_cksum(fin, ip, l4proto, l4hdr)
3393         fr_info_t *fin;
3394         ip_t *ip;
3395         int l4proto;
3396         void *l4hdr;
3397 {
3398         u_short *sp, slen, sumsave, *csump;
3399         u_int sum, sum2;
3400         int hlen;
3401         int off;
3402 #ifdef  USE_INET6
3403         ip6_t *ip6;
3404 #endif
3405
3406         csump = NULL;
3407         sumsave = 0;
3408         sp = NULL;
3409         slen = 0;
3410         hlen = 0;
3411         sum = 0;
3412
3413         sum = htons((u_short)l4proto);
3414         /*
3415          * Add up IP Header portion
3416          */
3417 #ifdef  USE_INET6
3418         if (IP_V(ip) == 4) {
3419 #endif
3420                 hlen = IP_HL(ip) << 2;
3421                 off = hlen;
3422                 sp = (u_short *)&ip->ip_src;
3423                 sum += *sp++;   /* ip_src */
3424                 sum += *sp++;
3425                 sum += *sp++;   /* ip_dst */
3426                 sum += *sp++;
3427                 slen = fin->fin_plen - off;
3428                 sum += htons(slen);
3429 #ifdef  USE_INET6
3430         } else if (IP_V(ip) == 6) {
3431                 mb_t *m;
3432
3433                 m = fin->fin_m;
3434                 ip6 = (ip6_t *)ip;
3435                 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3436                 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3437                 return(ipf_pcksum6(fin, ip6, off, len));
3438         } else {
3439                 return 0xffff;
3440         }
3441 #endif
3442
3443         switch (l4proto)
3444         {
3445         case IPPROTO_UDP :
3446                 csump = &((udphdr_t *)l4hdr)->uh_sum;
3447                 break;
3448
3449         case IPPROTO_TCP :
3450                 csump = &((tcphdr_t *)l4hdr)->th_sum;
3451                 break;
3452         case IPPROTO_ICMP :
3453                 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3454                 sum = 0;        /* Pseudo-checksum is not included */
3455                 break;
3456 #ifdef USE_INET6
3457         case IPPROTO_ICMPV6 :
3458                 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3459                 break;
3460 #endif
3461         default :
3462                 break;
3463         }
3464
3465         if (csump != NULL) {
3466                 sumsave = *csump;
3467                 *csump = 0;
3468         }
3469
3470         sum2 = ipf_pcksum(fin, off, sum);
3471         if (csump != NULL)
3472                 *csump = sumsave;
3473         return sum2;
3474 }
3475
3476
3477 /* ------------------------------------------------------------------------ */
3478 /* Function:    ipf_findgroup                                               */
3479 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3480 /* Parameters:  softc(I) - pointer to soft context main structure           */
3481 /*              group(I) - group name to search for                         */
3482 /*              unit(I)  - device to which this group belongs               */
3483 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3484 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3485 /*                         to where to add the next (last) group or where   */
3486 /*                         to delete group from.                            */
3487 /*                                                                          */
3488 /* Search amongst the defined groups for a particular group number.         */
3489 /* ------------------------------------------------------------------------ */
3490 frgroup_t *
3491 ipf_findgroup(softc, group, unit, set, fgpp)
3492         ipf_main_softc_t *softc;
3493         char *group;
3494         minor_t unit;
3495         int set;
3496         frgroup_t ***fgpp;
3497 {
3498         frgroup_t *fg, **fgp;
3499
3500         /*
3501          * Which list of groups to search in is dependent on which list of
3502          * rules are being operated on.
3503          */
3504         fgp = &softc->ipf_groups[unit][set];
3505
3506         while ((fg = *fgp) != NULL) {
3507                 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3508                         break;
3509                 else
3510                         fgp = &fg->fg_next;
3511         }
3512         if (fgpp != NULL)
3513                 *fgpp = fgp;
3514         return fg;
3515 }
3516
3517
3518 /* ------------------------------------------------------------------------ */
3519 /* Function:    ipf_group_add                                               */
3520 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3521 /*                            != NULL == pointer to the group               */
3522 /* Parameters:  softc(I) - pointer to soft context main structure           */
3523 /*              num(I)   - group number to add                              */
3524 /*              head(I)  - rule pointer that is using this as the head      */
3525 /*              flags(I) - rule flags which describe the type of rule it is */
3526 /*              unit(I)  - device to which this group will belong to        */
3527 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3528 /* Write Locks: ipf_mutex                                                   */
3529 /*                                                                          */
3530 /* Add a new group head, or if it already exists, increase the reference    */
3531 /* count to it.                                                             */
3532 /* ------------------------------------------------------------------------ */
3533 frgroup_t *
3534 ipf_group_add(softc, group, head, flags, unit, set)
3535         ipf_main_softc_t *softc;
3536         char *group;
3537         void *head;
3538         u_32_t flags;
3539         minor_t unit;
3540         int set;
3541 {
3542         frgroup_t *fg, **fgp;
3543         u_32_t gflags;
3544
3545         if (group == NULL)
3546                 return NULL;
3547
3548         if (unit == IPL_LOGIPF && *group == '\0')
3549                 return NULL;
3550
3551         fgp = NULL;
3552         gflags = flags & FR_INOUT;
3553
3554         fg = ipf_findgroup(softc, group, unit, set, &fgp);
3555         if (fg != NULL) {
3556                 if (fg->fg_head == NULL && head != NULL)
3557                         fg->fg_head = head;
3558                 if (fg->fg_flags == 0)
3559                         fg->fg_flags = gflags;
3560                 else if (gflags != fg->fg_flags)
3561                         return NULL;
3562                 fg->fg_ref++;
3563                 return fg;
3564         }
3565
3566         KMALLOC(fg, frgroup_t *);
3567         if (fg != NULL) {
3568                 fg->fg_head = head;
3569                 fg->fg_start = NULL;
3570                 fg->fg_next = *fgp;
3571                 bcopy(group, fg->fg_name, strlen(group) + 1);
3572                 fg->fg_flags = gflags;
3573                 fg->fg_ref = 1;
3574                 fg->fg_set = &softc->ipf_groups[unit][set];
3575                 *fgp = fg;
3576         }
3577         return fg;
3578 }
3579
3580
3581 /* ------------------------------------------------------------------------ */
3582 /* Function:    ipf_group_del                                               */
3583 /* Returns:     int      - number of rules deleted                          */
3584 /* Parameters:  softc(I) - pointer to soft context main structure           */
3585 /*              group(I) - group name to delete                             */
3586 /*              fr(I)    - filter rule from which group is referenced       */
3587 /* Write Locks: ipf_mutex                                                   */
3588 /*                                                                          */
3589 /* This function is called whenever a reference to a group is to be dropped */
3590 /* and thus its reference count needs to be lowered and the group free'd if */
3591 /* the reference count reaches zero. Passing in fr is really for the sole   */
3592 /* purpose of knowing when the head rule is being deleted.                  */
3593 /* ------------------------------------------------------------------------ */
3594 void
3595 ipf_group_del(softc, group, fr)
3596         ipf_main_softc_t *softc;
3597         frgroup_t *group;
3598         frentry_t *fr;
3599 {
3600
3601         if (group->fg_head == fr)
3602                 group->fg_head = NULL;
3603
3604         group->fg_ref--;
3605         if ((group->fg_ref == 0) && (group->fg_start == NULL))
3606                 ipf_group_free(group);
3607 }
3608
3609
3610 /* ------------------------------------------------------------------------ */
3611 /* Function:    ipf_group_free                                              */
3612 /* Returns:     Nil                                                         */
3613 /* Parameters:  group(I) - pointer to filter rule group                     */
3614 /*                                                                          */
3615 /* Remove the group from the list of groups and free it.                    */
3616 /* ------------------------------------------------------------------------ */
3617 static void
3618 ipf_group_free(group)
3619         frgroup_t *group;
3620 {
3621         frgroup_t **gp;
3622
3623         for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3624                 if (*gp == group) {
3625                         *gp = group->fg_next;
3626                         break;
3627                 }
3628         }
3629         KFREE(group);
3630 }
3631
3632
3633 /* ------------------------------------------------------------------------ */
3634 /* Function:    ipf_group_flush                                             */
3635 /* Returns:     int      - number of rules flush from group                 */
3636 /* Parameters:  softc(I) - pointer to soft context main structure           */
3637 /* Parameters:  group(I) - pointer to filter rule group                     */
3638 /*                                                                          */
3639 /* Remove all of the rules that currently are listed under the given group. */
3640 /* ------------------------------------------------------------------------ */
3641 static int
3642 ipf_group_flush(softc, group)
3643         ipf_main_softc_t *softc;
3644         frgroup_t *group;
3645 {
3646         int gone = 0;
3647
3648         (void) ipf_flushlist(softc, &gone, &group->fg_start);
3649
3650         return gone;
3651 }
3652
3653
3654 /* ------------------------------------------------------------------------ */
3655 /* Function:    ipf_getrulen                                                */
3656 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3657 /* Parameters:  softc(I) - pointer to soft context main structure           */
3658 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3659 /*              flags(I) - which set of rules to find the rule in           */
3660 /*              group(I) - group name                                       */
3661 /*              n(I)     - rule number to find                              */
3662 /*                                                                          */
3663 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3664 /* group # g doesn't exist or there are less than n rules in the group.     */
3665 /* ------------------------------------------------------------------------ */
3666 frentry_t *
3667 ipf_getrulen(softc, unit, group, n)
3668         ipf_main_softc_t *softc;
3669         int unit;
3670         char *group;
3671         u_32_t n;
3672 {
3673         frentry_t *fr;
3674         frgroup_t *fg;
3675
3676         fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3677         if (fg == NULL)
3678                 return NULL;
3679         for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3680                 ;
3681         if (n != 0)
3682                 return NULL;
3683         return fr;
3684 }
3685
3686
3687 /* ------------------------------------------------------------------------ */
3688 /* Function:    ipf_flushlist                                               */
3689 /* Returns:     int - >= 0 - number of flushed rules                        */
3690 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3691 /*              nfreedp(O) - pointer to int where flush count is stored     */
3692 /*              listp(I)   - pointer to list to flush pointer               */
3693 /* Write Locks: ipf_mutex                                                   */
3694 /*                                                                          */
3695 /* Recursively flush rules from the list, descending groups as they are     */
3696 /* encountered.  if a rule is the head of a group and it has lost all its   */
3697 /* group members, then also delete the group reference.  nfreedp is needed  */
3698 /* to store the accumulating count of rules removed, whereas the returned   */
3699 /* value is just the number removed from the current list.  The latter is   */
3700 /* needed to correctly adjust reference counts on rules that define groups. */
3701 /*                                                                          */
3702 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3703 /* ------------------------------------------------------------------------ */
3704 static int
3705 ipf_flushlist(softc, nfreedp, listp)
3706         ipf_main_softc_t *softc;
3707         int *nfreedp;
3708         frentry_t **listp;
3709 {
3710         int freed = 0;
3711         frentry_t *fp;
3712
3713         while ((fp = *listp) != NULL) {
3714                 if ((fp->fr_type & FR_T_BUILTIN) ||
3715                     !(fp->fr_flags & FR_COPIED)) {
3716                         listp = &fp->fr_next;
3717                         continue;
3718                 }
3719                 *listp = fp->fr_next;
3720                 if (fp->fr_next != NULL)
3721                         fp->fr_next->fr_pnext = fp->fr_pnext;
3722                 fp->fr_pnext = NULL;
3723
3724                 if (fp->fr_grphead != NULL) {
3725                         freed += ipf_group_flush(softc, fp->fr_grphead);
3726                         fp->fr_names[fp->fr_grhead] = '\0';
3727                 }
3728
3729                 if (fp->fr_icmpgrp != NULL) {
3730                         freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3731                         fp->fr_names[fp->fr_icmphead] = '\0';
3732                 }
3733
3734                 if (fp->fr_srctrack.ht_max_nodes)
3735                         ipf_rb_ht_flush(&fp->fr_srctrack);
3736
3737                 fp->fr_next = NULL;
3738
3739                 ASSERT(fp->fr_ref > 0);
3740                 if (ipf_derefrule(softc, &fp) == 0)
3741                         freed++;
3742         }
3743         *nfreedp += freed;
3744         return freed;
3745 }
3746
3747
3748 /* ------------------------------------------------------------------------ */
3749 /* Function:    ipf_flush                                                   */
3750 /* Returns:     int - >= 0 - number of flushed rules                        */
3751 /* Parameters:  softc(I) - pointer to soft context main structure           */
3752 /*              unit(I)  - device for which to flush rules                  */
3753 /*              flags(I) - which set of rules to flush                      */
3754 /*                                                                          */
3755 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3756 /* and IPv6) as defined by the value of flags.                              */
3757 /* ------------------------------------------------------------------------ */
3758 int
3759 ipf_flush(softc, unit, flags)
3760         ipf_main_softc_t *softc;
3761         minor_t unit;
3762         int flags;
3763 {
3764         int flushed = 0, set;
3765
3766         WRITE_ENTER(&softc->ipf_mutex);
3767
3768         set = softc->ipf_active;
3769         if ((flags & FR_INACTIVE) == FR_INACTIVE)
3770                 set = 1 - set;
3771
3772         if (flags & FR_OUTQUE) {
3773                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3774                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3775         }
3776         if (flags & FR_INQUE) {
3777                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3778                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3779         }
3780
3781         flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3782                                     flags & (FR_INQUE|FR_OUTQUE));
3783
3784         RWLOCK_EXIT(&softc->ipf_mutex);
3785
3786         if (unit == IPL_LOGIPF) {
3787                 int tmp;
3788
3789                 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3790                 if (tmp >= 0)
3791                         flushed += tmp;
3792         }
3793         return flushed;
3794 }
3795
3796
3797 /* ------------------------------------------------------------------------ */
3798 /* Function:    ipf_flush_groups                                            */
3799 /* Returns:     int - >= 0 - number of flushed rules                        */
3800 /* Parameters:  softc(I)  - soft context pointerto work with                */
3801 /*              grhead(I) - pointer to the start of the group list to flush */
3802 /*              flags(I)  - which set of rules to flush                     */
3803 /*                                                                          */
3804 /* Walk through all of the groups under the given group head and remove all */
3805 /* of those that match the flags passed in. The for loop here is bit more   */
3806 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3807 /* may end up removing not only the structure pointed to by "fg" but also   */
3808 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3809 /* removed from the group then it is necessary to start again.              */
3810 /* ------------------------------------------------------------------------ */
3811 static int
3812 ipf_flush_groups(softc, grhead, flags)
3813         ipf_main_softc_t *softc;
3814         frgroup_t **grhead;
3815         int flags;
3816 {
3817         frentry_t *fr, **frp;
3818         frgroup_t *fg, **fgp;
3819         int flushed = 0;
3820         int removed = 0;
3821
3822         for (fgp = grhead; (fg = *fgp) != NULL; ) {
3823                 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3824                         fg = fg->fg_next;
3825                 if (fg == NULL)
3826                         break;
3827                 removed = 0;
3828                 frp = &fg->fg_start;
3829                 while ((removed == 0) && ((fr = *frp) != NULL)) {
3830                         if ((fr->fr_flags & flags) == 0) {
3831                                 frp = &fr->fr_next;
3832                         } else {
3833                                 if (fr->fr_next != NULL)
3834                                         fr->fr_next->fr_pnext = fr->fr_pnext;
3835                                 *frp = fr->fr_next;
3836                                 fr->fr_pnext = NULL;
3837                                 fr->fr_next = NULL;
3838                                 (void) ipf_derefrule(softc, &fr);
3839                                 flushed++;
3840                                 removed++;
3841                         }
3842                 }
3843                 if (removed == 0)
3844                         fgp = &fg->fg_next;
3845         }
3846         return flushed;
3847 }
3848
3849
3850 /* ------------------------------------------------------------------------ */
3851 /* Function:    memstr                                                      */
3852 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3853 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3854 /*              dst(I)  - pointer to byte sequence to search                */
3855 /*              slen(I) - match length                                      */
3856 /*              dlen(I) - length available to search in                     */
3857 /*                                                                          */
3858 /* Search dst for a sequence of bytes matching those at src and extend for  */
3859 /* slen bytes.                                                              */
3860 /* ------------------------------------------------------------------------ */
3861 char *
3862 memstr(src, dst, slen, dlen)
3863         const char *src;
3864         char *dst;
3865         size_t slen, dlen;
3866 {
3867         char *s = NULL;
3868
3869         while (dlen >= slen) {
3870                 if (bcmp(src, dst, slen) == 0) {
3871                         s = dst;
3872                         break;
3873                 }
3874                 dst++;
3875                 dlen--;
3876         }
3877         return s;
3878 }
3879 /* ------------------------------------------------------------------------ */
3880 /* Function:    ipf_fixskip                                                 */
3881 /* Returns:     Nil                                                         */
3882 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3883 /*              rp(I)        - rule added/removed with skip in it.          */
3884 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3885 /*                             depending on whether a rule was just added   */
3886 /*                             or removed.                                  */
3887 /*                                                                          */
3888 /* Adjust all the rules in a list which would have skip'd past the position */
3889 /* where we are inserting to skip to the right place given the change.      */
3890 /* ------------------------------------------------------------------------ */
3891 void
3892 ipf_fixskip(listp, rp, addremove)
3893         frentry_t **listp, *rp;
3894         int addremove;
3895 {
3896         int rules, rn;
3897         frentry_t *fp;
3898
3899         rules = 0;
3900         for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3901                 rules++;
3902
3903         if (fp == NULL)
3904                 return;
3905
3906         for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3907                 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3908                         fp->fr_arg += addremove;
3909 }
3910
3911
3912 #ifdef  _KERNEL
3913 /* ------------------------------------------------------------------------ */
3914 /* Function:    count4bits                                                  */
3915 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3916 /* Parameters:  ip(I) - 32bit IP address                                    */
3917 /*                                                                          */
3918 /* IPv4 ONLY                                                                */
3919 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3920 /* consecutive 1's is different to that passed, return -1, else return #    */
3921 /* of bits.                                                                 */
3922 /* ------------------------------------------------------------------------ */
3923 int
3924 count4bits(ip)
3925         u_32_t  ip;
3926 {
3927         u_32_t  ipn;
3928         int     cnt = 0, i, j;
3929
3930         ip = ipn = ntohl(ip);
3931         for (i = 32; i; i--, ipn *= 2)
3932                 if (ipn & 0x80000000)
3933                         cnt++;
3934                 else
3935                         break;
3936         ipn = 0;
3937         for (i = 32, j = cnt; i; i--, j--) {
3938                 ipn *= 2;
3939                 if (j > 0)
3940                         ipn++;
3941         }
3942         if (ipn == ip)
3943                 return cnt;
3944         return -1;
3945 }
3946
3947
3948 /* ------------------------------------------------------------------------ */
3949 /* Function:    count6bits                                                  */
3950 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3951 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3952 /*                                                                          */
3953 /* IPv6 ONLY                                                                */
3954 /* count consecutive 1's in bit mask.                                       */
3955 /* ------------------------------------------------------------------------ */
3956 # ifdef USE_INET6
3957 int
3958 count6bits(msk)
3959         u_32_t *msk;
3960 {
3961         int i = 0, k;
3962         u_32_t j;
3963
3964         for (k = 3; k >= 0; k--)
3965                 if (msk[k] == 0xffffffff)
3966                         i += 32;
3967                 else {
3968                         for (j = msk[k]; j; j <<= 1)
3969                                 if (j & 0x80000000)
3970                                         i++;
3971                 }
3972         return i;
3973 }
3974 # endif
3975 #endif /* _KERNEL */
3976
3977
3978 /* ------------------------------------------------------------------------ */
3979 /* Function:    ipf_synclist                                                */
3980 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3981 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3982 /*              ifp(I) - interface pointer for limiting sync lookups        */
3983 /* Write Locks: ipf_mutex                                                   */
3984 /*                                                                          */
3985 /* Walk through a list of filter rules and resolve any interface names into */
3986 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3987 /* used in the rule.  The interface pointer is used to limit the lookups to */
3988 /* a specific set of matching names if it is non-NULL.                      */
3989 /* Errors can occur when resolving the destination name of to/dup-to fields */
3990 /* when the name points to a pool and that pool doest not exist. If this    */
3991 /* does happen then it is necessary to check if there are any lookup refs   */
3992 /* that need to be dropped before returning with an error.                  */
3993 /* ------------------------------------------------------------------------ */
3994 static int
3995 ipf_synclist(softc, fr, ifp)
3996         ipf_main_softc_t *softc;
3997         frentry_t *fr;
3998         void *ifp;
3999 {
4000         frentry_t *frt, *start = fr;
4001         frdest_t *fdp;
4002         char *name;
4003         int error;
4004         void *ifa;
4005         int v, i;
4006
4007         error = 0;
4008
4009         for (; fr; fr = fr->fr_next) {
4010                 if (fr->fr_family == AF_INET)
4011                         v = 4;
4012                 else if (fr->fr_family == AF_INET6)
4013                         v = 6;
4014                 else
4015                         v = 0;
4016
4017                 /*
4018                  * Lookup all the interface names that are part of the rule.
4019                  */
4020                 for (i = 0; i < 4; i++) {
4021                         if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4022                                 continue;
4023                         if (fr->fr_ifnames[i] == -1)
4024                                 continue;
4025                         name = FR_NAME(fr, fr_ifnames[i]);
4026                         fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4027                 }
4028
4029                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4030                         if (fr->fr_satype != FRI_NORMAL &&
4031                             fr->fr_satype != FRI_LOOKUP) {
4032                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4033                                                      fr->fr_sifpidx, v);
4034                                 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4035                                             &fr->fr_src6, &fr->fr_smsk6);
4036                         }
4037                         if (fr->fr_datype != FRI_NORMAL &&
4038                             fr->fr_datype != FRI_LOOKUP) {
4039                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4040                                                      fr->fr_sifpidx, v);
4041                                 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4042                                             &fr->fr_dst6, &fr->fr_dmsk6);
4043                         }
4044                 }
4045
4046                 fdp = &fr->fr_tifs[0];
4047                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4048                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4049                         if (error != 0)
4050                                 goto unwind;
4051                 }
4052
4053                 fdp = &fr->fr_tifs[1];
4054                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4055                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4056                         if (error != 0)
4057                                 goto unwind;
4058                 }
4059
4060                 fdp = &fr->fr_dif;
4061                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4062                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4063                         if (error != 0)
4064                                 goto unwind;
4065                 }
4066
4067                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4068                     (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4069                         fr->fr_srcptr = ipf_lookup_res_num(softc,
4070                                                            fr->fr_srctype,
4071                                                            IPL_LOGIPF,
4072                                                            fr->fr_srcnum,
4073                                                            &fr->fr_srcfunc);
4074                 }
4075                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4076                     (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4077                         fr->fr_dstptr = ipf_lookup_res_num(softc,
4078                                                            fr->fr_dsttype,
4079                                                            IPL_LOGIPF,
4080                                                            fr->fr_dstnum,
4081                                                            &fr->fr_dstfunc);
4082                 }
4083         }
4084         return 0;
4085
4086 unwind:
4087         for (frt = start; frt != fr; fr = fr->fr_next) {
4088                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4089                     (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4090                                 ipf_lookup_deref(softc, frt->fr_srctype,
4091                                                  frt->fr_srcptr);
4092                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4093                     (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4094                                 ipf_lookup_deref(softc, frt->fr_dsttype,
4095                                                  frt->fr_dstptr);
4096         }
4097         return error;
4098 }
4099
4100
4101 /* ------------------------------------------------------------------------ */
4102 /* Function:    ipf_sync                                                    */
4103 /* Returns:     void                                                        */
4104 /* Parameters:  Nil                                                         */
4105 /*                                                                          */
4106 /* ipf_sync() is called when we suspect that the interface list or          */
4107 /* information about interfaces (like IP#) has changed.  Go through all     */
4108 /* filter rules, NAT entries and the state table and check if anything      */
4109 /* needs to be changed/updated.                                             */
4110 /* ------------------------------------------------------------------------ */
4111 int
4112 ipf_sync(softc, ifp)
4113         ipf_main_softc_t *softc;
4114         void *ifp;
4115 {
4116         int i;
4117
4118 # if !SOLARIS
4119         ipf_nat_sync(softc, ifp);
4120         ipf_state_sync(softc, ifp);
4121         ipf_lookup_sync(softc, ifp);
4122 # endif
4123
4124         WRITE_ENTER(&softc->ipf_mutex);
4125         (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4126         (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4127         (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4128         (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4129
4130         for (i = 0; i < IPL_LOGSIZE; i++) {
4131                 frgroup_t *g;
4132
4133                 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4134                         (void) ipf_synclist(softc, g->fg_start, ifp);
4135                 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4136                         (void) ipf_synclist(softc, g->fg_start, ifp);
4137         }
4138         RWLOCK_EXIT(&softc->ipf_mutex);
4139
4140         return 0;
4141 }
4142
4143
4144 /*
4145  * In the functions below, bcopy() is called because the pointer being
4146  * copied _from_ in this instance is a pointer to a char buf (which could
4147  * end up being unaligned) and on the kernel's local stack.
4148  */
4149 /* ------------------------------------------------------------------------ */
4150 /* Function:    copyinptr                                                   */
4151 /* Returns:     int - 0 = success, else failure                             */
4152 /* Parameters:  src(I)  - pointer to the source address                     */
4153 /*              dst(I)  - destination address                               */
4154 /*              size(I) - number of bytes to copy                           */
4155 /*                                                                          */
4156 /* Copy a block of data in from user space, given a pointer to the pointer  */
4157 /* to start copying from (src) and a pointer to where to store it (dst).    */
4158 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4159 /* ------------------------------------------------------------------------ */
4160 int
4161 copyinptr(softc, src, dst, size)
4162         ipf_main_softc_t *softc;
4163         void *src, *dst;
4164         size_t size;
4165 {
4166         caddr_t ca;
4167         int error;
4168
4169 # if SOLARIS
4170         error = COPYIN(src, &ca, sizeof(ca));
4171         if (error != 0)
4172                 return error;
4173 # else
4174         bcopy(src, (caddr_t)&ca, sizeof(ca));
4175 # endif
4176         error = COPYIN(ca, dst, size);
4177         if (error != 0) {
4178                 IPFERROR(3);
4179                 error = EFAULT;
4180         }
4181         return error;
4182 }
4183
4184
4185 /* ------------------------------------------------------------------------ */
4186 /* Function:    copyoutptr                                                  */
4187 /* Returns:     int - 0 = success, else failure                             */
4188 /* Parameters:  src(I)  - pointer to the source address                     */
4189 /*              dst(I)  - destination address                               */
4190 /*              size(I) - number of bytes to copy                           */
4191 /*                                                                          */
4192 /* Copy a block of data out to user space, given a pointer to the pointer   */
4193 /* to start copying from (src) and a pointer to where to store it (dst).    */
4194 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4195 /* ------------------------------------------------------------------------ */
4196 int
4197 copyoutptr(softc, src, dst, size)
4198         ipf_main_softc_t *softc;
4199         void *src, *dst;
4200         size_t size;
4201 {
4202         caddr_t ca;
4203         int error;
4204
4205         bcopy(dst, (caddr_t)&ca, sizeof(ca));
4206         error = COPYOUT(src, ca, size);
4207         if (error != 0) {
4208                 IPFERROR(4);
4209                 error = EFAULT;
4210         }
4211         return error;
4212 }
4213
4214
4215 /* ------------------------------------------------------------------------ */
4216 /* Function:    ipf_lock                                                    */
4217 /* Returns:     int      - 0 = success, else error                          */
4218 /* Parameters:  data(I)  - pointer to lock value to set                     */
4219 /*              lockp(O) - pointer to location to store old lock value      */
4220 /*                                                                          */
4221 /* Get the new value for the lock integer, set it and return the old value  */
4222 /* in *lockp.                                                               */
4223 /* ------------------------------------------------------------------------ */
4224 int
4225 ipf_lock(data, lockp)
4226         caddr_t data;
4227         int *lockp;
4228 {
4229         int arg, err;
4230
4231         err = BCOPYIN(data, &arg, sizeof(arg));
4232         if (err != 0)
4233                 return EFAULT;
4234         err = BCOPYOUT(lockp, data, sizeof(*lockp));
4235         if (err != 0)
4236                 return EFAULT;
4237         *lockp = arg;
4238         return 0;
4239 }
4240
4241
4242 /* ------------------------------------------------------------------------ */
4243 /* Function:    ipf_getstat                                                 */
4244 /* Returns:     Nil                                                         */
4245 /* Parameters:  softc(I) - pointer to soft context main structure           */
4246 /*              fiop(I)  - pointer to ipfilter stats structure              */
4247 /*              rev(I)   - version claim by program doing ioctl             */
4248 /*                                                                          */
4249 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4250 /* structure.                                                               */
4251 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4252 /* program is looking for. This ensure that validation of the version it    */
4253 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4254 /* allow older binaries to work but kernels without it will not.            */
4255 /* ------------------------------------------------------------------------ */
4256 /*ARGSUSED*/
4257 static void
4258 ipf_getstat(softc, fiop, rev)
4259         ipf_main_softc_t *softc;
4260         friostat_t *fiop;
4261         int rev;
4262 {
4263         int i;
4264
4265         bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4266               sizeof(ipf_statistics_t) * 2);
4267         fiop->f_locks[IPL_LOGSTATE] = -1;
4268         fiop->f_locks[IPL_LOGNAT] = -1;
4269         fiop->f_locks[IPL_LOGIPF] = -1;
4270         fiop->f_locks[IPL_LOGAUTH] = -1;
4271
4272         fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4273         fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4274         fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4275         fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4276         fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4277         fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4278         fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4279         fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4280
4281         fiop->f_ticks = softc->ipf_ticks;
4282         fiop->f_active = softc->ipf_active;
4283         fiop->f_froute[0] = softc->ipf_frouteok[0];
4284         fiop->f_froute[1] = softc->ipf_frouteok[1];
4285         fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4286         fiop->f_rb_node_max = softc->ipf_rb_node_max;
4287
4288         fiop->f_running = softc->ipf_running;
4289         for (i = 0; i < IPL_LOGSIZE; i++) {
4290                 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4291                 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4292         }
4293 #ifdef  IPFILTER_LOG
4294         fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4295         fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4296         fiop->f_logging = 1;
4297 #else
4298         fiop->f_log_ok = 0;
4299         fiop->f_log_fail = 0;
4300         fiop->f_logging = 0;
4301 #endif
4302         fiop->f_defpass = softc->ipf_pass;
4303         fiop->f_features = ipf_features;
4304
4305 #ifdef IPFILTER_COMPAT
4306         sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4307                 (rev / 1000000) % 100,
4308                 (rev / 10000) % 100,
4309                 (rev / 100) % 100);
4310 #else
4311         rev = rev;
4312         (void) strncpy(fiop->f_version, ipfilter_version,
4313                        sizeof(fiop->f_version));
4314 #endif
4315 }
4316
4317
4318 #ifdef  USE_INET6
4319 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4320         ICMP6_ECHO_REPLY,       /* 0: ICMP_ECHOREPLY */
4321         -1,                     /* 1: UNUSED */
4322         -1,                     /* 2: UNUSED */
4323         ICMP6_DST_UNREACH,      /* 3: ICMP_UNREACH */
4324         -1,                     /* 4: ICMP_SOURCEQUENCH */
4325         ND_REDIRECT,            /* 5: ICMP_REDIRECT */
4326         -1,                     /* 6: UNUSED */
4327         -1,                     /* 7: UNUSED */
4328         ICMP6_ECHO_REQUEST,     /* 8: ICMP_ECHO */
4329         -1,                     /* 9: UNUSED */
4330         -1,                     /* 10: UNUSED */
4331         ICMP6_TIME_EXCEEDED,    /* 11: ICMP_TIMXCEED */
4332         ICMP6_PARAM_PROB,       /* 12: ICMP_PARAMPROB */
4333         -1,                     /* 13: ICMP_TSTAMP */
4334         -1,                     /* 14: ICMP_TSTAMPREPLY */
4335         -1,                     /* 15: ICMP_IREQ */
4336         -1,                     /* 16: ICMP_IREQREPLY */
4337         -1,                     /* 17: ICMP_MASKREQ */
4338         -1,                     /* 18: ICMP_MASKREPLY */
4339 };
4340
4341
4342 int     icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4343         ICMP6_DST_UNREACH_ADDR,         /* 0: ICMP_UNREACH_NET */
4344         ICMP6_DST_UNREACH_ADDR,         /* 1: ICMP_UNREACH_HOST */
4345         -1,                             /* 2: ICMP_UNREACH_PROTOCOL */
4346         ICMP6_DST_UNREACH_NOPORT,       /* 3: ICMP_UNREACH_PORT */
4347         -1,                             /* 4: ICMP_UNREACH_NEEDFRAG */
4348         ICMP6_DST_UNREACH_NOTNEIGHBOR,  /* 5: ICMP_UNREACH_SRCFAIL */
4349         ICMP6_DST_UNREACH_ADDR,         /* 6: ICMP_UNREACH_NET_UNKNOWN */
4350         ICMP6_DST_UNREACH_ADDR,         /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4351         -1,                             /* 8: ICMP_UNREACH_ISOLATED */
4352         ICMP6_DST_UNREACH_ADMIN,        /* 9: ICMP_UNREACH_NET_PROHIB */
4353         ICMP6_DST_UNREACH_ADMIN,        /* 10: ICMP_UNREACH_HOST_PROHIB */
4354         -1,                             /* 11: ICMP_UNREACH_TOSNET */
4355         -1,                             /* 12: ICMP_UNREACH_TOSHOST */
4356         ICMP6_DST_UNREACH_ADMIN,        /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4357 };
4358 int     icmpreplytype6[ICMP6_MAXTYPE + 1];
4359 #endif
4360
4361 int     icmpreplytype4[ICMP_MAXTYPE + 1];
4362
4363
4364 /* ------------------------------------------------------------------------ */
4365 /* Function:    ipf_matchicmpqueryreply                                     */
4366 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4367 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4368 /*              ic(I)   - ICMP information                                  */
4369 /*              icmp(I) - ICMP packet header                                */
4370 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4371 /*                                                                          */
4372 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4373 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4374 /* else return 0 for no match.                                              */
4375 /* ------------------------------------------------------------------------ */
4376 int
4377 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4378         int v;
4379         icmpinfo_t *ic;
4380         icmphdr_t *icmp;
4381         int rev;
4382 {
4383         int ictype;
4384
4385         ictype = ic->ici_type;
4386
4387         if (v == 4) {
4388                 /*
4389                  * If we matched its type on the way in, then when going out
4390                  * it will still be the same type.
4391                  */
4392                 if ((!rev && (icmp->icmp_type == ictype)) ||
4393                     (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4394                         if (icmp->icmp_type != ICMP_ECHOREPLY)
4395                                 return 1;
4396                         if (icmp->icmp_id == ic->ici_id)
4397                                 return 1;
4398                 }
4399         }
4400 #ifdef  USE_INET6
4401         else if (v == 6) {
4402                 if ((!rev && (icmp->icmp_type == ictype)) ||
4403                     (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4404                         if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4405                                 return 1;
4406                         if (icmp->icmp_id == ic->ici_id)
4407                                 return 1;
4408                 }
4409         }
4410 #endif
4411         return 0;
4412 }
4413
4414
4415 /* ------------------------------------------------------------------------ */
4416 /* Function:    ipf_rule_compare                                            */
4417 /* Parameters:  fr1(I) - first rule structure to compare                    */
4418 /*              fr2(I) - second rule structure to compare                   */
4419 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4420 /*                                                                          */
4421 /* Compare two rules and return 0 if they match or a number indicating      */
4422 /* which of the individual checks failed.                                   */
4423 /* ------------------------------------------------------------------------ */
4424 static int
4425 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4426 {
4427         if (fr1->fr_cksum != fr2->fr_cksum)
4428                 return 1;
4429         if (fr1->fr_size != fr2->fr_size)
4430                 return 2;
4431         if (fr1->fr_dsize != fr2->fr_dsize)
4432                 return 3;
4433         if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4434                  fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4435                 return 4;
4436         if (fr1->fr_data && !fr2->fr_data)
4437                 return 5;
4438         if (!fr1->fr_data && fr2->fr_data)
4439                 return 6;
4440         if (fr1->fr_data) {
4441                 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4442                         return 7;
4443         }
4444         return 0;
4445 }
4446
4447
4448 /* ------------------------------------------------------------------------ */
4449 /* Function:    frrequest                                                   */
4450 /* Returns:     int - 0 == success, > 0 == errno value                      */
4451 /* Parameters:  unit(I)     - device for which this is for                  */
4452 /*              req(I)      - ioctl command (SIOC*)                         */
4453 /*              data(I)     - pointr to ioctl data                          */
4454 /*              set(I)      - 1 or 0 (filter set)                           */
4455 /*              makecopy(I) - flag indicating whether data points to a rule */
4456 /*                            in kernel space & hence doesn't need copying. */
4457 /*                                                                          */
4458 /* This function handles all the requests which operate on the list of      */
4459 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4460 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4461 /* names are resolved here and other sanity checks are made on the content  */
4462 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4463 /* then make sure they are created and initialised before exiting.          */
4464 /* ------------------------------------------------------------------------ */
4465 int
4466 frrequest(softc, unit, req, data, set, makecopy)
4467         ipf_main_softc_t *softc;
4468         int unit;
4469         ioctlcmd_t req;
4470         int set, makecopy;
4471         caddr_t data;
4472 {
4473         int error = 0, in, family, addrem, need_free = 0;
4474         frentry_t frd, *fp, *f, **fprev, **ftail;
4475         void *ptr, *uptr, *cptr;
4476         u_int *p, *pp;
4477         frgroup_t *fg;
4478         char *group;
4479
4480         ptr = NULL;
4481         cptr = NULL;
4482         fg = NULL;
4483         fp = &frd;
4484         if (makecopy != 0) {
4485                 bzero(fp, sizeof(frd));
4486                 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4487                 if (error) {
4488                         return error;
4489                 }
4490                 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4491                         IPFERROR(6);
4492                         return EINVAL;
4493                 }
4494                 KMALLOCS(f, frentry_t *, fp->fr_size);
4495                 if (f == NULL) {
4496                         IPFERROR(131);
4497                         return ENOMEM;
4498                 }
4499                 bzero(f, fp->fr_size);
4500                 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4501                                     fp->fr_size);
4502                 if (error) {
4503                         KFREES(f, fp->fr_size);
4504                         return error;
4505                 }
4506
4507                 fp = f;
4508                 f = NULL;
4509                 fp->fr_next = NULL;
4510                 fp->fr_dnext = NULL;
4511                 fp->fr_pnext = NULL;
4512                 fp->fr_pdnext = NULL;
4513                 fp->fr_grp = NULL;
4514                 fp->fr_grphead = NULL;
4515                 fp->fr_icmpgrp = NULL;
4516                 fp->fr_isc = (void *)-1;
4517                 fp->fr_ptr = NULL;
4518                 fp->fr_ref = 0;
4519                 fp->fr_flags |= FR_COPIED;
4520         } else {
4521                 fp = (frentry_t *)data;
4522                 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4523                         IPFERROR(7);
4524                         return EINVAL;
4525                 }
4526                 fp->fr_flags &= ~FR_COPIED;
4527         }
4528
4529         if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4530             ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4531                 IPFERROR(8);
4532                 error = EINVAL;
4533                 goto donenolock;
4534         }
4535
4536         family = fp->fr_family;
4537         uptr = fp->fr_data;
4538
4539         if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4540             req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4541                 addrem = 0;
4542         else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4543                 addrem = 1;
4544         else if (req == (ioctlcmd_t)SIOCZRLST)
4545                 addrem = 2;
4546         else {
4547                 IPFERROR(9);
4548                 error = EINVAL;
4549                 goto donenolock;
4550         }
4551
4552         /*
4553          * Only filter rules for IPv4 or IPv6 are accepted.
4554          */
4555         if (family == AF_INET) {
4556                 /*EMPTY*/;
4557 #ifdef  USE_INET6
4558         } else if (family == AF_INET6) {
4559                 /*EMPTY*/;
4560 #endif
4561         } else if (family != 0) {
4562                 IPFERROR(10);
4563                 error = EINVAL;
4564                 goto donenolock;
4565         }
4566
4567         /*
4568          * If the rule is being loaded from user space, i.e. we had to copy it
4569          * into kernel space, then do not trust the function pointer in the
4570          * rule.
4571          */
4572         if ((makecopy == 1) && (fp->fr_func != NULL)) {
4573                 if (ipf_findfunc(fp->fr_func) == NULL) {
4574                         IPFERROR(11);
4575                         error = ESRCH;
4576                         goto donenolock;
4577                 }
4578
4579                 if (addrem == 0) {
4580                         error = ipf_funcinit(softc, fp);
4581                         if (error != 0)
4582                                 goto donenolock;
4583                 }
4584         }
4585         if ((fp->fr_flags & FR_CALLNOW) &&
4586             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4587                 IPFERROR(142);
4588                 error = ESRCH;
4589                 goto donenolock;
4590         }
4591         if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4592             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4593                 IPFERROR(143);
4594                 error = ESRCH;
4595                 goto donenolock;
4596         }
4597
4598         ptr = NULL;
4599         cptr = NULL;
4600
4601         if (FR_ISACCOUNT(fp->fr_flags))
4602                 unit = IPL_LOGCOUNT;
4603
4604         /*
4605          * Check that each group name in the rule has a start index that
4606          * is valid.
4607          */
4608         if (fp->fr_icmphead != -1) {
4609                 if ((fp->fr_icmphead < 0) ||
4610                     (fp->fr_icmphead >= fp->fr_namelen)) {
4611                         IPFERROR(136);
4612                         error = EINVAL;
4613                         goto donenolock;
4614                 }
4615                 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4616                         fp->fr_names[fp->fr_icmphead] = '\0';
4617         }
4618
4619         if (fp->fr_grhead != -1) {
4620                 if ((fp->fr_grhead < 0) ||
4621                     (fp->fr_grhead >= fp->fr_namelen)) {
4622                         IPFERROR(137);
4623                         error = EINVAL;
4624                         goto donenolock;
4625                 }
4626                 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4627                         fp->fr_names[fp->fr_grhead] = '\0';
4628         }
4629
4630         if (fp->fr_group != -1) {
4631                 if ((fp->fr_group < 0) ||
4632                     (fp->fr_group >= fp->fr_namelen)) {
4633                         IPFERROR(138);
4634                         error = EINVAL;
4635                         goto donenolock;
4636                 }
4637                 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4638                         /*
4639                          * Allow loading rules that are in groups to cause
4640                          * them to be created if they don't already exit.
4641                          */
4642                         group = FR_NAME(fp, fr_group);
4643                         if (addrem == 0) {
4644                                 fg = ipf_group_add(softc, group, NULL,
4645                                                    fp->fr_flags, unit, set);
4646                                 fp->fr_grp = fg;
4647                         } else {
4648                                 fg = ipf_findgroup(softc, group, unit,
4649                                                    set, NULL);
4650                                 if (fg == NULL) {
4651                                         IPFERROR(12);
4652                                         error = ESRCH;
4653                                         goto donenolock;
4654                                 }
4655                         }
4656
4657                         if (fg->fg_flags == 0) {
4658                                 fg->fg_flags = fp->fr_flags & FR_INOUT;
4659                         } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4660                                 IPFERROR(13);
4661                                 error = ESRCH;
4662                                 goto donenolock;
4663                         }
4664                 }
4665         } else {
4666                 /*
4667                  * If a rule is going to be part of a group then it does
4668                  * not matter whether it is an in or out rule, but if it
4669                  * isn't in a group, then it does...
4670                  */
4671                 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4672                         IPFERROR(14);
4673                         error = EINVAL;
4674                         goto donenolock;
4675                 }
4676         }
4677         in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4678
4679         /*
4680          * Work out which rule list this change is being applied to.
4681          */
4682         ftail = NULL;
4683         fprev = NULL;
4684         if (unit == IPL_LOGAUTH) {
4685                 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4686                     (fp->fr_tifs[1].fd_ptr != NULL) ||
4687                     (fp->fr_dif.fd_ptr != NULL) ||
4688                     (fp->fr_flags & FR_FASTROUTE)) {
4689                         softc->ipf_interror = 145;
4690                         error = EINVAL;
4691                         goto donenolock;
4692                 }
4693                 fprev = ipf_auth_rulehead(softc);
4694         } else {
4695                 if (FR_ISACCOUNT(fp->fr_flags))
4696                         fprev = &softc->ipf_acct[in][set];
4697                 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4698                         fprev = &softc->ipf_rules[in][set];
4699         }
4700         if (fprev == NULL) {
4701                 IPFERROR(15);
4702                 error = ESRCH;
4703                 goto donenolock;
4704         }
4705
4706         if (fg != NULL)
4707                 fprev = &fg->fg_start;
4708
4709         /*
4710          * Copy in extra data for the rule.
4711          */
4712         if (fp->fr_dsize != 0) {
4713                 if (makecopy != 0) {
4714                         KMALLOCS(ptr, void *, fp->fr_dsize);
4715                         if (ptr == NULL) {
4716                                 IPFERROR(16);
4717                                 error = ENOMEM;
4718                                 goto donenolock;
4719                         }
4720
4721                         /*
4722                          * The bcopy case is for when the data is appended
4723                          * to the rule by ipf_in_compat().
4724                          */
4725                         if (uptr >= (void *)fp &&
4726                             uptr < (void *)((char *)fp + fp->fr_size)) {
4727                                 bcopy(uptr, ptr, fp->fr_dsize);
4728                                 error = 0;
4729                         } else {
4730                                 error = COPYIN(uptr, ptr, fp->fr_dsize);
4731                                 if (error != 0) {
4732                                         IPFERROR(17);
4733                                         error = EFAULT;
4734                                         goto donenolock;
4735                                 }
4736                         }
4737                 } else {
4738                         ptr = uptr;
4739                 }
4740                 fp->fr_data = ptr;
4741         } else {
4742                 fp->fr_data = NULL;
4743         }
4744
4745         /*
4746          * Perform per-rule type sanity checks of their members.
4747          * All code after this needs to be aware that allocated memory
4748          * may need to be free'd before exiting.
4749          */
4750         switch (fp->fr_type & ~FR_T_BUILTIN)
4751         {
4752 #if defined(IPFILTER_BPF)
4753         case FR_T_BPFOPC :
4754                 if (fp->fr_dsize == 0) {
4755                         IPFERROR(19);
4756                         error = EINVAL;
4757                         break;
4758                 }
4759                 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4760                         IPFERROR(20);
4761                         error = EINVAL;
4762                         break;
4763                 }
4764                 break;
4765 #endif
4766         case FR_T_IPF :
4767                 /*
4768                  * Preparation for error case at the bottom of this function.
4769                  */
4770                 if (fp->fr_datype == FRI_LOOKUP)
4771                         fp->fr_dstptr = NULL;
4772                 if (fp->fr_satype == FRI_LOOKUP)
4773                         fp->fr_srcptr = NULL;
4774
4775                 if (fp->fr_dsize != sizeof(fripf_t)) {
4776                         IPFERROR(21);
4777                         error = EINVAL;
4778                         break;
4779                 }
4780
4781                 /*
4782                  * Allowing a rule with both "keep state" and "with oow" is
4783                  * pointless because adding a state entry to the table will
4784                  * fail with the out of window (oow) flag set.
4785                  */
4786                 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4787                         IPFERROR(22);
4788                         error = EINVAL;
4789                         break;
4790                 }
4791
4792                 switch (fp->fr_satype)
4793                 {
4794                 case FRI_BROADCAST :
4795                 case FRI_DYNAMIC :
4796                 case FRI_NETWORK :
4797                 case FRI_NETMASKED :
4798                 case FRI_PEERADDR :
4799                         if (fp->fr_sifpidx < 0) {
4800                                 IPFERROR(23);
4801                                 error = EINVAL;
4802                         }
4803                         break;
4804                 case FRI_LOOKUP :
4805                         fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4806                                                        &fp->fr_src6,
4807                                                        &fp->fr_smsk6);
4808                         if (fp->fr_srcfunc == NULL) {
4809                                 IPFERROR(132);
4810                                 error = ESRCH;
4811                                 break;
4812                         }
4813                         break;
4814                 case FRI_NORMAL :
4815                         break;
4816                 default :
4817                         IPFERROR(133);
4818                         error = EINVAL;
4819                         break;
4820                 }
4821                 if (error != 0)
4822                         break;
4823
4824                 switch (fp->fr_datype)
4825                 {
4826                 case FRI_BROADCAST :
4827                 case FRI_DYNAMIC :
4828                 case FRI_NETWORK :
4829                 case FRI_NETMASKED :
4830                 case FRI_PEERADDR :
4831                         if (fp->fr_difpidx < 0) {
4832                                 IPFERROR(24);
4833                                 error = EINVAL;
4834                         }
4835                         break;
4836                 case FRI_LOOKUP :
4837                         fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4838                                                        &fp->fr_dst6,
4839                                                        &fp->fr_dmsk6);
4840                         if (fp->fr_dstfunc == NULL) {
4841                                 IPFERROR(134);
4842                                 error = ESRCH;
4843                         }
4844                         break;
4845                 case FRI_NORMAL :
4846                         break;
4847                 default :
4848                         IPFERROR(135);
4849                         error = EINVAL;
4850                 }
4851                 break;
4852
4853         case FR_T_NONE :
4854         case FR_T_CALLFUNC :
4855         case FR_T_COMPIPF :
4856                 break;
4857
4858         case FR_T_IPFEXPR :
4859                 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4860                         IPFERROR(25);
4861                         error = EINVAL;
4862                 }
4863                 break;
4864
4865         default :
4866                 IPFERROR(26);
4867                 error = EINVAL;
4868                 break;
4869         }
4870         if (error != 0)
4871                 goto donenolock;
4872
4873         if (fp->fr_tif.fd_name != -1) {
4874                 if ((fp->fr_tif.fd_name < 0) ||
4875                     (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4876                         IPFERROR(139);
4877                         error = EINVAL;
4878                         goto donenolock;
4879                 }
4880         }
4881
4882         if (fp->fr_dif.fd_name != -1) {
4883                 if ((fp->fr_dif.fd_name < 0) ||
4884                     (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4885                         IPFERROR(140);
4886                         error = EINVAL;
4887                         goto donenolock;
4888                 }
4889         }
4890
4891         if (fp->fr_rif.fd_name != -1) {
4892                 if ((fp->fr_rif.fd_name < 0) ||
4893                     (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4894                         IPFERROR(141);
4895                         error = EINVAL;
4896                         goto donenolock;
4897                 }
4898         }
4899
4900         /*
4901          * Lookup all the interface names that are part of the rule.
4902          */
4903         error = ipf_synclist(softc, fp, NULL);
4904         if (error != 0)
4905                 goto donenolock;
4906         fp->fr_statecnt = 0;
4907         if (fp->fr_srctrack.ht_max_nodes != 0)
4908                 ipf_rb_ht_init(&fp->fr_srctrack);
4909
4910         /*
4911          * Look for an existing matching filter rule, but don't include the
4912          * next or interface pointer in the comparison (fr_next, fr_ifa).
4913          * This elminates rules which are indentical being loaded.  Checksum
4914          * the constant part of the filter rule to make comparisons quicker
4915          * (this meaning no pointers are included).
4916          */
4917         for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4918              p < pp; p++)
4919                 fp->fr_cksum += *p;
4920         pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4921         for (p = (u_int *)fp->fr_data; p < pp; p++)
4922                 fp->fr_cksum += *p;
4923
4924         WRITE_ENTER(&softc->ipf_mutex);
4925
4926         /*
4927          * Now that the filter rule lists are locked, we can walk the
4928          * chain of them without fear.
4929          */
4930         ftail = fprev;
4931         for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4932                 if (fp->fr_collect <= f->fr_collect) {
4933                         ftail = fprev;
4934                         f = NULL;
4935                         break;
4936                 }
4937                 fprev = ftail;
4938         }
4939
4940         for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4941                 if (ipf_rule_compare(fp, f) == 0)
4942                         break;
4943         }
4944
4945         /*
4946          * If zero'ing statistics, copy current to caller and zero.
4947          */
4948         if (addrem == 2) {
4949                 if (f == NULL) {
4950                         IPFERROR(27);
4951                         error = ESRCH;
4952                 } else {
4953                         /*
4954                          * Copy and reduce lock because of impending copyout.
4955                          * Well we should, but if we do then the atomicity of
4956                          * this call and the correctness of fr_hits and
4957                          * fr_bytes cannot be guaranteed.  As it is, this code
4958                          * only resets them to 0 if they are successfully
4959                          * copied out into user space.
4960                          */
4961                         bcopy((char *)f, (char *)fp, f->fr_size);
4962                         /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4963
4964                         /*
4965                          * When we copy this rule back out, set the data
4966                          * pointer to be what it was in user space.
4967                          */
4968                         fp->fr_data = uptr;
4969                         error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4970
4971                         if (error == 0) {
4972                                 if ((f->fr_dsize != 0) && (uptr != NULL)) {
4973                                         error = COPYOUT(f->fr_data, uptr,
4974                                                         f->fr_dsize);
4975                                         if (error == 0) {
4976                                                 f->fr_hits = 0;
4977                                                 f->fr_bytes = 0;
4978                                         } else {
4979                                                 IPFERROR(28);
4980                                                 error = EFAULT;
4981                                         }
4982                                 }
4983                         }
4984                 }
4985
4986                 if (makecopy != 0) {
4987                         if (ptr != NULL) {
4988                                 KFREES(ptr, fp->fr_dsize);
4989                         }
4990                         KFREES(fp, fp->fr_size);
4991                 }
4992                 RWLOCK_EXIT(&softc->ipf_mutex);
4993                 return error;
4994         }
4995
4996         if (f == NULL) {
4997                 /*
4998                  * At the end of this, ftail must point to the place where the
4999                  * new rule is to be saved/inserted/added.
5000                  * For SIOCAD*FR, this should be the last rule in the group of
5001                  * rules that have equal fr_collect fields.
5002                  * For SIOCIN*FR, ...
5003                  */
5004                 if (req == (ioctlcmd_t)SIOCADAFR ||
5005                     req == (ioctlcmd_t)SIOCADIFR) {
5006
5007                         for (ftail = fprev; (f = *ftail) != NULL; ) {
5008                                 if (f->fr_collect > fp->fr_collect)
5009                                         break;
5010                                 ftail = &f->fr_next;
5011                                 fprev = ftail;
5012                         }
5013                         ftail = fprev;
5014                         f = NULL;
5015                         ptr = NULL;
5016                 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5017                            req == (ioctlcmd_t)SIOCINIFR) {
5018                         while ((f = *fprev) != NULL) {
5019                                 if (f->fr_collect >= fp->fr_collect)
5020                                         break;
5021                                 fprev = &f->fr_next;
5022                         }
5023                         ftail = fprev;
5024                         if (fp->fr_hits != 0) {
5025                                 while (fp->fr_hits && (f = *ftail)) {
5026                                         if (f->fr_collect != fp->fr_collect)
5027                                                 break;
5028                                         fprev = ftail;
5029                                         ftail = &f->fr_next;
5030                                         fp->fr_hits--;
5031                                 }
5032                         }
5033                         f = NULL;
5034                         ptr = NULL;
5035                 }
5036         }
5037
5038         /*
5039          * Request to remove a rule.
5040          */
5041         if (addrem == 1) {
5042                 if (f == NULL) {
5043                         IPFERROR(29);
5044                         error = ESRCH;
5045                 } else {
5046                         /*
5047                          * Do not allow activity from user space to interfere
5048                          * with rules not loaded that way.
5049                          */
5050                         if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5051                                 IPFERROR(30);
5052                                 error = EPERM;
5053                                 goto done;
5054                         }
5055
5056                         /*
5057                          * Return EBUSY if the rule is being reference by
5058                          * something else (eg state information.)
5059                          */
5060                         if (f->fr_ref > 1) {
5061                                 IPFERROR(31);
5062                                 error = EBUSY;
5063                                 goto done;
5064                         }
5065 #ifdef  IPFILTER_SCAN
5066                         if (f->fr_isctag != -1 &&
5067                             (f->fr_isc != (struct ipscan *)-1))
5068                                 ipf_scan_detachfr(f);
5069 #endif
5070
5071                         if (unit == IPL_LOGAUTH) {
5072                                 error = ipf_auth_precmd(softc, req, f, ftail);
5073                                 goto done;
5074                         }
5075
5076                         ipf_rule_delete(softc, f, unit, set);
5077
5078                         need_free = makecopy;
5079                 }
5080         } else {
5081                 /*
5082                  * Not removing, so we must be adding/inserting a rule.
5083                  */
5084                 if (f != NULL) {
5085                         IPFERROR(32);
5086                         error = EEXIST;
5087                         goto done;
5088                 }
5089                 if (unit == IPL_LOGAUTH) {
5090                         error = ipf_auth_precmd(softc, req, fp, ftail);
5091                         goto done;
5092                 }
5093
5094                 MUTEX_NUKE(&fp->fr_lock);
5095                 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5096                 if (fp->fr_die != 0)
5097                         ipf_rule_expire_insert(softc, fp, set);
5098
5099                 fp->fr_hits = 0;
5100                 if (makecopy != 0)
5101                         fp->fr_ref = 1;
5102                 fp->fr_pnext = ftail;
5103                 fp->fr_next = *ftail;
5104                 if (fp->fr_next != NULL)
5105                         fp->fr_next->fr_pnext = &fp->fr_next;
5106                 *ftail = fp;
5107                 if (addrem == 0)
5108                         ipf_fixskip(ftail, fp, 1);
5109
5110                 fp->fr_icmpgrp = NULL;
5111                 if (fp->fr_icmphead != -1) {
5112                         group = FR_NAME(fp, fr_icmphead);
5113                         fg = ipf_group_add(softc, group, fp, 0, unit, set);
5114                         fp->fr_icmpgrp = fg;
5115                 }
5116
5117                 fp->fr_grphead = NULL;
5118                 if (fp->fr_grhead != -1) {
5119                         group = FR_NAME(fp, fr_grhead);
5120                         fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5121                                            unit, set);
5122                         fp->fr_grphead = fg;
5123                 }
5124         }
5125 done:
5126         RWLOCK_EXIT(&softc->ipf_mutex);
5127 donenolock:
5128         if (need_free || (error != 0)) {
5129                 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5130                         if ((fp->fr_satype == FRI_LOOKUP) &&
5131                             (fp->fr_srcptr != NULL))
5132                                 ipf_lookup_deref(softc, fp->fr_srctype,
5133                                                  fp->fr_srcptr);
5134                         if ((fp->fr_datype == FRI_LOOKUP) &&
5135                             (fp->fr_dstptr != NULL))
5136                                 ipf_lookup_deref(softc, fp->fr_dsttype,
5137                                                  fp->fr_dstptr);
5138                 }
5139                 if (fp->fr_grp != NULL) {
5140                         WRITE_ENTER(&softc->ipf_mutex);
5141                         ipf_group_del(softc, fp->fr_grp, fp);
5142                         RWLOCK_EXIT(&softc->ipf_mutex);
5143                 }
5144                 if ((ptr != NULL) && (makecopy != 0)) {
5145                         KFREES(ptr, fp->fr_dsize);
5146                 }
5147                 KFREES(fp, fp->fr_size);
5148         }
5149         return (error);
5150 }
5151
5152
5153 /* ------------------------------------------------------------------------ */
5154 /* Function:   ipf_rule_delete                                              */
5155 /* Returns:    Nil                                                          */
5156 /* Parameters: softc(I) - pointer to soft context main structure            */
5157 /*             f(I)     - pointer to the rule being deleted                 */
5158 /*             ftail(I) - pointer to the pointer to f                       */
5159 /*             unit(I)  - device for which this is for                      */
5160 /*             set(I)   - 1 or 0 (filter set)                               */
5161 /*                                                                          */
5162 /* This function attempts to do what it can to delete a filter rule: remove */
5163 /* it from any linked lists and remove any groups it is responsible for.    */
5164 /* But in the end, removing a rule can only drop the reference count - we   */
5165 /* must use that as the guide for whether or not it can be freed.           */
5166 /* ------------------------------------------------------------------------ */
5167 static void
5168 ipf_rule_delete(softc, f, unit, set)
5169         ipf_main_softc_t *softc;
5170         frentry_t *f;
5171         int unit, set;
5172 {
5173
5174         /*
5175          * If fr_pdnext is set, then the rule is on the expire list, so
5176          * remove it from there.
5177          */
5178         if (f->fr_pdnext != NULL) {
5179                 *f->fr_pdnext = f->fr_dnext;
5180                 if (f->fr_dnext != NULL)
5181                         f->fr_dnext->fr_pdnext = f->fr_pdnext;
5182                 f->fr_pdnext = NULL;
5183                 f->fr_dnext = NULL;
5184         }
5185
5186         ipf_fixskip(f->fr_pnext, f, -1);
5187         if (f->fr_pnext != NULL)
5188                 *f->fr_pnext = f->fr_next;
5189         if (f->fr_next != NULL)
5190                 f->fr_next->fr_pnext = f->fr_pnext;
5191         f->fr_pnext = NULL;
5192         f->fr_next = NULL;
5193
5194         (void) ipf_derefrule(softc, &f);
5195 }
5196
5197 /* ------------------------------------------------------------------------ */
5198 /* Function:   ipf_rule_expire_insert                                       */
5199 /* Returns:    Nil                                                          */
5200 /* Parameters: softc(I) - pointer to soft context main structure            */
5201 /*             f(I)     - pointer to rule to be added to expire list        */
5202 /*             set(I)   - 1 or 0 (filter set)                               */
5203 /*                                                                          */
5204 /* If the new rule has a given expiration time, insert it into the list of  */
5205 /* expiring rules with the ones to be removed first added to the front of   */
5206 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5207 /* expiration interval checks.                                              */
5208 /* ------------------------------------------------------------------------ */
5209 static void
5210 ipf_rule_expire_insert(softc, f, set)
5211         ipf_main_softc_t *softc;
5212         frentry_t *f;
5213         int set;
5214 {
5215         frentry_t *fr;
5216
5217         /*
5218          */
5219
5220         f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5221         for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5222              fr = fr->fr_dnext) {
5223                 if (f->fr_die < fr->fr_die)
5224                         break;
5225                 if (fr->fr_dnext == NULL) {
5226                         /*
5227                          * We've got to the last rule and everything
5228                          * wanted to be expired before this new node,
5229                          * so we have to tack it on the end...
5230                          */
5231                         fr->fr_dnext = f;
5232                         f->fr_pdnext = &fr->fr_dnext;
5233                         fr = NULL;
5234                         break;
5235                 }
5236         }
5237
5238         if (softc->ipf_rule_explist[set] == NULL) {
5239                 softc->ipf_rule_explist[set] = f;
5240                 f->fr_pdnext = &softc->ipf_rule_explist[set];
5241         } else if (fr != NULL) {
5242                 f->fr_dnext = fr;
5243                 f->fr_pdnext = fr->fr_pdnext;
5244                 fr->fr_pdnext = &f->fr_dnext;
5245         }
5246 }
5247
5248
5249 /* ------------------------------------------------------------------------ */
5250 /* Function:   ipf_findlookup                                               */
5251 /* Returns:    NULL = failure, else success                                 */
5252 /* Parameters: softc(I) - pointer to soft context main structure            */
5253 /*             unit(I)  - ipf device we want to find match for              */
5254 /*             fp(I)    - rule for which lookup is for                      */
5255 /*             addrp(I) - pointer to lookup information in address struct   */
5256 /*             maskp(O) - pointer to lookup information for storage         */
5257 /*                                                                          */
5258 /* When using pools and hash tables to store addresses for matching in      */
5259 /* rules, it is necessary to resolve both the object referred to by the     */
5260 /* name or address (and return that pointer) and also provide the means by  */
5261 /* which to determine if an address belongs to that object to make the      */
5262 /* packet matching quicker.                                                 */
5263 /* ------------------------------------------------------------------------ */
5264 static void *
5265 ipf_findlookup(softc, unit, fr, addrp, maskp)
5266         ipf_main_softc_t *softc;
5267         int unit;
5268         frentry_t *fr;
5269         i6addr_t *addrp, *maskp;
5270 {
5271         void *ptr = NULL;
5272
5273         switch (addrp->iplookupsubtype)
5274         {
5275         case 0 :
5276                 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5277                                          addrp->iplookupnum,
5278                                          &maskp->iplookupfunc);
5279                 break;
5280         case 1 :
5281                 if (addrp->iplookupname < 0)
5282                         break;
5283                 if (addrp->iplookupname >= fr->fr_namelen)
5284                         break;
5285                 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5286                                           fr->fr_names + addrp->iplookupname,
5287                                           &maskp->iplookupfunc);
5288                 break;
5289         default :
5290                 break;
5291         }
5292
5293         return ptr;
5294 }
5295
5296
5297 /* ------------------------------------------------------------------------ */
5298 /* Function:    ipf_funcinit                                                */
5299 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5300 /* Parameters:  softc(I) - pointer to soft context main structure           */
5301 /*              fr(I)    - pointer to filter rule                           */
5302 /*                                                                          */
5303 /* If a rule is a call rule, then check if the function it points to needs  */
5304 /* an init function to be called now the rule has been loaded.              */
5305 /* ------------------------------------------------------------------------ */
5306 static int
5307 ipf_funcinit(softc, fr)
5308         ipf_main_softc_t *softc;
5309         frentry_t *fr;
5310 {
5311         ipfunc_resolve_t *ft;
5312         int err;
5313
5314         IPFERROR(34);
5315         err = ESRCH;
5316
5317         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5318                 if (ft->ipfu_addr == fr->fr_func) {
5319                         err = 0;
5320                         if (ft->ipfu_init != NULL)
5321                                 err = (*ft->ipfu_init)(softc, fr);
5322                         break;
5323                 }
5324         return err;
5325 }
5326
5327
5328 /* ------------------------------------------------------------------------ */
5329 /* Function:    ipf_funcfini                                                */
5330 /* Returns:     Nil                                                         */
5331 /* Parameters:  softc(I) - pointer to soft context main structure           */
5332 /*              fr(I)    - pointer to filter rule                           */
5333 /*                                                                          */
5334 /* For a given filter rule, call the matching "fini" function if the rule   */
5335 /* is using a known function that would have resulted in the "init" being   */
5336 /* called for ealier.                                                       */
5337 /* ------------------------------------------------------------------------ */
5338 static void
5339 ipf_funcfini(softc, fr)
5340         ipf_main_softc_t *softc;
5341         frentry_t *fr;
5342 {
5343         ipfunc_resolve_t *ft;
5344
5345         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5346                 if (ft->ipfu_addr == fr->fr_func) {
5347                         if (ft->ipfu_fini != NULL)
5348                                 (void) (*ft->ipfu_fini)(softc, fr);
5349                         break;
5350                 }
5351 }
5352
5353
5354 /* ------------------------------------------------------------------------ */
5355 /* Function:    ipf_findfunc                                                */
5356 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5357 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5358 /*                                                                          */
5359 /* Look for a function in the table of known functions.                     */
5360 /* ------------------------------------------------------------------------ */
5361 static ipfunc_t
5362 ipf_findfunc(funcptr)
5363         ipfunc_t funcptr;
5364 {
5365         ipfunc_resolve_t *ft;
5366
5367         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5368                 if (ft->ipfu_addr == funcptr)
5369                         return funcptr;
5370         return NULL;
5371 }
5372
5373
5374 /* ------------------------------------------------------------------------ */
5375 /* Function:    ipf_resolvefunc                                             */
5376 /* Returns:     int - 0 == success, else error                              */
5377 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5378 /*                                                                          */
5379 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5380 /* This will either be the function name (if the pointer is set) or the     */
5381 /* function pointer if the name is set.  When found, fill in the other one  */
5382 /* so that the entire, complete, structure can be copied back to user space.*/
5383 /* ------------------------------------------------------------------------ */
5384 int
5385 ipf_resolvefunc(softc, data)
5386         ipf_main_softc_t *softc;
5387         void *data;
5388 {
5389         ipfunc_resolve_t res, *ft;
5390         int error;
5391
5392         error = BCOPYIN(data, &res, sizeof(res));
5393         if (error != 0) {
5394                 IPFERROR(123);
5395                 return EFAULT;
5396         }
5397
5398         if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5399                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5400                         if (strncmp(res.ipfu_name, ft->ipfu_name,
5401                                     sizeof(res.ipfu_name)) == 0) {
5402                                 res.ipfu_addr = ft->ipfu_addr;
5403                                 res.ipfu_init = ft->ipfu_init;
5404                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5405                                         IPFERROR(35);
5406                                         return EFAULT;
5407                                 }
5408                                 return 0;
5409                         }
5410         }
5411         if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5412                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5413                         if (ft->ipfu_addr == res.ipfu_addr) {
5414                                 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5415                                                sizeof(res.ipfu_name));
5416                                 res.ipfu_init = ft->ipfu_init;
5417                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5418                                         IPFERROR(36);
5419                                         return EFAULT;
5420                                 }
5421                                 return 0;
5422                         }
5423         }
5424         IPFERROR(37);
5425         return ESRCH;
5426 }
5427
5428
5429 #if !defined(_KERNEL) || SOLARIS
5430 /*
5431  * From: NetBSD
5432  * ppsratecheck(): packets (or events) per second limitation.
5433  */
5434 int
5435 ppsratecheck(lasttime, curpps, maxpps)
5436         struct timeval *lasttime;
5437         int *curpps;
5438         int maxpps;     /* maximum pps allowed */
5439 {
5440         struct timeval tv, delta;
5441         int rv;
5442
5443         GETKTIME(&tv);
5444
5445         delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5446         delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5447         if (delta.tv_usec < 0) {
5448                 delta.tv_sec--;
5449                 delta.tv_usec += 1000000;
5450         }
5451
5452         /*
5453          * check for 0,0 is so that the message will be seen at least once.
5454          * if more than one second have passed since the last update of
5455          * lasttime, reset the counter.
5456          *
5457          * we do increment *curpps even in *curpps < maxpps case, as some may
5458          * try to use *curpps for stat purposes as well.
5459          */
5460         if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5461             delta.tv_sec >= 1) {
5462                 *lasttime = tv;
5463                 *curpps = 0;
5464                 rv = 1;
5465         } else if (maxpps < 0)
5466                 rv = 1;
5467         else if (*curpps < maxpps)
5468                 rv = 1;
5469         else
5470                 rv = 0;
5471         *curpps = *curpps + 1;
5472
5473         return (rv);
5474 }
5475 #endif
5476
5477
5478 /* ------------------------------------------------------------------------ */
5479 /* Function:    ipf_derefrule                                               */
5480 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5481 /* Parameters:  fr(I) - pointer to filter rule                              */
5482 /*                                                                          */
5483 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5484 /* free it and any associated storage space being used by it.               */
5485 /* ------------------------------------------------------------------------ */
5486 int
5487 ipf_derefrule(softc, frp)
5488         ipf_main_softc_t *softc;
5489         frentry_t **frp;
5490 {
5491         frentry_t *fr;
5492         frdest_t *fdp;
5493
5494         fr = *frp;
5495         *frp = NULL;
5496
5497         MUTEX_ENTER(&fr->fr_lock);
5498         fr->fr_ref--;
5499         if (fr->fr_ref == 0) {
5500                 MUTEX_EXIT(&fr->fr_lock);
5501                 MUTEX_DESTROY(&fr->fr_lock);
5502
5503                 ipf_funcfini(softc, fr);
5504
5505                 fdp = &fr->fr_tif;
5506                 if (fdp->fd_type == FRD_DSTLIST)
5507                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5508
5509                 fdp = &fr->fr_rif;
5510                 if (fdp->fd_type == FRD_DSTLIST)
5511                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5512
5513                 fdp = &fr->fr_dif;
5514                 if (fdp->fd_type == FRD_DSTLIST)
5515                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5516
5517                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5518                     fr->fr_satype == FRI_LOOKUP)
5519                         ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5520                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5521                     fr->fr_datype == FRI_LOOKUP)
5522                         ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5523
5524                 if (fr->fr_grp != NULL)
5525                         ipf_group_del(softc, fr->fr_grp, fr);
5526
5527                 if (fr->fr_grphead != NULL)
5528                         ipf_group_del(softc, fr->fr_grphead, fr);
5529
5530                 if (fr->fr_icmpgrp != NULL)
5531                         ipf_group_del(softc, fr->fr_icmpgrp, fr);
5532
5533                 if ((fr->fr_flags & FR_COPIED) != 0) {
5534                         if (fr->fr_dsize) {
5535                                 KFREES(fr->fr_data, fr->fr_dsize);
5536                         }
5537                         KFREES(fr, fr->fr_size);
5538                         return 0;
5539                 }
5540                 return 1;
5541         } else {
5542                 MUTEX_EXIT(&fr->fr_lock);
5543         }
5544         return -1;
5545 }
5546
5547
5548 /* ------------------------------------------------------------------------ */
5549 /* Function:    ipf_grpmapinit                                              */
5550 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5551 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5552 /*                                                                          */
5553 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5554 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5555 /* ------------------------------------------------------------------------ */
5556 static int
5557 ipf_grpmapinit(softc, fr)
5558         ipf_main_softc_t *softc;
5559         frentry_t *fr;
5560 {
5561         char name[FR_GROUPLEN];
5562         iphtable_t *iph;
5563
5564 #if defined(SNPRINTF) && defined(_KERNEL)
5565         SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5566 #else
5567         (void) sprintf(name, "%d", fr->fr_arg);
5568 #endif
5569         iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5570         if (iph == NULL) {
5571                 IPFERROR(38);
5572                 return ESRCH;
5573         }
5574         if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5575                 IPFERROR(39);
5576                 return ESRCH;
5577         }
5578         iph->iph_ref++;
5579         fr->fr_ptr = iph;
5580         return 0;
5581 }
5582
5583
5584 /* ------------------------------------------------------------------------ */
5585 /* Function:    ipf_grpmapfini                                              */
5586 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5587 /* Parameters:  softc(I) - pointer to soft context main structure           */
5588 /*              fr(I)    - pointer to rule to release hash table for        */
5589 /*                                                                          */
5590 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5591 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5592 /* ------------------------------------------------------------------------ */
5593 static int
5594 ipf_grpmapfini(softc, fr)
5595         ipf_main_softc_t *softc;
5596         frentry_t *fr;
5597 {
5598         iphtable_t *iph;
5599         iph = fr->fr_ptr;
5600         if (iph != NULL)
5601                 ipf_lookup_deref(softc, IPLT_HASH, iph);
5602         return 0;
5603 }
5604
5605
5606 /* ------------------------------------------------------------------------ */
5607 /* Function:    ipf_srcgrpmap                                               */
5608 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5609 /* Parameters:  fin(I)    - pointer to packet information                   */
5610 /*              passp(IO) - pointer to current/new filter decision (unused) */
5611 /*                                                                          */
5612 /* Look for a rule group head in a hash table, using the source address as  */
5613 /* the key, and descend into that group and continue matching rules against */
5614 /* the packet.                                                              */
5615 /* ------------------------------------------------------------------------ */
5616 frentry_t *
5617 ipf_srcgrpmap(fin, passp)
5618         fr_info_t *fin;
5619         u_32_t *passp;
5620 {
5621         frgroup_t *fg;
5622         void *rval;
5623
5624         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5625                                  &fin->fin_src);
5626         if (rval == NULL)
5627                 return NULL;
5628
5629         fg = rval;
5630         fin->fin_fr = fg->fg_start;
5631         (void) ipf_scanlist(fin, *passp);
5632         return fin->fin_fr;
5633 }
5634
5635
5636 /* ------------------------------------------------------------------------ */
5637 /* Function:    ipf_dstgrpmap                                               */
5638 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5639 /* Parameters:  fin(I)    - pointer to packet information                   */
5640 /*              passp(IO) - pointer to current/new filter decision (unused) */
5641 /*                                                                          */
5642 /* Look for a rule group head in a hash table, using the destination        */
5643 /* address as the key, and descend into that group and continue matching    */
5644 /* rules against  the packet.                                               */
5645 /* ------------------------------------------------------------------------ */
5646 frentry_t *
5647 ipf_dstgrpmap(fin, passp)
5648         fr_info_t *fin;
5649         u_32_t *passp;
5650 {
5651         frgroup_t *fg;
5652         void *rval;
5653
5654         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5655                                  &fin->fin_dst);
5656         if (rval == NULL)
5657                 return NULL;
5658
5659         fg = rval;
5660         fin->fin_fr = fg->fg_start;
5661         (void) ipf_scanlist(fin, *passp);
5662         return fin->fin_fr;
5663 }
5664
5665 /*
5666  * Queue functions
5667  * ===============
5668  * These functions manage objects on queues for efficient timeouts.  There
5669  * are a number of system defined queues as well as user defined timeouts.
5670  * It is expected that a lock is held in the domain in which the queue
5671  * belongs (i.e. either state or NAT) when calling any of these functions
5672  * that prevents ipf_freetimeoutqueue() from being called at the same time
5673  * as any other.
5674  */
5675
5676
5677 /* ------------------------------------------------------------------------ */
5678 /* Function:    ipf_addtimeoutqueue                                         */
5679 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5680 /*                               timeout queue with given interval.         */
5681 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5682 /*                           of interface queues.                           */
5683 /*              seconds(I) - timeout value in seconds for this queue.       */
5684 /*                                                                          */
5685 /* This routine first looks for a timeout queue that matches the interval   */
5686 /* being requested.  If it finds one, increments the reference counter and  */
5687 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5688 /* inserts it at the top of the list.                                       */
5689 /*                                                                          */
5690 /* Locking.                                                                 */
5691 /* It is assumed that the caller of this function has an appropriate lock   */
5692 /* held (exclusively) in the domain that encompases 'parent'.               */
5693 /* ------------------------------------------------------------------------ */
5694 ipftq_t *
5695 ipf_addtimeoutqueue(softc, parent, seconds)
5696         ipf_main_softc_t *softc;
5697         ipftq_t **parent;
5698         u_int seconds;
5699 {
5700         ipftq_t *ifq;
5701         u_int period;
5702
5703         period = seconds * IPF_HZ_DIVIDE;
5704
5705         MUTEX_ENTER(&softc->ipf_timeoutlock);
5706         for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5707                 if (ifq->ifq_ttl == period) {
5708                         /*
5709                          * Reset the delete flag, if set, so the structure
5710                          * gets reused rather than freed and reallocated.
5711                          */
5712                         MUTEX_ENTER(&ifq->ifq_lock);
5713                         ifq->ifq_flags &= ~IFQF_DELETE;
5714                         ifq->ifq_ref++;
5715                         MUTEX_EXIT(&ifq->ifq_lock);
5716                         MUTEX_EXIT(&softc->ipf_timeoutlock);
5717
5718                         return ifq;
5719                 }
5720         }
5721
5722         KMALLOC(ifq, ipftq_t *);
5723         if (ifq != NULL) {
5724                 MUTEX_NUKE(&ifq->ifq_lock);
5725                 IPFTQ_INIT(ifq, period, "ipftq mutex");
5726                 ifq->ifq_next = *parent;
5727                 ifq->ifq_pnext = parent;
5728                 ifq->ifq_flags = IFQF_USER;
5729                 ifq->ifq_ref++;
5730                 *parent = ifq;
5731                 softc->ipf_userifqs++;
5732         }
5733         MUTEX_EXIT(&softc->ipf_timeoutlock);
5734         return ifq;
5735 }
5736
5737
5738 /* ------------------------------------------------------------------------ */
5739 /* Function:    ipf_deletetimeoutqueue                                      */
5740 /* Returns:     int    - new reference count value of the timeout queue     */
5741 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5742 /* Locks:       ifq->ifq_lock                                               */
5743 /*                                                                          */
5744 /* This routine must be called when we're discarding a pointer to a timeout */
5745 /* queue object, taking care of the reference counter.                      */
5746 /*                                                                          */
5747 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5748 /* check the list of user defined timeout queues and call the free function */
5749 /* below (currently commented out) to stop memory leaking.  It is done this */
5750 /* way because the locking may not be sufficient to safely do a free when   */
5751 /* this function is called.                                                 */
5752 /* ------------------------------------------------------------------------ */
5753 int
5754 ipf_deletetimeoutqueue(ifq)
5755         ipftq_t *ifq;
5756 {
5757
5758         ifq->ifq_ref--;
5759         if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5760                 ifq->ifq_flags |= IFQF_DELETE;
5761         }
5762
5763         return ifq->ifq_ref;
5764 }
5765
5766
5767 /* ------------------------------------------------------------------------ */
5768 /* Function:    ipf_freetimeoutqueue                                        */
5769 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5770 /* Returns:     Nil                                                         */
5771 /*                                                                          */
5772 /* Locking:                                                                 */
5773 /* It is assumed that the caller of this function has an appropriate lock   */
5774 /* held (exclusively) in the domain that encompases the callers "domain".   */
5775 /* The ifq_lock for this structure should not be held.                      */
5776 /*                                                                          */
5777 /* Remove a user defined timeout queue from the list of queues it is in and */
5778 /* tidy up after this is done.                                              */
5779 /* ------------------------------------------------------------------------ */
5780 void
5781 ipf_freetimeoutqueue(softc, ifq)
5782         ipf_main_softc_t *softc;
5783         ipftq_t *ifq;
5784 {
5785
5786         if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5787             ((ifq->ifq_flags & IFQF_USER) == 0)) {
5788                 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5789                        (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5790                        ifq->ifq_ref);
5791                 return;
5792         }
5793
5794         /*
5795          * Remove from its position in the list.
5796          */
5797         *ifq->ifq_pnext = ifq->ifq_next;
5798         if (ifq->ifq_next != NULL)
5799                 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5800         ifq->ifq_next = NULL;
5801         ifq->ifq_pnext = NULL;
5802
5803         MUTEX_DESTROY(&ifq->ifq_lock);
5804         ATOMIC_DEC(softc->ipf_userifqs);
5805         KFREE(ifq);
5806 }
5807
5808
5809 /* ------------------------------------------------------------------------ */
5810 /* Function:    ipf_deletequeueentry                                        */
5811 /* Returns:     Nil                                                         */
5812 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5813 /*                                                                          */
5814 /* Remove a tail queue entry from its queue and make it an orphan.          */
5815 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5816 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5817 /* the correct lock(s) may not be held that would make it safe to do so.    */
5818 /* ------------------------------------------------------------------------ */
5819 void
5820 ipf_deletequeueentry(tqe)
5821         ipftqent_t *tqe;
5822 {
5823         ipftq_t *ifq;
5824
5825         ifq = tqe->tqe_ifq;
5826
5827         MUTEX_ENTER(&ifq->ifq_lock);
5828
5829         if (tqe->tqe_pnext != NULL) {
5830                 *tqe->tqe_pnext = tqe->tqe_next;
5831                 if (tqe->tqe_next != NULL)
5832                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5833                 else    /* we must be the tail anyway */
5834                         ifq->ifq_tail = tqe->tqe_pnext;
5835
5836                 tqe->tqe_pnext = NULL;
5837                 tqe->tqe_ifq = NULL;
5838         }
5839
5840         (void) ipf_deletetimeoutqueue(ifq);
5841         ASSERT(ifq->ifq_ref > 0);
5842
5843         MUTEX_EXIT(&ifq->ifq_lock);
5844 }
5845
5846
5847 /* ------------------------------------------------------------------------ */
5848 /* Function:    ipf_queuefront                                              */
5849 /* Returns:     Nil                                                         */
5850 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5851 /*                                                                          */
5852 /* Move a queue entry to the front of the queue, if it isn't already there. */
5853 /* ------------------------------------------------------------------------ */
5854 void
5855 ipf_queuefront(tqe)
5856         ipftqent_t *tqe;
5857 {
5858         ipftq_t *ifq;
5859
5860         ifq = tqe->tqe_ifq;
5861         if (ifq == NULL)
5862                 return;
5863
5864         MUTEX_ENTER(&ifq->ifq_lock);
5865         if (ifq->ifq_head != tqe) {
5866                 *tqe->tqe_pnext = tqe->tqe_next;
5867                 if (tqe->tqe_next)
5868                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5869                 else
5870                         ifq->ifq_tail = tqe->tqe_pnext;
5871
5872                 tqe->tqe_next = ifq->ifq_head;
5873                 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5874                 ifq->ifq_head = tqe;
5875                 tqe->tqe_pnext = &ifq->ifq_head;
5876         }
5877         MUTEX_EXIT(&ifq->ifq_lock);
5878 }
5879
5880
5881 /* ------------------------------------------------------------------------ */
5882 /* Function:    ipf_queueback                                               */
5883 /* Returns:     Nil                                                         */
5884 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5885 /*              tqe(I)   - pointer to timeout queue entry                   */
5886 /*                                                                          */
5887 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5888 /* We use use ticks to calculate the expiration and mark for when we last   */
5889 /* touched the structure.                                                   */
5890 /* ------------------------------------------------------------------------ */
5891 void
5892 ipf_queueback(ticks, tqe)
5893         u_long ticks;
5894         ipftqent_t *tqe;
5895 {
5896         ipftq_t *ifq;
5897
5898         ifq = tqe->tqe_ifq;
5899         if (ifq == NULL)
5900                 return;
5901         tqe->tqe_die = ticks + ifq->ifq_ttl;
5902         tqe->tqe_touched = ticks;
5903
5904         MUTEX_ENTER(&ifq->ifq_lock);
5905         if (tqe->tqe_next != NULL) {            /* at the end already ? */
5906                 /*
5907                  * Remove from list
5908                  */
5909                 *tqe->tqe_pnext = tqe->tqe_next;
5910                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5911
5912                 /*
5913                  * Make it the last entry.
5914                  */
5915                 tqe->tqe_next = NULL;
5916                 tqe->tqe_pnext = ifq->ifq_tail;
5917                 *ifq->ifq_tail = tqe;
5918                 ifq->ifq_tail = &tqe->tqe_next;
5919         }
5920         MUTEX_EXIT(&ifq->ifq_lock);
5921 }
5922
5923
5924 /* ------------------------------------------------------------------------ */
5925 /* Function:    ipf_queueappend                                             */
5926 /* Returns:     Nil                                                         */
5927 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5928 /*              tqe(I)    - pointer to timeout queue entry                  */
5929 /*              ifq(I)    - pointer to timeout queue                        */
5930 /*              parent(I) - owing object pointer                            */
5931 /*                                                                          */
5932 /* Add a new item to this queue and put it on the very end.                 */
5933 /* We use use ticks to calculate the expiration and mark for when we last   */
5934 /* touched the structure.                                                   */
5935 /* ------------------------------------------------------------------------ */
5936 void
5937 ipf_queueappend(ticks, tqe, ifq, parent)
5938         u_long ticks;
5939         ipftqent_t *tqe;
5940         ipftq_t *ifq;
5941         void *parent;
5942 {
5943
5944         MUTEX_ENTER(&ifq->ifq_lock);
5945         tqe->tqe_parent = parent;
5946         tqe->tqe_pnext = ifq->ifq_tail;
5947         *ifq->ifq_tail = tqe;
5948         ifq->ifq_tail = &tqe->tqe_next;
5949         tqe->tqe_next = NULL;
5950         tqe->tqe_ifq = ifq;
5951         tqe->tqe_die = ticks + ifq->ifq_ttl;
5952         tqe->tqe_touched = ticks;
5953         ifq->ifq_ref++;
5954         MUTEX_EXIT(&ifq->ifq_lock);
5955 }
5956
5957
5958 /* ------------------------------------------------------------------------ */
5959 /* Function:    ipf_movequeue                                               */
5960 /* Returns:     Nil                                                         */
5961 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5962 /*              oifp(I) - old timeout queue entry was on                    */
5963 /*              nifp(I) - new timeout queue to put entry on                 */
5964 /*                                                                          */
5965 /* Move a queue entry from one timeout queue to another timeout queue.      */
5966 /* If it notices that the current entry is already last and does not need   */
5967 /* to move queue, the return.                                               */
5968 /* ------------------------------------------------------------------------ */
5969 void
5970 ipf_movequeue(ticks, tqe, oifq, nifq)
5971         u_long ticks;
5972         ipftqent_t *tqe;
5973         ipftq_t *oifq, *nifq;
5974 {
5975
5976         /*
5977          * If the queue hasn't changed and we last touched this entry at the
5978          * same ipf time, then we're not going to achieve anything by either
5979          * changing the ttl or moving it on the queue.
5980          */
5981         if (oifq == nifq && tqe->tqe_touched == ticks)
5982                 return;
5983
5984         /*
5985          * For any of this to be outside the lock, there is a risk that two
5986          * packets entering simultaneously, with one changing to a different
5987          * queue and one not, could end up with things in a bizarre state.
5988          */
5989         MUTEX_ENTER(&oifq->ifq_lock);
5990
5991         tqe->tqe_touched = ticks;
5992         tqe->tqe_die = ticks + nifq->ifq_ttl;
5993         /*
5994          * Is the operation here going to be a no-op ?
5995          */
5996         if (oifq == nifq) {
5997                 if ((tqe->tqe_next == NULL) ||
5998                     (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5999                         MUTEX_EXIT(&oifq->ifq_lock);
6000                         return;
6001                 }
6002         }
6003
6004         /*
6005          * Remove from the old queue
6006          */
6007         *tqe->tqe_pnext = tqe->tqe_next;
6008         if (tqe->tqe_next)
6009                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6010         else
6011                 oifq->ifq_tail = tqe->tqe_pnext;
6012         tqe->tqe_next = NULL;
6013
6014         /*
6015          * If we're moving from one queue to another, release the
6016          * lock on the old queue and get a lock on the new queue.
6017          * For user defined queues, if we're moving off it, call
6018          * delete in case it can now be freed.
6019          */
6020         if (oifq != nifq) {
6021                 tqe->tqe_ifq = NULL;
6022
6023                 (void) ipf_deletetimeoutqueue(oifq);
6024
6025                 MUTEX_EXIT(&oifq->ifq_lock);
6026
6027                 MUTEX_ENTER(&nifq->ifq_lock);
6028
6029                 tqe->tqe_ifq = nifq;
6030                 nifq->ifq_ref++;
6031         }
6032
6033         /*
6034          * Add to the bottom of the new queue
6035          */
6036         tqe->tqe_pnext = nifq->ifq_tail;
6037         *nifq->ifq_tail = tqe;
6038         nifq->ifq_tail = &tqe->tqe_next;
6039         MUTEX_EXIT(&nifq->ifq_lock);
6040 }
6041
6042
6043 /* ------------------------------------------------------------------------ */
6044 /* Function:    ipf_updateipid                                              */
6045 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6046 /* Parameters:  fin(I) - pointer to packet information                      */
6047 /*                                                                          */
6048 /* When we are doing NAT, change the IP of every packet to represent a      */
6049 /* single sequence of packets coming from the host, hiding any host         */
6050 /* specific sequencing that might otherwise be revealed.  If the packet is  */
6051 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6052 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
6053 /* has no match in the cache, return an error.                              */
6054 /* ------------------------------------------------------------------------ */
6055 static int
6056 ipf_updateipid(fin)
6057         fr_info_t *fin;
6058 {
6059         u_short id, ido, sums;
6060         u_32_t sumd, sum;
6061         ip_t *ip;
6062
6063         ip = fin->fin_ip;
6064         ido = ntohs(ip->ip_id);
6065         if (fin->fin_off != 0) {
6066                 sum = ipf_frag_ipidknown(fin);
6067                 if (sum == 0xffffffff)
6068                         return -1;
6069                 sum &= 0xffff;
6070                 id = (u_short)sum;
6071                 ip->ip_id = htons(id);
6072         } else {
6073                 ip_fillid(ip);
6074                 id = ntohs(ip->ip_id);
6075                 if ((fin->fin_flx & FI_FRAG) != 0)
6076                         (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6077         }
6078
6079         if (id == ido)
6080                 return 0;
6081         CALC_SUMD(ido, id, sumd);       /* DESTRUCTIVE MACRO! id,ido change */
6082         sum = (~ntohs(ip->ip_sum)) & 0xffff;
6083         sum += sumd;
6084         sum = (sum >> 16) + (sum & 0xffff);
6085         sum = (sum >> 16) + (sum & 0xffff);
6086         sums = ~(u_short)sum;
6087         ip->ip_sum = htons(sums);
6088         return 0;
6089 }
6090
6091
6092 #ifdef  NEED_FRGETIFNAME
6093 /* ------------------------------------------------------------------------ */
6094 /* Function:    ipf_getifname                                               */
6095 /* Returns:     char *    - pointer to interface name                       */
6096 /* Parameters:  ifp(I)    - pointer to network interface                    */
6097 /*              buffer(O) - pointer to where to store interface name        */
6098 /*                                                                          */
6099 /* Constructs an interface name in the buffer passed.  The buffer passed is */
6100 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6101 /* as a NULL pointer then return a pointer to a static array.               */
6102 /* ------------------------------------------------------------------------ */
6103 char *
6104 ipf_getifname(ifp, buffer)
6105         struct ifnet *ifp;
6106         char *buffer;
6107 {
6108         static char namebuf[LIFNAMSIZ];
6109 # if defined(MENTAT) || defined(__FreeBSD__)
6110         int unit, space;
6111         char temp[20];
6112         char *s;
6113 # endif
6114
6115         if (buffer == NULL)
6116                 buffer = namebuf;
6117         (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6118         buffer[LIFNAMSIZ - 1] = '\0';
6119 # if defined(MENTAT) || defined(__FreeBSD__)
6120         for (s = buffer; *s; s++)
6121                 ;
6122         unit = ifp->if_unit;
6123         space = LIFNAMSIZ - (s - buffer);
6124         if ((space > 0) && (unit >= 0)) {
6125 #  if defined(SNPRINTF) && defined(_KERNEL)
6126                 SNPRINTF(temp, sizeof(temp), "%d", unit);
6127 #  else
6128                 (void) sprintf(temp, "%d", unit);
6129 #  endif
6130                 (void) strncpy(s, temp, space);
6131         }
6132 # endif
6133         return buffer;
6134 }
6135 #endif
6136
6137
6138 /* ------------------------------------------------------------------------ */
6139 /* Function:    ipf_ioctlswitch                                             */
6140 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6141 /* Parameters:  unit(I) - device unit opened                                */
6142 /*              data(I) - pointer to ioctl data                             */
6143 /*              cmd(I)  - ioctl command                                     */
6144 /*              mode(I) - mode value                                        */
6145 /*              uid(I)  - uid making the ioctl call                         */
6146 /*              ctx(I)  - pointer to context data                           */
6147 /*                                                                          */
6148 /* Based on the value of unit, call the appropriate ioctl handler or return */
6149 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6150 /* for the device in order to execute the ioctl.  A special case is made    */
6151 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6152 /* The context data pointer is passed through as this is used as the key    */
6153 /* for locating a matching token for continued access for walking lists,    */
6154 /* etc.                                                                     */
6155 /* ------------------------------------------------------------------------ */
6156 int
6157 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6158         ipf_main_softc_t *softc;
6159         int unit, mode, uid;
6160         ioctlcmd_t cmd;
6161         void *data, *ctx;
6162 {
6163         int error = 0;
6164
6165         switch (cmd)
6166         {
6167         case SIOCIPFINTERROR :
6168                 error = BCOPYOUT(&softc->ipf_interror, data,
6169                                  sizeof(softc->ipf_interror));
6170                 if (error != 0) {
6171                         IPFERROR(40);
6172                         error = EFAULT;
6173                 }
6174                 return error;
6175         default :
6176                 break;
6177         }
6178
6179         switch (unit)
6180         {
6181         case IPL_LOGIPF :
6182                 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6183                 break;
6184         case IPL_LOGNAT :
6185                 if (softc->ipf_running > 0) {
6186                         error = ipf_nat_ioctl(softc, data, cmd, mode,
6187                                               uid, ctx);
6188                 } else {
6189                         IPFERROR(42);
6190                         error = EIO;
6191                 }
6192                 break;
6193         case IPL_LOGSTATE :
6194                 if (softc->ipf_running > 0) {
6195                         error = ipf_state_ioctl(softc, data, cmd, mode,
6196                                                 uid, ctx);
6197                 } else {
6198                         IPFERROR(43);
6199                         error = EIO;
6200                 }
6201                 break;
6202         case IPL_LOGAUTH :
6203                 if (softc->ipf_running > 0) {
6204                         error = ipf_auth_ioctl(softc, data, cmd, mode,
6205                                                uid, ctx);
6206                 } else {
6207                         IPFERROR(44);
6208                         error = EIO;
6209                 }
6210                 break;
6211         case IPL_LOGSYNC :
6212                 if (softc->ipf_running > 0) {
6213                         error = ipf_sync_ioctl(softc, data, cmd, mode,
6214                                                uid, ctx);
6215                 } else {
6216                         error = EIO;
6217                         IPFERROR(45);
6218                 }
6219                 break;
6220         case IPL_LOGSCAN :
6221 #ifdef IPFILTER_SCAN
6222                 if (softc->ipf_running > 0)
6223                         error = ipf_scan_ioctl(softc, data, cmd, mode,
6224                                                uid, ctx);
6225                 else
6226 #endif
6227                 {
6228                         error = EIO;
6229                         IPFERROR(46);
6230                 }
6231                 break;
6232         case IPL_LOGLOOKUP :
6233                 if (softc->ipf_running > 0) {
6234                         error = ipf_lookup_ioctl(softc, data, cmd, mode,
6235                                                  uid, ctx);
6236                 } else {
6237                         error = EIO;
6238                         IPFERROR(47);
6239                 }
6240                 break;
6241         default :
6242                 IPFERROR(48);
6243                 error = EIO;
6244                 break;
6245         }
6246
6247         return error;
6248 }
6249
6250
6251 /*
6252  * This array defines the expected size of objects coming into the kernel
6253  * for the various recognised object types. The first column is flags (see
6254  * below), 2nd column is current size, 3rd column is the version number of
6255  * when the current size became current.
6256  * Flags:
6257  * 1 = minimum size, not absolute size
6258  */
6259 static const int        ipf_objbytes[IPFOBJ_COUNT][3] = {
6260         { 1,    sizeof(struct frentry),         5010000 },      /* 0 */
6261         { 1,    sizeof(struct friostat),        5010000 },
6262         { 0,    sizeof(struct fr_info),         5010000 },
6263         { 0,    sizeof(struct ipf_authstat),    4010100 },
6264         { 0,    sizeof(struct ipfrstat),        5010000 },
6265         { 1,    sizeof(struct ipnat),           5010000 },      /* 5 */
6266         { 0,    sizeof(struct natstat),         5010000 },
6267         { 0,    sizeof(struct ipstate_save),    5010000 },
6268         { 1,    sizeof(struct nat_save),        5010000 },
6269         { 0,    sizeof(struct natlookup),       5010000 },
6270         { 1,    sizeof(struct ipstate),         5010000 },      /* 10 */
6271         { 0,    sizeof(struct ips_stat),        5010000 },
6272         { 0,    sizeof(struct frauth),          5010000 },
6273         { 0,    sizeof(struct ipftune),         4010100 },
6274         { 0,    sizeof(struct nat),             5010000 },
6275         { 0,    sizeof(struct ipfruleiter),     4011400 },      /* 15 */
6276         { 0,    sizeof(struct ipfgeniter),      4011400 },
6277         { 0,    sizeof(struct ipftable),        4011400 },
6278         { 0,    sizeof(struct ipflookupiter),   4011400 },
6279         { 0,    sizeof(struct ipftq) * IPF_TCP_NSTATES },
6280         { 1,    0,                              0       }, /* IPFEXPR */
6281         { 0,    0,                              0       }, /* PROXYCTL */
6282         { 0,    sizeof (struct fripf),          5010000 }
6283 };
6284
6285
6286 /* ------------------------------------------------------------------------ */
6287 /* Function:    ipf_inobj                                                   */
6288 /* Returns:     int     - 0 = success, else failure                         */
6289 /* Parameters:  softc(I) - soft context pointerto work with                 */
6290 /*              data(I)  - pointer to ioctl data                            */
6291 /*              objp(O)  - where to store ipfobj structure                  */
6292 /*              ptr(I)   - pointer to data to copy out                      */
6293 /*              type(I)  - type of structure being moved                    */
6294 /*                                                                          */
6295 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6296 /* add things to check for version numbers, sizes, etc, to make it backward */
6297 /* compatible at the ABI for user land.                                     */
6298 /* If objp is not NULL then we assume that the caller wants to see what is  */
6299 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6300 /* the caller what version of ipfilter the ioctl program was written to.    */
6301 /* ------------------------------------------------------------------------ */
6302 int
6303 ipf_inobj(softc, data, objp, ptr, type)
6304         ipf_main_softc_t *softc;
6305         void *data;
6306         ipfobj_t *objp;
6307         void *ptr;
6308         int type;
6309 {
6310         ipfobj_t obj;
6311         int error;
6312         int size;
6313
6314         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6315                 IPFERROR(49);
6316                 return EINVAL;
6317         }
6318
6319         if (objp == NULL)
6320                 objp = &obj;
6321         error = BCOPYIN(data, objp, sizeof(*objp));
6322         if (error != 0) {
6323                 IPFERROR(124);
6324                 return EFAULT;
6325         }
6326
6327         if (objp->ipfo_type != type) {
6328                 IPFERROR(50);
6329                 return EINVAL;
6330         }
6331
6332         if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6333                 if ((ipf_objbytes[type][0] & 1) != 0) {
6334                         if (objp->ipfo_size < ipf_objbytes[type][1]) {
6335                                 IPFERROR(51);
6336                                 return EINVAL;
6337                         }
6338                         size =  ipf_objbytes[type][1];
6339                 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6340                         size =  objp->ipfo_size;
6341                 } else {
6342                         IPFERROR(52);
6343                         return EINVAL;
6344                 }
6345                 error = COPYIN(objp->ipfo_ptr, ptr, size);
6346                 if (error != 0) {
6347                         IPFERROR(55);
6348                         error = EFAULT;
6349                 }
6350         } else {
6351 #ifdef  IPFILTER_COMPAT
6352                 error = ipf_in_compat(softc, objp, ptr, 0);
6353 #else
6354                 IPFERROR(54);
6355                 error = EINVAL;
6356 #endif
6357         }
6358         return error;
6359 }
6360
6361
6362 /* ------------------------------------------------------------------------ */
6363 /* Function:    ipf_inobjsz                                                 */
6364 /* Returns:     int     - 0 = success, else failure                         */
6365 /* Parameters:  softc(I) - soft context pointerto work with                 */
6366 /*              data(I)  - pointer to ioctl data                            */
6367 /*              ptr(I)   - pointer to store real data in                    */
6368 /*              type(I)  - type of structure being moved                    */
6369 /*              sz(I)    - size of data to copy                             */
6370 /*                                                                          */
6371 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6372 /* but it must not be smaller than the size defined for the type and the    */
6373 /* type must allow for varied sized objects.  The extra requirement here is */
6374 /* that sz must match the size of the object being passed in - this is not  */
6375 /* not possible nor required in ipf_inobj().                                */
6376 /* ------------------------------------------------------------------------ */
6377 int
6378 ipf_inobjsz(softc, data, ptr, type, sz)
6379         ipf_main_softc_t *softc;
6380         void *data;
6381         void *ptr;
6382         int type, sz;
6383 {
6384         ipfobj_t obj;
6385         int error;
6386
6387         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6388                 IPFERROR(56);
6389                 return EINVAL;
6390         }
6391
6392         error = BCOPYIN(data, &obj, sizeof(obj));
6393         if (error != 0) {
6394                 IPFERROR(125);
6395                 return EFAULT;
6396         }
6397
6398         if (obj.ipfo_type != type) {
6399                 IPFERROR(58);
6400                 return EINVAL;
6401         }
6402
6403         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6404                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6405                     (sz < ipf_objbytes[type][1])) {
6406                         IPFERROR(57);
6407                         return EINVAL;
6408                 }
6409                 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6410                 if (error != 0) {
6411                         IPFERROR(61);
6412                         error = EFAULT;
6413                 }
6414         } else {
6415 #ifdef  IPFILTER_COMPAT
6416                 error = ipf_in_compat(softc, &obj, ptr, sz);
6417 #else
6418                 IPFERROR(60);
6419                 error = EINVAL;
6420 #endif
6421         }
6422         return error;
6423 }
6424
6425
6426 /* ------------------------------------------------------------------------ */
6427 /* Function:    ipf_outobjsz                                                */
6428 /* Returns:     int     - 0 = success, else failure                         */
6429 /* Parameters:  data(I) - pointer to ioctl data                             */
6430 /*              ptr(I)  - pointer to store real data in                     */
6431 /*              type(I) - type of structure being moved                     */
6432 /*              sz(I)   - size of data to copy                              */
6433 /*                                                                          */
6434 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6435 /* but it must not be smaller than the size defined for the type and the    */
6436 /* type must allow for varied sized objects.  The extra requirement here is */
6437 /* that sz must match the size of the object being passed in - this is not  */
6438 /* not possible nor required in ipf_outobj().                               */
6439 /* ------------------------------------------------------------------------ */
6440 int
6441 ipf_outobjsz(softc, data, ptr, type, sz)
6442         ipf_main_softc_t *softc;
6443         void *data;
6444         void *ptr;
6445         int type, sz;
6446 {
6447         ipfobj_t obj;
6448         int error;
6449
6450         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6451                 IPFERROR(62);
6452                 return EINVAL;
6453         }
6454
6455         error = BCOPYIN(data, &obj, sizeof(obj));
6456         if (error != 0) {
6457                 IPFERROR(127);
6458                 return EFAULT;
6459         }
6460
6461         if (obj.ipfo_type != type) {
6462                 IPFERROR(63);
6463                 return EINVAL;
6464         }
6465
6466         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6467                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6468                     (sz < ipf_objbytes[type][1])) {
6469                         IPFERROR(146);
6470                         return EINVAL;
6471                 }
6472                 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6473                 if (error != 0) {
6474                         IPFERROR(66);
6475                         error = EFAULT;
6476                 }
6477         } else {
6478 #ifdef  IPFILTER_COMPAT
6479                 error = ipf_out_compat(softc, &obj, ptr);
6480 #else
6481                 IPFERROR(65);
6482                 error = EINVAL;
6483 #endif
6484         }
6485         return error;
6486 }
6487
6488
6489 /* ------------------------------------------------------------------------ */
6490 /* Function:    ipf_outobj                                                  */
6491 /* Returns:     int     - 0 = success, else failure                         */
6492 /* Parameters:  data(I) - pointer to ioctl data                             */
6493 /*              ptr(I)  - pointer to store real data in                     */
6494 /*              type(I) - type of structure being moved                     */
6495 /*                                                                          */
6496 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6497 /* future, we add things to check for version numbers, sizes, etc, to make  */
6498 /* it backward  compatible at the ABI for user land.                        */
6499 /* ------------------------------------------------------------------------ */
6500 int
6501 ipf_outobj(softc, data, ptr, type)
6502         ipf_main_softc_t *softc;
6503         void *data;
6504         void *ptr;
6505         int type;
6506 {
6507         ipfobj_t obj;
6508         int error;
6509
6510         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6511                 IPFERROR(67);
6512                 return EINVAL;
6513         }
6514
6515         error = BCOPYIN(data, &obj, sizeof(obj));
6516         if (error != 0) {
6517                 IPFERROR(126);
6518                 return EFAULT;
6519         }
6520
6521         if (obj.ipfo_type != type) {
6522                 IPFERROR(68);
6523                 return EINVAL;
6524         }
6525
6526         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6527                 if ((ipf_objbytes[type][0] & 1) != 0) {
6528                         if (obj.ipfo_size < ipf_objbytes[type][1]) {
6529                                 IPFERROR(69);
6530                                 return EINVAL;
6531                         }
6532                 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6533                         IPFERROR(70);
6534                         return EINVAL;
6535                 }
6536
6537                 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6538                 if (error != 0) {
6539                         IPFERROR(73);
6540                         error = EFAULT;
6541                 }
6542         } else {
6543 #ifdef  IPFILTER_COMPAT
6544                 error = ipf_out_compat(softc, &obj, ptr);
6545 #else
6546                 IPFERROR(72);
6547                 error = EINVAL;
6548 #endif
6549         }
6550         return error;
6551 }
6552
6553
6554 /* ------------------------------------------------------------------------ */
6555 /* Function:    ipf_outobjk                                                 */
6556 /* Returns:     int     - 0 = success, else failure                         */
6557 /* Parameters:  obj(I)  - pointer to data description structure             */
6558 /*              ptr(I)  - pointer to kernel data to copy out                */
6559 /*                                                                          */
6560 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6561 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6562 /* already populated with information and now we just need to use it.       */
6563 /* There is no need for this function to have a "type" parameter as there   */
6564 /* is no point in validating information that comes from the kernel with    */
6565 /* itself.                                                                  */
6566 /* ------------------------------------------------------------------------ */
6567 int
6568 ipf_outobjk(softc, obj, ptr)
6569         ipf_main_softc_t *softc;
6570         ipfobj_t *obj;
6571         void *ptr;
6572 {
6573         int type = obj->ipfo_type;
6574         int error;
6575
6576         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6577                 IPFERROR(147);
6578                 return EINVAL;
6579         }
6580
6581         if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6582                 if ((ipf_objbytes[type][0] & 1) != 0) {
6583                         if (obj->ipfo_size < ipf_objbytes[type][1]) {
6584                                 IPFERROR(148);
6585                                 return EINVAL;
6586                         }
6587
6588                 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6589                         IPFERROR(149);
6590                         return EINVAL;
6591                 }
6592
6593                 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6594                 if (error != 0) {
6595                         IPFERROR(150);
6596                         error = EFAULT;
6597                 }
6598         } else {
6599 #ifdef  IPFILTER_COMPAT
6600                 error = ipf_out_compat(softc, obj, ptr);
6601 #else
6602                 IPFERROR(151);
6603                 error = EINVAL;
6604 #endif
6605         }
6606         return error;
6607 }
6608
6609
6610 /* ------------------------------------------------------------------------ */
6611 /* Function:    ipf_checkl4sum                                              */
6612 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6613 /* Parameters:  fin(I) - pointer to packet information                      */
6614 /*                                                                          */
6615 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6616 /* not possible, return without indicating a failure or success but in a    */
6617 /* way that is ditinguishable. This function should only be called by the   */
6618 /* ipf_checkv6sum() for each platform.                                      */
6619 /* ------------------------------------------------------------------------ */
6620 INLINE int
6621 ipf_checkl4sum(fin)
6622         fr_info_t *fin;
6623 {
6624         u_short sum, hdrsum, *csump;
6625         udphdr_t *udp;
6626         int dosum;
6627
6628         /*
6629          * If the TCP packet isn't a fragment, isn't too short and otherwise
6630          * isn't already considered "bad", then validate the checksum.  If
6631          * this check fails then considered the packet to be "bad".
6632          */
6633         if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6634                 return 1;
6635
6636         DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6637         if (fin->fin_out == 1) {
6638                 fin->fin_cksum = FI_CK_SUMOK;
6639                 return 0;
6640         }
6641
6642         csump = NULL;
6643         hdrsum = 0;
6644         dosum = 0;
6645         sum = 0;
6646
6647         switch (fin->fin_p)
6648         {
6649         case IPPROTO_TCP :
6650                 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6651                 dosum = 1;
6652                 break;
6653
6654         case IPPROTO_UDP :
6655                 udp = fin->fin_dp;
6656                 if (udp->uh_sum != 0) {
6657                         csump = &udp->uh_sum;
6658                         dosum = 1;
6659                 }
6660                 break;
6661
6662 #ifdef USE_INET6
6663         case IPPROTO_ICMPV6 :
6664                 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6665                 dosum = 1;
6666                 break;
6667 #endif
6668
6669         case IPPROTO_ICMP :
6670                 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6671                 dosum = 1;
6672                 break;
6673
6674         default :
6675                 return 1;
6676                 /*NOTREACHED*/
6677         }
6678
6679         if (csump != NULL)
6680                 hdrsum = *csump;
6681
6682         if (dosum) {
6683                 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6684         }
6685 #if !defined(_KERNEL)
6686         if (sum == hdrsum) {
6687                 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6688         } else {
6689                 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6690         }
6691 #endif
6692         DT2(l4sums, u_short, hdrsum, u_short, sum);
6693 #ifdef USE_INET6
6694         if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6695 #else
6696         if (hdrsum == sum) {
6697 #endif
6698                 fin->fin_cksum = FI_CK_SUMOK;
6699                 return 0;
6700         }
6701         fin->fin_cksum = FI_CK_BAD;
6702         return -1;
6703 }
6704
6705
6706 /* ------------------------------------------------------------------------ */
6707 /* Function:    ipf_ifpfillv4addr                                           */
6708 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6709 /* Parameters:  atype(I)   - type of network address update to perform      */
6710 /*              sin(I)     - pointer to source of address information       */
6711 /*              mask(I)    - pointer to source of netmask information       */
6712 /*              inp(I)     - pointer to destination address store           */
6713 /*              inpmask(I) - pointer to destination netmask store           */
6714 /*                                                                          */
6715 /* Given a type of network address update (atype) to perform, copy          */
6716 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6717 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6718 /* which case the operation fails.  For all values of atype other than      */
6719 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6720 /* value.                                                                   */
6721 /* ------------------------------------------------------------------------ */
6722 int
6723 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6724         int atype;
6725         struct sockaddr_in *sin, *mask;
6726         struct in_addr *inp, *inpmask;
6727 {
6728         if (inpmask != NULL && atype != FRI_NETMASKED)
6729                 inpmask->s_addr = 0xffffffff;
6730
6731         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6732                 if (atype == FRI_NETMASKED) {
6733                         if (inpmask == NULL)
6734                                 return -1;
6735                         inpmask->s_addr = mask->sin_addr.s_addr;
6736                 }
6737                 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6738         } else {
6739                 inp->s_addr = sin->sin_addr.s_addr;
6740         }
6741         return 0;
6742 }
6743
6744
6745 #ifdef  USE_INET6
6746 /* ------------------------------------------------------------------------ */
6747 /* Function:    ipf_ifpfillv6addr                                           */
6748 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6749 /* Parameters:  atype(I)   - type of network address update to perform      */
6750 /*              sin(I)     - pointer to source of address information       */
6751 /*              mask(I)    - pointer to source of netmask information       */
6752 /*              inp(I)     - pointer to destination address store           */
6753 /*              inpmask(I) - pointer to destination netmask store           */
6754 /*                                                                          */
6755 /* Given a type of network address update (atype) to perform, copy          */
6756 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6757 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6758 /* which case the operation fails.  For all values of atype other than      */
6759 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6760 /* value.                                                                   */
6761 /* ------------------------------------------------------------------------ */
6762 int
6763 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6764         int atype;
6765         struct sockaddr_in6 *sin, *mask;
6766         i6addr_t *inp, *inpmask;
6767 {
6768         i6addr_t *src, *and;
6769
6770         src = (i6addr_t *)&sin->sin6_addr;
6771         and = (i6addr_t *)&mask->sin6_addr;
6772
6773         if (inpmask != NULL && atype != FRI_NETMASKED) {
6774                 inpmask->i6[0] = 0xffffffff;
6775                 inpmask->i6[1] = 0xffffffff;
6776                 inpmask->i6[2] = 0xffffffff;
6777                 inpmask->i6[3] = 0xffffffff;
6778         }
6779
6780         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6781                 if (atype == FRI_NETMASKED) {
6782                         if (inpmask == NULL)
6783                                 return -1;
6784                         inpmask->i6[0] = and->i6[0];
6785                         inpmask->i6[1] = and->i6[1];
6786                         inpmask->i6[2] = and->i6[2];
6787                         inpmask->i6[3] = and->i6[3];
6788                 }
6789
6790                 inp->i6[0] = src->i6[0] & and->i6[0];
6791                 inp->i6[1] = src->i6[1] & and->i6[1];
6792                 inp->i6[2] = src->i6[2] & and->i6[2];
6793                 inp->i6[3] = src->i6[3] & and->i6[3];
6794         } else {
6795                 inp->i6[0] = src->i6[0];
6796                 inp->i6[1] = src->i6[1];
6797                 inp->i6[2] = src->i6[2];
6798                 inp->i6[3] = src->i6[3];
6799         }
6800         return 0;
6801 }
6802 #endif
6803
6804
6805 /* ------------------------------------------------------------------------ */
6806 /* Function:    ipf_matchtag                                                */
6807 /* Returns:     0 == mismatch, 1 == match.                                  */
6808 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6809 /*              tag2(I) - pointer to second tag to compare                  */
6810 /*                                                                          */
6811 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6812 /* considered to be a match or not match, respectively.  The tag is 16      */
6813 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6814 /* compare the ints instead, for speed. tag1 is the master of the           */
6815 /* comparison.  This function should only be called with both tag1 and tag2 */
6816 /* as non-NULL pointers.                                                    */
6817 /* ------------------------------------------------------------------------ */
6818 int
6819 ipf_matchtag(tag1, tag2)
6820         ipftag_t *tag1, *tag2;
6821 {
6822         if (tag1 == tag2)
6823                 return 1;
6824
6825         if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6826                 return 1;
6827
6828         if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6829             (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6830             (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6831             (tag1->ipt_num[3] == tag2->ipt_num[3]))
6832                 return 1;
6833         return 0;
6834 }
6835
6836
6837 /* ------------------------------------------------------------------------ */
6838 /* Function:    ipf_coalesce                                                */
6839 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6840 /* Parameters:  fin(I) - pointer to packet information                      */
6841 /*                                                                          */
6842 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6843 /* If this call returns a failure then the buffers have also been freed.    */
6844 /* ------------------------------------------------------------------------ */
6845 int
6846 ipf_coalesce(fin)
6847         fr_info_t *fin;
6848 {
6849
6850         if ((fin->fin_flx & FI_COALESCE) != 0)
6851                 return 1;
6852
6853         /*
6854          * If the mbuf pointers indicate that there is no mbuf to work with,
6855          * return but do not indicate success or failure.
6856          */
6857         if (fin->fin_m == NULL || fin->fin_mp == NULL)
6858                 return 0;
6859
6860 #if defined(_KERNEL)
6861         if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6862                 ipf_main_softc_t *softc = fin->fin_main_soft;
6863
6864                 DT1(frb_coalesce, fr_info_t *, fin);
6865                 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6866 # ifdef MENTAT
6867                 FREE_MB_T(*fin->fin_mp);
6868 # endif
6869                 fin->fin_reason = FRB_COALESCE;
6870                 *fin->fin_mp = NULL;
6871                 fin->fin_m = NULL;
6872                 return -1;
6873         }
6874 #else
6875         fin = fin;      /* LINT */
6876 #endif
6877         return 1;
6878 }
6879
6880
6881 /*
6882  * The following table lists all of the tunable variables that can be
6883  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6884  * in the table below is as follows:
6885  *
6886  * pointer to value, name of value, minimum, maximum, size of the value's
6887  *     container, value attribute flags
6888  *
6889  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6890  * means the value can only be written to when IPFilter is loaded but disabled.
6891  * The obvious implication is if neither of these are set then the value can be
6892  * changed at any time without harm.
6893  */
6894
6895
6896 /* ------------------------------------------------------------------------ */
6897 /* Function:    ipf_tune_findbycookie                                       */
6898 /* Returns:     NULL = search failed, else pointer to tune struct           */
6899 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6900 /*              next(O)   - pointer to place to store the cookie for the    */
6901 /*                          "next" tuneable, if it is desired.              */
6902 /*                                                                          */
6903 /* This function is used to walk through all of the existing tunables with  */
6904 /* successive calls.  It searches the known tunables for the one which has  */
6905 /* a matching value for "cookie" - ie its address.  When returning a match, */
6906 /* the next one to be found may be returned inside next.                    */
6907 /* ------------------------------------------------------------------------ */
6908 static ipftuneable_t *
6909 ipf_tune_findbycookie(ptop, cookie, next)
6910         ipftuneable_t **ptop;
6911         void *cookie, **next;
6912 {
6913         ipftuneable_t *ta, **tap;
6914
6915         for (ta = *ptop; ta->ipft_name != NULL; ta++)
6916                 if (ta == cookie) {
6917                         if (next != NULL) {
6918                                 /*
6919                                  * If the next entry in the array has a name
6920                                  * present, then return a pointer to it for
6921                                  * where to go next, else return a pointer to
6922                                  * the dynaminc list as a key to search there
6923                                  * next.  This facilitates a weak linking of
6924                                  * the two "lists" together.
6925                                  */
6926                                 if ((ta + 1)->ipft_name != NULL)
6927                                         *next = ta + 1;
6928                                 else
6929                                         *next = ptop;
6930                         }
6931                         return ta;
6932                 }
6933
6934         for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6935                 if (tap == cookie) {
6936                         if (next != NULL)
6937                                 *next = &ta->ipft_next;
6938                         return ta;
6939                 }
6940
6941         if (next != NULL)
6942                 *next = NULL;
6943         return NULL;
6944 }
6945
6946
6947 /* ------------------------------------------------------------------------ */
6948 /* Function:    ipf_tune_findbyname                                         */
6949 /* Returns:     NULL = search failed, else pointer to tune struct           */
6950 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6951 /*                                                                          */
6952 /* Search the static array of tuneables and the list of dynamic tuneables   */
6953 /* for an entry with a matching name.  If we can find one, return a pointer */
6954 /* to the matching structure.                                               */
6955 /* ------------------------------------------------------------------------ */
6956 static ipftuneable_t *
6957 ipf_tune_findbyname(top, name)
6958         ipftuneable_t *top;
6959         const char *name;
6960 {
6961         ipftuneable_t *ta;
6962
6963         for (ta = top; ta != NULL; ta = ta->ipft_next)
6964                 if (!strcmp(ta->ipft_name, name)) {
6965                         return ta;
6966                 }
6967
6968         return NULL;
6969 }
6970
6971
6972 /* ------------------------------------------------------------------------ */
6973 /* Function:    ipf_tune_add_array                                          */
6974 /* Returns:     int - 0 == success, else failure                            */
6975 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6976 /*                                                                          */
6977 /* Appends tune structures from the array passed in (newtune) to the end of */
6978 /* the current list of "dynamic" tuneable parameters.                       */
6979 /* If any entry to be added is already present (by name) then the operation */
6980 /* is aborted - entries that have been added are removed before returning.  */
6981 /* An entry with no name (NULL) is used as the indication that the end of   */
6982 /* the array has been reached.                                              */
6983 /* ------------------------------------------------------------------------ */
6984 int
6985 ipf_tune_add_array(softc, newtune)
6986         ipf_main_softc_t *softc;
6987         ipftuneable_t *newtune;
6988 {
6989         ipftuneable_t *nt, *dt;
6990         int error = 0;
6991
6992         for (nt = newtune; nt->ipft_name != NULL; nt++) {
6993                 error = ipf_tune_add(softc, nt);
6994                 if (error != 0) {
6995                         for (dt = newtune; dt != nt; dt++) {
6996                                 (void) ipf_tune_del(softc, dt);
6997                         }
6998                 }
6999         }
7000
7001         return error;
7002 }
7003
7004
7005 /* ------------------------------------------------------------------------ */
7006 /* Function:    ipf_tune_array_link                                         */
7007 /* Returns:     0 == success, -1 == failure                                 */
7008 /* Parameters:  softc(I) - soft context pointerto work with                 */
7009 /*              array(I) - pointer to an array of tuneables                 */
7010 /*                                                                          */
7011 /* Given an array of tunables (array), append them to the current list of   */
7012 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7013 /* the array for being appended to the list, initialise all of the next     */
7014 /* pointers so we don't need to walk parts of it with ++ and others with    */
7015 /* next. The array is expected to have an entry with a NULL name as the     */
7016 /* terminator. Trying to add an array with no non-NULL names will return as */
7017 /* a failure.                                                               */
7018 /* ------------------------------------------------------------------------ */
7019 int
7020 ipf_tune_array_link(softc, array)
7021         ipf_main_softc_t *softc;
7022         ipftuneable_t *array;
7023 {
7024         ipftuneable_t *t, **p;
7025
7026         t = array;
7027         if (t->ipft_name == NULL)
7028                 return -1;
7029
7030         for (; t[1].ipft_name != NULL; t++)
7031                 t[0].ipft_next = &t[1];
7032         t->ipft_next = NULL;
7033
7034         /*
7035          * Since a pointer to the last entry isn't kept, we need to find it
7036          * each time we want to add new variables to the list.
7037          */
7038         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7039                 if (t->ipft_name == NULL)
7040                         break;
7041         *p = array;
7042
7043         return 0;
7044 }
7045
7046
7047 /* ------------------------------------------------------------------------ */
7048 /* Function:    ipf_tune_array_unlink                                       */
7049 /* Returns:     0 == success, -1 == failure                                 */
7050 /* Parameters:  softc(I) - soft context pointerto work with                 */
7051 /*              array(I) - pointer to an array of tuneables                 */
7052 /*                                                                          */
7053 /* ------------------------------------------------------------------------ */
7054 int
7055 ipf_tune_array_unlink(softc, array)
7056         ipf_main_softc_t *softc;
7057         ipftuneable_t *array;
7058 {
7059         ipftuneable_t *t, **p;
7060
7061         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7062                 if (t == array)
7063                         break;
7064         if (t == NULL)
7065                 return -1;
7066
7067         for (; t[1].ipft_name != NULL; t++)
7068                 ;
7069
7070         *p = t->ipft_next;
7071
7072         return 0;
7073 }
7074
7075
7076 /* ------------------------------------------------------------------------ */
7077 /* Function:   ipf_tune_array_copy                                          */
7078 /* Returns:    NULL = failure, else pointer to new array                    */
7079 /* Parameters: base(I)     - pointer to structure base                      */
7080 /*             size(I)     - size of the array at template                  */
7081 /*             template(I) - original array to copy                         */
7082 /*                                                                          */
7083 /* Allocate memory for a new set of tuneable values and copy everything     */
7084 /* from template into the new region of memory.  The new region is full of  */
7085 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7086 /*                                                                          */
7087 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7088 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
7089 /* location of the tuneable value inside the structure pointed to by base.  */
7090 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7091 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7092 /* ipftp_void that points to the stored value.                              */
7093 /* ------------------------------------------------------------------------ */
7094 ipftuneable_t *
7095 ipf_tune_array_copy(base, size, template)
7096         void *base;
7097         size_t size;
7098         ipftuneable_t *template;
7099 {
7100         ipftuneable_t *copy;
7101         int i;
7102
7103
7104         KMALLOCS(copy, ipftuneable_t *, size);
7105         if (copy == NULL) {
7106                 return NULL;
7107         }
7108         bcopy(template, copy, size);
7109
7110         for (i = 0; copy[i].ipft_name; i++) {
7111                 copy[i].ipft_una.ipftp_offset += (u_long)base;
7112                 copy[i].ipft_next = copy + i + 1;
7113         }
7114
7115         return copy;
7116 }
7117
7118
7119 /* ------------------------------------------------------------------------ */
7120 /* Function:    ipf_tune_add                                                */
7121 /* Returns:     int - 0 == success, else failure                            */
7122 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7123 /*                                                                          */
7124 /* Appends tune structures from the array passed in (newtune) to the end of */
7125 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
7126 /* owner of the object is not expected to ever change "ipft_next".          */
7127 /* ------------------------------------------------------------------------ */
7128 int
7129 ipf_tune_add(softc, newtune)
7130         ipf_main_softc_t *softc;
7131         ipftuneable_t *newtune;
7132 {
7133         ipftuneable_t *ta, **tap;
7134
7135         ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7136         if (ta != NULL) {
7137                 IPFERROR(74);
7138                 return EEXIST;
7139         }
7140
7141         for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7142                 ;
7143
7144         newtune->ipft_next = NULL;
7145         *tap = newtune;
7146         return 0;
7147 }
7148
7149
7150 /* ------------------------------------------------------------------------ */
7151 /* Function:    ipf_tune_del                                                */
7152 /* Returns:     int - 0 == success, else failure                            */
7153 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7154 /*                        current dynamic tuneables                         */
7155 /*                                                                          */
7156 /* Search for the tune structure, by pointer, in the list of those that are */
7157 /* dynamically added at run time.  If found, adjust the list so that this   */
7158 /* structure is no longer part of it.                                       */
7159 /* ------------------------------------------------------------------------ */
7160 int
7161 ipf_tune_del(softc, oldtune)
7162         ipf_main_softc_t *softc;
7163         ipftuneable_t *oldtune;
7164 {
7165         ipftuneable_t *ta, **tap;
7166         int error = 0;
7167
7168         for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7169              tap = &ta->ipft_next) {
7170                 if (ta == oldtune) {
7171                         *tap = oldtune->ipft_next;
7172                         oldtune->ipft_next = NULL;
7173                         break;
7174                 }
7175         }
7176
7177         if (ta == NULL) {
7178                 error = ESRCH;
7179                 IPFERROR(75);
7180         }
7181         return error;
7182 }
7183
7184
7185 /* ------------------------------------------------------------------------ */
7186 /* Function:    ipf_tune_del_array                                          */
7187 /* Returns:     int - 0 == success, else failure                            */
7188 /* Parameters:  oldtune - pointer to tuneables array                        */
7189 /*                                                                          */
7190 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7191 /* tunables.  If one entry should fail to be found, an error will be        */
7192 /* returned and no further ones removed.                                    */
7193 /* An entry with a NULL name is used as the indicator of the last entry in  */
7194 /* the array.                                                               */
7195 /* ------------------------------------------------------------------------ */
7196 int
7197 ipf_tune_del_array(softc, oldtune)
7198         ipf_main_softc_t *softc;
7199         ipftuneable_t *oldtune;
7200 {
7201         ipftuneable_t *ot;
7202         int error = 0;
7203
7204         for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7205                 error = ipf_tune_del(softc, ot);
7206                 if (error != 0)
7207                         break;
7208         }
7209
7210         return error;
7211
7212 }
7213
7214
7215 /* ------------------------------------------------------------------------ */
7216 /* Function:    ipf_tune                                                    */
7217 /* Returns:     int - 0 == success, else failure                            */
7218 /* Parameters:  cmd(I)  - ioctl command number                              */
7219 /*              data(I) - pointer to ioctl data structure                   */
7220 /*                                                                          */
7221 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7222 /* three ioctls provide the means to access and control global variables    */
7223 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7224 /* changed without rebooting, reloading or recompiling.  The initialisation */
7225 /* and 'destruction' routines of the various components of ipfilter are all */
7226 /* each responsible for handling their own values being too big.            */
7227 /* ------------------------------------------------------------------------ */
7228 int
7229 ipf_ipftune(softc, cmd, data)
7230         ipf_main_softc_t *softc;
7231         ioctlcmd_t cmd;
7232         void *data;
7233 {
7234         ipftuneable_t *ta;
7235         ipftune_t tu;
7236         void *cookie;
7237         int error;
7238
7239         error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7240         if (error != 0)
7241                 return error;
7242
7243         tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7244         cookie = tu.ipft_cookie;
7245         ta = NULL;
7246
7247         switch (cmd)
7248         {
7249         case SIOCIPFGETNEXT :
7250                 /*
7251                  * If cookie is non-NULL, assume it to be a pointer to the last
7252                  * entry we looked at, so find it (if possible) and return a
7253                  * pointer to the next one after it.  The last entry in the
7254                  * the table is a NULL entry, so when we get to it, set cookie
7255                  * to NULL and return that, indicating end of list, erstwhile
7256                  * if we come in with cookie set to NULL, we are starting anew
7257                  * at the front of the list.
7258                  */
7259                 if (cookie != NULL) {
7260                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7261                                                    cookie, &tu.ipft_cookie);
7262                 } else {
7263                         ta = softc->ipf_tuners;
7264                         tu.ipft_cookie = ta + 1;
7265                 }
7266                 if (ta != NULL) {
7267                         /*
7268                          * Entry found, but does the data pointed to by that
7269                          * row fit in what we can return?
7270                          */
7271                         if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7272                                 IPFERROR(76);
7273                                 return EINVAL;
7274                         }
7275
7276                         tu.ipft_vlong = 0;
7277                         if (ta->ipft_sz == sizeof(u_long))
7278                                 tu.ipft_vlong = *ta->ipft_plong;
7279                         else if (ta->ipft_sz == sizeof(u_int))
7280                                 tu.ipft_vint = *ta->ipft_pint;
7281                         else if (ta->ipft_sz == sizeof(u_short))
7282                                 tu.ipft_vshort = *ta->ipft_pshort;
7283                         else if (ta->ipft_sz == sizeof(u_char))
7284                                 tu.ipft_vchar = *ta->ipft_pchar;
7285
7286                         tu.ipft_sz = ta->ipft_sz;
7287                         tu.ipft_min = ta->ipft_min;
7288                         tu.ipft_max = ta->ipft_max;
7289                         tu.ipft_flags = ta->ipft_flags;
7290                         bcopy(ta->ipft_name, tu.ipft_name,
7291                               MIN(sizeof(tu.ipft_name),
7292                                   strlen(ta->ipft_name) + 1));
7293                 }
7294                 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7295                 break;
7296
7297         case SIOCIPFGET :
7298         case SIOCIPFSET :
7299                 /*
7300                  * Search by name or by cookie value for a particular entry
7301                  * in the tuning paramter table.
7302                  */
7303                 IPFERROR(77);
7304                 error = ESRCH;
7305                 if (cookie != NULL) {
7306                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7307                                                    cookie, NULL);
7308                         if (ta != NULL)
7309                                 error = 0;
7310                 } else if (tu.ipft_name[0] != '\0') {
7311                         ta = ipf_tune_findbyname(softc->ipf_tuners,
7312                                                  tu.ipft_name);
7313                         if (ta != NULL)
7314                                 error = 0;
7315                 }
7316                 if (error != 0)
7317                         break;
7318
7319                 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7320                         /*
7321                          * Fetch the tuning parameters for a particular value
7322                          */
7323                         tu.ipft_vlong = 0;
7324                         if (ta->ipft_sz == sizeof(u_long))
7325                                 tu.ipft_vlong = *ta->ipft_plong;
7326                         else if (ta->ipft_sz == sizeof(u_int))
7327                                 tu.ipft_vint = *ta->ipft_pint;
7328                         else if (ta->ipft_sz == sizeof(u_short))
7329                                 tu.ipft_vshort = *ta->ipft_pshort;
7330                         else if (ta->ipft_sz == sizeof(u_char))
7331                                 tu.ipft_vchar = *ta->ipft_pchar;
7332                         tu.ipft_cookie = ta;
7333                         tu.ipft_sz = ta->ipft_sz;
7334                         tu.ipft_min = ta->ipft_min;
7335                         tu.ipft_max = ta->ipft_max;
7336                         tu.ipft_flags = ta->ipft_flags;
7337                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7338
7339                 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7340                         /*
7341                          * Set an internal parameter.  The hard part here is
7342                          * getting the new value safely and correctly out of
7343                          * the kernel (given we only know its size, not type.)
7344                          */
7345                         u_long in;
7346
7347                         if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7348                             (softc->ipf_running > 0)) {
7349                                 IPFERROR(78);
7350                                 error = EBUSY;
7351                                 break;
7352                         }
7353
7354                         in = tu.ipft_vlong;
7355                         if (in < ta->ipft_min || in > ta->ipft_max) {
7356                                 IPFERROR(79);
7357                                 error = EINVAL;
7358                                 break;
7359                         }
7360
7361                         if (ta->ipft_func != NULL) {
7362                                 SPL_INT(s);
7363
7364                                 SPL_NET(s);
7365                                 error = (*ta->ipft_func)(softc, ta,
7366                                                          &tu.ipft_un);
7367                                 SPL_X(s);
7368
7369                         } else if (ta->ipft_sz == sizeof(u_long)) {
7370                                 tu.ipft_vlong = *ta->ipft_plong;
7371                                 *ta->ipft_plong = in;
7372
7373                         } else if (ta->ipft_sz == sizeof(u_int)) {
7374                                 tu.ipft_vint = *ta->ipft_pint;
7375                                 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7376
7377                         } else if (ta->ipft_sz == sizeof(u_short)) {
7378                                 tu.ipft_vshort = *ta->ipft_pshort;
7379                                 *ta->ipft_pshort = (u_short)(in & 0xffff);
7380
7381                         } else if (ta->ipft_sz == sizeof(u_char)) {
7382                                 tu.ipft_vchar = *ta->ipft_pchar;
7383                                 *ta->ipft_pchar = (u_char)(in & 0xff);
7384                         }
7385                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7386                 }
7387                 break;
7388
7389         default :
7390                 IPFERROR(80);
7391                 error = EINVAL;
7392                 break;
7393         }
7394
7395         return error;
7396 }
7397
7398
7399 /* ------------------------------------------------------------------------ */
7400 /* Function:    ipf_zerostats                                               */
7401 /* Returns:     int - 0 = success, else failure                             */
7402 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7403 /*                                                                          */
7404 /* Copies the current statistics out to userspace and then zero's the       */
7405 /* current ones in the kernel. The lock is only held across the bzero() as  */
7406 /* the copyout may result in paging (ie network activity.)                  */
7407 /* ------------------------------------------------------------------------ */
7408 int
7409 ipf_zerostats(softc, data)
7410         ipf_main_softc_t *softc;
7411         caddr_t data;
7412 {
7413         friostat_t fio;
7414         ipfobj_t obj;
7415         int error;
7416
7417         error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7418         if (error != 0)
7419                 return error;
7420         ipf_getstat(softc, &fio, obj.ipfo_rev);
7421         error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7422         if (error != 0)
7423                 return error;
7424
7425         WRITE_ENTER(&softc->ipf_mutex);
7426         bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7427         RWLOCK_EXIT(&softc->ipf_mutex);
7428
7429         return 0;
7430 }
7431
7432
7433 /* ------------------------------------------------------------------------ */
7434 /* Function:    ipf_resolvedest                                             */
7435 /* Returns:     Nil                                                         */
7436 /* Parameters:  softc(I) - pointer to soft context main structure           */
7437 /*              base(I)  - where strings are stored                         */
7438 /*              fdp(IO)  - pointer to destination information to resolve    */
7439 /*              v(I)     - IP protocol version to match                     */
7440 /*                                                                          */
7441 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7442 /* if a matching name can be found for the particular IP protocol version   */
7443 /* then store the interface pointer in the frdest struct.  If no match is   */
7444 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7445 /* indicate there is no information at all in the structure.                */
7446 /* ------------------------------------------------------------------------ */
7447 int
7448 ipf_resolvedest(softc, base, fdp, v)
7449         ipf_main_softc_t *softc;
7450         char *base;
7451         frdest_t *fdp;
7452         int v;
7453 {
7454         int errval = 0;
7455         void *ifp;
7456
7457         ifp = NULL;
7458
7459         if (fdp->fd_name != -1) {
7460                 if (fdp->fd_type == FRD_DSTLIST) {
7461                         ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7462                                                   IPLT_DSTLIST,
7463                                                   base + fdp->fd_name,
7464                                                   NULL);
7465                         if (ifp == NULL) {
7466                                 IPFERROR(144);
7467                                 errval = ESRCH;
7468                         }
7469                 } else {
7470                         ifp = GETIFP(base + fdp->fd_name, v);
7471                         if (ifp == NULL)
7472                                 ifp = (void *)-1;
7473                 }
7474         }
7475         fdp->fd_ptr = ifp;
7476
7477         return errval;
7478 }
7479
7480
7481 /* ------------------------------------------------------------------------ */
7482 /* Function:    ipf_resolvenic                                              */
7483 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7484 /*                      pointer to interface structure for NIC              */
7485 /* Parameters:  softc(I)- pointer to soft context main structure            */
7486 /*              name(I) - complete interface name                           */
7487 /*              v(I)    - IP protocol version                               */
7488 /*                                                                          */
7489 /* Look for a network interface structure that firstly has a matching name  */
7490 /* to that passed in and that is also being used for that IP protocol       */
7491 /* version (necessary on some platforms where there are separate listings   */
7492 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7493 /* ------------------------------------------------------------------------ */
7494 void *
7495 ipf_resolvenic(softc, name, v)
7496         ipf_main_softc_t *softc;
7497         char *name;
7498         int v;
7499 {
7500         void *nic;
7501
7502         softc = softc;  /* gcc -Wextra */
7503         if (name[0] == '\0')
7504                 return NULL;
7505
7506         if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7507                 return NULL;
7508         }
7509
7510         nic = GETIFP(name, v);
7511         if (nic == NULL)
7512                 nic = (void *)-1;
7513         return nic;
7514 }
7515
7516
7517 /* ------------------------------------------------------------------------ */
7518 /* Function:    ipf_token_expire                                            */
7519 /* Returns:     None.                                                       */
7520 /* Parameters:  softc(I) - pointer to soft context main structure           */
7521 /*                                                                          */
7522 /* This function is run every ipf tick to see if there are any tokens that  */
7523 /* have been held for too long and need to be freed up.                     */
7524 /* ------------------------------------------------------------------------ */
7525 void
7526 ipf_token_expire(softc)
7527         ipf_main_softc_t *softc;
7528 {
7529         ipftoken_t *it;
7530
7531         WRITE_ENTER(&softc->ipf_tokens);
7532         while ((it = softc->ipf_token_head) != NULL) {
7533                 if (it->ipt_die > softc->ipf_ticks)
7534                         break;
7535
7536                 ipf_token_deref(softc, it);
7537         }
7538         RWLOCK_EXIT(&softc->ipf_tokens);
7539 }
7540
7541
7542 /* ------------------------------------------------------------------------ */
7543 /* Function:    ipf_token_flush                                             */
7544 /* Returns:     None.                                                       */
7545 /* Parameters:  softc(I) - pointer to soft context main structure           */
7546 /*                                                                          */
7547 /* Loop through all of the existing tokens and call deref to see if they    */
7548 /* can be freed. Normally a function like this might just loop on           */
7549 /* ipf_token_head but there is a chance that a token might have a ref count */
7550 /* of greater than one and in that case the the reference would drop twice  */
7551 /* by code that is only entitled to drop it once.                           */
7552 /* ------------------------------------------------------------------------ */
7553 static void
7554 ipf_token_flush(softc)
7555         ipf_main_softc_t *softc;
7556 {
7557         ipftoken_t *it, *next;
7558
7559         WRITE_ENTER(&softc->ipf_tokens);
7560         for (it = softc->ipf_token_head; it != NULL; it = next) {
7561                 next = it->ipt_next;
7562                 (void) ipf_token_deref(softc, it);
7563         }
7564         RWLOCK_EXIT(&softc->ipf_tokens);
7565 }
7566
7567
7568 /* ------------------------------------------------------------------------ */
7569 /* Function:    ipf_token_del                                               */
7570 /* Returns:     int     - 0 = success, else error                           */
7571 /* Parameters:  softc(I)- pointer to soft context main structure            */
7572 /*              type(I) - the token type to match                           */
7573 /*              uid(I)  - uid owning the token                              */
7574 /*              ptr(I)  - context pointer for the token                     */
7575 /*                                                                          */
7576 /* This function looks for a a token in the current list that matches up    */
7577 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7578 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7579 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7580 /* enables debugging to distinguish between the two paths that ultimately   */
7581 /* lead to a token to be deleted.                                           */
7582 /* ------------------------------------------------------------------------ */
7583 int
7584 ipf_token_del(softc, type, uid, ptr)
7585         ipf_main_softc_t *softc;
7586         int type, uid;
7587         void *ptr;
7588 {
7589         ipftoken_t *it;
7590         int error;
7591
7592         IPFERROR(82);
7593         error = ESRCH;
7594
7595         WRITE_ENTER(&softc->ipf_tokens);
7596         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7597                 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7598                     uid == it->ipt_uid) {
7599                         it->ipt_complete = 2;
7600                         ipf_token_deref(softc, it);
7601                         error = 0;
7602                         break;
7603                 }
7604         }
7605         RWLOCK_EXIT(&softc->ipf_tokens);
7606
7607         return error;
7608 }
7609
7610
7611 /* ------------------------------------------------------------------------ */
7612 /* Function:    ipf_token_mark_complete                                     */
7613 /* Returns:     None.                                                       */
7614 /* Parameters:  token(I) - pointer to token structure                       */
7615 /*                                                                          */
7616 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7617 /* ------------------------------------------------------------------------ */
7618 void
7619 ipf_token_mark_complete(token)
7620         ipftoken_t *token;
7621 {
7622         if (token->ipt_complete == 0)
7623                 token->ipt_complete = 1;
7624 }
7625
7626
7627 /* ------------------------------------------------------------------------ */
7628 /* Function:    ipf_token_find                                               */
7629 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7630 /* Parameters:  softc(I)- pointer to soft context main structure            */
7631 /*              type(I) - the token type to match                           */
7632 /*              uid(I)  - uid owning the token                              */
7633 /*              ptr(I)  - context pointer for the token                     */
7634 /*                                                                          */
7635 /* This function looks for a live token in the list of current tokens that  */
7636 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7637 /* allocated.  If one is found then it is moved to the top of the list of   */
7638 /* currently active tokens.                                                 */
7639 /* ------------------------------------------------------------------------ */
7640 ipftoken_t *
7641 ipf_token_find(softc, type, uid, ptr)
7642         ipf_main_softc_t *softc;
7643         int type, uid;
7644         void *ptr;
7645 {
7646         ipftoken_t *it, *new;
7647
7648         KMALLOC(new, ipftoken_t *);
7649         if (new != NULL)
7650                 bzero((char *)new, sizeof(*new));
7651
7652         WRITE_ENTER(&softc->ipf_tokens);
7653         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7654                 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7655                     (uid == it->ipt_uid) && (it->ipt_complete < 2))
7656                         break;
7657         }
7658
7659         if (it == NULL) {
7660                 it = new;
7661                 new = NULL;
7662                 if (it == NULL) {
7663                         RWLOCK_EXIT(&softc->ipf_tokens);
7664                         return NULL;
7665                 }
7666                 it->ipt_ctx = ptr;
7667                 it->ipt_uid = uid;
7668                 it->ipt_type = type;
7669                 it->ipt_ref = 1;
7670         } else {
7671                 if (new != NULL) {
7672                         KFREE(new);
7673                         new = NULL;
7674                 }
7675
7676                 if (it->ipt_complete > 0)
7677                         it = NULL;
7678                 else
7679                         ipf_token_unlink(softc, it);
7680         }
7681
7682         if (it != NULL) {
7683                 it->ipt_pnext = softc->ipf_token_tail;
7684                 *softc->ipf_token_tail = it;
7685                 softc->ipf_token_tail = &it->ipt_next;
7686                 it->ipt_next = NULL;
7687                 it->ipt_ref++;
7688
7689                 it->ipt_die = softc->ipf_ticks + 20;
7690         }
7691
7692         RWLOCK_EXIT(&softc->ipf_tokens);
7693
7694         return it;
7695 }
7696
7697
7698 /* ------------------------------------------------------------------------ */
7699 /* Function:    ipf_token_unlink                                            */
7700 /* Returns:     None.                                                       */
7701 /* Parameters:  softc(I) - pointer to soft context main structure           */
7702 /*              token(I) - pointer to token structure                       */
7703 /* Write Locks: ipf_tokens                                                  */
7704 /*                                                                          */
7705 /* This function unlinks a token structure from the linked list of tokens   */
7706 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7707 /* but the tail does due to the linked list implementation.                 */
7708 /* ------------------------------------------------------------------------ */
7709 static void
7710 ipf_token_unlink(softc, token)
7711         ipf_main_softc_t *softc;
7712         ipftoken_t *token;
7713 {
7714
7715         if (softc->ipf_token_tail == &token->ipt_next)
7716                 softc->ipf_token_tail = token->ipt_pnext;
7717
7718         *token->ipt_pnext = token->ipt_next;
7719         if (token->ipt_next != NULL)
7720                 token->ipt_next->ipt_pnext = token->ipt_pnext;
7721         token->ipt_next = NULL;
7722         token->ipt_pnext = NULL;
7723 }
7724
7725
7726 /* ------------------------------------------------------------------------ */
7727 /* Function:    ipf_token_deref                                             */
7728 /* Returns:     int      - 0 == token freed, else reference count           */
7729 /* Parameters:  softc(I) - pointer to soft context main structure           */
7730 /*              token(I) - pointer to token structure                       */
7731 /* Write Locks: ipf_tokens                                                  */
7732 /*                                                                          */
7733 /* Drop the reference count on the token structure and if it drops to zero, */
7734 /* call the dereference function for the token type because it is then      */
7735 /* possible to free the token data structure.                               */
7736 /* ------------------------------------------------------------------------ */
7737 int
7738 ipf_token_deref(softc, token)
7739         ipf_main_softc_t *softc;
7740         ipftoken_t *token;
7741 {
7742         void *data, **datap;
7743
7744         ASSERT(token->ipt_ref > 0);
7745         token->ipt_ref--;
7746         if (token->ipt_ref > 0)
7747                 return token->ipt_ref;
7748
7749         data = token->ipt_data;
7750         datap = &data;
7751
7752         if ((data != NULL) && (data != (void *)-1)) {
7753                 switch (token->ipt_type)
7754                 {
7755                 case IPFGENITER_IPF :
7756                         (void) ipf_derefrule(softc, (frentry_t **)datap);
7757                         break;
7758                 case IPFGENITER_IPNAT :
7759                         WRITE_ENTER(&softc->ipf_nat);
7760                         ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7761                         RWLOCK_EXIT(&softc->ipf_nat);
7762                         break;
7763                 case IPFGENITER_NAT :
7764                         ipf_nat_deref(softc, (nat_t **)datap);
7765                         break;
7766                 case IPFGENITER_STATE :
7767                         ipf_state_deref(softc, (ipstate_t **)datap);
7768                         break;
7769                 case IPFGENITER_FRAG :
7770                         ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7771                         break;
7772                 case IPFGENITER_NATFRAG :
7773                         ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7774                         break;
7775                 case IPFGENITER_HOSTMAP :
7776                         WRITE_ENTER(&softc->ipf_nat);
7777                         ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7778                         RWLOCK_EXIT(&softc->ipf_nat);
7779                         break;
7780                 default :
7781                         ipf_lookup_iterderef(softc, token->ipt_type, data);
7782                         break;
7783                 }
7784         }
7785
7786         ipf_token_unlink(softc, token);
7787         KFREE(token);
7788         return 0;
7789 }
7790
7791
7792 /* ------------------------------------------------------------------------ */
7793 /* Function:    ipf_nextrule                                                */
7794 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7795 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7796 /*              fr(I)       - pointer to filter rule                        */
7797 /*              out(I)      - 1 == out rules, 0 == input rules              */
7798 /*                                                                          */
7799 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7800 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7801 /* last rule in the list. When walking rule lists, it is either input or    */
7802 /* output rules that are returned, never both.                              */
7803 /* ------------------------------------------------------------------------ */
7804 static frentry_t *
7805 ipf_nextrule(softc, active, unit, fr, out)
7806         ipf_main_softc_t *softc;
7807         int active, unit;
7808         frentry_t *fr;
7809         int out;
7810 {
7811         frentry_t *next;
7812         frgroup_t *fg;
7813
7814         if (fr != NULL && fr->fr_group != -1) {
7815                 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7816                                    unit, active, NULL);
7817                 if (fg != NULL)
7818                         fg = fg->fg_next;
7819         } else {
7820                 fg = softc->ipf_groups[unit][active];
7821         }
7822
7823         while (fg != NULL) {
7824                 next = fg->fg_start;
7825                 while (next != NULL) {
7826                         if (out) {
7827                                 if (next->fr_flags & FR_OUTQUE)
7828                                         return next;
7829                         } else if (next->fr_flags & FR_INQUE) {
7830                                 return next;
7831                         }
7832                         next = next->fr_next;
7833                 }
7834                 if (next == NULL)
7835                         fg = fg->fg_next;
7836         }
7837
7838         return NULL;
7839 }
7840
7841 /* ------------------------------------------------------------------------ */
7842 /* Function:    ipf_getnextrule                                             */
7843 /* Returns:     int - 0 = success, else error                               */
7844 /* Parameters:  softc(I)- pointer to soft context main structure            */
7845 /*              t(I)   - pointer to destination information to resolve      */
7846 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7847 /*                                                                          */
7848 /* This function's first job is to bring in the ipfruleiter_t structure via */
7849 /* the ipfobj_t structure to determine what should be the next rule to      */
7850 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7851 /* find the 'next rule'.  This may include searching rule group lists or    */
7852 /* just be as simple as looking at the 'next' field in the rule structure.  */
7853 /* When we have found the rule to return, increase its reference count and  */
7854 /* if we used an existing rule to get here, decrease its reference count.   */
7855 /* ------------------------------------------------------------------------ */
7856 int
7857 ipf_getnextrule(softc, t, ptr)
7858         ipf_main_softc_t *softc;
7859         ipftoken_t *t;
7860         void *ptr;
7861 {
7862         frentry_t *fr, *next, zero;
7863         ipfruleiter_t it;
7864         int error, out;
7865         frgroup_t *fg;
7866         ipfobj_t obj;
7867         int predict;
7868         char *dst;
7869         int unit;
7870
7871         if (t == NULL || ptr == NULL) {
7872                 IPFERROR(84);
7873                 return EFAULT;
7874         }
7875
7876         error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7877         if (error != 0)
7878                 return error;
7879
7880         if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7881                 IPFERROR(85);
7882                 return EINVAL;
7883         }
7884         if ((it.iri_active != 0) && (it.iri_active != 1)) {
7885                 IPFERROR(86);
7886                 return EINVAL;
7887         }
7888         if (it.iri_nrules == 0) {
7889                 IPFERROR(87);
7890                 return ENOSPC;
7891         }
7892         if (it.iri_rule == NULL) {
7893                 IPFERROR(88);
7894                 return EFAULT;
7895         }
7896
7897         fg = NULL;
7898         fr = t->ipt_data;
7899         if ((it.iri_inout & F_OUT) != 0)
7900                 out = 1;
7901         else
7902                 out = 0;
7903         if ((it.iri_inout & F_ACIN) != 0)
7904                 unit = IPL_LOGCOUNT;
7905         else
7906                 unit = IPL_LOGIPF;
7907
7908         READ_ENTER(&softc->ipf_mutex);
7909         if (fr == NULL) {
7910                 if (*it.iri_group == '\0') {
7911                         if (unit == IPL_LOGCOUNT) {
7912                                 next = softc->ipf_acct[out][it.iri_active];
7913                         } else {
7914                                 next = softc->ipf_rules[out][it.iri_active];
7915                         }
7916                         if (next == NULL)
7917                                 next = ipf_nextrule(softc, it.iri_active,
7918                                                     unit, NULL, out);
7919                 } else {
7920                         fg = ipf_findgroup(softc, it.iri_group, unit,
7921                                            it.iri_active, NULL);
7922                         if (fg != NULL)
7923                                 next = fg->fg_start;
7924                         else
7925                                 next = NULL;
7926                 }
7927         } else {
7928                 next = fr->fr_next;
7929                 if (next == NULL)
7930                         next = ipf_nextrule(softc, it.iri_active, unit,
7931                                             fr, out);
7932         }
7933
7934         if (next != NULL && next->fr_next != NULL)
7935                 predict = 1;
7936         else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7937                 predict = 1;
7938         else
7939                 predict = 0;
7940
7941         if (fr != NULL)
7942                 (void) ipf_derefrule(softc, &fr);
7943
7944         obj.ipfo_type = IPFOBJ_FRENTRY;
7945         dst = (char *)it.iri_rule;
7946
7947         if (next != NULL) {
7948                 obj.ipfo_size = next->fr_size;
7949                 MUTEX_ENTER(&next->fr_lock);
7950                 next->fr_ref++;
7951                 MUTEX_EXIT(&next->fr_lock);
7952                 t->ipt_data = next;
7953         } else {
7954                 obj.ipfo_size = sizeof(frentry_t);
7955                 bzero(&zero, sizeof(zero));
7956                 next = &zero;
7957                 t->ipt_data = NULL;
7958         }
7959         it.iri_rule = predict ? next : NULL;
7960         if (predict == 0)
7961                 ipf_token_mark_complete(t);
7962
7963         RWLOCK_EXIT(&softc->ipf_mutex);
7964
7965         obj.ipfo_ptr = dst;
7966         error = ipf_outobjk(softc, &obj, next);
7967         if (error == 0 && t->ipt_data != NULL) {
7968                 dst += obj.ipfo_size;
7969                 if (next->fr_data != NULL) {
7970                         ipfobj_t dobj;
7971
7972                         if (next->fr_type == FR_T_IPFEXPR)
7973                                 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7974                         else
7975                                 dobj.ipfo_type = IPFOBJ_FRIPF;
7976                         dobj.ipfo_size = next->fr_dsize;
7977                         dobj.ipfo_rev = obj.ipfo_rev;
7978                         dobj.ipfo_ptr = dst;
7979                         error = ipf_outobjk(softc, &dobj, next->fr_data);
7980                 }
7981         }
7982
7983         if ((fr != NULL) && (next == &zero))
7984                 (void) ipf_derefrule(softc, &fr);
7985
7986         return error;
7987 }
7988
7989
7990 /* ------------------------------------------------------------------------ */
7991 /* Function:    ipf_frruleiter                                              */
7992 /* Returns:     int - 0 = success, else error                               */
7993 /* Parameters:  softc(I)- pointer to soft context main structure            */
7994 /*              data(I) - the token type to match                           */
7995 /*              uid(I)  - uid owning the token                              */
7996 /*              ptr(I)  - context pointer for the token                     */
7997 /*                                                                          */
7998 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
7999 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8000 /* the process doing the ioctl and use that to ask for the next rule.       */
8001 /* ------------------------------------------------------------------------ */
8002 static int
8003 ipf_frruleiter(softc, data, uid, ctx)
8004         ipf_main_softc_t *softc;
8005         void *data, *ctx;
8006         int uid;
8007 {
8008         ipftoken_t *token;
8009         ipfruleiter_t it;
8010         ipfobj_t obj;
8011         int error;
8012
8013         token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8014         if (token != NULL) {
8015                 error = ipf_getnextrule(softc, token, data);
8016                 WRITE_ENTER(&softc->ipf_tokens);
8017                 ipf_token_deref(softc, token);
8018                 RWLOCK_EXIT(&softc->ipf_tokens);
8019         } else {
8020                 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8021                 if (error != 0)
8022                         return error;
8023                 it.iri_rule = NULL;
8024                 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8025         }
8026
8027         return error;
8028 }
8029
8030
8031 /* ------------------------------------------------------------------------ */
8032 /* Function:    ipf_geniter                                                 */
8033 /* Returns:     int - 0 = success, else error                               */
8034 /* Parameters:  softc(I) - pointer to soft context main structure           */
8035 /*              token(I) - pointer to ipftoken_t structure                  */
8036 /*              itp(I)   - pointer to iterator data                         */
8037 /*                                                                          */
8038 /* Decide which iterator function to call using information passed through  */
8039 /* the ipfgeniter_t structure at itp.                                       */
8040 /* ------------------------------------------------------------------------ */
8041 static int
8042 ipf_geniter(softc, token, itp)
8043         ipf_main_softc_t *softc;
8044         ipftoken_t *token;
8045         ipfgeniter_t *itp;
8046 {
8047         int error;
8048
8049         switch (itp->igi_type)
8050         {
8051         case IPFGENITER_FRAG :
8052                 error = ipf_frag_pkt_next(softc, token, itp);
8053                 break;
8054         default :
8055                 IPFERROR(92);
8056                 error = EINVAL;
8057                 break;
8058         }
8059
8060         return error;
8061 }
8062
8063
8064 /* ------------------------------------------------------------------------ */
8065 /* Function:    ipf_genericiter                                             */
8066 /* Returns:     int - 0 = success, else error                               */
8067 /* Parameters:  softc(I)- pointer to soft context main structure            */
8068 /*              data(I) - the token type to match                           */
8069 /*              uid(I)  - uid owning the token                              */
8070 /*              ptr(I)  - context pointer for the token                     */
8071 /*                                                                          */
8072 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8073 /* ------------------------------------------------------------------------ */
8074 int
8075 ipf_genericiter(softc, data, uid, ctx)
8076         ipf_main_softc_t *softc;
8077         void *data, *ctx;
8078         int uid;
8079 {
8080         ipftoken_t *token;
8081         ipfgeniter_t iter;
8082         int error;
8083
8084         error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8085         if (error != 0)
8086                 return error;
8087
8088         token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8089         if (token != NULL) {
8090                 token->ipt_subtype = iter.igi_type;
8091                 error = ipf_geniter(softc, token, &iter);
8092                 WRITE_ENTER(&softc->ipf_tokens);
8093                 ipf_token_deref(softc, token);
8094                 RWLOCK_EXIT(&softc->ipf_tokens);
8095         } else {
8096                 IPFERROR(93);
8097                 error = 0;
8098         }
8099
8100         return error;
8101 }
8102
8103
8104 /* ------------------------------------------------------------------------ */
8105 /* Function:    ipf_ipf_ioctl                                               */
8106 /* Returns:     int - 0 = success, else error                               */
8107 /* Parameters:  softc(I)- pointer to soft context main structure           */
8108 /*              data(I) - the token type to match                           */
8109 /*              cmd(I)  - the ioctl command number                          */
8110 /*              mode(I) - mode flags for the ioctl                          */
8111 /*              uid(I)  - uid owning the token                              */
8112 /*              ptr(I)  - context pointer for the token                     */
8113 /*                                                                          */
8114 /* This function handles all of the ioctl command that are actually isssued */
8115 /* to the /dev/ipl device.                                                  */
8116 /* ------------------------------------------------------------------------ */
8117 int
8118 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8119         ipf_main_softc_t *softc;
8120         caddr_t data;
8121         ioctlcmd_t cmd;
8122         int mode, uid;
8123         void *ctx;
8124 {
8125         friostat_t fio;
8126         int error, tmp;
8127         ipfobj_t obj;
8128         SPL_INT(s);
8129
8130         switch (cmd)
8131         {
8132         case SIOCFRENB :
8133                 if (!(mode & FWRITE)) {
8134                         IPFERROR(94);
8135                         error = EPERM;
8136                 } else {
8137                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8138                         if (error != 0) {
8139                                 IPFERROR(95);
8140                                 error = EFAULT;
8141                                 break;
8142                         }
8143
8144                         WRITE_ENTER(&softc->ipf_global);
8145                         if (tmp) {
8146                                 if (softc->ipf_running > 0)
8147                                         error = 0;
8148                                 else
8149                                         error = ipfattach(softc);
8150                                 if (error == 0)
8151                                         softc->ipf_running = 1;
8152                                 else
8153                                         (void) ipfdetach(softc);
8154                         } else {
8155                                 if (softc->ipf_running == 1)
8156                                         error = ipfdetach(softc);
8157                                 else
8158                                         error = 0;
8159                                 if (error == 0)
8160                                         softc->ipf_running = -1;
8161                         }
8162                         RWLOCK_EXIT(&softc->ipf_global);
8163                 }
8164                 break;
8165
8166         case SIOCIPFSET :
8167                 if (!(mode & FWRITE)) {
8168                         IPFERROR(96);
8169                         error = EPERM;
8170                         break;
8171                 }
8172                 /* FALLTHRU */
8173         case SIOCIPFGETNEXT :
8174         case SIOCIPFGET :
8175                 error = ipf_ipftune(softc, cmd, (void *)data);
8176                 break;
8177
8178         case SIOCSETFF :
8179                 if (!(mode & FWRITE)) {
8180                         IPFERROR(97);
8181                         error = EPERM;
8182                 } else {
8183                         error = BCOPYIN(data, &softc->ipf_flags,
8184                                         sizeof(softc->ipf_flags));
8185                         if (error != 0) {
8186                                 IPFERROR(98);
8187                                 error = EFAULT;
8188                         }
8189                 }
8190                 break;
8191
8192         case SIOCGETFF :
8193                 error = BCOPYOUT(&softc->ipf_flags, data,
8194                                  sizeof(softc->ipf_flags));
8195                 if (error != 0) {
8196                         IPFERROR(99);
8197                         error = EFAULT;
8198                 }
8199                 break;
8200
8201         case SIOCFUNCL :
8202                 error = ipf_resolvefunc(softc, (void *)data);
8203                 break;
8204
8205         case SIOCINAFR :
8206         case SIOCRMAFR :
8207         case SIOCADAFR :
8208         case SIOCZRLST :
8209                 if (!(mode & FWRITE)) {
8210                         IPFERROR(100);
8211                         error = EPERM;
8212                 } else {
8213                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8214                                           softc->ipf_active, 1);
8215                 }
8216                 break;
8217
8218         case SIOCINIFR :
8219         case SIOCRMIFR :
8220         case SIOCADIFR :
8221                 if (!(mode & FWRITE)) {
8222                         IPFERROR(101);
8223                         error = EPERM;
8224                 } else {
8225                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8226                                           1 - softc->ipf_active, 1);
8227                 }
8228                 break;
8229
8230         case SIOCSWAPA :
8231                 if (!(mode & FWRITE)) {
8232                         IPFERROR(102);
8233                         error = EPERM;
8234                 } else {
8235                         WRITE_ENTER(&softc->ipf_mutex);
8236                         error = BCOPYOUT(&softc->ipf_active, data,
8237                                          sizeof(softc->ipf_active));
8238                         if (error != 0) {
8239                                 IPFERROR(103);
8240                                 error = EFAULT;
8241                         } else {
8242                                 softc->ipf_active = 1 - softc->ipf_active;
8243                         }
8244                         RWLOCK_EXIT(&softc->ipf_mutex);
8245                 }
8246                 break;
8247
8248         case SIOCGETFS :
8249                 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8250                                   IPFOBJ_IPFSTAT);
8251                 if (error != 0)
8252                         break;
8253                 ipf_getstat(softc, &fio, obj.ipfo_rev);
8254                 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8255                 break;
8256
8257         case SIOCFRZST :
8258                 if (!(mode & FWRITE)) {
8259                         IPFERROR(104);
8260                         error = EPERM;
8261                 } else
8262                         error = ipf_zerostats(softc, (caddr_t)data);
8263                 break;
8264
8265         case SIOCIPFFL :
8266                 if (!(mode & FWRITE)) {
8267                         IPFERROR(105);
8268                         error = EPERM;
8269                 } else {
8270                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8271                         if (!error) {
8272                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8273                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8274                                 if (error != 0) {
8275                                         IPFERROR(106);
8276                                         error = EFAULT;
8277                                 }
8278                         } else {
8279                                 IPFERROR(107);
8280                                 error = EFAULT;
8281                         }
8282                 }
8283                 break;
8284
8285 #ifdef USE_INET6
8286         case SIOCIPFL6 :
8287                 if (!(mode & FWRITE)) {
8288                         IPFERROR(108);
8289                         error = EPERM;
8290                 } else {
8291                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8292                         if (!error) {
8293                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8294                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8295                                 if (error != 0) {
8296                                         IPFERROR(109);
8297                                         error = EFAULT;
8298                                 }
8299                         } else {
8300                                 IPFERROR(110);
8301                                 error = EFAULT;
8302                         }
8303                 }
8304                 break;
8305 #endif
8306
8307         case SIOCSTLCK :
8308                 if (!(mode & FWRITE)) {
8309                         IPFERROR(122);
8310                         error = EPERM;
8311                 } else {
8312                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8313                         if (error == 0) {
8314                                 ipf_state_setlock(softc->ipf_state_soft, tmp);
8315                                 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8316                                 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8317                                 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8318                         } else {
8319                                 IPFERROR(111);
8320                                 error = EFAULT;
8321                         }
8322                 }
8323                 break;
8324
8325 #ifdef  IPFILTER_LOG
8326         case SIOCIPFFB :
8327                 if (!(mode & FWRITE)) {
8328                         IPFERROR(112);
8329                         error = EPERM;
8330                 } else {
8331                         tmp = ipf_log_clear(softc, IPL_LOGIPF);
8332                         error = BCOPYOUT(&tmp, data, sizeof(tmp));
8333                         if (error) {
8334                                 IPFERROR(113);
8335                                 error = EFAULT;
8336                         }
8337                 }
8338                 break;
8339 #endif /* IPFILTER_LOG */
8340
8341         case SIOCFRSYN :
8342                 if (!(mode & FWRITE)) {
8343                         IPFERROR(114);
8344                         error = EPERM;
8345                 } else {
8346                         WRITE_ENTER(&softc->ipf_global);
8347 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8348                         error = ipfsync();
8349 #else
8350                         ipf_sync(softc, NULL);
8351                         error = 0;
8352 #endif
8353                         RWLOCK_EXIT(&softc->ipf_global);
8354
8355                 }
8356                 break;
8357
8358         case SIOCGFRST :
8359                 error = ipf_outobj(softc, (void *)data,
8360                                    ipf_frag_stats(softc->ipf_frag_soft),
8361                                    IPFOBJ_FRAGSTAT);
8362                 break;
8363
8364 #ifdef  IPFILTER_LOG
8365         case FIONREAD :
8366                 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8367                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8368                 break;
8369 #endif
8370
8371         case SIOCIPFITER :
8372                 SPL_SCHED(s);
8373                 error = ipf_frruleiter(softc, data, uid, ctx);
8374                 SPL_X(s);
8375                 break;
8376
8377         case SIOCGENITER :
8378                 SPL_SCHED(s);
8379                 error = ipf_genericiter(softc, data, uid, ctx);
8380                 SPL_X(s);
8381                 break;
8382
8383         case SIOCIPFDELTOK :
8384                 error = BCOPYIN(data, &tmp, sizeof(tmp));
8385                 if (error == 0) {
8386                         SPL_SCHED(s);
8387                         error = ipf_token_del(softc, tmp, uid, ctx);
8388                         SPL_X(s);
8389                 }
8390                 break;
8391
8392         default :
8393                 IPFERROR(115);
8394                 error = EINVAL;
8395                 break;
8396         }
8397
8398         return error;
8399 }
8400
8401
8402 /* ------------------------------------------------------------------------ */
8403 /* Function:    ipf_decaps                                                  */
8404 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8405 /*                           flags indicating packet filtering decision.    */
8406 /* Parameters:  fin(I)     - pointer to packet information                  */
8407 /*              pass(I)    - IP protocol version to match                   */
8408 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8409 /*                                                                          */
8410 /* This function is called for packets that are wrapt up in other packets,  */
8411 /* for example, an IP packet that is the entire data segment for another IP */
8412 /* packet.  If the basic constraints for this are satisfied, change the     */
8413 /* buffer to point to the start of the inner packet and start processing    */
8414 /* rules belonging to the head group this rule specifies.                   */
8415 /* ------------------------------------------------------------------------ */
8416 u_32_t
8417 ipf_decaps(fin, pass, l5proto)
8418         fr_info_t *fin;
8419         u_32_t pass;
8420         int l5proto;
8421 {
8422         fr_info_t fin2, *fino = NULL;
8423         int elen, hlen, nh;
8424         grehdr_t gre;
8425         ip_t *ip;
8426         mb_t *m;
8427
8428         if ((fin->fin_flx & FI_COALESCE) == 0)
8429                 if (ipf_coalesce(fin) == -1)
8430                         goto cantdecaps;
8431
8432         m = fin->fin_m;
8433         hlen = fin->fin_hlen;
8434
8435         switch (fin->fin_p)
8436         {
8437         case IPPROTO_UDP :
8438                 /*
8439                  * In this case, the specific protocol being decapsulated
8440                  * inside UDP frames comes from the rule.
8441                  */
8442                 nh = fin->fin_fr->fr_icode;
8443                 break;
8444
8445         case IPPROTO_GRE :      /* 47 */
8446                 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8447                 hlen += sizeof(grehdr_t);
8448                 if (gre.gr_R|gre.gr_s)
8449                         goto cantdecaps;
8450                 if (gre.gr_C)
8451                         hlen += 4;
8452                 if (gre.gr_K)
8453                         hlen += 4;
8454                 if (gre.gr_S)
8455                         hlen += 4;
8456
8457                 nh = IPPROTO_IP;
8458
8459                 /*
8460                  * If the routing options flag is set, validate that it is
8461                  * there and bounce over it.
8462                  */
8463 #if 0
8464                 /* This is really heavy weight and lots of room for error, */
8465                 /* so for now, put it off and get the simple stuff right.  */
8466                 if (gre.gr_R) {
8467                         u_char off, len, *s;
8468                         u_short af;
8469                         int end;
8470
8471                         end = 0;
8472                         s = fin->fin_dp;
8473                         s += hlen;
8474                         aplen = fin->fin_plen - hlen;
8475                         while (aplen > 3) {
8476                                 af = (s[0] << 8) | s[1];
8477                                 off = s[2];
8478                                 len = s[3];
8479                                 aplen -= 4;
8480                                 s += 4;
8481                                 if (af == 0 && len == 0) {
8482                                         end = 1;
8483                                         break;
8484                                 }
8485                                 if (aplen < len)
8486                                         break;
8487                                 s += len;
8488                                 aplen -= len;
8489                         }
8490                         if (end != 1)
8491                                 goto cantdecaps;
8492                         hlen = s - (u_char *)fin->fin_dp;
8493                 }
8494 #endif
8495                 break;
8496
8497 #ifdef IPPROTO_IPIP
8498         case IPPROTO_IPIP :     /* 4 */
8499 #endif
8500                 nh = IPPROTO_IP;
8501                 break;
8502
8503         default :       /* Includes ESP, AH is special for IPv4 */
8504                 goto cantdecaps;
8505         }
8506
8507         switch (nh)
8508         {
8509         case IPPROTO_IP :
8510         case IPPROTO_IPV6 :
8511                 break;
8512         default :
8513                 goto cantdecaps;
8514         }
8515
8516         bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8517         fino = fin;
8518         fin = &fin2;
8519         elen = hlen;
8520 #if defined(MENTAT) && defined(_KERNEL)
8521         m->b_rptr += elen;
8522 #else
8523         m->m_data += elen;
8524         m->m_len -= elen;
8525 #endif
8526         fin->fin_plen -= elen;
8527
8528         ip = (ip_t *)((char *)fin->fin_ip + elen);
8529
8530         /*
8531          * Make sure we have at least enough data for the network layer
8532          * header.
8533          */
8534         if (IP_V(ip) == 4)
8535                 hlen = IP_HL(ip) << 2;
8536 #ifdef USE_INET6
8537         else if (IP_V(ip) == 6)
8538                 hlen = sizeof(ip6_t);
8539 #endif
8540         else
8541                 goto cantdecaps2;
8542
8543         if (fin->fin_plen < hlen)
8544                 goto cantdecaps2;
8545
8546         fin->fin_dp = (char *)ip + hlen;
8547
8548         if (IP_V(ip) == 4) {
8549                 /*
8550                  * Perform IPv4 header checksum validation.
8551                  */
8552                 if (ipf_cksum((u_short *)ip, hlen))
8553                         goto cantdecaps2;
8554         }
8555
8556         if (ipf_makefrip(hlen, ip, fin) == -1) {
8557 cantdecaps2:
8558                 if (m != NULL) {
8559 #if defined(MENTAT) && defined(_KERNEL)
8560                         m->b_rptr -= elen;
8561 #else
8562                         m->m_data -= elen;
8563                         m->m_len += elen;
8564 #endif
8565                 }
8566 cantdecaps:
8567                 DT1(frb_decapfrip, fr_info_t *, fin);
8568                 pass &= ~FR_CMDMASK;
8569                 pass |= FR_BLOCK|FR_QUICK;
8570                 fin->fin_reason = FRB_DECAPFRIP;
8571                 return -1;
8572         }
8573
8574         pass = ipf_scanlist(fin, pass);
8575
8576         /*
8577          * Copy the packet filter "result" fields out of the fr_info_t struct
8578          * that is local to the decapsulation processing and back into the
8579          * one we were called with.
8580          */
8581         fino->fin_flx = fin->fin_flx;
8582         fino->fin_rev = fin->fin_rev;
8583         fino->fin_icode = fin->fin_icode;
8584         fino->fin_rule = fin->fin_rule;
8585         (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8586         fino->fin_fr = fin->fin_fr;
8587         fino->fin_error = fin->fin_error;
8588         fino->fin_mp = fin->fin_mp;
8589         fino->fin_m = fin->fin_m;
8590         m = fin->fin_m;
8591         if (m != NULL) {
8592 #if defined(MENTAT) && defined(_KERNEL)
8593                 m->b_rptr -= elen;
8594 #else
8595                 m->m_data -= elen;
8596                 m->m_len += elen;
8597 #endif
8598         }
8599         return pass;
8600 }
8601
8602
8603 /* ------------------------------------------------------------------------ */
8604 /* Function:    ipf_matcharray_load                                         */
8605 /* Returns:     int         - 0 = success, else error                       */
8606 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8607 /*              data(I)     - pointer to ioctl data                         */
8608 /*              objp(I)     - ipfobj_t structure to load data into          */
8609 /*              arrayptr(I) - pointer to location to store array pointer    */
8610 /*                                                                          */
8611 /* This function loads in a mathing array through the ipfobj_t struct that  */
8612 /* describes it.  Sanity checking and array size limitations are enforced   */
8613 /* in this function to prevent userspace from trying to load in something   */
8614 /* that is insanely big.  Once the size of the array is known, the memory   */
8615 /* required is malloc'd and returned through changing *arrayptr.  The       */
8616 /* contents of the array are verified before returning.  Only in the event  */
8617 /* of a successful call is the caller required to free up the malloc area.  */
8618 /* ------------------------------------------------------------------------ */
8619 int
8620 ipf_matcharray_load(softc, data, objp, arrayptr)
8621         ipf_main_softc_t *softc;
8622         caddr_t data;
8623         ipfobj_t *objp;
8624         int **arrayptr;
8625 {
8626         int arraysize, *array, error;
8627
8628         *arrayptr = NULL;
8629
8630         error = BCOPYIN(data, objp, sizeof(*objp));
8631         if (error != 0) {
8632                 IPFERROR(116);
8633                 return EFAULT;
8634         }
8635
8636         if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8637                 IPFERROR(117);
8638                 return EINVAL;
8639         }
8640
8641         if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8642             (objp->ipfo_size > 1024)) {
8643                 IPFERROR(118);
8644                 return EINVAL;
8645         }
8646
8647         arraysize = objp->ipfo_size * sizeof(*array);
8648         KMALLOCS(array, int *, arraysize);
8649         if (array == NULL) {
8650                 IPFERROR(119);
8651                 return ENOMEM;
8652         }
8653
8654         error = COPYIN(objp->ipfo_ptr, array, arraysize);
8655         if (error != 0) {
8656                 KFREES(array, arraysize);
8657                 IPFERROR(120);
8658                 return EFAULT;
8659         }
8660
8661         if (ipf_matcharray_verify(array, arraysize) != 0) {
8662                 KFREES(array, arraysize);
8663                 IPFERROR(121);
8664                 return EINVAL;
8665         }
8666
8667         *arrayptr = array;
8668         return 0;
8669 }
8670
8671
8672 /* ------------------------------------------------------------------------ */
8673 /* Function:    ipf_matcharray_verify                                       */
8674 /* Returns:     Nil                                                         */
8675 /* Parameters:  array(I)     - pointer to matching array                    */
8676 /*              arraysize(I) - number of elements in the array              */
8677 /*                                                                          */
8678 /* Verify the contents of a matching array by stepping through each element */
8679 /* in it.  The actual commands in the array are not verified for            */
8680 /* correctness, only that all of the sizes are correctly within limits.     */
8681 /* ------------------------------------------------------------------------ */
8682 int
8683 ipf_matcharray_verify(array, arraysize)
8684         int *array, arraysize;
8685 {
8686         int i, nelem, maxidx;
8687         ipfexp_t *e;
8688
8689         nelem = arraysize / sizeof(*array);
8690
8691         /*
8692          * Currently, it makes no sense to have an array less than 6
8693          * elements long - the initial size at the from, a single operation
8694          * (minimum 4 in length) and a trailer, for a total of 6.
8695          */
8696         if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8697                 return -1;
8698         }
8699
8700         /*
8701          * Verify the size of data pointed to by array with how long
8702          * the array claims to be itself.
8703          */
8704         if (array[0] * sizeof(*array) != arraysize) {
8705                 return -1;
8706         }
8707
8708         maxidx = nelem - 1;
8709         /*
8710          * The last opcode in this array should be an IPF_EXP_END.
8711          */
8712         if (array[maxidx] != IPF_EXP_END) {
8713                 return -1;
8714         }
8715
8716         for (i = 1; i < maxidx; ) {
8717                 e = (ipfexp_t *)(array + i);
8718
8719                 /*
8720                  * The length of the bits to check must be at least 1
8721                  * (or else there is nothing to comapre with!) and it
8722                  * cannot exceed the length of the data present.
8723                  */
8724                 if ((e->ipfe_size < 1 ) ||
8725                     (e->ipfe_size + i > maxidx)) {
8726                         return -1;
8727                 }
8728                 i += e->ipfe_size;
8729         }
8730         return 0;
8731 }
8732
8733
8734 /* ------------------------------------------------------------------------ */
8735 /* Function:    ipf_fr_matcharray                                           */
8736 /* Returns:     int      - 0 = match failed, else positive match            */
8737 /* Parameters:  fin(I)   - pointer to packet information                    */
8738 /*              array(I) - pointer to matching array                        */
8739 /*                                                                          */
8740 /* This function is used to apply a matching array against a packet and     */
8741 /* return an indication of whether or not the packet successfully matches   */
8742 /* all of the commands in it.                                               */
8743 /* ------------------------------------------------------------------------ */
8744 static int
8745 ipf_fr_matcharray(fin, array)
8746         fr_info_t *fin;
8747         int *array;
8748 {
8749         int i, n, *x, rv, p;
8750         ipfexp_t *e;
8751
8752         rv = 0;
8753         n = array[0];
8754         x = array + 1;
8755
8756         for (; n > 0; x += 3 + x[3], rv = 0) {
8757                 e = (ipfexp_t *)x;
8758                 if (e->ipfe_cmd == IPF_EXP_END)
8759                         break;
8760                 n -= e->ipfe_size;
8761
8762                 /*
8763                  * The upper 16 bits currently store the protocol value.
8764                  * This is currently used with TCP and UDP port compares and
8765                  * allows "tcp.port = 80" without requiring an explicit
8766                  " "ip.pr = tcp" first.
8767                  */
8768                 p = e->ipfe_cmd >> 16;
8769                 if ((p != 0) && (p != fin->fin_p))
8770                         break;
8771
8772                 switch (e->ipfe_cmd)
8773                 {
8774                 case IPF_EXP_IP_PR :
8775                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8776                                 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8777                         }
8778                         break;
8779
8780                 case IPF_EXP_IP_SRCADDR :
8781                         if (fin->fin_v != 4)
8782                                 break;
8783                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8784                                 rv |= ((fin->fin_saddr &
8785                                         e->ipfe_arg0[i * 2 + 1]) ==
8786                                        e->ipfe_arg0[i * 2]);
8787                         }
8788                         break;
8789
8790                 case IPF_EXP_IP_DSTADDR :
8791                         if (fin->fin_v != 4)
8792                                 break;
8793                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8794                                 rv |= ((fin->fin_daddr &
8795                                         e->ipfe_arg0[i * 2 + 1]) ==
8796                                        e->ipfe_arg0[i * 2]);
8797                         }
8798                         break;
8799
8800                 case IPF_EXP_IP_ADDR :
8801                         if (fin->fin_v != 4)
8802                                 break;
8803                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8804                                 rv |= ((fin->fin_saddr &
8805                                         e->ipfe_arg0[i * 2 + 1]) ==
8806                                        e->ipfe_arg0[i * 2]) ||
8807                                       ((fin->fin_daddr &
8808                                         e->ipfe_arg0[i * 2 + 1]) ==
8809                                        e->ipfe_arg0[i * 2]);
8810                         }
8811                         break;
8812
8813 #ifdef USE_INET6
8814                 case IPF_EXP_IP6_SRCADDR :
8815                         if (fin->fin_v != 6)
8816                                 break;
8817                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8818                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8819                                                  &e->ipfe_arg0[i * 8 + 4],
8820                                                  &e->ipfe_arg0[i * 8]);
8821                         }
8822                         break;
8823
8824                 case IPF_EXP_IP6_DSTADDR :
8825                         if (fin->fin_v != 6)
8826                                 break;
8827                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8828                                 rv |= IP6_MASKEQ(&fin->fin_dst6,
8829                                                  &e->ipfe_arg0[i * 8 + 4],
8830                                                  &e->ipfe_arg0[i * 8]);
8831                         }
8832                         break;
8833
8834                 case IPF_EXP_IP6_ADDR :
8835                         if (fin->fin_v != 6)
8836                                 break;
8837                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8838                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8839                                                  &e->ipfe_arg0[i * 8 + 4],
8840                                                  &e->ipfe_arg0[i * 8]) ||
8841                                       IP6_MASKEQ(&fin->fin_dst6,
8842                                                  &e->ipfe_arg0[i * 8 + 4],
8843                                                  &e->ipfe_arg0[i * 8]);
8844                         }
8845                         break;
8846 #endif
8847
8848                 case IPF_EXP_UDP_PORT :
8849                 case IPF_EXP_TCP_PORT :
8850                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8851                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8852                                       (fin->fin_dport == e->ipfe_arg0[i]);
8853                         }
8854                         break;
8855
8856                 case IPF_EXP_UDP_SPORT :
8857                 case IPF_EXP_TCP_SPORT :
8858                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8859                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8860                         }
8861                         break;
8862
8863                 case IPF_EXP_UDP_DPORT :
8864                 case IPF_EXP_TCP_DPORT :
8865                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8866                                 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8867                         }
8868                         break;
8869
8870                 case IPF_EXP_TCP_FLAGS :
8871                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8872                                 rv |= ((fin->fin_tcpf &
8873                                         e->ipfe_arg0[i * 2 + 1]) ==
8874                                        e->ipfe_arg0[i * 2]);
8875                         }
8876                         break;
8877                 }
8878                 rv ^= e->ipfe_not;
8879
8880                 if (rv == 0)
8881                         break;
8882         }
8883
8884         return rv;
8885 }
8886
8887
8888 /* ------------------------------------------------------------------------ */
8889 /* Function:    ipf_queueflush                                              */
8890 /* Returns:     int - number of entries flushed (0 = none)                  */
8891 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8892 /*              deletefn(I) - function to call to delete entry              */
8893 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8894 /*              userqs(I)   - top of the list of user defined timeouts      */
8895 /*                                                                          */
8896 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8897 /* need to try a bit harder to free up some space.  The algorithm used here */
8898 /* split into two parts but both halves have the same goal: to reduce the   */
8899 /* number of connections considered to be "active" to the low watermark.    */
8900 /* There are two steps in doing this:                                       */
8901 /* 1) Remove any TCP connections that are already considered to be "closed" */
8902 /*    but have not yet been removed from the state table.  The two states   */
8903 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8904 /*    candidates for this style of removal.  If freeing up entries in       */
8905 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8906 /*    we do not go on to step 2.                                            */
8907 /*                                                                          */
8908 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8909 /*    they are within the given window we are considering.  Where the       */
8910 /*    window starts and the steps taken to increase its size depend upon    */
8911 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8912 /*    last 30 seconds is not touched.                                       */
8913 /*                                              touched                     */
8914 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8915 /*           |          |        |           |     |     |                  */
8916 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8917 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8918 /*                                                                          */
8919 /* Points to note:                                                          */
8920 /* - tqe_die is the time, in the future, when entries die.                  */
8921 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8922 /*   ticks.                                                                 */
8923 /* - tqe_touched is when the entry was last used by NAT/state               */
8924 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8925 /*   ipf_ticks any given timeout queue and vice versa.                      */
8926 /* - both tqe_die and tqe_touched increase over time                        */
8927 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8928 /*   bottom and therefore the smallest values of each are at the top        */
8929 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8930 /*   queues representing each of the TCP states                             */
8931 /*                                                                          */
8932 /* We start by setting up a maximum range to scan for things to move of     */
8933 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8934 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8935 /* we start again with a new value for "iend" and "istart".  This is        */
8936 /* continued until we either finish the scan of 30 second intervals or the  */
8937 /* low water mark is reached.                                               */
8938 /* ------------------------------------------------------------------------ */
8939 int
8940 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8941         ipf_main_softc_t *softc;
8942         ipftq_delete_fn_t deletefn;
8943         ipftq_t *ipfqs, *userqs;
8944         u_int *activep;
8945         int size, low;
8946 {
8947         u_long interval, istart, iend;
8948         ipftq_t *ifq, *ifqnext;
8949         ipftqent_t *tqe, *tqn;
8950         int removed = 0;
8951
8952         for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8953                 tqn = tqe->tqe_next;
8954                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8955                         removed++;
8956         }
8957         if ((*activep * 100 / size) > low) {
8958                 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8959                      ((tqe = tqn) != NULL); ) {
8960                         tqn = tqe->tqe_next;
8961                         if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8962                                 removed++;
8963                 }
8964         }
8965
8966         if ((*activep * 100 / size) <= low) {
8967                 return removed;
8968         }
8969
8970         /*
8971          * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8972          *       used then the operations are upgraded to floating point
8973          *       and kernels don't like floating point...
8974          */
8975         if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8976                 istart = IPF_TTLVAL(86400 * 4);
8977                 interval = IPF_TTLVAL(43200);
8978         } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8979                 istart = IPF_TTLVAL(43200);
8980                 interval = IPF_TTLVAL(1800);
8981         } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8982                 istart = IPF_TTLVAL(1800);
8983                 interval = IPF_TTLVAL(30);
8984         } else {
8985                 return 0;
8986         }
8987         if (istart > softc->ipf_ticks) {
8988                 if (softc->ipf_ticks - interval < interval)
8989                         istart = interval;
8990                 else
8991                         istart = (softc->ipf_ticks / interval) * interval;
8992         }
8993
8994         iend = softc->ipf_ticks - interval;
8995
8996         while ((*activep * 100 / size) > low) {
8997                 u_long try;
8998
8999                 try = softc->ipf_ticks - istart;
9000
9001                 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9002                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9003                                 if (try < tqe->tqe_touched)
9004                                         break;
9005                                 tqn = tqe->tqe_next;
9006                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9007                                         removed++;
9008                         }
9009                 }
9010
9011                 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9012                         ifqnext = ifq->ifq_next;
9013
9014                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9015                                 if (try < tqe->tqe_touched)
9016                                         break;
9017                                 tqn = tqe->tqe_next;
9018                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9019                                         removed++;
9020                         }
9021                 }
9022
9023                 if (try >= iend) {
9024                         if (interval == IPF_TTLVAL(43200)) {
9025                                 interval = IPF_TTLVAL(1800);
9026                         } else if (interval == IPF_TTLVAL(1800)) {
9027                                 interval = IPF_TTLVAL(30);
9028                         } else {
9029                                 break;
9030                         }
9031                         if (interval >= softc->ipf_ticks)
9032                                 break;
9033
9034                         iend = softc->ipf_ticks - interval;
9035                 }
9036                 istart -= interval;
9037         }
9038
9039         return removed;
9040 }
9041
9042
9043 /* ------------------------------------------------------------------------ */
9044 /* Function:    ipf_deliverlocal                                            */
9045 /* Returns:     int - 1 = local address, 0 = non-local address              */
9046 /* Parameters:  softc(I)     - pointer to soft context main structure       */
9047 /*              ipversion(I) - IP protocol version (4 or 6)                 */
9048 /*              ifp(I)       - network interface pointer                    */
9049 /*              ipaddr(I)    - IPv4/6 destination address                   */
9050 /*                                                                          */
9051 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
9052 /* the network interface represented by ifp.                                */
9053 /* ------------------------------------------------------------------------ */
9054 int
9055 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9056         ipf_main_softc_t *softc;
9057         int ipversion;
9058         void *ifp;
9059         i6addr_t *ipaddr;
9060 {
9061         i6addr_t addr;
9062         int islocal = 0;
9063
9064         if (ipversion == 4) {
9065                 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9066                         if (addr.in4.s_addr == ipaddr->in4.s_addr)
9067                                 islocal = 1;
9068                 }
9069
9070 #ifdef USE_INET6
9071         } else if (ipversion == 6) {
9072                 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9073                         if (IP6_EQ(&addr, ipaddr))
9074                                 islocal = 1;
9075                 }
9076 #endif
9077         }
9078
9079         return islocal;
9080 }
9081
9082
9083 /* ------------------------------------------------------------------------ */
9084 /* Function:    ipf_settimeout                                              */
9085 /* Returns:     int - 0 = success, -1 = failure                             */
9086 /* Parameters:  softc(I) - pointer to soft context main structure           */
9087 /*              t(I)     - pointer to tuneable array entry                  */
9088 /*              p(I)     - pointer to values passed in to apply             */
9089 /*                                                                          */
9090 /* This function is called to set the timeout values for each distinct      */
9091 /* queue timeout that is available.  When called, it calls into both the    */
9092 /* state and NAT code, telling them to update their timeout queues.         */
9093 /* ------------------------------------------------------------------------ */
9094 static int
9095 ipf_settimeout(softc, t, p)
9096         struct ipf_main_softc_s *softc;
9097         ipftuneable_t *t;
9098         ipftuneval_t *p;
9099 {
9100
9101         /*
9102          * ipf_interror should be set by the functions called here, not
9103          * by this function - it's just a middle man.
9104          */
9105         if (ipf_state_settimeout(softc, t, p) == -1)
9106                 return -1;
9107         if (ipf_nat_settimeout(softc, t, p) == -1)
9108                 return -1;
9109         return 0;
9110 }
9111
9112
9113 /* ------------------------------------------------------------------------ */
9114 /* Function:    ipf_apply_timeout                                           */
9115 /* Returns:     int - 0 = success, -1 = failure                             */
9116 /* Parameters:  head(I)    - pointer to tuneable array entry                */
9117 /*              seconds(I) - pointer to values passed in to apply           */
9118 /*                                                                          */
9119 /* This function applies a timeout of "seconds" to the timeout queue that   */
9120 /* is pointed to by "head".  All entries on this list have an expiration    */
9121 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
9122 /* function should only be called when the delta is non-zero, the task is   */
9123 /* to walk the entire list and apply the change.  The sort order will not   */
9124 /* change.  The only catch is that this is O(n) across the list, so if the  */
9125 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9126 /* could take a relatively long time to work through them all.              */
9127 /* ------------------------------------------------------------------------ */
9128 void
9129 ipf_apply_timeout(head, seconds)
9130         ipftq_t *head;
9131         u_int seconds;
9132 {
9133         u_int oldtimeout, newtimeout;
9134         ipftqent_t *tqe;
9135         int delta;
9136
9137         MUTEX_ENTER(&head->ifq_lock);
9138         oldtimeout = head->ifq_ttl;
9139         newtimeout = IPF_TTLVAL(seconds);
9140         delta = oldtimeout - newtimeout;
9141
9142         head->ifq_ttl = newtimeout;
9143
9144         for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9145                 tqe->tqe_die += delta;
9146         }
9147         MUTEX_EXIT(&head->ifq_lock);
9148 }
9149
9150
9151 /* ------------------------------------------------------------------------ */
9152 /* Function:   ipf_settimeout_tcp                                           */
9153 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
9154 /* Parameters: t(I)   - pointer to tuneable to change                       */
9155 /*             p(I)   - pointer to new timeout information                  */
9156 /*             tab(I) - pointer to table of TCP queues                      */
9157 /*                                                                          */
9158 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
9159 /* updates all of the entries on the relevant timeout queue by calling      */
9160 /* ipf_apply_timeout().                                                     */
9161 /* ------------------------------------------------------------------------ */
9162 int
9163 ipf_settimeout_tcp(t, p, tab)
9164         ipftuneable_t *t;
9165         ipftuneval_t *p;
9166         ipftq_t *tab;
9167 {
9168         if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9169             !strcmp(t->ipft_name, "tcp_established")) {
9170                 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9171         } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9172                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9173         } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9174                 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9175         } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9176                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9177                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9178                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9179         } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9180                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9181         } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9182                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9183         } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9184                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9185         } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9186                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9187         } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9188                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9189         } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9190                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9191         } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9192                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9193         } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9194                 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9195         } else {
9196                 /*
9197                  * ipf_interror isn't set here because it should be set
9198                  * by whatever called this function.
9199                  */
9200                 return -1;
9201         }
9202         return 0;
9203 }
9204
9205
9206 /* ------------------------------------------------------------------------ */
9207 /* Function:   ipf_main_soft_create                                         */
9208 /* Returns:    NULL = failure, else success                                 */
9209 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9210 /*                                                                          */
9211 /* Create the foundation soft context structure. In circumstances where it  */
9212 /* is not required to dynamically allocate the context, a pointer can be    */
9213 /* passed in (rather than NULL) to a structure to be initialised.           */
9214 /* The main thing of interest is that a number of locks are initialised     */
9215 /* here instead of in the where might be expected - in the relevant create  */
9216 /* function elsewhere.  This is done because the current locking design has */
9217 /* some areas where these locks are used outside of their module.           */
9218 /* Possibly the most important exercise that is done here is setting of all */
9219 /* the timeout values, allowing them to be changed before init().           */
9220 /* ------------------------------------------------------------------------ */
9221 void *
9222 ipf_main_soft_create(arg)
9223         void *arg;
9224 {
9225         ipf_main_softc_t *softc;
9226
9227         if (arg == NULL) {
9228                 KMALLOC(softc, ipf_main_softc_t *);
9229                 if (softc == NULL)
9230                         return NULL;
9231         } else {
9232                 softc = arg;
9233         }
9234
9235         bzero((char *)softc, sizeof(*softc));
9236
9237         /*
9238          * This serves as a flag as to whether or not the softc should be
9239          * free'd when _destroy is called.
9240          */
9241         softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9242
9243         softc->ipf_tuners = ipf_tune_array_copy(softc,
9244                                                 sizeof(ipf_main_tuneables),
9245                                                 ipf_main_tuneables);
9246         if (softc->ipf_tuners == NULL) {
9247                 ipf_main_soft_destroy(softc);
9248                 return NULL;
9249         }
9250
9251         MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9252         MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9253         RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9254         RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9255         RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9256         RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9257         RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9258         RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9259         RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9260
9261         softc->ipf_token_head = NULL;
9262         softc->ipf_token_tail = &softc->ipf_token_head;
9263
9264         softc->ipf_tcpidletimeout = FIVE_DAYS;
9265         softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9266         softc->ipf_tcplastack = IPF_TTLVAL(30);
9267         softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9268         softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9269         softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9270         softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9271         softc->ipf_tcpclosed = IPF_TTLVAL(30);
9272         softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9273         softc->ipf_udptimeout = IPF_TTLVAL(120);
9274         softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9275         softc->ipf_icmptimeout = IPF_TTLVAL(60);
9276         softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9277         softc->ipf_iptimeout = IPF_TTLVAL(60);
9278
9279 #if defined(IPFILTER_DEFAULT_BLOCK)
9280         softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9281 #else
9282         softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9283 #endif
9284         softc->ipf_minttl = 4;
9285         softc->ipf_icmpminfragmtu = 68;
9286         softc->ipf_flags = IPF_LOGGING;
9287
9288         return softc;
9289 }
9290
9291 /* ------------------------------------------------------------------------ */
9292 /* Function:   ipf_main_soft_init                                           */
9293 /* Returns:    0 = success, -1 = failure                                    */
9294 /* Parameters: softc(I) - pointer to soft context main structure            */
9295 /*                                                                          */
9296 /* A null-op function that exists as a placeholder so that the flow in      */
9297 /* other functions is obvious.                                              */
9298 /* ------------------------------------------------------------------------ */
9299 /*ARGSUSED*/
9300 int
9301 ipf_main_soft_init(softc)
9302         ipf_main_softc_t *softc;
9303 {
9304         return 0;
9305 }
9306
9307
9308 /* ------------------------------------------------------------------------ */
9309 /* Function:   ipf_main_soft_destroy                                        */
9310 /* Returns:    void                                                         */
9311 /* Parameters: softc(I) - pointer to soft context main structure            */
9312 /*                                                                          */
9313 /* Undo everything that we did in ipf_main_soft_create.                     */
9314 /*                                                                          */
9315 /* The most important check that needs to be made here is whether or not    */
9316 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9317 /* value is stored in ipf_dynamic_main.                                     */
9318 /* ------------------------------------------------------------------------ */
9319 /*ARGSUSED*/
9320 void
9321 ipf_main_soft_destroy(softc)
9322         ipf_main_softc_t *softc;
9323 {
9324
9325         RW_DESTROY(&softc->ipf_frag);
9326         RW_DESTROY(&softc->ipf_poolrw);
9327         RW_DESTROY(&softc->ipf_nat);
9328         RW_DESTROY(&softc->ipf_state);
9329         RW_DESTROY(&softc->ipf_tokens);
9330         RW_DESTROY(&softc->ipf_mutex);
9331         RW_DESTROY(&softc->ipf_global);
9332         MUTEX_DESTROY(&softc->ipf_timeoutlock);
9333         MUTEX_DESTROY(&softc->ipf_rw);
9334
9335         if (softc->ipf_tuners != NULL) {
9336                 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9337         }
9338         if (softc->ipf_dynamic_softc == 1) {
9339                 KFREE(softc);
9340         }
9341 }
9342
9343
9344 /* ------------------------------------------------------------------------ */
9345 /* Function:   ipf_main_soft_fini                                           */
9346 /* Returns:    0 = success, -1 = failure                                    */
9347 /* Parameters: softc(I) - pointer to soft context main structure            */
9348 /*                                                                          */
9349 /* Clean out the rules which have been added since _init was last called,   */
9350 /* the only dynamic part of the mainline.                                   */
9351 /* ------------------------------------------------------------------------ */
9352 int
9353 ipf_main_soft_fini(softc)
9354         ipf_main_softc_t *softc;
9355 {
9356         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9357         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9358         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9359         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9360
9361         return 0;
9362 }
9363
9364
9365 /* ------------------------------------------------------------------------ */
9366 /* Function:   ipf_main_load                                                */
9367 /* Returns:    0 = success, -1 = failure                                    */
9368 /* Parameters: none                                                         */
9369 /*                                                                          */
9370 /* Handle global initialisation that needs to be done for the base part of  */
9371 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9372 /* arrays that get used by the state/NAT code.                              */
9373 /* ------------------------------------------------------------------------ */
9374 int
9375 ipf_main_load()
9376 {
9377         int i;
9378
9379         /* fill icmp reply type table */
9380         for (i = 0; i <= ICMP_MAXTYPE; i++)
9381                 icmpreplytype4[i] = -1;
9382         icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9383         icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9384         icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9385         icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9386
9387 #ifdef  USE_INET6
9388         /* fill icmp reply type table */
9389         for (i = 0; i <= ICMP6_MAXTYPE; i++)
9390                 icmpreplytype6[i] = -1;
9391         icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9392         icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9393         icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9394         icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9395         icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9396 #endif
9397
9398         return 0;
9399 }
9400
9401
9402 /* ------------------------------------------------------------------------ */
9403 /* Function:   ipf_main_unload                                              */
9404 /* Returns:    0 = success, -1 = failure                                    */
9405 /* Parameters: none                                                         */
9406 /*                                                                          */
9407 /* A null-op function that exists as a placeholder so that the flow in      */
9408 /* other functions is obvious.                                              */
9409 /* ------------------------------------------------------------------------ */
9410 int
9411 ipf_main_unload()
9412 {
9413         return 0;
9414 }
9415
9416
9417 /* ------------------------------------------------------------------------ */
9418 /* Function:   ipf_load_all                                                 */
9419 /* Returns:    0 = success, -1 = failure                                    */
9420 /* Parameters: none                                                         */
9421 /*                                                                          */
9422 /* Work through all of the subsystems inside IPFilter and call the load     */
9423 /* function for each in an order that won't lead to a crash :)              */
9424 /* ------------------------------------------------------------------------ */
9425 int
9426 ipf_load_all()
9427 {
9428         if (ipf_main_load() == -1)
9429                 return -1;
9430
9431         if (ipf_state_main_load() == -1)
9432                 return -1;
9433
9434         if (ipf_nat_main_load() == -1)
9435                 return -1;
9436
9437         if (ipf_frag_main_load() == -1)
9438                 return -1;
9439
9440         if (ipf_auth_main_load() == -1)
9441                 return -1;
9442
9443         if (ipf_proxy_main_load() == -1)
9444                 return -1;
9445
9446         return 0;
9447 }
9448
9449
9450 /* ------------------------------------------------------------------------ */
9451 /* Function:   ipf_unload_all                                               */
9452 /* Returns:    0 = success, -1 = failure                                    */
9453 /* Parameters: none                                                         */
9454 /*                                                                          */
9455 /* Work through all of the subsystems inside IPFilter and call the unload   */
9456 /* function for each in an order that won't lead to a crash :)              */
9457 /* ------------------------------------------------------------------------ */
9458 int
9459 ipf_unload_all()
9460 {
9461         if (ipf_proxy_main_unload() == -1)
9462                 return -1;
9463
9464         if (ipf_auth_main_unload() == -1)
9465                 return -1;
9466
9467         if (ipf_frag_main_unload() == -1)
9468                 return -1;
9469
9470         if (ipf_nat_main_unload() == -1)
9471                 return -1;
9472
9473         if (ipf_state_main_unload() == -1)
9474                 return -1;
9475
9476         if (ipf_main_unload() == -1)
9477                 return -1;
9478
9479         return 0;
9480 }
9481
9482
9483 /* ------------------------------------------------------------------------ */
9484 /* Function:   ipf_create_all                                               */
9485 /* Returns:    NULL = failure, else success                                 */
9486 /* Parameters: arg(I) - pointer to soft context main structure              */
9487 /*                                                                          */
9488 /* Work through all of the subsystems inside IPFilter and call the create   */
9489 /* function for each in an order that won't lead to a crash :)              */
9490 /* ------------------------------------------------------------------------ */
9491 ipf_main_softc_t *
9492 ipf_create_all(arg)
9493         void *arg;
9494 {
9495         ipf_main_softc_t *softc;
9496
9497         softc = ipf_main_soft_create(arg);
9498         if (softc == NULL)
9499                 return NULL;
9500
9501 #ifdef IPFILTER_LOG
9502         softc->ipf_log_soft = ipf_log_soft_create(softc);
9503         if (softc->ipf_log_soft == NULL) {
9504                 ipf_destroy_all(softc);
9505                 return NULL;
9506         }
9507 #endif
9508
9509         softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9510         if (softc->ipf_lookup_soft == NULL) {
9511                 ipf_destroy_all(softc);
9512                 return NULL;
9513         }
9514
9515         softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9516         if (softc->ipf_sync_soft == NULL) {
9517                 ipf_destroy_all(softc);
9518                 return NULL;
9519         }
9520
9521         softc->ipf_state_soft = ipf_state_soft_create(softc);
9522         if (softc->ipf_state_soft == NULL) {
9523                 ipf_destroy_all(softc);
9524                 return NULL;
9525         }
9526
9527         softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9528         if (softc->ipf_nat_soft == NULL) {
9529                 ipf_destroy_all(softc);
9530                 return NULL;
9531         }
9532
9533         softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9534         if (softc->ipf_frag_soft == NULL) {
9535                 ipf_destroy_all(softc);
9536                 return NULL;
9537         }
9538
9539         softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9540         if (softc->ipf_auth_soft == NULL) {
9541                 ipf_destroy_all(softc);
9542                 return NULL;
9543         }
9544
9545         softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9546         if (softc->ipf_proxy_soft == NULL) {
9547                 ipf_destroy_all(softc);
9548                 return NULL;
9549         }
9550
9551         return softc;
9552 }
9553
9554
9555 /* ------------------------------------------------------------------------ */
9556 /* Function:   ipf_destroy_all                                              */
9557 /* Returns:    void                                                         */
9558 /* Parameters: softc(I) - pointer to soft context main structure            */
9559 /*                                                                          */
9560 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9561 /* function for each in an order that won't lead to a crash :)              */
9562 /*                                                                          */
9563 /* Every one of these functions is expected to succeed, so there is no      */
9564 /* checking of return values.                                               */
9565 /* ------------------------------------------------------------------------ */
9566 void
9567 ipf_destroy_all(softc)
9568         ipf_main_softc_t *softc;
9569 {
9570
9571         if (softc->ipf_state_soft != NULL) {
9572                 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9573                 softc->ipf_state_soft = NULL;
9574         }
9575
9576         if (softc->ipf_nat_soft != NULL) {
9577                 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9578                 softc->ipf_nat_soft = NULL;
9579         }
9580
9581         if (softc->ipf_frag_soft != NULL) {
9582                 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9583                 softc->ipf_frag_soft = NULL;
9584         }
9585
9586         if (softc->ipf_auth_soft != NULL) {
9587                 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9588                 softc->ipf_auth_soft = NULL;
9589         }
9590
9591         if (softc->ipf_proxy_soft != NULL) {
9592                 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9593                 softc->ipf_proxy_soft = NULL;
9594         }
9595
9596         if (softc->ipf_sync_soft != NULL) {
9597                 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9598                 softc->ipf_sync_soft = NULL;
9599         }
9600
9601         if (softc->ipf_lookup_soft != NULL) {
9602                 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9603                 softc->ipf_lookup_soft = NULL;
9604         }
9605
9606 #ifdef IPFILTER_LOG
9607         if (softc->ipf_log_soft != NULL) {
9608                 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9609                 softc->ipf_log_soft = NULL;
9610         }
9611 #endif
9612
9613         ipf_main_soft_destroy(softc);
9614 }
9615
9616
9617 /* ------------------------------------------------------------------------ */
9618 /* Function:   ipf_init_all                                                 */
9619 /* Returns:    0 = success, -1 = failure                                    */
9620 /* Parameters: softc(I) - pointer to soft context main structure            */
9621 /*                                                                          */
9622 /* Work through all of the subsystems inside IPFilter and call the init     */
9623 /* function for each in an order that won't lead to a crash :)              */
9624 /* ------------------------------------------------------------------------ */
9625 int
9626 ipf_init_all(softc)
9627         ipf_main_softc_t *softc;
9628 {
9629
9630         if (ipf_main_soft_init(softc) == -1)
9631                 return -1;
9632
9633 #ifdef IPFILTER_LOG
9634         if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9635                 return -1;
9636 #endif
9637
9638         if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9639                 return -1;
9640
9641         if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9642                 return -1;
9643
9644         if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9645                 return -1;
9646
9647         if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9648                 return -1;
9649
9650         if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9651                 return -1;
9652
9653         if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9654                 return -1;
9655
9656         if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9657                 return -1;
9658
9659         return 0;
9660 }
9661
9662
9663 /* ------------------------------------------------------------------------ */
9664 /* Function:   ipf_fini_all                                                 */
9665 /* Returns:    0 = success, -1 = failure                                    */
9666 /* Parameters: softc(I) - pointer to soft context main structure            */
9667 /*                                                                          */
9668 /* Work through all of the subsystems inside IPFilter and call the fini     */
9669 /* function for each in an order that won't lead to a crash :)              */
9670 /* ------------------------------------------------------------------------ */
9671 int
9672 ipf_fini_all(softc)
9673         ipf_main_softc_t *softc;
9674 {
9675
9676         ipf_token_flush(softc);
9677
9678         if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9679                 return -1;
9680
9681         if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9682                 return -1;
9683
9684         if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9685                 return -1;
9686
9687         if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9688                 return -1;
9689
9690         if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9691                 return -1;
9692
9693         if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9694                 return -1;
9695
9696         if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9697                 return -1;
9698
9699 #ifdef IPFILTER_LOG
9700         if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9701                 return -1;
9702 #endif
9703
9704         if (ipf_main_soft_fini(softc) == -1)
9705                 return -1;
9706
9707         return 0;
9708 }
9709
9710
9711 /* ------------------------------------------------------------------------ */
9712 /* Function:    ipf_rule_expire                                             */
9713 /* Returns:     Nil                                                         */
9714 /* Parameters:  softc(I) - pointer to soft context main structure           */
9715 /*                                                                          */
9716 /* At present this function exists just to support temporary addition of    */
9717 /* firewall rules. Both inactive and active lists are scanned for items to  */
9718 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9719 /* loaded in.                                                               */
9720 /* ------------------------------------------------------------------------ */
9721 void
9722 ipf_rule_expire(softc)
9723         ipf_main_softc_t *softc;
9724 {
9725         frentry_t *fr;
9726
9727         if ((softc->ipf_rule_explist[0] == NULL) &&
9728             (softc->ipf_rule_explist[1] == NULL))
9729                 return;
9730
9731         WRITE_ENTER(&softc->ipf_mutex);
9732
9733         while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9734                 /*
9735                  * Because the list is kept sorted on insertion, the fist
9736                  * one that dies in the future means no more work to do.
9737                  */
9738                 if (fr->fr_die > softc->ipf_ticks)
9739                         break;
9740                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9741         }
9742
9743         while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9744                 /*
9745                  * Because the list is kept sorted on insertion, the fist
9746                  * one that dies in the future means no more work to do.
9747                  */
9748                 if (fr->fr_die > softc->ipf_ticks)
9749                         break;
9750                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9751         }
9752
9753         RWLOCK_EXIT(&softc->ipf_mutex);
9754 }
9755
9756
9757 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9758 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9759                                       i6addr_t *));
9760
9761 host_node_t RBI_ZERO(ipf_rb);
9762 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9763
9764
9765 /* ------------------------------------------------------------------------ */
9766 /* Function:    ipf_ht_node_cmp                                             */
9767 /* Returns:     int   - 0 == nodes are the same, ..                         */
9768 /* Parameters:  k1(I) - pointer to first key to compare                     */
9769 /*              k2(I) - pointer to second key to compare                    */
9770 /*                                                                          */
9771 /* The "key" for the node is a combination of two fields: the address       */
9772 /* family and the address itself.                                           */
9773 /*                                                                          */
9774 /* Because we're not actually interpreting the address data, it isn't       */
9775 /* necessary to convert them to/from network/host byte order. The mask is   */
9776 /* just used to remove bits that aren't significant - it doesn't matter     */
9777 /* where they are, as long as they're always in the same place.             */
9778 /*                                                                          */
9779 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9780 /* this is where individual ones will differ the most - but not true for    */
9781 /* for /48's, etc.                                                          */
9782 /* ------------------------------------------------------------------------ */
9783 static int
9784 ipf_ht_node_cmp(k1, k2)
9785         struct host_node_s *k1, *k2;
9786 {
9787         int i;
9788
9789         i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9790         if (i != 0)
9791                 return i;
9792
9793         if (k1->hn_addr.adf_family == AF_INET)
9794                 return (k2->hn_addr.adf_addr.in4.s_addr -
9795                         k1->hn_addr.adf_addr.in4.s_addr);
9796
9797         i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9798         if (i != 0)
9799                 return i;
9800         i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9801         if (i != 0)
9802                 return i;
9803         i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9804         if (i != 0)
9805                 return i;
9806         i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9807         return i;
9808 }
9809
9810
9811 /* ------------------------------------------------------------------------ */
9812 /* Function:    ipf_ht_node_make_key                                        */
9813 /* Returns:     Nil                                                         */
9814 /* parameters:  htp(I)    - pointer to address tracking structure           */
9815 /*              key(I)    - where to store masked address for lookup        */
9816 /*              family(I) - protocol family of address                      */
9817 /*              addr(I)   - pointer to network address                      */
9818 /*                                                                          */
9819 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9820 /* copy the address passed in into the key structure whilst masking out the */
9821 /* bits that we don't want.                                                 */
9822 /*                                                                          */
9823 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9824 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9825 /* have to be wary of that and not allow 32-128 to happen.                  */
9826 /* ------------------------------------------------------------------------ */
9827 static void
9828 ipf_ht_node_make_key(htp, key, family, addr)
9829         host_track_t *htp;
9830         host_node_t *key;
9831         int family;
9832         i6addr_t *addr;
9833 {
9834         key->hn_addr.adf_family = family;
9835         if (family == AF_INET) {
9836                 u_32_t mask;
9837                 int bits;
9838
9839                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9840                 bits = htp->ht_netmask;
9841                 if (bits >= 32) {
9842                         mask = 0xffffffff;
9843                 } else {
9844                         mask = htonl(0xffffffff << (32 - bits));
9845                 }
9846                 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9847 #ifdef USE_INET6
9848         } else {
9849                 int bits = htp->ht_netmask;
9850
9851                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9852                 if (bits > 96) {
9853                         key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9854                                              htonl(0xffffffff << (128 - bits));
9855                         key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9856                         key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9857                         key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9858                 } else if (bits > 64) {
9859                         key->hn_addr.adf_addr.i6[3] = 0;
9860                         key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9861                                              htonl(0xffffffff << (96 - bits));
9862                         key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9863                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9864                 } else if (bits > 32) {
9865                         key->hn_addr.adf_addr.i6[3] = 0;
9866                         key->hn_addr.adf_addr.i6[2] = 0;
9867                         key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9868                                              htonl(0xffffffff << (64 - bits));
9869                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9870                 } else {
9871                         key->hn_addr.adf_addr.i6[3] = 0;
9872                         key->hn_addr.adf_addr.i6[2] = 0;
9873                         key->hn_addr.adf_addr.i6[1] = 0;
9874                         key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9875                                              htonl(0xffffffff << (32 - bits));
9876                 }
9877 #endif
9878         }
9879 }
9880
9881
9882 /* ------------------------------------------------------------------------ */
9883 /* Function:    ipf_ht_node_add                                             */
9884 /* Returns:     int       - 0 == success,  -1 == failure                    */
9885 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9886 /*              htp(I)    - pointer to address tracking structure           */
9887 /*              family(I) - protocol family of address                      */
9888 /*              addr(I)   - pointer to network address                      */
9889 /*                                                                          */
9890 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9891 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9892 /*                                                                          */
9893 /* After preparing the key with the address information to find, look in    */
9894 /* the red-black tree to see if the address is known. A successful call to  */
9895 /* this function can mean one of two things: a new node was added to the    */
9896 /* tree or a matching node exists and we're able to bump up its activity.   */
9897 /* ------------------------------------------------------------------------ */
9898 int
9899 ipf_ht_node_add(softc, htp, family, addr)
9900         ipf_main_softc_t *softc;
9901         host_track_t *htp;
9902         int family;
9903         i6addr_t *addr;
9904 {
9905         host_node_t *h;
9906         host_node_t k;
9907
9908         ipf_ht_node_make_key(htp, &k, family, addr);
9909
9910         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9911         if (h == NULL) {
9912                 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9913                         return -1;
9914                 KMALLOC(h, host_node_t *);
9915                 if (h == NULL) {
9916                         DT(ipf_rb_no_mem);
9917                         LBUMP(ipf_rb_no_mem);
9918                         return -1;
9919                 }
9920
9921                 /*
9922                  * If there was a macro to initialise the RB node then that
9923                  * would get used here, but there isn't...
9924                  */
9925                 bzero((char *)h, sizeof(*h));
9926                 h->hn_addr = k.hn_addr;
9927                 h->hn_addr.adf_family = k.hn_addr.adf_family;
9928                 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9929                 htp->ht_cur_nodes++;
9930         } else {
9931                 if ((htp->ht_max_per_node != 0) &&
9932                     (h->hn_active >= htp->ht_max_per_node)) {
9933                         DT(ipf_rb_node_max);
9934                         LBUMP(ipf_rb_node_max);
9935                         return -1;
9936                 }
9937         }
9938
9939         h->hn_active++;
9940
9941         return 0;
9942 }
9943
9944
9945 /* ------------------------------------------------------------------------ */
9946 /* Function:    ipf_ht_node_del                                             */
9947 /* Returns:     int       - 0 == success,  -1 == failure                    */
9948 /* parameters:  htp(I)    - pointer to address tracking structure           */
9949 /*              family(I) - protocol family of address                      */
9950 /*              addr(I)   - pointer to network address                      */
9951 /*                                                                          */
9952 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9953 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9954 /*                                                                          */
9955 /* Try and find the address passed in amongst the leavese on this tree to   */
9956 /* be friend. If found then drop the active account for that node drops by  */
9957 /* one. If that count reaches 0, it is time to free it all up.              */
9958 /* ------------------------------------------------------------------------ */
9959 int
9960 ipf_ht_node_del(htp, family, addr)
9961         host_track_t *htp;
9962         int family;
9963         i6addr_t *addr;
9964 {
9965         host_node_t *h;
9966         host_node_t k;
9967
9968         ipf_ht_node_make_key(htp, &k, family, addr);
9969
9970         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9971         if (h == NULL) {
9972                 return -1;
9973         } else {
9974                 h->hn_active--;
9975                 if (h->hn_active == 0) {
9976                         (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9977                         htp->ht_cur_nodes--;
9978                         KFREE(h);
9979                 }
9980         }
9981
9982         return 0;
9983 }
9984
9985
9986 /* ------------------------------------------------------------------------ */
9987 /* Function:    ipf_rb_ht_init                                              */
9988 /* Returns:     Nil                                                         */
9989 /* Parameters:  head(I) - pointer to host tracking structure                */
9990 /*                                                                          */
9991 /* Initialise the host tracking structure to be ready for use above.        */
9992 /* ------------------------------------------------------------------------ */
9993 void
9994 ipf_rb_ht_init(head)
9995         host_track_t *head;
9996 {
9997         RBI_INIT(ipf_rb, &head->ht_root);
9998 }
9999
10000
10001 /* ------------------------------------------------------------------------ */
10002 /* Function:    ipf_rb_ht_freenode                                          */
10003 /* Returns:     Nil                                                         */
10004 /* Parameters:  head(I) - pointer to host tracking structure                */
10005 /*              arg(I)  - additional argument from walk caller              */
10006 /*                                                                          */
10007 /* Free an actual host_node_t structure.                                    */
10008 /* ------------------------------------------------------------------------ */
10009 void
10010 ipf_rb_ht_freenode(node, arg)
10011         host_node_t *node;
10012         void *arg;
10013 {
10014         KFREE(node);
10015 }
10016
10017
10018 /* ------------------------------------------------------------------------ */
10019 /* Function:    ipf_rb_ht_flush                                             */
10020 /* Returns:     Nil                                                         */
10021 /* Parameters:  head(I) - pointer to host tracking structure                */
10022 /*                                                                          */
10023 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10024 /* and free'ing each one.                                                   */
10025 /* ------------------------------------------------------------------------ */
10026 void
10027 ipf_rb_ht_flush(head)
10028         host_track_t *head;
10029 {
10030         RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10031 }
10032
10033
10034 /* ------------------------------------------------------------------------ */
10035 /* Function:    ipf_slowtimer                                               */
10036 /* Returns:     Nil                                                         */
10037 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10038 /*                                                                          */
10039 /* Slowly expire held state for fragments.  Timeouts are set * in           */
10040 /* expectation of this being called twice per second.                       */
10041 /* ------------------------------------------------------------------------ */
10042 void
10043 ipf_slowtimer(softc)
10044         ipf_main_softc_t *softc;
10045 {
10046
10047         ipf_token_expire(softc);
10048         ipf_frag_expire(softc);
10049         ipf_state_expire(softc);
10050         ipf_nat_expire(softc);
10051         ipf_auth_expire(softc);
10052         ipf_lookup_expire(softc);
10053         ipf_rule_expire(softc);
10054         ipf_sync_expire(softc);
10055         softc->ipf_ticks++;
10056 }
10057
10058
10059 /* ------------------------------------------------------------------------ */
10060 /* Function:    ipf_inet_mask_add                                           */
10061 /* Returns:     Nil                                                         */
10062 /* Parameters:  bits(I) - pointer to nat context information                */
10063 /*              mtab(I) - pointer to mask hash table structure              */
10064 /*                                                                          */
10065 /* When called, bits represents the mask of a new NAT rule that has just    */
10066 /* been added. This function inserts a bitmask into the array of masks to   */
10067 /* search when searching for a matching NAT rule for a packet.              */
10068 /* Prevention of duplicate masks is achieved by checking the use count for  */
10069 /* a given netmask.                                                         */
10070 /* ------------------------------------------------------------------------ */
10071 void
10072 ipf_inet_mask_add(bits, mtab)
10073         int bits;
10074         ipf_v4_masktab_t *mtab;
10075 {
10076         u_32_t mask;
10077         int i, j;
10078
10079         mtab->imt4_masks[bits]++;
10080         if (mtab->imt4_masks[bits] > 1)
10081                 return;
10082
10083         if (bits == 0)
10084                 mask = 0;
10085         else
10086                 mask = 0xffffffff << (32 - bits);
10087
10088         for (i = 0; i < 33; i++) {
10089                 if (ntohl(mtab->imt4_active[i]) < mask) {
10090                         for (j = 32; j > i; j--)
10091                                 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10092                         mtab->imt4_active[i] = htonl(mask);
10093                         break;
10094                 }
10095         }
10096         mtab->imt4_max++;
10097 }
10098
10099
10100 /* ------------------------------------------------------------------------ */
10101 /* Function:    ipf_inet_mask_del                                           */
10102 /* Returns:     Nil                                                         */
10103 /* Parameters:  bits(I) - number of bits set in the netmask                 */
10104 /*              mtab(I) - pointer to mask hash table structure              */
10105 /*                                                                          */
10106 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
10107 /* netmasks stored inside of mtab.                                          */
10108 /* ------------------------------------------------------------------------ */
10109 void
10110 ipf_inet_mask_del(bits, mtab)
10111         int bits;
10112         ipf_v4_masktab_t *mtab;
10113 {
10114         u_32_t mask;
10115         int i, j;
10116
10117         mtab->imt4_masks[bits]--;
10118         if (mtab->imt4_masks[bits] > 0)
10119                 return;
10120
10121         mask = htonl(0xffffffff << (32 - bits));
10122         for (i = 0; i < 33; i++) {
10123                 if (mtab->imt4_active[i] == mask) {
10124                         for (j = i + 1; j < 33; j++)
10125                                 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10126                         break;
10127                 }
10128         }
10129         mtab->imt4_max--;
10130         ASSERT(mtab->imt4_max >= 0);
10131 }
10132
10133
10134 #ifdef USE_INET6
10135 /* ------------------------------------------------------------------------ */
10136 /* Function:    ipf_inet6_mask_add                                          */
10137 /* Returns:     Nil                                                         */
10138 /* Parameters:  bits(I) - number of bits set in mask                        */
10139 /*              mask(I) - pointer to mask to add                            */
10140 /*              mtab(I) - pointer to mask hash table structure              */
10141 /*                                                                          */
10142 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10143 /* has just been added. This function inserts a bitmask into the array of   */
10144 /* masks to search when searching for a matching NAT rule for a packet.     */
10145 /* Prevention of duplicate masks is achieved by checking the use count for  */
10146 /* a given netmask.                                                         */
10147 /* ------------------------------------------------------------------------ */
10148 void
10149 ipf_inet6_mask_add(bits, mask, mtab)
10150         int bits;
10151         i6addr_t *mask;
10152         ipf_v6_masktab_t *mtab;
10153 {
10154         i6addr_t zero;
10155         int i, j;
10156
10157         mtab->imt6_masks[bits]++;
10158         if (mtab->imt6_masks[bits] > 1)
10159                 return;
10160
10161         if (bits == 0) {
10162                 mask = &zero;
10163                 zero.i6[0] = 0;
10164                 zero.i6[1] = 0;
10165                 zero.i6[2] = 0;
10166                 zero.i6[3] = 0;
10167         }
10168
10169         for (i = 0; i < 129; i++) {
10170                 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10171                         for (j = 128; j > i; j--)
10172                                 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10173                         mtab->imt6_active[i] = *mask;
10174                         break;
10175                 }
10176         }
10177         mtab->imt6_max++;
10178 }
10179
10180
10181 /* ------------------------------------------------------------------------ */
10182 /* Function:    ipf_inet6_mask_del                                          */
10183 /* Returns:     Nil                                                         */
10184 /* Parameters:  bits(I) - number of bits set in mask                        */
10185 /*              mask(I) - pointer to mask to remove                         */
10186 /*              mtab(I) - pointer to mask hash table structure              */
10187 /*                                                                          */
10188 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
10189 /* netmasks stored inside of mtab.                                          */
10190 /* ------------------------------------------------------------------------ */
10191 void
10192 ipf_inet6_mask_del(bits, mask, mtab)
10193         int bits;
10194         i6addr_t *mask;
10195         ipf_v6_masktab_t *mtab;
10196 {
10197         i6addr_t zero;
10198         int i, j;
10199
10200         mtab->imt6_masks[bits]--;
10201         if (mtab->imt6_masks[bits] > 0)
10202                 return;
10203
10204         if (bits == 0)
10205                 mask = &zero;
10206         zero.i6[0] = 0;
10207         zero.i6[1] = 0;
10208         zero.i6[2] = 0;
10209         zero.i6[3] = 0;
10210
10211         for (i = 0; i < 129; i++) {
10212                 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10213                         for (j = i + 1; j < 129; j++) {
10214                                 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10215                                 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10216                                         break;
10217                         }
10218                         break;
10219                 }
10220         }
10221         mtab->imt6_max--;
10222         ASSERT(mtab->imt6_max >= 0);
10223 }
10224 #endif