]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/ipfilter/netinet/fil.c
Remove a tautological test for adding a rule in the block that
[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 != 0) {
1727                 int morefrag = off & IP_MF;
1728
1729                 fi->fi_flx |= FI_FRAG;
1730                 off &= IP_OFFMASK;
1731                 if (off == 1 && p == IPPROTO_TCP) {
1732                         fin->fin_flx |= FI_SHORT;       /* RFC 3128 */
1733                         DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1734                 }
1735                 if (off != 0) {
1736                         fin->fin_flx |= FI_FRAGBODY;
1737                         off <<= 3;
1738                         if ((off + fin->fin_dlen > 65535) ||
1739                             (fin->fin_dlen == 0) ||
1740                             ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1741                                 /*
1742                                  * The length of the packet, starting at its
1743                                  * offset cannot exceed 65535 (0xffff) as the
1744                                  * length of an IP packet is only 16 bits.
1745                                  *
1746                                  * Any fragment that isn't the last fragment
1747                                  * must have a length greater than 0 and it
1748                                  * must be an even multiple of 8.
1749                                  */
1750                                 fi->fi_flx |= FI_BAD;
1751                                 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1752                         }
1753                 }
1754         }
1755         fin->fin_off = off;
1756
1757         /*
1758          * Call per-protocol setup and checking
1759          */
1760         if (p == IPPROTO_AH) {
1761                 /*
1762                  * Treat AH differently because we expect there to be another
1763                  * layer 4 header after it.
1764                  */
1765                 p = ipf_pr_ah(fin);
1766         }
1767
1768         switch (p)
1769         {
1770         case IPPROTO_UDP :
1771                 ipf_pr_udp(fin);
1772                 break;
1773         case IPPROTO_TCP :
1774                 ipf_pr_tcp(fin);
1775                 break;
1776         case IPPROTO_ICMP :
1777                 ipf_pr_icmp(fin);
1778                 break;
1779         case IPPROTO_ESP :
1780                 ipf_pr_esp(fin);
1781                 break;
1782         case IPPROTO_GRE :
1783                 ipf_pr_gre(fin);
1784                 break;
1785         }
1786
1787         ip = fin->fin_ip;
1788         if (ip == NULL)
1789                 return;
1790
1791         /*
1792          * If it is a standard IP header (no options), set the flag fields
1793          * which relate to options to 0.
1794          */
1795         if (hlen == sizeof(*ip)) {
1796                 fi->fi_optmsk = 0;
1797                 fi->fi_secmsk = 0;
1798                 fi->fi_auth = 0;
1799                 return;
1800         }
1801
1802         /*
1803          * So the IP header has some IP options attached.  Walk the entire
1804          * list of options present with this packet and set flags to indicate
1805          * which ones are here and which ones are not.  For the somewhat out
1806          * of date and obscure security classification options, set a flag to
1807          * represent which classification is present.
1808          */
1809         fi->fi_flx |= FI_OPTIONS;
1810
1811         for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1812                 opt = *s;
1813                 if (opt == '\0')
1814                         break;
1815                 else if (opt == IPOPT_NOP)
1816                         ol = 1;
1817                 else {
1818                         if (hlen < 2)
1819                                 break;
1820                         ol = (int)*(s + 1);
1821                         if (ol < 2 || ol > hlen)
1822                                 break;
1823                 }
1824                 for (i = 9, mv = 4; mv >= 0; ) {
1825                         op = ipopts + i;
1826
1827                         if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1828                                 u_32_t doi;
1829
1830                                 switch (opt)
1831                                 {
1832                                 case IPOPT_SECURITY :
1833                                         if (optmsk & op->ol_bit) {
1834                                                 fin->fin_flx |= FI_BAD;
1835                                                 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1836                                         } else {
1837                                                 doi = ipf_checkripso(s);
1838                                                 secmsk = doi >> 16;
1839                                                 auth = doi & 0xffff;
1840                                         }
1841                                         break;
1842
1843                                 case IPOPT_CIPSO :
1844
1845                                         if (optmsk & op->ol_bit) {
1846                                                 fin->fin_flx |= FI_BAD;
1847                                                 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1848                                         } else {
1849                                                 doi = ipf_checkcipso(fin,
1850                                                                      s, ol);
1851                                                 secmsk = doi >> 16;
1852                                                 auth = doi & 0xffff;
1853                                         }
1854                                         break;
1855                                 }
1856                                 optmsk |= op->ol_bit;
1857                         }
1858
1859                         if (opt < op->ol_val)
1860                                 i -= mv;
1861                         else
1862                                 i += mv;
1863                         mv--;
1864                 }
1865                 hlen -= ol;
1866                 s += ol;
1867         }
1868
1869         /*
1870          *
1871          */
1872         if (auth && !(auth & 0x0100))
1873                 auth &= 0xff00;
1874         fi->fi_optmsk = optmsk;
1875         fi->fi_secmsk = secmsk;
1876         fi->fi_auth = auth;
1877 }
1878
1879
1880 /* ------------------------------------------------------------------------ */
1881 /* Function:    ipf_checkripso                                              */
1882 /* Returns:     void                                                        */
1883 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1884 /*                                                                          */
1885 /* ------------------------------------------------------------------------ */
1886 static u_32_t
1887 ipf_checkripso(s)
1888         u_char *s;
1889 {
1890         const struct optlist *sp;
1891         u_short secmsk = 0, auth = 0;
1892         u_char sec;
1893         int j, m;
1894
1895         sec = *(s + 2); /* classification */
1896         for (j = 3, m = 2; m >= 0; ) {
1897                 sp = secopt + j;
1898                 if (sec == sp->ol_val) {
1899                         secmsk |= sp->ol_bit;
1900                         auth = *(s + 3);
1901                         auth *= 256;
1902                         auth += *(s + 4);
1903                         break;
1904                 }
1905                 if (sec < sp->ol_val)
1906                         j -= m;
1907                 else
1908                         j += m;
1909                 m--;
1910         }
1911
1912         return (secmsk << 16) | auth;
1913 }
1914
1915
1916 /* ------------------------------------------------------------------------ */
1917 /* Function:    ipf_checkcipso                                              */
1918 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1919 /* Parameters:  fin(IO) - pointer to packet information                     */
1920 /*              s(I)    - pointer to start of CIPSO option                  */
1921 /*              ol(I)   - length of CIPSO option field                      */
1922 /*                                                                          */
1923 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1924 /* header and returns that whilst also storing the highest sensitivity      */
1925 /* value found in the fr_info_t structure.                                  */
1926 /*                                                                          */
1927 /* No attempt is made to extract the category bitmaps as these are defined  */
1928 /* by the user (rather than the protocol) and can be rather numerous on the */
1929 /* end nodes.                                                               */
1930 /* ------------------------------------------------------------------------ */
1931 static u_32_t
1932 ipf_checkcipso(fin, s, ol)
1933         fr_info_t *fin;
1934         u_char *s;
1935         int ol;
1936 {
1937         ipf_main_softc_t *softc = fin->fin_main_soft;
1938         fr_ip_t *fi;
1939         u_32_t doi;
1940         u_char *t, tag, tlen, sensitivity;
1941         int len;
1942
1943         if (ol < 6 || ol > 40) {
1944                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1945                 fin->fin_flx |= FI_BAD;
1946                 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1947                 return 0;
1948         }
1949
1950         fi = &fin->fin_fi;
1951         fi->fi_sensitivity = 0;
1952         /*
1953          * The DOI field MUST be there.
1954          */
1955         bcopy(s + 2, &doi, sizeof(doi));
1956
1957         t = (u_char *)s + 6;
1958         for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1959                 tag = *t;
1960                 tlen = *(t + 1);
1961                 if (tlen > len || tlen < 4 || tlen > 34) {
1962                         LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1963                         fin->fin_flx |= FI_BAD;
1964                         DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1965                         return 0;
1966                 }
1967
1968                 sensitivity = 0;
1969                 /*
1970                  * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1971                  * draft (16 July 1992) that has expired.
1972                  */
1973                 if (tag == 0) {
1974                         fin->fin_flx |= FI_BAD;
1975                         DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1976                         continue;
1977                 } else if (tag == 1) {
1978                         if (*(t + 2) != 0) {
1979                                 fin->fin_flx |= FI_BAD;
1980                                 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1981                                 continue;
1982                         }
1983                         sensitivity = *(t + 3);
1984                         /* Category bitmap for categories 0-239 */
1985
1986                 } else if (tag == 4) {
1987                         if (*(t + 2) != 0) {
1988                                 fin->fin_flx |= FI_BAD;
1989                                 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1990                                 continue;
1991                         }
1992                         sensitivity = *(t + 3);
1993                         /* Enumerated categories, 16bits each, upto 15 */
1994
1995                 } else if (tag == 5) {
1996                         if (*(t + 2) != 0) {
1997                                 fin->fin_flx |= FI_BAD;
1998                                 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1999                                 continue;
2000                         }
2001                         sensitivity = *(t + 3);
2002                         /* Range of categories (2*16bits), up to 7 pairs */
2003
2004                 } else if (tag > 127) {
2005                         /* Custom defined DOI */
2006                         ;
2007                 } else {
2008                         fin->fin_flx |= FI_BAD;
2009                         DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2010                         continue;
2011                 }
2012
2013                 if (sensitivity > fi->fi_sensitivity)
2014                         fi->fi_sensitivity = sensitivity;
2015         }
2016
2017         return doi;
2018 }
2019
2020
2021 /* ------------------------------------------------------------------------ */
2022 /* Function:    ipf_makefrip                                                */
2023 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2024 /* Parameters:  hlen(I) - length of IP packet header                        */
2025 /*              ip(I)   - pointer to the IP header                          */
2026 /*              fin(IO) - pointer to packet information                     */
2027 /*                                                                          */
2028 /* Compact the IP header into a structure which contains just the info.     */
2029 /* which is useful for comparing IP headers with and store this information */
2030 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2031 /* this function will be called with either an IPv4 or IPv6 packet.         */
2032 /* ------------------------------------------------------------------------ */
2033 int
2034 ipf_makefrip(hlen, ip, fin)
2035         int hlen;
2036         ip_t *ip;
2037         fr_info_t *fin;
2038 {
2039         ipf_main_softc_t *softc = fin->fin_main_soft;
2040         int v;
2041
2042         fin->fin_depth = 0;
2043         fin->fin_hlen = (u_short)hlen;
2044         fin->fin_ip = ip;
2045         fin->fin_rule = 0xffffffff;
2046         fin->fin_group[0] = -1;
2047         fin->fin_group[1] = '\0';
2048         fin->fin_dp = (char *)ip + hlen;
2049
2050         v = fin->fin_v;
2051         if (v == 4) {
2052                 fin->fin_plen = ntohs(ip->ip_len);
2053                 fin->fin_dlen = fin->fin_plen - hlen;
2054                 ipf_pr_ipv4hdr(fin);
2055 #ifdef  USE_INET6
2056         } else if (v == 6) {
2057                 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2058                 fin->fin_dlen = fin->fin_plen;
2059                 fin->fin_plen += hlen;
2060
2061                 ipf_pr_ipv6hdr(fin);
2062 #endif
2063         }
2064         if (fin->fin_ip == NULL) {
2065                 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2066                 return -1;
2067         }
2068         return 0;
2069 }
2070
2071
2072 /* ------------------------------------------------------------------------ */
2073 /* Function:    ipf_portcheck                                               */
2074 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2075 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2076 /*              pop(I) - port number to evaluate                            */
2077 /*                                                                          */
2078 /* Perform a comparison of a port number against some other(s), using a     */
2079 /* structure with compare information stored in it.                         */
2080 /* ------------------------------------------------------------------------ */
2081 static INLINE int
2082 ipf_portcheck(frp, pop)
2083         frpcmp_t *frp;
2084         u_32_t pop;
2085 {
2086         int err = 1;
2087         u_32_t po;
2088
2089         po = frp->frp_port;
2090
2091         /*
2092          * Do opposite test to that required and continue if that succeeds.
2093          */
2094         switch (frp->frp_cmp)
2095         {
2096         case FR_EQUAL :
2097                 if (pop != po) /* EQUAL */
2098                         err = 0;
2099                 break;
2100         case FR_NEQUAL :
2101                 if (pop == po) /* NOTEQUAL */
2102                         err = 0;
2103                 break;
2104         case FR_LESST :
2105                 if (pop >= po) /* LESSTHAN */
2106                         err = 0;
2107                 break;
2108         case FR_GREATERT :
2109                 if (pop <= po) /* GREATERTHAN */
2110                         err = 0;
2111                 break;
2112         case FR_LESSTE :
2113                 if (pop > po) /* LT or EQ */
2114                         err = 0;
2115                 break;
2116         case FR_GREATERTE :
2117                 if (pop < po) /* GT or EQ */
2118                         err = 0;
2119                 break;
2120         case FR_OUTRANGE :
2121                 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2122                         err = 0;
2123                 break;
2124         case FR_INRANGE :
2125                 if (pop <= po || pop >= frp->frp_top) /* In range */
2126                         err = 0;
2127                 break;
2128         case FR_INCRANGE :
2129                 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2130                         err = 0;
2131                 break;
2132         default :
2133                 break;
2134         }
2135         return err;
2136 }
2137
2138
2139 /* ------------------------------------------------------------------------ */
2140 /* Function:    ipf_tcpudpchk                                               */
2141 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2142 /* Parameters:  fda(I) - pointer to packet information                      */
2143 /*              ft(I)  - pointer to structure with comparison data          */
2144 /*                                                                          */
2145 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2146 /* structure containing information that we want to match against.          */
2147 /* ------------------------------------------------------------------------ */
2148 int
2149 ipf_tcpudpchk(fi, ft)
2150         fr_ip_t *fi;
2151         frtuc_t *ft;
2152 {
2153         int err = 1;
2154
2155         /*
2156          * Both ports should *always* be in the first fragment.
2157          * So far, I cannot find any cases where they can not be.
2158          *
2159          * compare destination ports
2160          */
2161         if (ft->ftu_dcmp)
2162                 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2163
2164         /*
2165          * compare source ports
2166          */
2167         if (err && ft->ftu_scmp)
2168                 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2169
2170         /*
2171          * If we don't have all the TCP/UDP header, then how can we
2172          * expect to do any sort of match on it ?  If we were looking for
2173          * TCP flags, then NO match.  If not, then match (which should
2174          * satisfy the "short" class too).
2175          */
2176         if (err && (fi->fi_p == IPPROTO_TCP)) {
2177                 if (fi->fi_flx & FI_SHORT)
2178                         return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2179                 /*
2180                  * Match the flags ?  If not, abort this match.
2181                  */
2182                 if (ft->ftu_tcpfm &&
2183                     ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2184                         FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2185                                  ft->ftu_tcpfm, ft->ftu_tcpf));
2186                         err = 0;
2187                 }
2188         }
2189         return err;
2190 }
2191
2192
2193 /* ------------------------------------------------------------------------ */
2194 /* Function:    ipf_check_ipf                                               */
2195 /* Returns:     int - 0 == match, else no match                             */
2196 /* Parameters:  fin(I)     - pointer to packet information                  */
2197 /*              fr(I)      - pointer to filter rule                         */
2198 /*              portcmp(I) - flag indicating whether to attempt matching on */
2199 /*                           TCP/UDP port data.                             */
2200 /*                                                                          */
2201 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2202 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2203 /* this function.                                                           */
2204 /* ------------------------------------------------------------------------ */
2205 static INLINE int
2206 ipf_check_ipf(fin, fr, portcmp)
2207         fr_info_t *fin;
2208         frentry_t *fr;
2209         int portcmp;
2210 {
2211         u_32_t  *ld, *lm, *lip;
2212         fripf_t *fri;
2213         fr_ip_t *fi;
2214         int i;
2215
2216         fi = &fin->fin_fi;
2217         fri = fr->fr_ipf;
2218         lip = (u_32_t *)fi;
2219         lm = (u_32_t *)&fri->fri_mip;
2220         ld = (u_32_t *)&fri->fri_ip;
2221
2222         /*
2223          * first 32 bits to check coversion:
2224          * IP version, TOS, TTL, protocol
2225          */
2226         i = ((*lip & *lm) != *ld);
2227         FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2228                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2229         if (i)
2230                 return 1;
2231
2232         /*
2233          * Next 32 bits is a constructed bitmask indicating which IP options
2234          * are present (if any) in this packet.
2235          */
2236         lip++, lm++, ld++;
2237         i = ((*lip & *lm) != *ld);
2238         FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2239                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2240         if (i != 0)
2241                 return 1;
2242
2243         lip++, lm++, ld++;
2244         /*
2245          * Unrolled loops (4 each, for 32 bits) for address checks.
2246          */
2247         /*
2248          * Check the source address.
2249          */
2250         if (fr->fr_satype == FRI_LOOKUP) {
2251                 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2252                                       fi->fi_v, lip, fin->fin_plen);
2253                 if (i == -1)
2254                         return 1;
2255                 lip += 3;
2256                 lm += 3;
2257                 ld += 3;
2258         } else {
2259                 i = ((*lip & *lm) != *ld);
2260                 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2261                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262                 if (fi->fi_v == 6) {
2263                         lip++, lm++, ld++;
2264                         i |= ((*lip & *lm) != *ld);
2265                         FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2266                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2267                         lip++, lm++, ld++;
2268                         i |= ((*lip & *lm) != *ld);
2269                         FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2270                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2271                         lip++, lm++, ld++;
2272                         i |= ((*lip & *lm) != *ld);
2273                         FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2274                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2275                 } else {
2276                         lip += 3;
2277                         lm += 3;
2278                         ld += 3;
2279                 }
2280         }
2281         i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2282         if (i != 0)
2283                 return 1;
2284
2285         /*
2286          * Check the destination address.
2287          */
2288         lip++, lm++, ld++;
2289         if (fr->fr_datype == FRI_LOOKUP) {
2290                 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2291                                       fi->fi_v, lip, fin->fin_plen);
2292                 if (i == -1)
2293                         return 1;
2294                 lip += 3;
2295                 lm += 3;
2296                 ld += 3;
2297         } else {
2298                 i = ((*lip & *lm) != *ld);
2299                 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2300                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2301                 if (fi->fi_v == 6) {
2302                         lip++, lm++, ld++;
2303                         i |= ((*lip & *lm) != *ld);
2304                         FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2305                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2306                         lip++, lm++, ld++;
2307                         i |= ((*lip & *lm) != *ld);
2308                         FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2309                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2310                         lip++, lm++, ld++;
2311                         i |= ((*lip & *lm) != *ld);
2312                         FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2313                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2314                 } else {
2315                         lip += 3;
2316                         lm += 3;
2317                         ld += 3;
2318                 }
2319         }
2320         i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2321         if (i != 0)
2322                 return 1;
2323         /*
2324          * IP addresses matched.  The next 32bits contains:
2325          * mast of old IP header security & authentication bits.
2326          */
2327         lip++, lm++, ld++;
2328         i = (*ld - (*lip & *lm));
2329         FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2330
2331         /*
2332          * Next we have 32 bits of packet flags.
2333          */
2334         lip++, lm++, ld++;
2335         i |= (*ld - (*lip & *lm));
2336         FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2337
2338         if (i == 0) {
2339                 /*
2340                  * If a fragment, then only the first has what we're
2341                  * looking for here...
2342                  */
2343                 if (portcmp) {
2344                         if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2345                                 i = 1;
2346                 } else {
2347                         if (fr->fr_dcmp || fr->fr_scmp ||
2348                             fr->fr_tcpf || fr->fr_tcpfm)
2349                                 i = 1;
2350                         if (fr->fr_icmpm || fr->fr_icmp) {
2351                                 if (((fi->fi_p != IPPROTO_ICMP) &&
2352                                      (fi->fi_p != IPPROTO_ICMPV6)) ||
2353                                     fin->fin_off || (fin->fin_dlen < 2))
2354                                         i = 1;
2355                                 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2356                                          fr->fr_icmp) {
2357                                         FR_DEBUG(("i. %#x & %#x != %#x\n",
2358                                                  fin->fin_data[0],
2359                                                  fr->fr_icmpm, fr->fr_icmp));
2360                                         i = 1;
2361                                 }
2362                         }
2363                 }
2364         }
2365         return i;
2366 }
2367
2368
2369 /* ------------------------------------------------------------------------ */
2370 /* Function:    ipf_scanlist                                                */
2371 /* Returns:     int - result flags of scanning filter list                  */
2372 /* Parameters:  fin(I) - pointer to packet information                      */
2373 /*              pass(I) - default result to return for filtering            */
2374 /*                                                                          */
2375 /* Check the input/output list of rules for a match to the current packet.  */
2376 /* If a match is found, the value of fr_flags from the rule becomes the     */
2377 /* return value and fin->fin_fr points to the matched rule.                 */
2378 /*                                                                          */
2379 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2380 /* When unwinding, it should finish up with fin_depth as 0.                 */
2381 /*                                                                          */
2382 /* Could be per interface, but this gets real nasty when you don't have,    */
2383 /* or can't easily change, the kernel source code to .                      */
2384 /* ------------------------------------------------------------------------ */
2385 int
2386 ipf_scanlist(fin, pass)
2387         fr_info_t *fin;
2388         u_32_t pass;
2389 {
2390         ipf_main_softc_t *softc = fin->fin_main_soft;
2391         int rulen, portcmp, off, skip;
2392         struct frentry *fr, *fnext;
2393         u_32_t passt, passo;
2394
2395         /*
2396          * Do not allow nesting deeper than 16 levels.
2397          */
2398         if (fin->fin_depth >= 16)
2399                 return pass;
2400
2401         fr = fin->fin_fr;
2402
2403         /*
2404          * If there are no rules in this list, return now.
2405          */
2406         if (fr == NULL)
2407                 return pass;
2408
2409         skip = 0;
2410         portcmp = 0;
2411         fin->fin_depth++;
2412         fin->fin_fr = NULL;
2413         off = fin->fin_off;
2414
2415         if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2416                 portcmp = 1;
2417
2418         for (rulen = 0; fr; fr = fnext, rulen++) {
2419                 fnext = fr->fr_next;
2420                 if (skip != 0) {
2421                         FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2422                         skip--;
2423                         continue;
2424                 }
2425
2426                 /*
2427                  * In all checks below, a null (zero) value in the
2428                  * filter struture is taken to mean a wildcard.
2429                  *
2430                  * check that we are working for the right interface
2431                  */
2432 #ifdef  _KERNEL
2433                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2434                         continue;
2435 #else
2436                 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2437                         printf("\n");
2438                 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2439                                   FR_ISPASS(pass) ? 'p' :
2440                                   FR_ISACCOUNT(pass) ? 'A' :
2441                                   FR_ISAUTH(pass) ? 'a' :
2442                                   (pass & FR_NOMATCH) ? 'n' :'b'));
2443                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2444                         continue;
2445                 FR_VERBOSE((":i"));
2446 #endif
2447
2448                 switch (fr->fr_type)
2449                 {
2450                 case FR_T_IPF :
2451                 case FR_T_IPF_BUILTIN :
2452                         if (ipf_check_ipf(fin, fr, portcmp))
2453                                 continue;
2454                         break;
2455 #if defined(IPFILTER_BPF)
2456                 case FR_T_BPFOPC :
2457                 case FR_T_BPFOPC_BUILTIN :
2458                     {
2459                         u_char *mc;
2460                         int wlen;
2461
2462                         if (*fin->fin_mp == NULL)
2463                                 continue;
2464                         if (fin->fin_family != fr->fr_family)
2465                                 continue;
2466                         mc = (u_char *)fin->fin_m;
2467                         wlen = fin->fin_dlen + fin->fin_hlen;
2468                         if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2469                                 continue;
2470                         break;
2471                     }
2472 #endif
2473                 case FR_T_CALLFUNC_BUILTIN :
2474                     {
2475                         frentry_t *f;
2476
2477                         f = (*fr->fr_func)(fin, &pass);
2478                         if (f != NULL)
2479                                 fr = f;
2480                         else
2481                                 continue;
2482                         break;
2483                     }
2484
2485                 case FR_T_IPFEXPR :
2486                 case FR_T_IPFEXPR_BUILTIN :
2487                         if (fin->fin_family != fr->fr_family)
2488                                 continue;
2489                         if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2490                                 continue;
2491                         break;
2492
2493                 default :
2494                         break;
2495                 }
2496
2497                 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2498                         if (fin->fin_nattag == NULL)
2499                                 continue;
2500                         if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2501                                 continue;
2502                 }
2503                 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2504
2505                 passt = fr->fr_flags;
2506
2507                 /*
2508                  * If the rule is a "call now" rule, then call the function
2509                  * in the rule, if it exists and use the results from that.
2510                  * If the function pointer is bad, just make like we ignore
2511                  * it, except for increasing the hit counter.
2512                  */
2513                 if ((passt & FR_CALLNOW) != 0) {
2514                         frentry_t *frs;
2515
2516                         ATOMIC_INC64(fr->fr_hits);
2517                         if ((fr->fr_func == NULL) ||
2518                             (fr->fr_func == (ipfunc_t)-1))
2519                                 continue;
2520
2521                         frs = fin->fin_fr;
2522                         fin->fin_fr = fr;
2523                         fr = (*fr->fr_func)(fin, &passt);
2524                         if (fr == NULL) {
2525                                 fin->fin_fr = frs;
2526                                 continue;
2527                         }
2528                         passt = fr->fr_flags;
2529                 }
2530                 fin->fin_fr = fr;
2531
2532 #ifdef  IPFILTER_LOG
2533                 /*
2534                  * Just log this packet...
2535                  */
2536                 if ((passt & FR_LOGMASK) == FR_LOG) {
2537                         if (ipf_log_pkt(fin, passt) == -1) {
2538                                 if (passt & FR_LOGORBLOCK) {
2539                                         DT(frb_logfail);
2540                                         passt &= ~FR_CMDMASK;
2541                                         passt |= FR_BLOCK|FR_QUICK;
2542                                         fin->fin_reason = FRB_LOGFAIL;
2543                                 }
2544                         }
2545                 }
2546 #endif /* IPFILTER_LOG */
2547
2548                 MUTEX_ENTER(&fr->fr_lock);
2549                 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2550                 fr->fr_hits++;
2551                 MUTEX_EXIT(&fr->fr_lock);
2552                 fin->fin_rule = rulen;
2553
2554                 passo = pass;
2555                 if (FR_ISSKIP(passt)) {
2556                         skip = fr->fr_arg;
2557                         continue;
2558                 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2559                            ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2560                         pass = passt;
2561                 }
2562
2563                 if (passt & (FR_RETICMP|FR_FAKEICMP))
2564                         fin->fin_icode = fr->fr_icode;
2565
2566                 if (fr->fr_group != -1) {
2567                         (void) strncpy(fin->fin_group,
2568                                        FR_NAME(fr, fr_group),
2569                                        strlen(FR_NAME(fr, fr_group)));
2570                 } else {
2571                         fin->fin_group[0] = '\0';
2572                 }
2573
2574                 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2575
2576                 if (fr->fr_grphead != NULL) {
2577                         fin->fin_fr = fr->fr_grphead->fg_start;
2578                         FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2579
2580                         if (FR_ISDECAPS(passt))
2581                                 passt = ipf_decaps(fin, pass, fr->fr_icode);
2582                         else
2583                                 passt = ipf_scanlist(fin, pass);
2584
2585                         if (fin->fin_fr == NULL) {
2586                                 fin->fin_rule = rulen;
2587                                 if (fr->fr_group != -1)
2588                                         (void) strncpy(fin->fin_group,
2589                                                        fr->fr_names +
2590                                                        fr->fr_group,
2591                                                        strlen(fr->fr_names +
2592                                                               fr->fr_group));
2593                                 fin->fin_fr = fr;
2594                                 passt = pass;
2595                         }
2596                         pass = passt;
2597                 }
2598
2599                 if (pass & FR_QUICK) {
2600                         /*
2601                          * Finally, if we've asked to track state for this
2602                          * packet, set it up.  Add state for "quick" rules
2603                          * here so that if the action fails we can consider
2604                          * the rule to "not match" and keep on processing
2605                          * filter rules.
2606                          */
2607                         if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2608                             !(fin->fin_flx & FI_STATE)) {
2609                                 int out = fin->fin_out;
2610
2611                                 fin->fin_fr = fr;
2612                                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2613                                         LBUMPD(ipf_stats[out], fr_ads);
2614                                 } else {
2615                                         LBUMPD(ipf_stats[out], fr_bads);
2616                                         pass = passo;
2617                                         continue;
2618                                 }
2619                         }
2620                         break;
2621                 }
2622         }
2623         fin->fin_depth--;
2624         return pass;
2625 }
2626
2627
2628 /* ------------------------------------------------------------------------ */
2629 /* Function:    ipf_acctpkt                                                 */
2630 /* Returns:     frentry_t* - always returns NULL                            */
2631 /* Parameters:  fin(I) - pointer to packet information                      */
2632 /*              passp(IO) - pointer to current/new filter decision (unused) */
2633 /*                                                                          */
2634 /* Checks a packet against accounting rules, if there are any for the given */
2635 /* IP protocol version.                                                     */
2636 /*                                                                          */
2637 /* N.B.: this function returns NULL to match the prototype used by other    */
2638 /* functions called from the IPFilter "mainline" in ipf_check().            */
2639 /* ------------------------------------------------------------------------ */
2640 frentry_t *
2641 ipf_acctpkt(fin, passp)
2642         fr_info_t *fin;
2643         u_32_t *passp;
2644 {
2645         ipf_main_softc_t *softc = fin->fin_main_soft;
2646         char group[FR_GROUPLEN];
2647         frentry_t *fr, *frsave;
2648         u_32_t pass, rulen;
2649
2650         passp = passp;
2651         fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2652
2653         if (fr != NULL) {
2654                 frsave = fin->fin_fr;
2655                 bcopy(fin->fin_group, group, FR_GROUPLEN);
2656                 rulen = fin->fin_rule;
2657                 fin->fin_fr = fr;
2658                 pass = ipf_scanlist(fin, FR_NOMATCH);
2659                 if (FR_ISACCOUNT(pass)) {
2660                         LBUMPD(ipf_stats[0], fr_acct);
2661                 }
2662                 fin->fin_fr = frsave;
2663                 bcopy(group, fin->fin_group, FR_GROUPLEN);
2664                 fin->fin_rule = rulen;
2665         }
2666         return NULL;
2667 }
2668
2669
2670 /* ------------------------------------------------------------------------ */
2671 /* Function:    ipf_firewall                                                */
2672 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2673 /*                           were found, returns NULL.                      */
2674 /* Parameters:  fin(I) - pointer to packet information                      */
2675 /*              passp(IO) - pointer to current/new filter decision (unused) */
2676 /*                                                                          */
2677 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2678 /* there are any matches.  The first check is to see if a match can be seen */
2679 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2680 /* matching rule is found, take any appropriate actions as defined by the   */
2681 /* rule - except logging.                                                   */
2682 /* ------------------------------------------------------------------------ */
2683 static frentry_t *
2684 ipf_firewall(fin, passp)
2685         fr_info_t *fin;
2686         u_32_t *passp;
2687 {
2688         ipf_main_softc_t *softc = fin->fin_main_soft;
2689         frentry_t *fr;
2690         u_32_t pass;
2691         int out;
2692
2693         out = fin->fin_out;
2694         pass = *passp;
2695
2696         /*
2697          * This rule cache will only affect packets that are not being
2698          * statefully filtered.
2699          */
2700         fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2701         if (fin->fin_fr != NULL)
2702                 pass = ipf_scanlist(fin, softc->ipf_pass);
2703
2704         if ((pass & FR_NOMATCH)) {
2705                 LBUMPD(ipf_stats[out], fr_nom);
2706         }
2707         fr = fin->fin_fr;
2708
2709         /*
2710          * Apply packets per second rate-limiting to a rule as required.
2711          */
2712         if ((fr != NULL) && (fr->fr_pps != 0) &&
2713             !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2714                 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2715                 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2716                 pass |= FR_BLOCK;
2717                 LBUMPD(ipf_stats[out], fr_ppshit);
2718                 fin->fin_reason = FRB_PPSRATE;
2719         }
2720
2721         /*
2722          * If we fail to add a packet to the authorization queue, then we
2723          * drop the packet later.  However, if it was added then pretend
2724          * we've dropped it already.
2725          */
2726         if (FR_ISAUTH(pass)) {
2727                 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2728                         DT1(frb_authnew, fr_info_t *, fin);
2729                         fin->fin_m = *fin->fin_mp = NULL;
2730                         fin->fin_reason = FRB_AUTHNEW;
2731                         fin->fin_error = 0;
2732                 } else {
2733                         IPFERROR(1);
2734                         fin->fin_error = ENOSPC;
2735                 }
2736         }
2737
2738         if ((fr != NULL) && (fr->fr_func != NULL) &&
2739             (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2740                 (void) (*fr->fr_func)(fin, &pass);
2741
2742         /*
2743          * If a rule is a pre-auth rule, check again in the list of rules
2744          * loaded for authenticated use.  It does not particulary matter
2745          * if this search fails because a "preauth" result, from a rule,
2746          * is treated as "not a pass", hence the packet is blocked.
2747          */
2748         if (FR_ISPREAUTH(pass)) {
2749                 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2750         }
2751
2752         /*
2753          * If the rule has "keep frag" and the packet is actually a fragment,
2754          * then create a fragment state entry.
2755          */
2756         if (pass & FR_KEEPFRAG) {
2757                 if (fin->fin_flx & FI_FRAG) {
2758                         if (ipf_frag_new(softc, fin, pass) == -1) {
2759                                 LBUMP(ipf_stats[out].fr_bnfr);
2760                         } else {
2761                                 LBUMP(ipf_stats[out].fr_nfr);
2762                         }
2763                 } else {
2764                         LBUMP(ipf_stats[out].fr_cfr);
2765                 }
2766         }
2767
2768         fr = fin->fin_fr;
2769         *passp = pass;
2770
2771         return fr;
2772 }
2773
2774
2775 /* ------------------------------------------------------------------------ */
2776 /* Function:    ipf_check                                                   */
2777 /* Returns:     int -  0 == packet allowed through,                         */
2778 /*              User space:                                                 */
2779 /*                    -1 == packet blocked                                  */
2780 /*                     1 == packet not matched                              */
2781 /*                    -2 == requires authentication                         */
2782 /*              Kernel:                                                     */
2783 /*                   > 0 == filter error # for packet                       */
2784 /* Parameters: ctx(I)  - pointer to the instance context                    */
2785 /*             ip(I)   - pointer to start of IPv4/6 packet                  */
2786 /*             hlen(I) - length of header                                   */
2787 /*             ifp(I)  - pointer to interface this packet is on             */
2788 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2789 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2790 /*                       IP packet.                                         */
2791 /* Solaris:                                                                 */
2792 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2793 /*                       interface & direction.                             */
2794 /*                                                                          */
2795 /* ipf_check() is the master function for all IPFilter packet processing.   */
2796 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2797 /* authorisation (or pre-authorisation), presence of related state info.,   */
2798 /* generating log entries, IP packet accounting, routing of packets as      */
2799 /* directed by firewall rules and of course whether or not to allow the     */
2800 /* packet to be further processed by the kernel.                            */
2801 /*                                                                          */
2802 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2803 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2804 /* by "mp" changed to a new buffer.                                         */
2805 /* ------------------------------------------------------------------------ */
2806 int
2807 ipf_check(ctx, ip, hlen, ifp, out
2808 #if defined(_KERNEL) && defined(MENTAT)
2809         , qif, mp)
2810         void *qif;
2811 #else
2812         , mp)
2813 #endif
2814         mb_t **mp;
2815         ip_t *ip;
2816         int hlen;
2817         struct ifnet *ifp;
2818         int out;
2819         void *ctx;
2820 {
2821         /*
2822          * The above really sucks, but short of writing a diff
2823          */
2824         ipf_main_softc_t *softc = ctx;
2825         fr_info_t frinfo;
2826         fr_info_t *fin = &frinfo;
2827         u_32_t pass = softc->ipf_pass;
2828         frentry_t *fr = NULL;
2829         int v = IP_V(ip);
2830         mb_t *mc = NULL;
2831         mb_t *m;
2832         /*
2833          * The first part of ipf_check() deals with making sure that what goes
2834          * into the filtering engine makes some sense.  Information about the
2835          * the packet is distilled, collected into a fr_info_t structure and
2836          * the an attempt to ensure the buffer the packet is in is big enough
2837          * to hold all the required packet headers.
2838          */
2839 #ifdef  _KERNEL
2840 # ifdef MENTAT
2841         qpktinfo_t *qpi = qif;
2842
2843 #  ifdef __sparc
2844         if ((u_int)ip & 0x3)
2845                 return 2;
2846 #  endif
2847 # else
2848         SPL_INT(s);
2849 # endif
2850
2851         if (softc->ipf_running <= 0) {
2852                 return 0;
2853         }
2854
2855         bzero((char *)fin, sizeof(*fin));
2856
2857 # ifdef MENTAT
2858         if (qpi->qpi_flags & QF_BROADCAST)
2859                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2860         if (qpi->qpi_flags & QF_MULTICAST)
2861                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2862         m = qpi->qpi_m;
2863         fin->fin_qfm = m;
2864         fin->fin_qpi = qpi;
2865 # else /* MENTAT */
2866
2867         m = *mp;
2868
2869 #  if defined(M_MCAST)
2870         if ((m->m_flags & M_MCAST) != 0)
2871                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2872 #  endif
2873 #  if defined(M_MLOOP)
2874         if ((m->m_flags & M_MLOOP) != 0)
2875                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2876 #  endif
2877 #  if defined(M_BCAST)
2878         if ((m->m_flags & M_BCAST) != 0)
2879                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2880 #  endif
2881 #  ifdef M_CANFASTFWD
2882         /*
2883          * XXX For now, IP Filter and fast-forwarding of cached flows
2884          * XXX are mutually exclusive.  Eventually, IP Filter should
2885          * XXX get a "can-fast-forward" filter rule.
2886          */
2887         m->m_flags &= ~M_CANFASTFWD;
2888 #  endif /* M_CANFASTFWD */
2889 #  if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD_version)
2890         /*
2891          * disable delayed checksums.
2892          */
2893         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2894                 in_delayed_cksum(m);
2895                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2896         }
2897 #  endif /* CSUM_DELAY_DATA */
2898 # endif /* MENTAT */
2899 #else
2900         bzero((char *)fin, sizeof(*fin));
2901         m = *mp;
2902 # if defined(M_MCAST)
2903         if ((m->m_flags & M_MCAST) != 0)
2904                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2905 # endif
2906 # if defined(M_MLOOP)
2907         if ((m->m_flags & M_MLOOP) != 0)
2908                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2909 # endif
2910 # if defined(M_BCAST)
2911         if ((m->m_flags & M_BCAST) != 0)
2912                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2913 # endif
2914 #endif /* _KERNEL */
2915
2916         fin->fin_v = v;
2917         fin->fin_m = m;
2918         fin->fin_ip = ip;
2919         fin->fin_mp = mp;
2920         fin->fin_out = out;
2921         fin->fin_ifp = ifp;
2922         fin->fin_error = ENETUNREACH;
2923         fin->fin_hlen = (u_short)hlen;
2924         fin->fin_dp = (char *)ip + hlen;
2925         fin->fin_main_soft = softc;
2926
2927         fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2928
2929         SPL_NET(s);
2930
2931 #ifdef  USE_INET6
2932         if (v == 6) {
2933                 LBUMP(ipf_stats[out].fr_ipv6);
2934                 /*
2935                  * Jumbo grams are quite likely too big for internal buffer
2936                  * structures to handle comfortably, for now, so just drop
2937                  * them.
2938                  */
2939                 if (((ip6_t *)ip)->ip6_plen == 0) {
2940                         DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2941                         pass = FR_BLOCK|FR_NOMATCH;
2942                         fin->fin_reason = FRB_JUMBO;
2943                         goto finished;
2944                 }
2945                 fin->fin_family = AF_INET6;
2946         } else
2947 #endif
2948         {
2949                 fin->fin_family = AF_INET;
2950         }
2951
2952         if (ipf_makefrip(hlen, ip, fin) == -1) {
2953                 DT1(frb_makefrip, fr_info_t *, fin);
2954                 pass = FR_BLOCK|FR_NOMATCH;
2955                 fin->fin_reason = FRB_MAKEFRIP;
2956                 goto finished;
2957         }
2958
2959         /*
2960          * For at least IPv6 packets, if a m_pullup() fails then this pointer
2961          * becomes NULL and so we have no packet to free.
2962          */
2963         if (*fin->fin_mp == NULL)
2964                 goto finished;
2965
2966         if (!out) {
2967                 if (v == 4) {
2968                         if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2969                                 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2970                                 fin->fin_flx |= FI_BADSRC;
2971                         }
2972                         if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2973                                 LBUMPD(ipf_stats[0], fr_v4_badttl);
2974                                 fin->fin_flx |= FI_LOWTTL;
2975                         }
2976                 }
2977 #ifdef USE_INET6
2978                 else  if (v == 6) {
2979                         if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2980                                 LBUMPD(ipf_stats[0], fr_v6_badttl);
2981                                 fin->fin_flx |= FI_LOWTTL;
2982                         }
2983                 }
2984 #endif
2985         }
2986
2987         if (fin->fin_flx & FI_SHORT) {
2988                 LBUMPD(ipf_stats[out], fr_short);
2989         }
2990
2991         READ_ENTER(&softc->ipf_mutex);
2992
2993         if (!out) {
2994                 switch (fin->fin_v)
2995                 {
2996                 case 4 :
2997                         if (ipf_nat_checkin(fin, &pass) == -1) {
2998                                 goto filterdone;
2999                         }
3000                         break;
3001 #ifdef USE_INET6
3002                 case 6 :
3003                         if (ipf_nat6_checkin(fin, &pass) == -1) {
3004                                 goto filterdone;
3005                         }
3006                         break;
3007 #endif
3008                 default :
3009                         break;
3010                 }
3011         }
3012         /*
3013          * Check auth now.
3014          * If a packet is found in the auth table, then skip checking
3015          * the access lists for permission but we do need to consider
3016          * the result as if it were from the ACL's.  In addition, being
3017          * found in the auth table means it has been seen before, so do
3018          * not pass it through accounting (again), lest it be counted twice.
3019          */
3020         fr = ipf_auth_check(fin, &pass);
3021         if (!out && (fr == NULL))
3022                 (void) ipf_acctpkt(fin, NULL);
3023
3024         if (fr == NULL) {
3025                 if ((fin->fin_flx & FI_FRAG) != 0)
3026                         fr = ipf_frag_known(fin, &pass);
3027
3028                 if (fr == NULL)
3029                         fr = ipf_state_check(fin, &pass);
3030         }
3031
3032         if ((pass & FR_NOMATCH) || (fr == NULL))
3033                 fr = ipf_firewall(fin, &pass);
3034
3035         /*
3036          * If we've asked to track state for this packet, set it up.
3037          * Here rather than ipf_firewall because ipf_checkauth may decide
3038          * to return a packet for "keep state"
3039          */
3040         if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3041             !(fin->fin_flx & FI_STATE)) {
3042                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3043                         LBUMP(ipf_stats[out].fr_ads);
3044                 } else {
3045                         LBUMP(ipf_stats[out].fr_bads);
3046                         if (FR_ISPASS(pass)) {
3047                                 DT(frb_stateadd);
3048                                 pass &= ~FR_CMDMASK;
3049                                 pass |= FR_BLOCK;
3050                                 fin->fin_reason = FRB_STATEADD;
3051                         }
3052                 }
3053         }
3054
3055         fin->fin_fr = fr;
3056         if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3057                 fin->fin_dif = &fr->fr_dif;
3058                 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3059         }
3060
3061         /*
3062          * Only count/translate packets which will be passed on, out the
3063          * interface.
3064          */
3065         if (out && FR_ISPASS(pass)) {
3066                 (void) ipf_acctpkt(fin, NULL);
3067
3068                 switch (fin->fin_v)
3069                 {
3070                 case 4 :
3071                         if (ipf_nat_checkout(fin, &pass) == -1) {
3072                                 ;
3073                         } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3074                                 if (ipf_updateipid(fin) == -1) {
3075                                         DT(frb_updateipid);
3076                                         LBUMP(ipf_stats[1].fr_ipud);
3077                                         pass &= ~FR_CMDMASK;
3078                                         pass |= FR_BLOCK;
3079                                         fin->fin_reason = FRB_UPDATEIPID;
3080                                 } else {
3081                                         LBUMP(ipf_stats[0].fr_ipud);
3082                                 }
3083                         }
3084                         break;
3085 #ifdef USE_INET6
3086                 case 6 :
3087                         (void) ipf_nat6_checkout(fin, &pass);
3088                         break;
3089 #endif
3090                 default :
3091                         break;
3092                 }
3093         }
3094
3095 filterdone:
3096 #ifdef  IPFILTER_LOG
3097         if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3098                 (void) ipf_dolog(fin, &pass);
3099         }
3100 #endif
3101
3102         /*
3103          * The FI_STATE flag is cleared here so that calling ipf_state_check
3104          * will work when called from inside of fr_fastroute.  Although
3105          * there is a similar flag, FI_NATED, for NAT, it does have the same
3106          * impact on code execution.
3107          */
3108         fin->fin_flx &= ~FI_STATE;
3109
3110 #if defined(FASTROUTE_RECURSION)
3111         /*
3112          * Up the reference on fr_lock and exit ipf_mutex. The generation of
3113          * a packet below can sometimes cause a recursive call into IPFilter.
3114          * On those platforms where that does happen, we need to hang onto
3115          * the filter rule just in case someone decides to remove or flush it
3116          * in the meantime.
3117          */
3118         if (fr != NULL) {
3119                 MUTEX_ENTER(&fr->fr_lock);
3120                 fr->fr_ref++;
3121                 MUTEX_EXIT(&fr->fr_lock);
3122         }
3123
3124         RWLOCK_EXIT(&softc->ipf_mutex);
3125 #endif
3126
3127         if ((pass & FR_RETMASK) != 0) {
3128                 /*
3129                  * Should we return an ICMP packet to indicate error
3130                  * status passing through the packet filter ?
3131                  * WARNING: ICMP error packets AND TCP RST packets should
3132                  * ONLY be sent in repsonse to incoming packets.  Sending
3133                  * them in response to outbound packets can result in a
3134                  * panic on some operating systems.
3135                  */
3136                 if (!out) {
3137                         if (pass & FR_RETICMP) {
3138                                 int dst;
3139
3140                                 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3141                                         dst = 1;
3142                                 else
3143                                         dst = 0;
3144                                 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3145                                                          dst);
3146                                 LBUMP(ipf_stats[0].fr_ret);
3147                         } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3148                                    !(fin->fin_flx & FI_SHORT)) {
3149                                 if (((fin->fin_flx & FI_OOW) != 0) ||
3150                                     (ipf_send_reset(fin) == 0)) {
3151                                         LBUMP(ipf_stats[1].fr_ret);
3152                                 }
3153                         }
3154
3155                         /*
3156                          * When using return-* with auth rules, the auth code
3157                          * takes over disposing of this packet.
3158                          */
3159                         if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3160                                 DT1(frb_authcapture, fr_info_t *, fin);
3161                                 fin->fin_m = *fin->fin_mp = NULL;
3162                                 fin->fin_reason = FRB_AUTHCAPTURE;
3163                                 m = NULL;
3164                         }
3165                 } else {
3166                         if (pass & FR_RETRST) {
3167                                 fin->fin_error = ECONNRESET;
3168                         }
3169                 }
3170         }
3171
3172         /*
3173          * After the above so that ICMP unreachables and TCP RSTs get
3174          * created properly.
3175          */
3176         if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3177                 ipf_nat_uncreate(fin);
3178
3179         /*
3180          * If we didn't drop off the bottom of the list of rules (and thus
3181          * the 'current' rule fr is not NULL), then we may have some extra
3182          * instructions about what to do with a packet.
3183          * Once we're finished return to our caller, freeing the packet if
3184          * we are dropping it.
3185          */
3186         if (fr != NULL) {
3187                 frdest_t *fdp;
3188
3189                 /*
3190                  * Generate a duplicated packet first because ipf_fastroute
3191                  * can lead to fin_m being free'd... not good.
3192                  */
3193                 fdp = fin->fin_dif;
3194                 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3195                     (fdp->fd_ptr != (void *)-1)) {
3196                         mc = M_COPY(fin->fin_m);
3197                         if (mc != NULL)
3198                                 ipf_fastroute(mc, &mc, fin, fdp);
3199                 }
3200
3201                 fdp = fin->fin_tif;
3202                 if (!out && (pass & FR_FASTROUTE)) {
3203                         /*
3204                          * For fastroute rule, no destination interface defined
3205                          * so pass NULL as the frdest_t parameter
3206                          */
3207                         (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3208                         m = *mp = NULL;
3209                 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3210                            (fdp->fd_ptr != (struct ifnet *)-1)) {
3211                         /* this is for to rules: */
3212                         ipf_fastroute(fin->fin_m, mp, fin, fdp);
3213                         m = *mp = NULL;
3214                 }
3215
3216 #if defined(FASTROUTE_RECURSION)
3217                 (void) ipf_derefrule(softc, &fr);
3218 #endif
3219         }
3220 #if !defined(FASTROUTE_RECURSION)
3221         RWLOCK_EXIT(&softc->ipf_mutex);
3222 #endif
3223
3224 finished:
3225         if (!FR_ISPASS(pass)) {
3226                 LBUMP(ipf_stats[out].fr_block);
3227                 if (*mp != NULL) {
3228 #ifdef _KERNEL
3229                         FREE_MB_T(*mp);
3230 #endif
3231                         m = *mp = NULL;
3232                 }
3233         } else {
3234                 LBUMP(ipf_stats[out].fr_pass);
3235         }
3236
3237         SPL_X(s);
3238
3239 #ifdef _KERNEL
3240         if (FR_ISPASS(pass))
3241                 return 0;
3242         LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3243         return fin->fin_error;
3244 #else /* _KERNEL */
3245         if (*mp != NULL)
3246                 (*mp)->mb_ifp = fin->fin_ifp;
3247         blockreason = fin->fin_reason;
3248         FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3249         /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3250                 if ((pass & FR_NOMATCH) != 0)
3251                         return 1;
3252
3253         if ((pass & FR_RETMASK) != 0)
3254                 switch (pass & FR_RETMASK)
3255                 {
3256                 case FR_RETRST :
3257                         return 3;
3258                 case FR_RETICMP :
3259                         return 4;
3260                 case FR_FAKEICMP :
3261                         return 5;
3262                 }
3263
3264         switch (pass & FR_CMDMASK)
3265         {
3266         case FR_PASS :
3267                 return 0;
3268         case FR_BLOCK :
3269                 return -1;
3270         case FR_AUTH :
3271                 return -2;
3272         case FR_ACCOUNT :
3273                 return -3;
3274         case FR_PREAUTH :
3275                 return -4;
3276         }
3277         return 2;
3278 #endif /* _KERNEL */
3279 }
3280
3281
3282 #ifdef  IPFILTER_LOG
3283 /* ------------------------------------------------------------------------ */
3284 /* Function:    ipf_dolog                                                   */
3285 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3286 /* Parameters:  fin(I) - pointer to packet information                      */
3287 /*              passp(IO) - pointer to current/new filter decision (unused) */
3288 /*                                                                          */
3289 /* Checks flags set to see how a packet should be logged, if it is to be    */
3290 /* logged.  Adjust statistics based on its success or not.                  */
3291 /* ------------------------------------------------------------------------ */
3292 frentry_t *
3293 ipf_dolog(fin, passp)
3294         fr_info_t *fin;
3295         u_32_t *passp;
3296 {
3297         ipf_main_softc_t *softc = fin->fin_main_soft;
3298         u_32_t pass;
3299         int out;
3300
3301         out = fin->fin_out;
3302         pass = *passp;
3303
3304         if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3305                 pass |= FF_LOGNOMATCH;
3306                 LBUMPD(ipf_stats[out], fr_npkl);
3307                 goto logit;
3308
3309         } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3310             (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3311                 if ((pass & FR_LOGMASK) != FR_LOGP)
3312                         pass |= FF_LOGPASS;
3313                 LBUMPD(ipf_stats[out], fr_ppkl);
3314                 goto logit;
3315
3316         } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3317                    (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3318                 if ((pass & FR_LOGMASK) != FR_LOGB)
3319                         pass |= FF_LOGBLOCK;
3320                 LBUMPD(ipf_stats[out], fr_bpkl);
3321
3322 logit:
3323                 if (ipf_log_pkt(fin, pass) == -1) {
3324                         /*
3325                          * If the "or-block" option has been used then
3326                          * block the packet if we failed to log it.
3327                          */
3328                         if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3329                                 DT1(frb_logfail2, u_int, pass);
3330                                 pass &= ~FR_CMDMASK;
3331                                 pass |= FR_BLOCK;
3332                                 fin->fin_reason = FRB_LOGFAIL2;
3333                         }
3334                 }
3335                 *passp = pass;
3336         }
3337
3338         return fin->fin_fr;
3339 }
3340 #endif /* IPFILTER_LOG */
3341
3342
3343 /* ------------------------------------------------------------------------ */
3344 /* Function:    ipf_cksum                                                   */
3345 /* Returns:     u_short - IP header checksum                                */
3346 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3347 /*              len(I)  - length of buffer in bytes                         */
3348 /*                                                                          */
3349 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3350 /*                                                                          */
3351 /* N.B.: addr should be 16bit aligned.                                      */
3352 /* ------------------------------------------------------------------------ */
3353 u_short
3354 ipf_cksum(addr, len)
3355         u_short *addr;
3356         int len;
3357 {
3358         u_32_t sum = 0;
3359
3360         for (sum = 0; len > 1; len -= 2)
3361                 sum += *addr++;
3362
3363         /* mop up an odd byte, if necessary */
3364         if (len == 1)
3365                 sum += *(u_char *)addr;
3366
3367         /*
3368          * add back carry outs from top 16 bits to low 16 bits
3369          */
3370         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
3371         sum += (sum >> 16);                     /* add carry */
3372         return (u_short)(~sum);
3373 }
3374
3375
3376 /* ------------------------------------------------------------------------ */
3377 /* Function:    fr_cksum                                                    */
3378 /* Returns:     u_short - layer 4 checksum                                  */
3379 /* Parameters:  fin(I)     - pointer to packet information                  */
3380 /*              ip(I)      - pointer to IP header                           */
3381 /*              l4proto(I) - protocol to caclulate checksum for             */
3382 /*              l4hdr(I)   - pointer to layer 4 header                      */
3383 /*                                                                          */
3384 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3385 /* in the IP header "ip" to seed it.                                        */
3386 /*                                                                          */
3387 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3388 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3389 /* odd sizes.                                                               */
3390 /*                                                                          */
3391 /* Expects ip_len and ip_off to be in network byte order when called.       */
3392 /* ------------------------------------------------------------------------ */
3393 u_short
3394 fr_cksum(fin, ip, l4proto, l4hdr)
3395         fr_info_t *fin;
3396         ip_t *ip;
3397         int l4proto;
3398         void *l4hdr;
3399 {
3400         u_short *sp, slen, sumsave, *csump;
3401         u_int sum, sum2;
3402         int hlen;
3403         int off;
3404 #ifdef  USE_INET6
3405         ip6_t *ip6;
3406 #endif
3407
3408         csump = NULL;
3409         sumsave = 0;
3410         sp = NULL;
3411         slen = 0;
3412         hlen = 0;
3413         sum = 0;
3414
3415         sum = htons((u_short)l4proto);
3416         /*
3417          * Add up IP Header portion
3418          */
3419 #ifdef  USE_INET6
3420         if (IP_V(ip) == 4) {
3421 #endif
3422                 hlen = IP_HL(ip) << 2;
3423                 off = hlen;
3424                 sp = (u_short *)&ip->ip_src;
3425                 sum += *sp++;   /* ip_src */
3426                 sum += *sp++;
3427                 sum += *sp++;   /* ip_dst */
3428                 sum += *sp++;
3429                 slen = fin->fin_plen - off;
3430                 sum += htons(slen);
3431 #ifdef  USE_INET6
3432         } else if (IP_V(ip) == 6) {
3433                 mb_t *m;
3434
3435                 m = fin->fin_m;
3436                 ip6 = (ip6_t *)ip;
3437                 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3438                 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3439                 return(ipf_pcksum6(fin, ip6, off, len));
3440         } else {
3441                 return 0xffff;
3442         }
3443 #endif
3444
3445         switch (l4proto)
3446         {
3447         case IPPROTO_UDP :
3448                 csump = &((udphdr_t *)l4hdr)->uh_sum;
3449                 break;
3450
3451         case IPPROTO_TCP :
3452                 csump = &((tcphdr_t *)l4hdr)->th_sum;
3453                 break;
3454         case IPPROTO_ICMP :
3455                 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3456                 sum = 0;        /* Pseudo-checksum is not included */
3457                 break;
3458 #ifdef USE_INET6
3459         case IPPROTO_ICMPV6 :
3460                 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3461                 break;
3462 #endif
3463         default :
3464                 break;
3465         }
3466
3467         if (csump != NULL) {
3468                 sumsave = *csump;
3469                 *csump = 0;
3470         }
3471
3472         sum2 = ipf_pcksum(fin, off, sum);
3473         if (csump != NULL)
3474                 *csump = sumsave;
3475         return sum2;
3476 }
3477
3478
3479 /* ------------------------------------------------------------------------ */
3480 /* Function:    ipf_findgroup                                               */
3481 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3482 /* Parameters:  softc(I) - pointer to soft context main structure           */
3483 /*              group(I) - group name to search for                         */
3484 /*              unit(I)  - device to which this group belongs               */
3485 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3486 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3487 /*                         to where to add the next (last) group or where   */
3488 /*                         to delete group from.                            */
3489 /*                                                                          */
3490 /* Search amongst the defined groups for a particular group number.         */
3491 /* ------------------------------------------------------------------------ */
3492 frgroup_t *
3493 ipf_findgroup(softc, group, unit, set, fgpp)
3494         ipf_main_softc_t *softc;
3495         char *group;
3496         minor_t unit;
3497         int set;
3498         frgroup_t ***fgpp;
3499 {
3500         frgroup_t *fg, **fgp;
3501
3502         /*
3503          * Which list of groups to search in is dependent on which list of
3504          * rules are being operated on.
3505          */
3506         fgp = &softc->ipf_groups[unit][set];
3507
3508         while ((fg = *fgp) != NULL) {
3509                 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3510                         break;
3511                 else
3512                         fgp = &fg->fg_next;
3513         }
3514         if (fgpp != NULL)
3515                 *fgpp = fgp;
3516         return fg;
3517 }
3518
3519
3520 /* ------------------------------------------------------------------------ */
3521 /* Function:    ipf_group_add                                               */
3522 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3523 /*                            != NULL == pointer to the group               */
3524 /* Parameters:  softc(I) - pointer to soft context main structure           */
3525 /*              num(I)   - group number to add                              */
3526 /*              head(I)  - rule pointer that is using this as the head      */
3527 /*              flags(I) - rule flags which describe the type of rule it is */
3528 /*              unit(I)  - device to which this group will belong to        */
3529 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3530 /* Write Locks: ipf_mutex                                                   */
3531 /*                                                                          */
3532 /* Add a new group head, or if it already exists, increase the reference    */
3533 /* count to it.                                                             */
3534 /* ------------------------------------------------------------------------ */
3535 frgroup_t *
3536 ipf_group_add(softc, group, head, flags, unit, set)
3537         ipf_main_softc_t *softc;
3538         char *group;
3539         void *head;
3540         u_32_t flags;
3541         minor_t unit;
3542         int set;
3543 {
3544         frgroup_t *fg, **fgp;
3545         u_32_t gflags;
3546
3547         if (group == NULL)
3548                 return NULL;
3549
3550         if (unit == IPL_LOGIPF && *group == '\0')
3551                 return NULL;
3552
3553         fgp = NULL;
3554         gflags = flags & FR_INOUT;
3555
3556         fg = ipf_findgroup(softc, group, unit, set, &fgp);
3557         if (fg != NULL) {
3558                 if (fg->fg_head == NULL && head != NULL)
3559                         fg->fg_head = head;
3560                 if (fg->fg_flags == 0)
3561                         fg->fg_flags = gflags;
3562                 else if (gflags != fg->fg_flags)
3563                         return NULL;
3564                 fg->fg_ref++;
3565                 return fg;
3566         }
3567
3568         KMALLOC(fg, frgroup_t *);
3569         if (fg != NULL) {
3570                 fg->fg_head = head;
3571                 fg->fg_start = NULL;
3572                 fg->fg_next = *fgp;
3573                 bcopy(group, fg->fg_name, strlen(group) + 1);
3574                 fg->fg_flags = gflags;
3575                 fg->fg_ref = 1;
3576                 fg->fg_set = &softc->ipf_groups[unit][set];
3577                 *fgp = fg;
3578         }
3579         return fg;
3580 }
3581
3582
3583 /* ------------------------------------------------------------------------ */
3584 /* Function:    ipf_group_del                                               */
3585 /* Returns:     int      - number of rules deleted                          */
3586 /* Parameters:  softc(I) - pointer to soft context main structure           */
3587 /*              group(I) - group name to delete                             */
3588 /*              fr(I)    - filter rule from which group is referenced       */
3589 /* Write Locks: ipf_mutex                                                   */
3590 /*                                                                          */
3591 /* This function is called whenever a reference to a group is to be dropped */
3592 /* and thus its reference count needs to be lowered and the group free'd if */
3593 /* the reference count reaches zero. Passing in fr is really for the sole   */
3594 /* purpose of knowing when the head rule is being deleted.                  */
3595 /* ------------------------------------------------------------------------ */
3596 void
3597 ipf_group_del(softc, group, fr)
3598         ipf_main_softc_t *softc;
3599         frgroup_t *group;
3600         frentry_t *fr;
3601 {
3602
3603         if (group->fg_head == fr)
3604                 group->fg_head = NULL;
3605
3606         group->fg_ref--;
3607         if ((group->fg_ref == 0) && (group->fg_start == NULL))
3608                 ipf_group_free(group);
3609 }
3610
3611
3612 /* ------------------------------------------------------------------------ */
3613 /* Function:    ipf_group_free                                              */
3614 /* Returns:     Nil                                                         */
3615 /* Parameters:  group(I) - pointer to filter rule group                     */
3616 /*                                                                          */
3617 /* Remove the group from the list of groups and free it.                    */
3618 /* ------------------------------------------------------------------------ */
3619 static void
3620 ipf_group_free(group)
3621         frgroup_t *group;
3622 {
3623         frgroup_t **gp;
3624
3625         for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3626                 if (*gp == group) {
3627                         *gp = group->fg_next;
3628                         break;
3629                 }
3630         }
3631         KFREE(group);
3632 }
3633
3634
3635 /* ------------------------------------------------------------------------ */
3636 /* Function:    ipf_group_flush                                             */
3637 /* Returns:     int      - number of rules flush from group                 */
3638 /* Parameters:  softc(I) - pointer to soft context main structure           */
3639 /* Parameters:  group(I) - pointer to filter rule group                     */
3640 /*                                                                          */
3641 /* Remove all of the rules that currently are listed under the given group. */
3642 /* ------------------------------------------------------------------------ */
3643 static int
3644 ipf_group_flush(softc, group)
3645         ipf_main_softc_t *softc;
3646         frgroup_t *group;
3647 {
3648         int gone = 0;
3649
3650         (void) ipf_flushlist(softc, &gone, &group->fg_start);
3651
3652         return gone;
3653 }
3654
3655
3656 /* ------------------------------------------------------------------------ */
3657 /* Function:    ipf_getrulen                                                */
3658 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3659 /* Parameters:  softc(I) - pointer to soft context main structure           */
3660 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3661 /*              flags(I) - which set of rules to find the rule in           */
3662 /*              group(I) - group name                                       */
3663 /*              n(I)     - rule number to find                              */
3664 /*                                                                          */
3665 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3666 /* group # g doesn't exist or there are less than n rules in the group.     */
3667 /* ------------------------------------------------------------------------ */
3668 frentry_t *
3669 ipf_getrulen(softc, unit, group, n)
3670         ipf_main_softc_t *softc;
3671         int unit;
3672         char *group;
3673         u_32_t n;
3674 {
3675         frentry_t *fr;
3676         frgroup_t *fg;
3677
3678         fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3679         if (fg == NULL)
3680                 return NULL;
3681         for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3682                 ;
3683         if (n != 0)
3684                 return NULL;
3685         return fr;
3686 }
3687
3688
3689 /* ------------------------------------------------------------------------ */
3690 /* Function:    ipf_flushlist                                               */
3691 /* Returns:     int - >= 0 - number of flushed rules                        */
3692 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3693 /*              nfreedp(O) - pointer to int where flush count is stored     */
3694 /*              listp(I)   - pointer to list to flush pointer               */
3695 /* Write Locks: ipf_mutex                                                   */
3696 /*                                                                          */
3697 /* Recursively flush rules from the list, descending groups as they are     */
3698 /* encountered.  if a rule is the head of a group and it has lost all its   */
3699 /* group members, then also delete the group reference.  nfreedp is needed  */
3700 /* to store the accumulating count of rules removed, whereas the returned   */
3701 /* value is just the number removed from the current list.  The latter is   */
3702 /* needed to correctly adjust reference counts on rules that define groups. */
3703 /*                                                                          */
3704 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3705 /* ------------------------------------------------------------------------ */
3706 static int
3707 ipf_flushlist(softc, nfreedp, listp)
3708         ipf_main_softc_t *softc;
3709         int *nfreedp;
3710         frentry_t **listp;
3711 {
3712         int freed = 0;
3713         frentry_t *fp;
3714
3715         while ((fp = *listp) != NULL) {
3716                 if ((fp->fr_type & FR_T_BUILTIN) ||
3717                     !(fp->fr_flags & FR_COPIED)) {
3718                         listp = &fp->fr_next;
3719                         continue;
3720                 }
3721                 *listp = fp->fr_next;
3722                 if (fp->fr_next != NULL)
3723                         fp->fr_next->fr_pnext = fp->fr_pnext;
3724                 fp->fr_pnext = NULL;
3725
3726                 if (fp->fr_grphead != NULL) {
3727                         freed += ipf_group_flush(softc, fp->fr_grphead);
3728                         fp->fr_names[fp->fr_grhead] = '\0';
3729                 }
3730
3731                 if (fp->fr_icmpgrp != NULL) {
3732                         freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3733                         fp->fr_names[fp->fr_icmphead] = '\0';
3734                 }
3735
3736                 if (fp->fr_srctrack.ht_max_nodes)
3737                         ipf_rb_ht_flush(&fp->fr_srctrack);
3738
3739                 fp->fr_next = NULL;
3740
3741                 ASSERT(fp->fr_ref > 0);
3742                 if (ipf_derefrule(softc, &fp) == 0)
3743                         freed++;
3744         }
3745         *nfreedp += freed;
3746         return freed;
3747 }
3748
3749
3750 /* ------------------------------------------------------------------------ */
3751 /* Function:    ipf_flush                                                   */
3752 /* Returns:     int - >= 0 - number of flushed rules                        */
3753 /* Parameters:  softc(I) - pointer to soft context main structure           */
3754 /*              unit(I)  - device for which to flush rules                  */
3755 /*              flags(I) - which set of rules to flush                      */
3756 /*                                                                          */
3757 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3758 /* and IPv6) as defined by the value of flags.                              */
3759 /* ------------------------------------------------------------------------ */
3760 int
3761 ipf_flush(softc, unit, flags)
3762         ipf_main_softc_t *softc;
3763         minor_t unit;
3764         int flags;
3765 {
3766         int flushed = 0, set;
3767
3768         WRITE_ENTER(&softc->ipf_mutex);
3769
3770         set = softc->ipf_active;
3771         if ((flags & FR_INACTIVE) == FR_INACTIVE)
3772                 set = 1 - set;
3773
3774         if (flags & FR_OUTQUE) {
3775                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3776                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3777         }
3778         if (flags & FR_INQUE) {
3779                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3780                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3781         }
3782
3783         flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3784                                     flags & (FR_INQUE|FR_OUTQUE));
3785
3786         RWLOCK_EXIT(&softc->ipf_mutex);
3787
3788         if (unit == IPL_LOGIPF) {
3789                 int tmp;
3790
3791                 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3792                 if (tmp >= 0)
3793                         flushed += tmp;
3794         }
3795         return flushed;
3796 }
3797
3798
3799 /* ------------------------------------------------------------------------ */
3800 /* Function:    ipf_flush_groups                                            */
3801 /* Returns:     int - >= 0 - number of flushed rules                        */
3802 /* Parameters:  softc(I)  - soft context pointerto work with                */
3803 /*              grhead(I) - pointer to the start of the group list to flush */
3804 /*              flags(I)  - which set of rules to flush                     */
3805 /*                                                                          */
3806 /* Walk through all of the groups under the given group head and remove all */
3807 /* of those that match the flags passed in. The for loop here is bit more   */
3808 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3809 /* may end up removing not only the structure pointed to by "fg" but also   */
3810 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3811 /* removed from the group then it is necessary to start again.              */
3812 /* ------------------------------------------------------------------------ */
3813 static int
3814 ipf_flush_groups(softc, grhead, flags)
3815         ipf_main_softc_t *softc;
3816         frgroup_t **grhead;
3817         int flags;
3818 {
3819         frentry_t *fr, **frp;
3820         frgroup_t *fg, **fgp;
3821         int flushed = 0;
3822         int removed = 0;
3823
3824         for (fgp = grhead; (fg = *fgp) != NULL; ) {
3825                 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3826                         fg = fg->fg_next;
3827                 if (fg == NULL)
3828                         break;
3829                 removed = 0;
3830                 frp = &fg->fg_start;
3831                 while ((removed == 0) && ((fr = *frp) != NULL)) {
3832                         if ((fr->fr_flags & flags) == 0) {
3833                                 frp = &fr->fr_next;
3834                         } else {
3835                                 if (fr->fr_next != NULL)
3836                                         fr->fr_next->fr_pnext = fr->fr_pnext;
3837                                 *frp = fr->fr_next;
3838                                 fr->fr_pnext = NULL;
3839                                 fr->fr_next = NULL;
3840                                 (void) ipf_derefrule(softc, &fr);
3841                                 flushed++;
3842                                 removed++;
3843                         }
3844                 }
3845                 if (removed == 0)
3846                         fgp = &fg->fg_next;
3847         }
3848         return flushed;
3849 }
3850
3851
3852 /* ------------------------------------------------------------------------ */
3853 /* Function:    memstr                                                      */
3854 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3855 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3856 /*              dst(I)  - pointer to byte sequence to search                */
3857 /*              slen(I) - match length                                      */
3858 /*              dlen(I) - length available to search in                     */
3859 /*                                                                          */
3860 /* Search dst for a sequence of bytes matching those at src and extend for  */
3861 /* slen bytes.                                                              */
3862 /* ------------------------------------------------------------------------ */
3863 char *
3864 memstr(src, dst, slen, dlen)
3865         const char *src;
3866         char *dst;
3867         size_t slen, dlen;
3868 {
3869         char *s = NULL;
3870
3871         while (dlen >= slen) {
3872                 if (bcmp(src, dst, slen) == 0) {
3873                         s = dst;
3874                         break;
3875                 }
3876                 dst++;
3877                 dlen--;
3878         }
3879         return s;
3880 }
3881 /* ------------------------------------------------------------------------ */
3882 /* Function:    ipf_fixskip                                                 */
3883 /* Returns:     Nil                                                         */
3884 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3885 /*              rp(I)        - rule added/removed with skip in it.          */
3886 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3887 /*                             depending on whether a rule was just added   */
3888 /*                             or removed.                                  */
3889 /*                                                                          */
3890 /* Adjust all the rules in a list which would have skip'd past the position */
3891 /* where we are inserting to skip to the right place given the change.      */
3892 /* ------------------------------------------------------------------------ */
3893 void
3894 ipf_fixskip(listp, rp, addremove)
3895         frentry_t **listp, *rp;
3896         int addremove;
3897 {
3898         int rules, rn;
3899         frentry_t *fp;
3900
3901         rules = 0;
3902         for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3903                 rules++;
3904
3905         if (fp == NULL)
3906                 return;
3907
3908         for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3909                 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3910                         fp->fr_arg += addremove;
3911 }
3912
3913
3914 #ifdef  _KERNEL
3915 /* ------------------------------------------------------------------------ */
3916 /* Function:    count4bits                                                  */
3917 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3918 /* Parameters:  ip(I) - 32bit IP address                                    */
3919 /*                                                                          */
3920 /* IPv4 ONLY                                                                */
3921 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3922 /* consecutive 1's is different to that passed, return -1, else return #    */
3923 /* of bits.                                                                 */
3924 /* ------------------------------------------------------------------------ */
3925 int
3926 count4bits(ip)
3927         u_32_t  ip;
3928 {
3929         u_32_t  ipn;
3930         int     cnt = 0, i, j;
3931
3932         ip = ipn = ntohl(ip);
3933         for (i = 32; i; i--, ipn *= 2)
3934                 if (ipn & 0x80000000)
3935                         cnt++;
3936                 else
3937                         break;
3938         ipn = 0;
3939         for (i = 32, j = cnt; i; i--, j--) {
3940                 ipn *= 2;
3941                 if (j > 0)
3942                         ipn++;
3943         }
3944         if (ipn == ip)
3945                 return cnt;
3946         return -1;
3947 }
3948
3949
3950 /* ------------------------------------------------------------------------ */
3951 /* Function:    count6bits                                                  */
3952 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3953 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
3954 /*                                                                          */
3955 /* IPv6 ONLY                                                                */
3956 /* count consecutive 1's in bit mask.                                       */
3957 /* ------------------------------------------------------------------------ */
3958 # ifdef USE_INET6
3959 int
3960 count6bits(msk)
3961         u_32_t *msk;
3962 {
3963         int i = 0, k;
3964         u_32_t j;
3965
3966         for (k = 3; k >= 0; k--)
3967                 if (msk[k] == 0xffffffff)
3968                         i += 32;
3969                 else {
3970                         for (j = msk[k]; j; j <<= 1)
3971                                 if (j & 0x80000000)
3972                                         i++;
3973                 }
3974         return i;
3975 }
3976 # endif
3977 #endif /* _KERNEL */
3978
3979
3980 /* ------------------------------------------------------------------------ */
3981 /* Function:    ipf_synclist                                                */
3982 /* Returns:     int    - 0 = no failures, else indication of first failure  */
3983 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
3984 /*              ifp(I) - interface pointer for limiting sync lookups        */
3985 /* Write Locks: ipf_mutex                                                   */
3986 /*                                                                          */
3987 /* Walk through a list of filter rules and resolve any interface names into */
3988 /* pointers.  Where dynamic addresses are used, also update the IP address  */
3989 /* used in the rule.  The interface pointer is used to limit the lookups to */
3990 /* a specific set of matching names if it is non-NULL.                      */
3991 /* Errors can occur when resolving the destination name of to/dup-to fields */
3992 /* when the name points to a pool and that pool doest not exist. If this    */
3993 /* does happen then it is necessary to check if there are any lookup refs   */
3994 /* that need to be dropped before returning with an error.                  */
3995 /* ------------------------------------------------------------------------ */
3996 static int
3997 ipf_synclist(softc, fr, ifp)
3998         ipf_main_softc_t *softc;
3999         frentry_t *fr;
4000         void *ifp;
4001 {
4002         frentry_t *frt, *start = fr;
4003         frdest_t *fdp;
4004         char *name;
4005         int error;
4006         void *ifa;
4007         int v, i;
4008
4009         error = 0;
4010
4011         for (; fr; fr = fr->fr_next) {
4012                 if (fr->fr_family == AF_INET)
4013                         v = 4;
4014                 else if (fr->fr_family == AF_INET6)
4015                         v = 6;
4016                 else
4017                         v = 0;
4018
4019                 /*
4020                  * Lookup all the interface names that are part of the rule.
4021                  */
4022                 for (i = 0; i < 4; i++) {
4023                         if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4024                                 continue;
4025                         if (fr->fr_ifnames[i] == -1)
4026                                 continue;
4027                         name = FR_NAME(fr, fr_ifnames[i]);
4028                         fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4029                 }
4030
4031                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4032                         if (fr->fr_satype != FRI_NORMAL &&
4033                             fr->fr_satype != FRI_LOOKUP) {
4034                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4035                                                      fr->fr_sifpidx, v);
4036                                 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4037                                             &fr->fr_src6, &fr->fr_smsk6);
4038                         }
4039                         if (fr->fr_datype != FRI_NORMAL &&
4040                             fr->fr_datype != FRI_LOOKUP) {
4041                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4042                                                      fr->fr_sifpidx, v);
4043                                 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4044                                             &fr->fr_dst6, &fr->fr_dmsk6);
4045                         }
4046                 }
4047
4048                 fdp = &fr->fr_tifs[0];
4049                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4050                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4051                         if (error != 0)
4052                                 goto unwind;
4053                 }
4054
4055                 fdp = &fr->fr_tifs[1];
4056                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4057                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4058                         if (error != 0)
4059                                 goto unwind;
4060                 }
4061
4062                 fdp = &fr->fr_dif;
4063                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4064                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4065                         if (error != 0)
4066                                 goto unwind;
4067                 }
4068
4069                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4070                     (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4071                         fr->fr_srcptr = ipf_lookup_res_num(softc,
4072                                                            fr->fr_srctype,
4073                                                            IPL_LOGIPF,
4074                                                            fr->fr_srcnum,
4075                                                            &fr->fr_srcfunc);
4076                 }
4077                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4078                     (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4079                         fr->fr_dstptr = ipf_lookup_res_num(softc,
4080                                                            fr->fr_dsttype,
4081                                                            IPL_LOGIPF,
4082                                                            fr->fr_dstnum,
4083                                                            &fr->fr_dstfunc);
4084                 }
4085         }
4086         return 0;
4087
4088 unwind:
4089         for (frt = start; frt != fr; fr = fr->fr_next) {
4090                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4091                     (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4092                                 ipf_lookup_deref(softc, frt->fr_srctype,
4093                                                  frt->fr_srcptr);
4094                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4095                     (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4096                                 ipf_lookup_deref(softc, frt->fr_dsttype,
4097                                                  frt->fr_dstptr);
4098         }
4099         return error;
4100 }
4101
4102
4103 /* ------------------------------------------------------------------------ */
4104 /* Function:    ipf_sync                                                    */
4105 /* Returns:     void                                                        */
4106 /* Parameters:  Nil                                                         */
4107 /*                                                                          */
4108 /* ipf_sync() is called when we suspect that the interface list or          */
4109 /* information about interfaces (like IP#) has changed.  Go through all     */
4110 /* filter rules, NAT entries and the state table and check if anything      */
4111 /* needs to be changed/updated.                                             */
4112 /* ------------------------------------------------------------------------ */
4113 int
4114 ipf_sync(softc, ifp)
4115         ipf_main_softc_t *softc;
4116         void *ifp;
4117 {
4118         int i;
4119
4120 # if !SOLARIS
4121         ipf_nat_sync(softc, ifp);
4122         ipf_state_sync(softc, ifp);
4123         ipf_lookup_sync(softc, ifp);
4124 # endif
4125
4126         WRITE_ENTER(&softc->ipf_mutex);
4127         (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4128         (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4129         (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4130         (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4131
4132         for (i = 0; i < IPL_LOGSIZE; i++) {
4133                 frgroup_t *g;
4134
4135                 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4136                         (void) ipf_synclist(softc, g->fg_start, ifp);
4137                 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4138                         (void) ipf_synclist(softc, g->fg_start, ifp);
4139         }
4140         RWLOCK_EXIT(&softc->ipf_mutex);
4141
4142         return 0;
4143 }
4144
4145
4146 /*
4147  * In the functions below, bcopy() is called because the pointer being
4148  * copied _from_ in this instance is a pointer to a char buf (which could
4149  * end up being unaligned) and on the kernel's local stack.
4150  */
4151 /* ------------------------------------------------------------------------ */
4152 /* Function:    copyinptr                                                   */
4153 /* Returns:     int - 0 = success, else failure                             */
4154 /* Parameters:  src(I)  - pointer to the source address                     */
4155 /*              dst(I)  - destination address                               */
4156 /*              size(I) - number of bytes to copy                           */
4157 /*                                                                          */
4158 /* Copy a block of data in from user space, given a pointer to the pointer  */
4159 /* to start copying from (src) and a pointer to where to store it (dst).    */
4160 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4161 /* ------------------------------------------------------------------------ */
4162 int
4163 copyinptr(softc, src, dst, size)
4164         ipf_main_softc_t *softc;
4165         void *src, *dst;
4166         size_t size;
4167 {
4168         caddr_t ca;
4169         int error;
4170
4171 # if SOLARIS
4172         error = COPYIN(src, &ca, sizeof(ca));
4173         if (error != 0)
4174                 return error;
4175 # else
4176         bcopy(src, (caddr_t)&ca, sizeof(ca));
4177 # endif
4178         error = COPYIN(ca, dst, size);
4179         if (error != 0) {
4180                 IPFERROR(3);
4181                 error = EFAULT;
4182         }
4183         return error;
4184 }
4185
4186
4187 /* ------------------------------------------------------------------------ */
4188 /* Function:    copyoutptr                                                  */
4189 /* Returns:     int - 0 = success, else failure                             */
4190 /* Parameters:  src(I)  - pointer to the source address                     */
4191 /*              dst(I)  - destination address                               */
4192 /*              size(I) - number of bytes to copy                           */
4193 /*                                                                          */
4194 /* Copy a block of data out to user space, given a pointer to the pointer   */
4195 /* to start copying from (src) and a pointer to where to store it (dst).    */
4196 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4197 /* ------------------------------------------------------------------------ */
4198 int
4199 copyoutptr(softc, src, dst, size)
4200         ipf_main_softc_t *softc;
4201         void *src, *dst;
4202         size_t size;
4203 {
4204         caddr_t ca;
4205         int error;
4206
4207         bcopy(dst, (caddr_t)&ca, sizeof(ca));
4208         error = COPYOUT(src, ca, size);
4209         if (error != 0) {
4210                 IPFERROR(4);
4211                 error = EFAULT;
4212         }
4213         return error;
4214 }
4215
4216
4217 /* ------------------------------------------------------------------------ */
4218 /* Function:    ipf_lock                                                    */
4219 /* Returns:     int      - 0 = success, else error                          */
4220 /* Parameters:  data(I)  - pointer to lock value to set                     */
4221 /*              lockp(O) - pointer to location to store old lock value      */
4222 /*                                                                          */
4223 /* Get the new value for the lock integer, set it and return the old value  */
4224 /* in *lockp.                                                               */
4225 /* ------------------------------------------------------------------------ */
4226 int
4227 ipf_lock(data, lockp)
4228         caddr_t data;
4229         int *lockp;
4230 {
4231         int arg, err;
4232
4233         err = BCOPYIN(data, &arg, sizeof(arg));
4234         if (err != 0)
4235                 return EFAULT;
4236         err = BCOPYOUT(lockp, data, sizeof(*lockp));
4237         if (err != 0)
4238                 return EFAULT;
4239         *lockp = arg;
4240         return 0;
4241 }
4242
4243
4244 /* ------------------------------------------------------------------------ */
4245 /* Function:    ipf_getstat                                                 */
4246 /* Returns:     Nil                                                         */
4247 /* Parameters:  softc(I) - pointer to soft context main structure           */
4248 /*              fiop(I)  - pointer to ipfilter stats structure              */
4249 /*              rev(I)   - version claim by program doing ioctl             */
4250 /*                                                                          */
4251 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4252 /* structure.                                                               */
4253 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4254 /* program is looking for. This ensure that validation of the version it    */
4255 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4256 /* allow older binaries to work but kernels without it will not.            */
4257 /* ------------------------------------------------------------------------ */
4258 /*ARGSUSED*/
4259 static void
4260 ipf_getstat(softc, fiop, rev)
4261         ipf_main_softc_t *softc;
4262         friostat_t *fiop;
4263         int rev;
4264 {
4265         int i;
4266
4267         bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4268               sizeof(ipf_statistics_t) * 2);
4269         fiop->f_locks[IPL_LOGSTATE] = -1;
4270         fiop->f_locks[IPL_LOGNAT] = -1;
4271         fiop->f_locks[IPL_LOGIPF] = -1;
4272         fiop->f_locks[IPL_LOGAUTH] = -1;
4273
4274         fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4275         fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4276         fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4277         fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4278         fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4279         fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4280         fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4281         fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4282
4283         fiop->f_ticks = softc->ipf_ticks;
4284         fiop->f_active = softc->ipf_active;
4285         fiop->f_froute[0] = softc->ipf_frouteok[0];
4286         fiop->f_froute[1] = softc->ipf_frouteok[1];
4287         fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4288         fiop->f_rb_node_max = softc->ipf_rb_node_max;
4289
4290         fiop->f_running = softc->ipf_running;
4291         for (i = 0; i < IPL_LOGSIZE; i++) {
4292                 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4293                 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4294         }
4295 #ifdef  IPFILTER_LOG
4296         fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4297         fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4298         fiop->f_logging = 1;
4299 #else
4300         fiop->f_log_ok = 0;
4301         fiop->f_log_fail = 0;
4302         fiop->f_logging = 0;
4303 #endif
4304         fiop->f_defpass = softc->ipf_pass;
4305         fiop->f_features = ipf_features;
4306
4307 #ifdef IPFILTER_COMPAT
4308         sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4309                 (rev / 1000000) % 100,
4310                 (rev / 10000) % 100,
4311                 (rev / 100) % 100);
4312 #else
4313         rev = rev;
4314         (void) strncpy(fiop->f_version, ipfilter_version,
4315                        sizeof(fiop->f_version));
4316 #endif
4317 }
4318
4319
4320 #ifdef  USE_INET6
4321 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4322         ICMP6_ECHO_REPLY,       /* 0: ICMP_ECHOREPLY */
4323         -1,                     /* 1: UNUSED */
4324         -1,                     /* 2: UNUSED */
4325         ICMP6_DST_UNREACH,      /* 3: ICMP_UNREACH */
4326         -1,                     /* 4: ICMP_SOURCEQUENCH */
4327         ND_REDIRECT,            /* 5: ICMP_REDIRECT */
4328         -1,                     /* 6: UNUSED */
4329         -1,                     /* 7: UNUSED */
4330         ICMP6_ECHO_REQUEST,     /* 8: ICMP_ECHO */
4331         -1,                     /* 9: UNUSED */
4332         -1,                     /* 10: UNUSED */
4333         ICMP6_TIME_EXCEEDED,    /* 11: ICMP_TIMXCEED */
4334         ICMP6_PARAM_PROB,       /* 12: ICMP_PARAMPROB */
4335         -1,                     /* 13: ICMP_TSTAMP */
4336         -1,                     /* 14: ICMP_TSTAMPREPLY */
4337         -1,                     /* 15: ICMP_IREQ */
4338         -1,                     /* 16: ICMP_IREQREPLY */
4339         -1,                     /* 17: ICMP_MASKREQ */
4340         -1,                     /* 18: ICMP_MASKREPLY */
4341 };
4342
4343
4344 int     icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4345         ICMP6_DST_UNREACH_ADDR,         /* 0: ICMP_UNREACH_NET */
4346         ICMP6_DST_UNREACH_ADDR,         /* 1: ICMP_UNREACH_HOST */
4347         -1,                             /* 2: ICMP_UNREACH_PROTOCOL */
4348         ICMP6_DST_UNREACH_NOPORT,       /* 3: ICMP_UNREACH_PORT */
4349         -1,                             /* 4: ICMP_UNREACH_NEEDFRAG */
4350         ICMP6_DST_UNREACH_NOTNEIGHBOR,  /* 5: ICMP_UNREACH_SRCFAIL */
4351         ICMP6_DST_UNREACH_ADDR,         /* 6: ICMP_UNREACH_NET_UNKNOWN */
4352         ICMP6_DST_UNREACH_ADDR,         /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4353         -1,                             /* 8: ICMP_UNREACH_ISOLATED */
4354         ICMP6_DST_UNREACH_ADMIN,        /* 9: ICMP_UNREACH_NET_PROHIB */
4355         ICMP6_DST_UNREACH_ADMIN,        /* 10: ICMP_UNREACH_HOST_PROHIB */
4356         -1,                             /* 11: ICMP_UNREACH_TOSNET */
4357         -1,                             /* 12: ICMP_UNREACH_TOSHOST */
4358         ICMP6_DST_UNREACH_ADMIN,        /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4359 };
4360 int     icmpreplytype6[ICMP6_MAXTYPE + 1];
4361 #endif
4362
4363 int     icmpreplytype4[ICMP_MAXTYPE + 1];
4364
4365
4366 /* ------------------------------------------------------------------------ */
4367 /* Function:    ipf_matchicmpqueryreply                                     */
4368 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4369 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4370 /*              ic(I)   - ICMP information                                  */
4371 /*              icmp(I) - ICMP packet header                                */
4372 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4373 /*                                                                          */
4374 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4375 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4376 /* else return 0 for no match.                                              */
4377 /* ------------------------------------------------------------------------ */
4378 int
4379 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4380         int v;
4381         icmpinfo_t *ic;
4382         icmphdr_t *icmp;
4383         int rev;
4384 {
4385         int ictype;
4386
4387         ictype = ic->ici_type;
4388
4389         if (v == 4) {
4390                 /*
4391                  * If we matched its type on the way in, then when going out
4392                  * it will still be the same type.
4393                  */
4394                 if ((!rev && (icmp->icmp_type == ictype)) ||
4395                     (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4396                         if (icmp->icmp_type != ICMP_ECHOREPLY)
4397                                 return 1;
4398                         if (icmp->icmp_id == ic->ici_id)
4399                                 return 1;
4400                 }
4401         }
4402 #ifdef  USE_INET6
4403         else if (v == 6) {
4404                 if ((!rev && (icmp->icmp_type == ictype)) ||
4405                     (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4406                         if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4407                                 return 1;
4408                         if (icmp->icmp_id == ic->ici_id)
4409                                 return 1;
4410                 }
4411         }
4412 #endif
4413         return 0;
4414 }
4415
4416
4417 /* ------------------------------------------------------------------------ */
4418 /* Function:    ipf_rule_compare                                            */
4419 /* Parameters:  fr1(I) - first rule structure to compare                    */
4420 /*              fr2(I) - second rule structure to compare                   */
4421 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4422 /*                                                                          */
4423 /* Compare two rules and return 0 if they match or a number indicating      */
4424 /* which of the individual checks failed.                                   */
4425 /* ------------------------------------------------------------------------ */
4426 static int
4427 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4428 {
4429         if (fr1->fr_cksum != fr2->fr_cksum)
4430                 return 1;
4431         if (fr1->fr_size != fr2->fr_size)
4432                 return 2;
4433         if (fr1->fr_dsize != fr2->fr_dsize)
4434                 return 3;
4435         if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4436                  fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4437                 return 4;
4438         if (fr1->fr_data && !fr2->fr_data)
4439                 return 5;
4440         if (!fr1->fr_data && fr2->fr_data)
4441                 return 6;
4442         if (fr1->fr_data) {
4443                 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4444                         return 7;
4445         }
4446         return 0;
4447 }
4448
4449
4450 /* ------------------------------------------------------------------------ */
4451 /* Function:    frrequest                                                   */
4452 /* Returns:     int - 0 == success, > 0 == errno value                      */
4453 /* Parameters:  unit(I)     - device for which this is for                  */
4454 /*              req(I)      - ioctl command (SIOC*)                         */
4455 /*              data(I)     - pointr to ioctl data                          */
4456 /*              set(I)      - 1 or 0 (filter set)                           */
4457 /*              makecopy(I) - flag indicating whether data points to a rule */
4458 /*                            in kernel space & hence doesn't need copying. */
4459 /*                                                                          */
4460 /* This function handles all the requests which operate on the list of      */
4461 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4462 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4463 /* names are resolved here and other sanity checks are made on the content  */
4464 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4465 /* then make sure they are created and initialised before exiting.          */
4466 /* ------------------------------------------------------------------------ */
4467 int
4468 frrequest(softc, unit, req, data, set, makecopy)
4469         ipf_main_softc_t *softc;
4470         int unit;
4471         ioctlcmd_t req;
4472         int set, makecopy;
4473         caddr_t data;
4474 {
4475         int error = 0, in, family, need_free = 0;
4476         enum {  OP_ADD,         /* add rule */
4477                 OP_REM,         /* remove rule */
4478                 OP_ZERO         /* zero statistics and counters */ }
4479                 addrem = OP_ADD;
4480         frentry_t frd, *fp, *f, **fprev, **ftail;
4481         void *ptr, *uptr, *cptr;
4482         u_int *p, *pp;
4483         frgroup_t *fg;
4484         char *group;
4485
4486         ptr = NULL;
4487         cptr = NULL;
4488         fg = NULL;
4489         fp = &frd;
4490         if (makecopy != 0) {
4491                 bzero(fp, sizeof(frd));
4492                 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4493                 if (error) {
4494                         return error;
4495                 }
4496                 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4497                         IPFERROR(6);
4498                         return EINVAL;
4499                 }
4500                 KMALLOCS(f, frentry_t *, fp->fr_size);
4501                 if (f == NULL) {
4502                         IPFERROR(131);
4503                         return ENOMEM;
4504                 }
4505                 bzero(f, fp->fr_size);
4506                 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4507                                     fp->fr_size);
4508                 if (error) {
4509                         KFREES(f, fp->fr_size);
4510                         return error;
4511                 }
4512
4513                 fp = f;
4514                 f = NULL;
4515                 fp->fr_next = NULL;
4516                 fp->fr_dnext = NULL;
4517                 fp->fr_pnext = NULL;
4518                 fp->fr_pdnext = NULL;
4519                 fp->fr_grp = NULL;
4520                 fp->fr_grphead = NULL;
4521                 fp->fr_icmpgrp = NULL;
4522                 fp->fr_isc = (void *)-1;
4523                 fp->fr_ptr = NULL;
4524                 fp->fr_ref = 0;
4525                 fp->fr_flags |= FR_COPIED;
4526         } else {
4527                 fp = (frentry_t *)data;
4528                 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4529                         IPFERROR(7);
4530                         return EINVAL;
4531                 }
4532                 fp->fr_flags &= ~FR_COPIED;
4533         }
4534
4535         if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4536             ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4537                 IPFERROR(8);
4538                 error = EINVAL;
4539                 goto donenolock;
4540         }
4541
4542         family = fp->fr_family;
4543         uptr = fp->fr_data;
4544
4545         if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4546             req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4547                 addrem = OP_ADD;        /* Add rule */
4548         else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4549                 addrem = OP_REM;                /* Remove rule */
4550         else if (req == (ioctlcmd_t)SIOCZRLST)
4551                 addrem = OP_ZERO;       /* Zero statistics and counters */
4552         else {
4553                 IPFERROR(9);
4554                 error = EINVAL;
4555                 goto donenolock;
4556         }
4557
4558         /*
4559          * Only filter rules for IPv4 or IPv6 are accepted.
4560          */
4561         if (family == AF_INET) {
4562                 /*EMPTY*/;
4563 #ifdef  USE_INET6
4564         } else if (family == AF_INET6) {
4565                 /*EMPTY*/;
4566 #endif
4567         } else if (family != 0) {
4568                 IPFERROR(10);
4569                 error = EINVAL;
4570                 goto donenolock;
4571         }
4572
4573         /*
4574          * If the rule is being loaded from user space, i.e. we had to copy it
4575          * into kernel space, then do not trust the function pointer in the
4576          * rule.
4577          */
4578         if ((makecopy == 1) && (fp->fr_func != NULL)) {
4579                 if (ipf_findfunc(fp->fr_func) == NULL) {
4580                         IPFERROR(11);
4581                         error = ESRCH;
4582                         goto donenolock;
4583                 }
4584
4585                 if (addrem == OP_ADD) {
4586                         error = ipf_funcinit(softc, fp);
4587                         if (error != 0)
4588                                 goto donenolock;
4589                 }
4590         }
4591         if ((fp->fr_flags & FR_CALLNOW) &&
4592             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4593                 IPFERROR(142);
4594                 error = ESRCH;
4595                 goto donenolock;
4596         }
4597         if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4598             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4599                 IPFERROR(143);
4600                 error = ESRCH;
4601                 goto donenolock;
4602         }
4603
4604         ptr = NULL;
4605         cptr = NULL;
4606
4607         if (FR_ISACCOUNT(fp->fr_flags))
4608                 unit = IPL_LOGCOUNT;
4609
4610         /*
4611          * Check that each group name in the rule has a start index that
4612          * is valid.
4613          */
4614         if (fp->fr_icmphead != -1) {
4615                 if ((fp->fr_icmphead < 0) ||
4616                     (fp->fr_icmphead >= fp->fr_namelen)) {
4617                         IPFERROR(136);
4618                         error = EINVAL;
4619                         goto donenolock;
4620                 }
4621                 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4622                         fp->fr_names[fp->fr_icmphead] = '\0';
4623         }
4624
4625         if (fp->fr_grhead != -1) {
4626                 if ((fp->fr_grhead < 0) ||
4627                     (fp->fr_grhead >= fp->fr_namelen)) {
4628                         IPFERROR(137);
4629                         error = EINVAL;
4630                         goto donenolock;
4631                 }
4632                 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4633                         fp->fr_names[fp->fr_grhead] = '\0';
4634         }
4635
4636         if (fp->fr_group != -1) {
4637                 if ((fp->fr_group < 0) ||
4638                     (fp->fr_group >= fp->fr_namelen)) {
4639                         IPFERROR(138);
4640                         error = EINVAL;
4641                         goto donenolock;
4642                 }
4643                 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4644                         /*
4645                          * Allow loading rules that are in groups to cause
4646                          * them to be created if they don't already exit.
4647                          */
4648                         group = FR_NAME(fp, fr_group);
4649                         if (addrem == OP_ADD) {
4650                                 fg = ipf_group_add(softc, group, NULL,
4651                                                    fp->fr_flags, unit, set);
4652                                 fp->fr_grp = fg;
4653                         } else {
4654                                 fg = ipf_findgroup(softc, group, unit,
4655                                                    set, NULL);
4656                                 if (fg == NULL) {
4657                                         IPFERROR(12);
4658                                         error = ESRCH;
4659                                         goto donenolock;
4660                                 }
4661                         }
4662
4663                         if (fg->fg_flags == 0) {
4664                                 fg->fg_flags = fp->fr_flags & FR_INOUT;
4665                         } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4666                                 IPFERROR(13);
4667                                 error = ESRCH;
4668                                 goto donenolock;
4669                         }
4670                 }
4671         } else {
4672                 /*
4673                  * If a rule is going to be part of a group then it does
4674                  * not matter whether it is an in or out rule, but if it
4675                  * isn't in a group, then it does...
4676                  */
4677                 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4678                         IPFERROR(14);
4679                         error = EINVAL;
4680                         goto donenolock;
4681                 }
4682         }
4683         in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4684
4685         /*
4686          * Work out which rule list this change is being applied to.
4687          */
4688         ftail = NULL;
4689         fprev = NULL;
4690         if (unit == IPL_LOGAUTH) {
4691                 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4692                     (fp->fr_tifs[1].fd_ptr != NULL) ||
4693                     (fp->fr_dif.fd_ptr != NULL) ||
4694                     (fp->fr_flags & FR_FASTROUTE)) {
4695                         softc->ipf_interror = 145;
4696                         error = EINVAL;
4697                         goto donenolock;
4698                 }
4699                 fprev = ipf_auth_rulehead(softc);
4700         } else {
4701                 if (FR_ISACCOUNT(fp->fr_flags))
4702                         fprev = &softc->ipf_acct[in][set];
4703                 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4704                         fprev = &softc->ipf_rules[in][set];
4705         }
4706         if (fprev == NULL) {
4707                 IPFERROR(15);
4708                 error = ESRCH;
4709                 goto donenolock;
4710         }
4711
4712         if (fg != NULL)
4713                 fprev = &fg->fg_start;
4714
4715         /*
4716          * Copy in extra data for the rule.
4717          */
4718         if (fp->fr_dsize != 0) {
4719                 if (makecopy != 0) {
4720                         KMALLOCS(ptr, void *, fp->fr_dsize);
4721                         if (ptr == NULL) {
4722                                 IPFERROR(16);
4723                                 error = ENOMEM;
4724                                 goto donenolock;
4725                         }
4726
4727                         /*
4728                          * The bcopy case is for when the data is appended
4729                          * to the rule by ipf_in_compat().
4730                          */
4731                         if (uptr >= (void *)fp &&
4732                             uptr < (void *)((char *)fp + fp->fr_size)) {
4733                                 bcopy(uptr, ptr, fp->fr_dsize);
4734                                 error = 0;
4735                         } else {
4736                                 error = COPYIN(uptr, ptr, fp->fr_dsize);
4737                                 if (error != 0) {
4738                                         IPFERROR(17);
4739                                         error = EFAULT;
4740                                         goto donenolock;
4741                                 }
4742                         }
4743                 } else {
4744                         ptr = uptr;
4745                 }
4746                 fp->fr_data = ptr;
4747         } else {
4748                 fp->fr_data = NULL;
4749         }
4750
4751         /*
4752          * Perform per-rule type sanity checks of their members.
4753          * All code after this needs to be aware that allocated memory
4754          * may need to be free'd before exiting.
4755          */
4756         switch (fp->fr_type & ~FR_T_BUILTIN)
4757         {
4758 #if defined(IPFILTER_BPF)
4759         case FR_T_BPFOPC :
4760                 if (fp->fr_dsize == 0) {
4761                         IPFERROR(19);
4762                         error = EINVAL;
4763                         break;
4764                 }
4765                 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4766                         IPFERROR(20);
4767                         error = EINVAL;
4768                         break;
4769                 }
4770                 break;
4771 #endif
4772         case FR_T_IPF :
4773                 /*
4774                  * Preparation for error case at the bottom of this function.
4775                  */
4776                 if (fp->fr_datype == FRI_LOOKUP)
4777                         fp->fr_dstptr = NULL;
4778                 if (fp->fr_satype == FRI_LOOKUP)
4779                         fp->fr_srcptr = NULL;
4780
4781                 if (fp->fr_dsize != sizeof(fripf_t)) {
4782                         IPFERROR(21);
4783                         error = EINVAL;
4784                         break;
4785                 }
4786
4787                 /*
4788                  * Allowing a rule with both "keep state" and "with oow" is
4789                  * pointless because adding a state entry to the table will
4790                  * fail with the out of window (oow) flag set.
4791                  */
4792                 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4793                         IPFERROR(22);
4794                         error = EINVAL;
4795                         break;
4796                 }
4797
4798                 switch (fp->fr_satype)
4799                 {
4800                 case FRI_BROADCAST :
4801                 case FRI_DYNAMIC :
4802                 case FRI_NETWORK :
4803                 case FRI_NETMASKED :
4804                 case FRI_PEERADDR :
4805                         if (fp->fr_sifpidx < 0) {
4806                                 IPFERROR(23);
4807                                 error = EINVAL;
4808                         }
4809                         break;
4810                 case FRI_LOOKUP :
4811                         fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4812                                                        &fp->fr_src6,
4813                                                        &fp->fr_smsk6);
4814                         if (fp->fr_srcfunc == NULL) {
4815                                 IPFERROR(132);
4816                                 error = ESRCH;
4817                                 break;
4818                         }
4819                         break;
4820                 case FRI_NORMAL :
4821                         break;
4822                 default :
4823                         IPFERROR(133);
4824                         error = EINVAL;
4825                         break;
4826                 }
4827                 if (error != 0)
4828                         break;
4829
4830                 switch (fp->fr_datype)
4831                 {
4832                 case FRI_BROADCAST :
4833                 case FRI_DYNAMIC :
4834                 case FRI_NETWORK :
4835                 case FRI_NETMASKED :
4836                 case FRI_PEERADDR :
4837                         if (fp->fr_difpidx < 0) {
4838                                 IPFERROR(24);
4839                                 error = EINVAL;
4840                         }
4841                         break;
4842                 case FRI_LOOKUP :
4843                         fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4844                                                        &fp->fr_dst6,
4845                                                        &fp->fr_dmsk6);
4846                         if (fp->fr_dstfunc == NULL) {
4847                                 IPFERROR(134);
4848                                 error = ESRCH;
4849                         }
4850                         break;
4851                 case FRI_NORMAL :
4852                         break;
4853                 default :
4854                         IPFERROR(135);
4855                         error = EINVAL;
4856                 }
4857                 break;
4858
4859         case FR_T_NONE :
4860         case FR_T_CALLFUNC :
4861         case FR_T_COMPIPF :
4862                 break;
4863
4864         case FR_T_IPFEXPR :
4865                 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4866                         IPFERROR(25);
4867                         error = EINVAL;
4868                 }
4869                 break;
4870
4871         default :
4872                 IPFERROR(26);
4873                 error = EINVAL;
4874                 break;
4875         }
4876         if (error != 0)
4877                 goto donenolock;
4878
4879         if (fp->fr_tif.fd_name != -1) {
4880                 if ((fp->fr_tif.fd_name < 0) ||
4881                     (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4882                         IPFERROR(139);
4883                         error = EINVAL;
4884                         goto donenolock;
4885                 }
4886         }
4887
4888         if (fp->fr_dif.fd_name != -1) {
4889                 if ((fp->fr_dif.fd_name < 0) ||
4890                     (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4891                         IPFERROR(140);
4892                         error = EINVAL;
4893                         goto donenolock;
4894                 }
4895         }
4896
4897         if (fp->fr_rif.fd_name != -1) {
4898                 if ((fp->fr_rif.fd_name < 0) ||
4899                     (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4900                         IPFERROR(141);
4901                         error = EINVAL;
4902                         goto donenolock;
4903                 }
4904         }
4905
4906         /*
4907          * Lookup all the interface names that are part of the rule.
4908          */
4909         error = ipf_synclist(softc, fp, NULL);
4910         if (error != 0)
4911                 goto donenolock;
4912         fp->fr_statecnt = 0;
4913         if (fp->fr_srctrack.ht_max_nodes != 0)
4914                 ipf_rb_ht_init(&fp->fr_srctrack);
4915
4916         /*
4917          * Look for an existing matching filter rule, but don't include the
4918          * next or interface pointer in the comparison (fr_next, fr_ifa).
4919          * This elminates rules which are indentical being loaded.  Checksum
4920          * the constant part of the filter rule to make comparisons quicker
4921          * (this meaning no pointers are included).
4922          */
4923         for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4924              p < pp; p++)
4925                 fp->fr_cksum += *p;
4926         pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4927         for (p = (u_int *)fp->fr_data; p < pp; p++)
4928                 fp->fr_cksum += *p;
4929
4930         WRITE_ENTER(&softc->ipf_mutex);
4931
4932         /*
4933          * Now that the filter rule lists are locked, we can walk the
4934          * chain of them without fear.
4935          */
4936         ftail = fprev;
4937         for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4938                 if (fp->fr_collect <= f->fr_collect) {
4939                         ftail = fprev;
4940                         f = NULL;
4941                         break;
4942                 }
4943                 fprev = ftail;
4944         }
4945
4946         for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4947                 if (ipf_rule_compare(fp, f) == 0)
4948                         break;
4949         }
4950
4951         /*
4952          * If zero'ing statistics, copy current to caller and zero.
4953          */
4954         if (addrem == OP_ZERO) {
4955                 if (f == NULL) {
4956                         IPFERROR(27);
4957                         error = ESRCH;
4958                 } else {
4959                         /*
4960                          * Copy and reduce lock because of impending copyout.
4961                          * Well we should, but if we do then the atomicity of
4962                          * this call and the correctness of fr_hits and
4963                          * fr_bytes cannot be guaranteed.  As it is, this code
4964                          * only resets them to 0 if they are successfully
4965                          * copied out into user space.
4966                          */
4967                         bcopy((char *)f, (char *)fp, f->fr_size);
4968                         /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4969
4970                         /*
4971                          * When we copy this rule back out, set the data
4972                          * pointer to be what it was in user space.
4973                          */
4974                         fp->fr_data = uptr;
4975                         error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4976
4977                         if (error == 0) {
4978                                 if ((f->fr_dsize != 0) && (uptr != NULL)) {
4979                                         error = COPYOUT(f->fr_data, uptr,
4980                                                         f->fr_dsize);
4981                                         if (error == 0) {
4982                                                 f->fr_hits = 0;
4983                                                 f->fr_bytes = 0;
4984                                         } else {
4985                                                 IPFERROR(28);
4986                                                 error = EFAULT;
4987                                         }
4988                                 }
4989                         }
4990                 }
4991
4992                 if (makecopy != 0) {
4993                         if (ptr != NULL) {
4994                                 KFREES(ptr, fp->fr_dsize);
4995                         }
4996                         KFREES(fp, fp->fr_size);
4997                 }
4998                 RWLOCK_EXIT(&softc->ipf_mutex);
4999                 return error;
5000         }
5001
5002         if (f == NULL) {
5003                 /*
5004                  * At the end of this, ftail must point to the place where the
5005                  * new rule is to be saved/inserted/added.
5006                  * For SIOCAD*FR, this should be the last rule in the group of
5007                  * rules that have equal fr_collect fields.
5008                  * For SIOCIN*FR, ...
5009                  */
5010                 if (req == (ioctlcmd_t)SIOCADAFR ||
5011                     req == (ioctlcmd_t)SIOCADIFR) {
5012
5013                         for (ftail = fprev; (f = *ftail) != NULL; ) {
5014                                 if (f->fr_collect > fp->fr_collect)
5015                                         break;
5016                                 ftail = &f->fr_next;
5017                                 fprev = ftail;
5018                         }
5019                         ftail = fprev;
5020                         f = NULL;
5021                         ptr = NULL;
5022                 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5023                            req == (ioctlcmd_t)SIOCINIFR) {
5024                         while ((f = *fprev) != NULL) {
5025                                 if (f->fr_collect >= fp->fr_collect)
5026                                         break;
5027                                 fprev = &f->fr_next;
5028                         }
5029                         ftail = fprev;
5030                         if (fp->fr_hits != 0) {
5031                                 while (fp->fr_hits && (f = *ftail)) {
5032                                         if (f->fr_collect != fp->fr_collect)
5033                                                 break;
5034                                         fprev = ftail;
5035                                         ftail = &f->fr_next;
5036                                         fp->fr_hits--;
5037                                 }
5038                         }
5039                         f = NULL;
5040                         ptr = NULL;
5041                 }
5042         }
5043
5044         /*
5045          * Request to remove a rule.
5046          */
5047         if (addrem == OP_REM) {
5048                 if (f == NULL) {
5049                         IPFERROR(29);
5050                         error = ESRCH;
5051                 } else {
5052                         /*
5053                          * Do not allow activity from user space to interfere
5054                          * with rules not loaded that way.
5055                          */
5056                         if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5057                                 IPFERROR(30);
5058                                 error = EPERM;
5059                                 goto done;
5060                         }
5061
5062                         /*
5063                          * Return EBUSY if the rule is being reference by
5064                          * something else (eg state information.)
5065                          */
5066                         if (f->fr_ref > 1) {
5067                                 IPFERROR(31);
5068                                 error = EBUSY;
5069                                 goto done;
5070                         }
5071 #ifdef  IPFILTER_SCAN
5072                         if (f->fr_isctag != -1 &&
5073                             (f->fr_isc != (struct ipscan *)-1))
5074                                 ipf_scan_detachfr(f);
5075 #endif
5076
5077                         if (unit == IPL_LOGAUTH) {
5078                                 error = ipf_auth_precmd(softc, req, f, ftail);
5079                                 goto done;
5080                         }
5081
5082                         ipf_rule_delete(softc, f, unit, set);
5083
5084                         need_free = makecopy;
5085                 }
5086         } else {
5087                 /*
5088                  * Not removing, so we must be adding/inserting a rule.
5089                  */
5090                 if (f != NULL) {
5091                         IPFERROR(32);
5092                         error = EEXIST;
5093                         goto done;
5094                 }
5095                 if (unit == IPL_LOGAUTH) {
5096                         error = ipf_auth_precmd(softc, req, fp, ftail);
5097                         goto done;
5098                 }
5099
5100                 MUTEX_NUKE(&fp->fr_lock);
5101                 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5102                 if (fp->fr_die != 0)
5103                         ipf_rule_expire_insert(softc, fp, set);
5104
5105                 fp->fr_hits = 0;
5106                 if (makecopy != 0)
5107                         fp->fr_ref = 1;
5108                 fp->fr_pnext = ftail;
5109                 fp->fr_next = *ftail;
5110                 if (fp->fr_next != NULL)
5111                         fp->fr_next->fr_pnext = &fp->fr_next;
5112                 *ftail = fp;
5113                 ipf_fixskip(ftail, fp, 1);
5114
5115                 fp->fr_icmpgrp = NULL;
5116                 if (fp->fr_icmphead != -1) {
5117                         group = FR_NAME(fp, fr_icmphead);
5118                         fg = ipf_group_add(softc, group, fp, 0, unit, set);
5119                         fp->fr_icmpgrp = fg;
5120                 }
5121
5122                 fp->fr_grphead = NULL;
5123                 if (fp->fr_grhead != -1) {
5124                         group = FR_NAME(fp, fr_grhead);
5125                         fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5126                                            unit, set);
5127                         fp->fr_grphead = fg;
5128                 }
5129         }
5130 done:
5131         RWLOCK_EXIT(&softc->ipf_mutex);
5132 donenolock:
5133         if (need_free || (error != 0)) {
5134                 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5135                         if ((fp->fr_satype == FRI_LOOKUP) &&
5136                             (fp->fr_srcptr != NULL))
5137                                 ipf_lookup_deref(softc, fp->fr_srctype,
5138                                                  fp->fr_srcptr);
5139                         if ((fp->fr_datype == FRI_LOOKUP) &&
5140                             (fp->fr_dstptr != NULL))
5141                                 ipf_lookup_deref(softc, fp->fr_dsttype,
5142                                                  fp->fr_dstptr);
5143                 }
5144                 if (fp->fr_grp != NULL) {
5145                         WRITE_ENTER(&softc->ipf_mutex);
5146                         ipf_group_del(softc, fp->fr_grp, fp);
5147                         RWLOCK_EXIT(&softc->ipf_mutex);
5148                 }
5149                 if ((ptr != NULL) && (makecopy != 0)) {
5150                         KFREES(ptr, fp->fr_dsize);
5151                 }
5152                 KFREES(fp, fp->fr_size);
5153         }
5154         return (error);
5155 }
5156
5157
5158 /* ------------------------------------------------------------------------ */
5159 /* Function:   ipf_rule_delete                                              */
5160 /* Returns:    Nil                                                          */
5161 /* Parameters: softc(I) - pointer to soft context main structure            */
5162 /*             f(I)     - pointer to the rule being deleted                 */
5163 /*             ftail(I) - pointer to the pointer to f                       */
5164 /*             unit(I)  - device for which this is for                      */
5165 /*             set(I)   - 1 or 0 (filter set)                               */
5166 /*                                                                          */
5167 /* This function attempts to do what it can to delete a filter rule: remove */
5168 /* it from any linked lists and remove any groups it is responsible for.    */
5169 /* But in the end, removing a rule can only drop the reference count - we   */
5170 /* must use that as the guide for whether or not it can be freed.           */
5171 /* ------------------------------------------------------------------------ */
5172 static void
5173 ipf_rule_delete(softc, f, unit, set)
5174         ipf_main_softc_t *softc;
5175         frentry_t *f;
5176         int unit, set;
5177 {
5178
5179         /*
5180          * If fr_pdnext is set, then the rule is on the expire list, so
5181          * remove it from there.
5182          */
5183         if (f->fr_pdnext != NULL) {
5184                 *f->fr_pdnext = f->fr_dnext;
5185                 if (f->fr_dnext != NULL)
5186                         f->fr_dnext->fr_pdnext = f->fr_pdnext;
5187                 f->fr_pdnext = NULL;
5188                 f->fr_dnext = NULL;
5189         }
5190
5191         ipf_fixskip(f->fr_pnext, f, -1);
5192         if (f->fr_pnext != NULL)
5193                 *f->fr_pnext = f->fr_next;
5194         if (f->fr_next != NULL)
5195                 f->fr_next->fr_pnext = f->fr_pnext;
5196         f->fr_pnext = NULL;
5197         f->fr_next = NULL;
5198
5199         (void) ipf_derefrule(softc, &f);
5200 }
5201
5202 /* ------------------------------------------------------------------------ */
5203 /* Function:   ipf_rule_expire_insert                                       */
5204 /* Returns:    Nil                                                          */
5205 /* Parameters: softc(I) - pointer to soft context main structure            */
5206 /*             f(I)     - pointer to rule to be added to expire list        */
5207 /*             set(I)   - 1 or 0 (filter set)                               */
5208 /*                                                                          */
5209 /* If the new rule has a given expiration time, insert it into the list of  */
5210 /* expiring rules with the ones to be removed first added to the front of   */
5211 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5212 /* expiration interval checks.                                              */
5213 /* ------------------------------------------------------------------------ */
5214 static void
5215 ipf_rule_expire_insert(softc, f, set)
5216         ipf_main_softc_t *softc;
5217         frentry_t *f;
5218         int set;
5219 {
5220         frentry_t *fr;
5221
5222         /*
5223          */
5224
5225         f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5226         for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5227              fr = fr->fr_dnext) {
5228                 if (f->fr_die < fr->fr_die)
5229                         break;
5230                 if (fr->fr_dnext == NULL) {
5231                         /*
5232                          * We've got to the last rule and everything
5233                          * wanted to be expired before this new node,
5234                          * so we have to tack it on the end...
5235                          */
5236                         fr->fr_dnext = f;
5237                         f->fr_pdnext = &fr->fr_dnext;
5238                         fr = NULL;
5239                         break;
5240                 }
5241         }
5242
5243         if (softc->ipf_rule_explist[set] == NULL) {
5244                 softc->ipf_rule_explist[set] = f;
5245                 f->fr_pdnext = &softc->ipf_rule_explist[set];
5246         } else if (fr != NULL) {
5247                 f->fr_dnext = fr;
5248                 f->fr_pdnext = fr->fr_pdnext;
5249                 fr->fr_pdnext = &f->fr_dnext;
5250         }
5251 }
5252
5253
5254 /* ------------------------------------------------------------------------ */
5255 /* Function:   ipf_findlookup                                               */
5256 /* Returns:    NULL = failure, else success                                 */
5257 /* Parameters: softc(I) - pointer to soft context main structure            */
5258 /*             unit(I)  - ipf device we want to find match for              */
5259 /*             fp(I)    - rule for which lookup is for                      */
5260 /*             addrp(I) - pointer to lookup information in address struct   */
5261 /*             maskp(O) - pointer to lookup information for storage         */
5262 /*                                                                          */
5263 /* When using pools and hash tables to store addresses for matching in      */
5264 /* rules, it is necessary to resolve both the object referred to by the     */
5265 /* name or address (and return that pointer) and also provide the means by  */
5266 /* which to determine if an address belongs to that object to make the      */
5267 /* packet matching quicker.                                                 */
5268 /* ------------------------------------------------------------------------ */
5269 static void *
5270 ipf_findlookup(softc, unit, fr, addrp, maskp)
5271         ipf_main_softc_t *softc;
5272         int unit;
5273         frentry_t *fr;
5274         i6addr_t *addrp, *maskp;
5275 {
5276         void *ptr = NULL;
5277
5278         switch (addrp->iplookupsubtype)
5279         {
5280         case 0 :
5281                 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5282                                          addrp->iplookupnum,
5283                                          &maskp->iplookupfunc);
5284                 break;
5285         case 1 :
5286                 if (addrp->iplookupname < 0)
5287                         break;
5288                 if (addrp->iplookupname >= fr->fr_namelen)
5289                         break;
5290                 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5291                                           fr->fr_names + addrp->iplookupname,
5292                                           &maskp->iplookupfunc);
5293                 break;
5294         default :
5295                 break;
5296         }
5297
5298         return ptr;
5299 }
5300
5301
5302 /* ------------------------------------------------------------------------ */
5303 /* Function:    ipf_funcinit                                                */
5304 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5305 /* Parameters:  softc(I) - pointer to soft context main structure           */
5306 /*              fr(I)    - pointer to filter rule                           */
5307 /*                                                                          */
5308 /* If a rule is a call rule, then check if the function it points to needs  */
5309 /* an init function to be called now the rule has been loaded.              */
5310 /* ------------------------------------------------------------------------ */
5311 static int
5312 ipf_funcinit(softc, fr)
5313         ipf_main_softc_t *softc;
5314         frentry_t *fr;
5315 {
5316         ipfunc_resolve_t *ft;
5317         int err;
5318
5319         IPFERROR(34);
5320         err = ESRCH;
5321
5322         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5323                 if (ft->ipfu_addr == fr->fr_func) {
5324                         err = 0;
5325                         if (ft->ipfu_init != NULL)
5326                                 err = (*ft->ipfu_init)(softc, fr);
5327                         break;
5328                 }
5329         return err;
5330 }
5331
5332
5333 /* ------------------------------------------------------------------------ */
5334 /* Function:    ipf_funcfini                                                */
5335 /* Returns:     Nil                                                         */
5336 /* Parameters:  softc(I) - pointer to soft context main structure           */
5337 /*              fr(I)    - pointer to filter rule                           */
5338 /*                                                                          */
5339 /* For a given filter rule, call the matching "fini" function if the rule   */
5340 /* is using a known function that would have resulted in the "init" being   */
5341 /* called for ealier.                                                       */
5342 /* ------------------------------------------------------------------------ */
5343 static void
5344 ipf_funcfini(softc, fr)
5345         ipf_main_softc_t *softc;
5346         frentry_t *fr;
5347 {
5348         ipfunc_resolve_t *ft;
5349
5350         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5351                 if (ft->ipfu_addr == fr->fr_func) {
5352                         if (ft->ipfu_fini != NULL)
5353                                 (void) (*ft->ipfu_fini)(softc, fr);
5354                         break;
5355                 }
5356 }
5357
5358
5359 /* ------------------------------------------------------------------------ */
5360 /* Function:    ipf_findfunc                                                */
5361 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5362 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5363 /*                                                                          */
5364 /* Look for a function in the table of known functions.                     */
5365 /* ------------------------------------------------------------------------ */
5366 static ipfunc_t
5367 ipf_findfunc(funcptr)
5368         ipfunc_t funcptr;
5369 {
5370         ipfunc_resolve_t *ft;
5371
5372         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5373                 if (ft->ipfu_addr == funcptr)
5374                         return funcptr;
5375         return NULL;
5376 }
5377
5378
5379 /* ------------------------------------------------------------------------ */
5380 /* Function:    ipf_resolvefunc                                             */
5381 /* Returns:     int - 0 == success, else error                              */
5382 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5383 /*                                                                          */
5384 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5385 /* This will either be the function name (if the pointer is set) or the     */
5386 /* function pointer if the name is set.  When found, fill in the other one  */
5387 /* so that the entire, complete, structure can be copied back to user space.*/
5388 /* ------------------------------------------------------------------------ */
5389 int
5390 ipf_resolvefunc(softc, data)
5391         ipf_main_softc_t *softc;
5392         void *data;
5393 {
5394         ipfunc_resolve_t res, *ft;
5395         int error;
5396
5397         error = BCOPYIN(data, &res, sizeof(res));
5398         if (error != 0) {
5399                 IPFERROR(123);
5400                 return EFAULT;
5401         }
5402
5403         if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5404                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5405                         if (strncmp(res.ipfu_name, ft->ipfu_name,
5406                                     sizeof(res.ipfu_name)) == 0) {
5407                                 res.ipfu_addr = ft->ipfu_addr;
5408                                 res.ipfu_init = ft->ipfu_init;
5409                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5410                                         IPFERROR(35);
5411                                         return EFAULT;
5412                                 }
5413                                 return 0;
5414                         }
5415         }
5416         if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5417                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5418                         if (ft->ipfu_addr == res.ipfu_addr) {
5419                                 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5420                                                sizeof(res.ipfu_name));
5421                                 res.ipfu_init = ft->ipfu_init;
5422                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5423                                         IPFERROR(36);
5424                                         return EFAULT;
5425                                 }
5426                                 return 0;
5427                         }
5428         }
5429         IPFERROR(37);
5430         return ESRCH;
5431 }
5432
5433
5434 #if !defined(_KERNEL) || SOLARIS
5435 /*
5436  * From: NetBSD
5437  * ppsratecheck(): packets (or events) per second limitation.
5438  */
5439 int
5440 ppsratecheck(lasttime, curpps, maxpps)
5441         struct timeval *lasttime;
5442         int *curpps;
5443         int maxpps;     /* maximum pps allowed */
5444 {
5445         struct timeval tv, delta;
5446         int rv;
5447
5448         GETKTIME(&tv);
5449
5450         delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5451         delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5452         if (delta.tv_usec < 0) {
5453                 delta.tv_sec--;
5454                 delta.tv_usec += 1000000;
5455         }
5456
5457         /*
5458          * check for 0,0 is so that the message will be seen at least once.
5459          * if more than one second have passed since the last update of
5460          * lasttime, reset the counter.
5461          *
5462          * we do increment *curpps even in *curpps < maxpps case, as some may
5463          * try to use *curpps for stat purposes as well.
5464          */
5465         if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5466             delta.tv_sec >= 1) {
5467                 *lasttime = tv;
5468                 *curpps = 0;
5469                 rv = 1;
5470         } else if (maxpps < 0)
5471                 rv = 1;
5472         else if (*curpps < maxpps)
5473                 rv = 1;
5474         else
5475                 rv = 0;
5476         *curpps = *curpps + 1;
5477
5478         return (rv);
5479 }
5480 #endif
5481
5482
5483 /* ------------------------------------------------------------------------ */
5484 /* Function:    ipf_derefrule                                               */
5485 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5486 /* Parameters:  fr(I) - pointer to filter rule                              */
5487 /*                                                                          */
5488 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5489 /* free it and any associated storage space being used by it.               */
5490 /* ------------------------------------------------------------------------ */
5491 int
5492 ipf_derefrule(softc, frp)
5493         ipf_main_softc_t *softc;
5494         frentry_t **frp;
5495 {
5496         frentry_t *fr;
5497         frdest_t *fdp;
5498
5499         fr = *frp;
5500         *frp = NULL;
5501
5502         MUTEX_ENTER(&fr->fr_lock);
5503         fr->fr_ref--;
5504         if (fr->fr_ref == 0) {
5505                 MUTEX_EXIT(&fr->fr_lock);
5506                 MUTEX_DESTROY(&fr->fr_lock);
5507
5508                 ipf_funcfini(softc, fr);
5509
5510                 fdp = &fr->fr_tif;
5511                 if (fdp->fd_type == FRD_DSTLIST)
5512                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5513
5514                 fdp = &fr->fr_rif;
5515                 if (fdp->fd_type == FRD_DSTLIST)
5516                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5517
5518                 fdp = &fr->fr_dif;
5519                 if (fdp->fd_type == FRD_DSTLIST)
5520                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5521
5522                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5523                     fr->fr_satype == FRI_LOOKUP)
5524                         ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5525                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5526                     fr->fr_datype == FRI_LOOKUP)
5527                         ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5528
5529                 if (fr->fr_grp != NULL)
5530                         ipf_group_del(softc, fr->fr_grp, fr);
5531
5532                 if (fr->fr_grphead != NULL)
5533                         ipf_group_del(softc, fr->fr_grphead, fr);
5534
5535                 if (fr->fr_icmpgrp != NULL)
5536                         ipf_group_del(softc, fr->fr_icmpgrp, fr);
5537
5538                 if ((fr->fr_flags & FR_COPIED) != 0) {
5539                         if (fr->fr_dsize) {
5540                                 KFREES(fr->fr_data, fr->fr_dsize);
5541                         }
5542                         KFREES(fr, fr->fr_size);
5543                         return 0;
5544                 }
5545                 return 1;
5546         } else {
5547                 MUTEX_EXIT(&fr->fr_lock);
5548         }
5549         return -1;
5550 }
5551
5552
5553 /* ------------------------------------------------------------------------ */
5554 /* Function:    ipf_grpmapinit                                              */
5555 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5556 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5557 /*                                                                          */
5558 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5559 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5560 /* ------------------------------------------------------------------------ */
5561 static int
5562 ipf_grpmapinit(softc, fr)
5563         ipf_main_softc_t *softc;
5564         frentry_t *fr;
5565 {
5566         char name[FR_GROUPLEN];
5567         iphtable_t *iph;
5568
5569 #if defined(SNPRINTF) && defined(_KERNEL)
5570         SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5571 #else
5572         (void) sprintf(name, "%d", fr->fr_arg);
5573 #endif
5574         iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5575         if (iph == NULL) {
5576                 IPFERROR(38);
5577                 return ESRCH;
5578         }
5579         if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5580                 IPFERROR(39);
5581                 return ESRCH;
5582         }
5583         iph->iph_ref++;
5584         fr->fr_ptr = iph;
5585         return 0;
5586 }
5587
5588
5589 /* ------------------------------------------------------------------------ */
5590 /* Function:    ipf_grpmapfini                                              */
5591 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5592 /* Parameters:  softc(I) - pointer to soft context main structure           */
5593 /*              fr(I)    - pointer to rule to release hash table for        */
5594 /*                                                                          */
5595 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5596 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5597 /* ------------------------------------------------------------------------ */
5598 static int
5599 ipf_grpmapfini(softc, fr)
5600         ipf_main_softc_t *softc;
5601         frentry_t *fr;
5602 {
5603         iphtable_t *iph;
5604         iph = fr->fr_ptr;
5605         if (iph != NULL)
5606                 ipf_lookup_deref(softc, IPLT_HASH, iph);
5607         return 0;
5608 }
5609
5610
5611 /* ------------------------------------------------------------------------ */
5612 /* Function:    ipf_srcgrpmap                                               */
5613 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5614 /* Parameters:  fin(I)    - pointer to packet information                   */
5615 /*              passp(IO) - pointer to current/new filter decision (unused) */
5616 /*                                                                          */
5617 /* Look for a rule group head in a hash table, using the source address as  */
5618 /* the key, and descend into that group and continue matching rules against */
5619 /* the packet.                                                              */
5620 /* ------------------------------------------------------------------------ */
5621 frentry_t *
5622 ipf_srcgrpmap(fin, passp)
5623         fr_info_t *fin;
5624         u_32_t *passp;
5625 {
5626         frgroup_t *fg;
5627         void *rval;
5628
5629         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5630                                  &fin->fin_src);
5631         if (rval == NULL)
5632                 return NULL;
5633
5634         fg = rval;
5635         fin->fin_fr = fg->fg_start;
5636         (void) ipf_scanlist(fin, *passp);
5637         return fin->fin_fr;
5638 }
5639
5640
5641 /* ------------------------------------------------------------------------ */
5642 /* Function:    ipf_dstgrpmap                                               */
5643 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5644 /* Parameters:  fin(I)    - pointer to packet information                   */
5645 /*              passp(IO) - pointer to current/new filter decision (unused) */
5646 /*                                                                          */
5647 /* Look for a rule group head in a hash table, using the destination        */
5648 /* address as the key, and descend into that group and continue matching    */
5649 /* rules against  the packet.                                               */
5650 /* ------------------------------------------------------------------------ */
5651 frentry_t *
5652 ipf_dstgrpmap(fin, passp)
5653         fr_info_t *fin;
5654         u_32_t *passp;
5655 {
5656         frgroup_t *fg;
5657         void *rval;
5658
5659         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5660                                  &fin->fin_dst);
5661         if (rval == NULL)
5662                 return NULL;
5663
5664         fg = rval;
5665         fin->fin_fr = fg->fg_start;
5666         (void) ipf_scanlist(fin, *passp);
5667         return fin->fin_fr;
5668 }
5669
5670 /*
5671  * Queue functions
5672  * ===============
5673  * These functions manage objects on queues for efficient timeouts.  There
5674  * are a number of system defined queues as well as user defined timeouts.
5675  * It is expected that a lock is held in the domain in which the queue
5676  * belongs (i.e. either state or NAT) when calling any of these functions
5677  * that prevents ipf_freetimeoutqueue() from being called at the same time
5678  * as any other.
5679  */
5680
5681
5682 /* ------------------------------------------------------------------------ */
5683 /* Function:    ipf_addtimeoutqueue                                         */
5684 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5685 /*                               timeout queue with given interval.         */
5686 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5687 /*                           of interface queues.                           */
5688 /*              seconds(I) - timeout value in seconds for this queue.       */
5689 /*                                                                          */
5690 /* This routine first looks for a timeout queue that matches the interval   */
5691 /* being requested.  If it finds one, increments the reference counter and  */
5692 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5693 /* inserts it at the top of the list.                                       */
5694 /*                                                                          */
5695 /* Locking.                                                                 */
5696 /* It is assumed that the caller of this function has an appropriate lock   */
5697 /* held (exclusively) in the domain that encompases 'parent'.               */
5698 /* ------------------------------------------------------------------------ */
5699 ipftq_t *
5700 ipf_addtimeoutqueue(softc, parent, seconds)
5701         ipf_main_softc_t *softc;
5702         ipftq_t **parent;
5703         u_int seconds;
5704 {
5705         ipftq_t *ifq;
5706         u_int period;
5707
5708         period = seconds * IPF_HZ_DIVIDE;
5709
5710         MUTEX_ENTER(&softc->ipf_timeoutlock);
5711         for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5712                 if (ifq->ifq_ttl == period) {
5713                         /*
5714                          * Reset the delete flag, if set, so the structure
5715                          * gets reused rather than freed and reallocated.
5716                          */
5717                         MUTEX_ENTER(&ifq->ifq_lock);
5718                         ifq->ifq_flags &= ~IFQF_DELETE;
5719                         ifq->ifq_ref++;
5720                         MUTEX_EXIT(&ifq->ifq_lock);
5721                         MUTEX_EXIT(&softc->ipf_timeoutlock);
5722
5723                         return ifq;
5724                 }
5725         }
5726
5727         KMALLOC(ifq, ipftq_t *);
5728         if (ifq != NULL) {
5729                 MUTEX_NUKE(&ifq->ifq_lock);
5730                 IPFTQ_INIT(ifq, period, "ipftq mutex");
5731                 ifq->ifq_next = *parent;
5732                 ifq->ifq_pnext = parent;
5733                 ifq->ifq_flags = IFQF_USER;
5734                 ifq->ifq_ref++;
5735                 *parent = ifq;
5736                 softc->ipf_userifqs++;
5737         }
5738         MUTEX_EXIT(&softc->ipf_timeoutlock);
5739         return ifq;
5740 }
5741
5742
5743 /* ------------------------------------------------------------------------ */
5744 /* Function:    ipf_deletetimeoutqueue                                      */
5745 /* Returns:     int    - new reference count value of the timeout queue     */
5746 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5747 /* Locks:       ifq->ifq_lock                                               */
5748 /*                                                                          */
5749 /* This routine must be called when we're discarding a pointer to a timeout */
5750 /* queue object, taking care of the reference counter.                      */
5751 /*                                                                          */
5752 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5753 /* check the list of user defined timeout queues and call the free function */
5754 /* below (currently commented out) to stop memory leaking.  It is done this */
5755 /* way because the locking may not be sufficient to safely do a free when   */
5756 /* this function is called.                                                 */
5757 /* ------------------------------------------------------------------------ */
5758 int
5759 ipf_deletetimeoutqueue(ifq)
5760         ipftq_t *ifq;
5761 {
5762
5763         ifq->ifq_ref--;
5764         if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5765                 ifq->ifq_flags |= IFQF_DELETE;
5766         }
5767
5768         return ifq->ifq_ref;
5769 }
5770
5771
5772 /* ------------------------------------------------------------------------ */
5773 /* Function:    ipf_freetimeoutqueue                                        */
5774 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5775 /* Returns:     Nil                                                         */
5776 /*                                                                          */
5777 /* Locking:                                                                 */
5778 /* It is assumed that the caller of this function has an appropriate lock   */
5779 /* held (exclusively) in the domain that encompases the callers "domain".   */
5780 /* The ifq_lock for this structure should not be held.                      */
5781 /*                                                                          */
5782 /* Remove a user defined timeout queue from the list of queues it is in and */
5783 /* tidy up after this is done.                                              */
5784 /* ------------------------------------------------------------------------ */
5785 void
5786 ipf_freetimeoutqueue(softc, ifq)
5787         ipf_main_softc_t *softc;
5788         ipftq_t *ifq;
5789 {
5790
5791         if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5792             ((ifq->ifq_flags & IFQF_USER) == 0)) {
5793                 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5794                        (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5795                        ifq->ifq_ref);
5796                 return;
5797         }
5798
5799         /*
5800          * Remove from its position in the list.
5801          */
5802         *ifq->ifq_pnext = ifq->ifq_next;
5803         if (ifq->ifq_next != NULL)
5804                 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5805         ifq->ifq_next = NULL;
5806         ifq->ifq_pnext = NULL;
5807
5808         MUTEX_DESTROY(&ifq->ifq_lock);
5809         ATOMIC_DEC(softc->ipf_userifqs);
5810         KFREE(ifq);
5811 }
5812
5813
5814 /* ------------------------------------------------------------------------ */
5815 /* Function:    ipf_deletequeueentry                                        */
5816 /* Returns:     Nil                                                         */
5817 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5818 /*                                                                          */
5819 /* Remove a tail queue entry from its queue and make it an orphan.          */
5820 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5821 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5822 /* the correct lock(s) may not be held that would make it safe to do so.    */
5823 /* ------------------------------------------------------------------------ */
5824 void
5825 ipf_deletequeueentry(tqe)
5826         ipftqent_t *tqe;
5827 {
5828         ipftq_t *ifq;
5829
5830         ifq = tqe->tqe_ifq;
5831
5832         MUTEX_ENTER(&ifq->ifq_lock);
5833
5834         if (tqe->tqe_pnext != NULL) {
5835                 *tqe->tqe_pnext = tqe->tqe_next;
5836                 if (tqe->tqe_next != NULL)
5837                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5838                 else    /* we must be the tail anyway */
5839                         ifq->ifq_tail = tqe->tqe_pnext;
5840
5841                 tqe->tqe_pnext = NULL;
5842                 tqe->tqe_ifq = NULL;
5843         }
5844
5845         (void) ipf_deletetimeoutqueue(ifq);
5846         ASSERT(ifq->ifq_ref > 0);
5847
5848         MUTEX_EXIT(&ifq->ifq_lock);
5849 }
5850
5851
5852 /* ------------------------------------------------------------------------ */
5853 /* Function:    ipf_queuefront                                              */
5854 /* Returns:     Nil                                                         */
5855 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5856 /*                                                                          */
5857 /* Move a queue entry to the front of the queue, if it isn't already there. */
5858 /* ------------------------------------------------------------------------ */
5859 void
5860 ipf_queuefront(tqe)
5861         ipftqent_t *tqe;
5862 {
5863         ipftq_t *ifq;
5864
5865         ifq = tqe->tqe_ifq;
5866         if (ifq == NULL)
5867                 return;
5868
5869         MUTEX_ENTER(&ifq->ifq_lock);
5870         if (ifq->ifq_head != tqe) {
5871                 *tqe->tqe_pnext = tqe->tqe_next;
5872                 if (tqe->tqe_next)
5873                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5874                 else
5875                         ifq->ifq_tail = tqe->tqe_pnext;
5876
5877                 tqe->tqe_next = ifq->ifq_head;
5878                 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5879                 ifq->ifq_head = tqe;
5880                 tqe->tqe_pnext = &ifq->ifq_head;
5881         }
5882         MUTEX_EXIT(&ifq->ifq_lock);
5883 }
5884
5885
5886 /* ------------------------------------------------------------------------ */
5887 /* Function:    ipf_queueback                                               */
5888 /* Returns:     Nil                                                         */
5889 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5890 /*              tqe(I)   - pointer to timeout queue entry                   */
5891 /*                                                                          */
5892 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5893 /* We use use ticks to calculate the expiration and mark for when we last   */
5894 /* touched the structure.                                                   */
5895 /* ------------------------------------------------------------------------ */
5896 void
5897 ipf_queueback(ticks, tqe)
5898         u_long ticks;
5899         ipftqent_t *tqe;
5900 {
5901         ipftq_t *ifq;
5902
5903         ifq = tqe->tqe_ifq;
5904         if (ifq == NULL)
5905                 return;
5906         tqe->tqe_die = ticks + ifq->ifq_ttl;
5907         tqe->tqe_touched = ticks;
5908
5909         MUTEX_ENTER(&ifq->ifq_lock);
5910         if (tqe->tqe_next != NULL) {            /* at the end already ? */
5911                 /*
5912                  * Remove from list
5913                  */
5914                 *tqe->tqe_pnext = tqe->tqe_next;
5915                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5916
5917                 /*
5918                  * Make it the last entry.
5919                  */
5920                 tqe->tqe_next = NULL;
5921                 tqe->tqe_pnext = ifq->ifq_tail;
5922                 *ifq->ifq_tail = tqe;
5923                 ifq->ifq_tail = &tqe->tqe_next;
5924         }
5925         MUTEX_EXIT(&ifq->ifq_lock);
5926 }
5927
5928
5929 /* ------------------------------------------------------------------------ */
5930 /* Function:    ipf_queueappend                                             */
5931 /* Returns:     Nil                                                         */
5932 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5933 /*              tqe(I)    - pointer to timeout queue entry                  */
5934 /*              ifq(I)    - pointer to timeout queue                        */
5935 /*              parent(I) - owing object pointer                            */
5936 /*                                                                          */
5937 /* Add a new item to this queue and put it on the very end.                 */
5938 /* We use use ticks to calculate the expiration and mark for when we last   */
5939 /* touched the structure.                                                   */
5940 /* ------------------------------------------------------------------------ */
5941 void
5942 ipf_queueappend(ticks, tqe, ifq, parent)
5943         u_long ticks;
5944         ipftqent_t *tqe;
5945         ipftq_t *ifq;
5946         void *parent;
5947 {
5948
5949         MUTEX_ENTER(&ifq->ifq_lock);
5950         tqe->tqe_parent = parent;
5951         tqe->tqe_pnext = ifq->ifq_tail;
5952         *ifq->ifq_tail = tqe;
5953         ifq->ifq_tail = &tqe->tqe_next;
5954         tqe->tqe_next = NULL;
5955         tqe->tqe_ifq = ifq;
5956         tqe->tqe_die = ticks + ifq->ifq_ttl;
5957         tqe->tqe_touched = ticks;
5958         ifq->ifq_ref++;
5959         MUTEX_EXIT(&ifq->ifq_lock);
5960 }
5961
5962
5963 /* ------------------------------------------------------------------------ */
5964 /* Function:    ipf_movequeue                                               */
5965 /* Returns:     Nil                                                         */
5966 /* Parameters:  tq(I)   - pointer to timeout queue information              */
5967 /*              oifp(I) - old timeout queue entry was on                    */
5968 /*              nifp(I) - new timeout queue to put entry on                 */
5969 /*                                                                          */
5970 /* Move a queue entry from one timeout queue to another timeout queue.      */
5971 /* If it notices that the current entry is already last and does not need   */
5972 /* to move queue, the return.                                               */
5973 /* ------------------------------------------------------------------------ */
5974 void
5975 ipf_movequeue(ticks, tqe, oifq, nifq)
5976         u_long ticks;
5977         ipftqent_t *tqe;
5978         ipftq_t *oifq, *nifq;
5979 {
5980
5981         /*
5982          * If the queue hasn't changed and we last touched this entry at the
5983          * same ipf time, then we're not going to achieve anything by either
5984          * changing the ttl or moving it on the queue.
5985          */
5986         if (oifq == nifq && tqe->tqe_touched == ticks)
5987                 return;
5988
5989         /*
5990          * For any of this to be outside the lock, there is a risk that two
5991          * packets entering simultaneously, with one changing to a different
5992          * queue and one not, could end up with things in a bizarre state.
5993          */
5994         MUTEX_ENTER(&oifq->ifq_lock);
5995
5996         tqe->tqe_touched = ticks;
5997         tqe->tqe_die = ticks + nifq->ifq_ttl;
5998         /*
5999          * Is the operation here going to be a no-op ?
6000          */
6001         if (oifq == nifq) {
6002                 if ((tqe->tqe_next == NULL) ||
6003                     (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6004                         MUTEX_EXIT(&oifq->ifq_lock);
6005                         return;
6006                 }
6007         }
6008
6009         /*
6010          * Remove from the old queue
6011          */
6012         *tqe->tqe_pnext = tqe->tqe_next;
6013         if (tqe->tqe_next)
6014                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6015         else
6016                 oifq->ifq_tail = tqe->tqe_pnext;
6017         tqe->tqe_next = NULL;
6018
6019         /*
6020          * If we're moving from one queue to another, release the
6021          * lock on the old queue and get a lock on the new queue.
6022          * For user defined queues, if we're moving off it, call
6023          * delete in case it can now be freed.
6024          */
6025         if (oifq != nifq) {
6026                 tqe->tqe_ifq = NULL;
6027
6028                 (void) ipf_deletetimeoutqueue(oifq);
6029
6030                 MUTEX_EXIT(&oifq->ifq_lock);
6031
6032                 MUTEX_ENTER(&nifq->ifq_lock);
6033
6034                 tqe->tqe_ifq = nifq;
6035                 nifq->ifq_ref++;
6036         }
6037
6038         /*
6039          * Add to the bottom of the new queue
6040          */
6041         tqe->tqe_pnext = nifq->ifq_tail;
6042         *nifq->ifq_tail = tqe;
6043         nifq->ifq_tail = &tqe->tqe_next;
6044         MUTEX_EXIT(&nifq->ifq_lock);
6045 }
6046
6047
6048 /* ------------------------------------------------------------------------ */
6049 /* Function:    ipf_updateipid                                              */
6050 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6051 /* Parameters:  fin(I) - pointer to packet information                      */
6052 /*                                                                          */
6053 /* When we are doing NAT, change the IP of every packet to represent a      */
6054 /* single sequence of packets coming from the host, hiding any host         */
6055 /* specific sequencing that might otherwise be revealed.  If the packet is  */
6056 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6057 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
6058 /* has no match in the cache, return an error.                              */
6059 /* ------------------------------------------------------------------------ */
6060 static int
6061 ipf_updateipid(fin)
6062         fr_info_t *fin;
6063 {
6064         u_short id, ido, sums;
6065         u_32_t sumd, sum;
6066         ip_t *ip;
6067
6068         ip = fin->fin_ip;
6069         ido = ntohs(ip->ip_id);
6070         if (fin->fin_off != 0) {
6071                 sum = ipf_frag_ipidknown(fin);
6072                 if (sum == 0xffffffff)
6073                         return -1;
6074                 sum &= 0xffff;
6075                 id = (u_short)sum;
6076                 ip->ip_id = htons(id);
6077         } else {
6078                 ip_fillid(ip);
6079                 id = ntohs(ip->ip_id);
6080                 if ((fin->fin_flx & FI_FRAG) != 0)
6081                         (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6082         }
6083
6084         if (id == ido)
6085                 return 0;
6086         CALC_SUMD(ido, id, sumd);       /* DESTRUCTIVE MACRO! id,ido change */
6087         sum = (~ntohs(ip->ip_sum)) & 0xffff;
6088         sum += sumd;
6089         sum = (sum >> 16) + (sum & 0xffff);
6090         sum = (sum >> 16) + (sum & 0xffff);
6091         sums = ~(u_short)sum;
6092         ip->ip_sum = htons(sums);
6093         return 0;
6094 }
6095
6096
6097 #ifdef  NEED_FRGETIFNAME
6098 /* ------------------------------------------------------------------------ */
6099 /* Function:    ipf_getifname                                               */
6100 /* Returns:     char *    - pointer to interface name                       */
6101 /* Parameters:  ifp(I)    - pointer to network interface                    */
6102 /*              buffer(O) - pointer to where to store interface name        */
6103 /*                                                                          */
6104 /* Constructs an interface name in the buffer passed.  The buffer passed is */
6105 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6106 /* as a NULL pointer then return a pointer to a static array.               */
6107 /* ------------------------------------------------------------------------ */
6108 char *
6109 ipf_getifname(ifp, buffer)
6110         struct ifnet *ifp;
6111         char *buffer;
6112 {
6113         static char namebuf[LIFNAMSIZ];
6114 # if defined(MENTAT) || defined(__FreeBSD__)
6115         int unit, space;
6116         char temp[20];
6117         char *s;
6118 # endif
6119
6120         if (buffer == NULL)
6121                 buffer = namebuf;
6122         (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6123         buffer[LIFNAMSIZ - 1] = '\0';
6124 # if defined(MENTAT) || defined(__FreeBSD__)
6125         for (s = buffer; *s; s++)
6126                 ;
6127         unit = ifp->if_unit;
6128         space = LIFNAMSIZ - (s - buffer);
6129         if ((space > 0) && (unit >= 0)) {
6130 #  if defined(SNPRINTF) && defined(_KERNEL)
6131                 SNPRINTF(temp, sizeof(temp), "%d", unit);
6132 #  else
6133                 (void) sprintf(temp, "%d", unit);
6134 #  endif
6135                 (void) strncpy(s, temp, space);
6136         }
6137 # endif
6138         return buffer;
6139 }
6140 #endif
6141
6142
6143 /* ------------------------------------------------------------------------ */
6144 /* Function:    ipf_ioctlswitch                                             */
6145 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6146 /* Parameters:  unit(I) - device unit opened                                */
6147 /*              data(I) - pointer to ioctl data                             */
6148 /*              cmd(I)  - ioctl command                                     */
6149 /*              mode(I) - mode value                                        */
6150 /*              uid(I)  - uid making the ioctl call                         */
6151 /*              ctx(I)  - pointer to context data                           */
6152 /*                                                                          */
6153 /* Based on the value of unit, call the appropriate ioctl handler or return */
6154 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6155 /* for the device in order to execute the ioctl.  A special case is made    */
6156 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6157 /* The context data pointer is passed through as this is used as the key    */
6158 /* for locating a matching token for continued access for walking lists,    */
6159 /* etc.                                                                     */
6160 /* ------------------------------------------------------------------------ */
6161 int
6162 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6163         ipf_main_softc_t *softc;
6164         int unit, mode, uid;
6165         ioctlcmd_t cmd;
6166         void *data, *ctx;
6167 {
6168         int error = 0;
6169
6170         switch (cmd)
6171         {
6172         case SIOCIPFINTERROR :
6173                 error = BCOPYOUT(&softc->ipf_interror, data,
6174                                  sizeof(softc->ipf_interror));
6175                 if (error != 0) {
6176                         IPFERROR(40);
6177                         error = EFAULT;
6178                 }
6179                 return error;
6180         default :
6181                 break;
6182         }
6183
6184         switch (unit)
6185         {
6186         case IPL_LOGIPF :
6187                 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6188                 break;
6189         case IPL_LOGNAT :
6190                 if (softc->ipf_running > 0) {
6191                         error = ipf_nat_ioctl(softc, data, cmd, mode,
6192                                               uid, ctx);
6193                 } else {
6194                         IPFERROR(42);
6195                         error = EIO;
6196                 }
6197                 break;
6198         case IPL_LOGSTATE :
6199                 if (softc->ipf_running > 0) {
6200                         error = ipf_state_ioctl(softc, data, cmd, mode,
6201                                                 uid, ctx);
6202                 } else {
6203                         IPFERROR(43);
6204                         error = EIO;
6205                 }
6206                 break;
6207         case IPL_LOGAUTH :
6208                 if (softc->ipf_running > 0) {
6209                         error = ipf_auth_ioctl(softc, data, cmd, mode,
6210                                                uid, ctx);
6211                 } else {
6212                         IPFERROR(44);
6213                         error = EIO;
6214                 }
6215                 break;
6216         case IPL_LOGSYNC :
6217                 if (softc->ipf_running > 0) {
6218                         error = ipf_sync_ioctl(softc, data, cmd, mode,
6219                                                uid, ctx);
6220                 } else {
6221                         error = EIO;
6222                         IPFERROR(45);
6223                 }
6224                 break;
6225         case IPL_LOGSCAN :
6226 #ifdef IPFILTER_SCAN
6227                 if (softc->ipf_running > 0)
6228                         error = ipf_scan_ioctl(softc, data, cmd, mode,
6229                                                uid, ctx);
6230                 else
6231 #endif
6232                 {
6233                         error = EIO;
6234                         IPFERROR(46);
6235                 }
6236                 break;
6237         case IPL_LOGLOOKUP :
6238                 if (softc->ipf_running > 0) {
6239                         error = ipf_lookup_ioctl(softc, data, cmd, mode,
6240                                                  uid, ctx);
6241                 } else {
6242                         error = EIO;
6243                         IPFERROR(47);
6244                 }
6245                 break;
6246         default :
6247                 IPFERROR(48);
6248                 error = EIO;
6249                 break;
6250         }
6251
6252         return error;
6253 }
6254
6255
6256 /*
6257  * This array defines the expected size of objects coming into the kernel
6258  * for the various recognised object types. The first column is flags (see
6259  * below), 2nd column is current size, 3rd column is the version number of
6260  * when the current size became current.
6261  * Flags:
6262  * 1 = minimum size, not absolute size
6263  */
6264 static const int        ipf_objbytes[IPFOBJ_COUNT][3] = {
6265         { 1,    sizeof(struct frentry),         5010000 },      /* 0 */
6266         { 1,    sizeof(struct friostat),        5010000 },
6267         { 0,    sizeof(struct fr_info),         5010000 },
6268         { 0,    sizeof(struct ipf_authstat),    4010100 },
6269         { 0,    sizeof(struct ipfrstat),        5010000 },
6270         { 1,    sizeof(struct ipnat),           5010000 },      /* 5 */
6271         { 0,    sizeof(struct natstat),         5010000 },
6272         { 0,    sizeof(struct ipstate_save),    5010000 },
6273         { 1,    sizeof(struct nat_save),        5010000 },
6274         { 0,    sizeof(struct natlookup),       5010000 },
6275         { 1,    sizeof(struct ipstate),         5010000 },      /* 10 */
6276         { 0,    sizeof(struct ips_stat),        5010000 },
6277         { 0,    sizeof(struct frauth),          5010000 },
6278         { 0,    sizeof(struct ipftune),         4010100 },
6279         { 0,    sizeof(struct nat),             5010000 },
6280         { 0,    sizeof(struct ipfruleiter),     4011400 },      /* 15 */
6281         { 0,    sizeof(struct ipfgeniter),      4011400 },
6282         { 0,    sizeof(struct ipftable),        4011400 },
6283         { 0,    sizeof(struct ipflookupiter),   4011400 },
6284         { 0,    sizeof(struct ipftq) * IPF_TCP_NSTATES },
6285         { 1,    0,                              0       }, /* IPFEXPR */
6286         { 0,    0,                              0       }, /* PROXYCTL */
6287         { 0,    sizeof (struct fripf),          5010000 }
6288 };
6289
6290
6291 /* ------------------------------------------------------------------------ */
6292 /* Function:    ipf_inobj                                                   */
6293 /* Returns:     int     - 0 = success, else failure                         */
6294 /* Parameters:  softc(I) - soft context pointerto work with                 */
6295 /*              data(I)  - pointer to ioctl data                            */
6296 /*              objp(O)  - where to store ipfobj structure                  */
6297 /*              ptr(I)   - pointer to data to copy out                      */
6298 /*              type(I)  - type of structure being moved                    */
6299 /*                                                                          */
6300 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6301 /* add things to check for version numbers, sizes, etc, to make it backward */
6302 /* compatible at the ABI for user land.                                     */
6303 /* If objp is not NULL then we assume that the caller wants to see what is  */
6304 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6305 /* the caller what version of ipfilter the ioctl program was written to.    */
6306 /* ------------------------------------------------------------------------ */
6307 int
6308 ipf_inobj(softc, data, objp, ptr, type)
6309         ipf_main_softc_t *softc;
6310         void *data;
6311         ipfobj_t *objp;
6312         void *ptr;
6313         int type;
6314 {
6315         ipfobj_t obj;
6316         int error;
6317         int size;
6318
6319         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6320                 IPFERROR(49);
6321                 return EINVAL;
6322         }
6323
6324         if (objp == NULL)
6325                 objp = &obj;
6326         error = BCOPYIN(data, objp, sizeof(*objp));
6327         if (error != 0) {
6328                 IPFERROR(124);
6329                 return EFAULT;
6330         }
6331
6332         if (objp->ipfo_type != type) {
6333                 IPFERROR(50);
6334                 return EINVAL;
6335         }
6336
6337         if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6338                 if ((ipf_objbytes[type][0] & 1) != 0) {
6339                         if (objp->ipfo_size < ipf_objbytes[type][1]) {
6340                                 IPFERROR(51);
6341                                 return EINVAL;
6342                         }
6343                         size =  ipf_objbytes[type][1];
6344                 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6345                         size =  objp->ipfo_size;
6346                 } else {
6347                         IPFERROR(52);
6348                         return EINVAL;
6349                 }
6350                 error = COPYIN(objp->ipfo_ptr, ptr, size);
6351                 if (error != 0) {
6352                         IPFERROR(55);
6353                         error = EFAULT;
6354                 }
6355         } else {
6356 #ifdef  IPFILTER_COMPAT
6357                 error = ipf_in_compat(softc, objp, ptr, 0);
6358 #else
6359                 IPFERROR(54);
6360                 error = EINVAL;
6361 #endif
6362         }
6363         return error;
6364 }
6365
6366
6367 /* ------------------------------------------------------------------------ */
6368 /* Function:    ipf_inobjsz                                                 */
6369 /* Returns:     int     - 0 = success, else failure                         */
6370 /* Parameters:  softc(I) - soft context pointerto work with                 */
6371 /*              data(I)  - pointer to ioctl data                            */
6372 /*              ptr(I)   - pointer to store real data in                    */
6373 /*              type(I)  - type of structure being moved                    */
6374 /*              sz(I)    - size of data to copy                             */
6375 /*                                                                          */
6376 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6377 /* but it must not be smaller than the size defined for the type and the    */
6378 /* type must allow for varied sized objects.  The extra requirement here is */
6379 /* that sz must match the size of the object being passed in - this is not  */
6380 /* not possible nor required in ipf_inobj().                                */
6381 /* ------------------------------------------------------------------------ */
6382 int
6383 ipf_inobjsz(softc, data, ptr, type, sz)
6384         ipf_main_softc_t *softc;
6385         void *data;
6386         void *ptr;
6387         int type, sz;
6388 {
6389         ipfobj_t obj;
6390         int error;
6391
6392         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6393                 IPFERROR(56);
6394                 return EINVAL;
6395         }
6396
6397         error = BCOPYIN(data, &obj, sizeof(obj));
6398         if (error != 0) {
6399                 IPFERROR(125);
6400                 return EFAULT;
6401         }
6402
6403         if (obj.ipfo_type != type) {
6404                 IPFERROR(58);
6405                 return EINVAL;
6406         }
6407
6408         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6409                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6410                     (sz < ipf_objbytes[type][1])) {
6411                         IPFERROR(57);
6412                         return EINVAL;
6413                 }
6414                 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6415                 if (error != 0) {
6416                         IPFERROR(61);
6417                         error = EFAULT;
6418                 }
6419         } else {
6420 #ifdef  IPFILTER_COMPAT
6421                 error = ipf_in_compat(softc, &obj, ptr, sz);
6422 #else
6423                 IPFERROR(60);
6424                 error = EINVAL;
6425 #endif
6426         }
6427         return error;
6428 }
6429
6430
6431 /* ------------------------------------------------------------------------ */
6432 /* Function:    ipf_outobjsz                                                */
6433 /* Returns:     int     - 0 = success, else failure                         */
6434 /* Parameters:  data(I) - pointer to ioctl data                             */
6435 /*              ptr(I)  - pointer to store real data in                     */
6436 /*              type(I) - type of structure being moved                     */
6437 /*              sz(I)   - size of data to copy                              */
6438 /*                                                                          */
6439 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6440 /* but it must not be smaller than the size defined for the type and the    */
6441 /* type must allow for varied sized objects.  The extra requirement here is */
6442 /* that sz must match the size of the object being passed in - this is not  */
6443 /* not possible nor required in ipf_outobj().                               */
6444 /* ------------------------------------------------------------------------ */
6445 int
6446 ipf_outobjsz(softc, data, ptr, type, sz)
6447         ipf_main_softc_t *softc;
6448         void *data;
6449         void *ptr;
6450         int type, sz;
6451 {
6452         ipfobj_t obj;
6453         int error;
6454
6455         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6456                 IPFERROR(62);
6457                 return EINVAL;
6458         }
6459
6460         error = BCOPYIN(data, &obj, sizeof(obj));
6461         if (error != 0) {
6462                 IPFERROR(127);
6463                 return EFAULT;
6464         }
6465
6466         if (obj.ipfo_type != type) {
6467                 IPFERROR(63);
6468                 return EINVAL;
6469         }
6470
6471         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6472                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6473                     (sz < ipf_objbytes[type][1])) {
6474                         IPFERROR(146);
6475                         return EINVAL;
6476                 }
6477                 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6478                 if (error != 0) {
6479                         IPFERROR(66);
6480                         error = EFAULT;
6481                 }
6482         } else {
6483 #ifdef  IPFILTER_COMPAT
6484                 error = ipf_out_compat(softc, &obj, ptr);
6485 #else
6486                 IPFERROR(65);
6487                 error = EINVAL;
6488 #endif
6489         }
6490         return error;
6491 }
6492
6493
6494 /* ------------------------------------------------------------------------ */
6495 /* Function:    ipf_outobj                                                  */
6496 /* Returns:     int     - 0 = success, else failure                         */
6497 /* Parameters:  data(I) - pointer to ioctl data                             */
6498 /*              ptr(I)  - pointer to store real data in                     */
6499 /*              type(I) - type of structure being moved                     */
6500 /*                                                                          */
6501 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6502 /* future, we add things to check for version numbers, sizes, etc, to make  */
6503 /* it backward  compatible at the ABI for user land.                        */
6504 /* ------------------------------------------------------------------------ */
6505 int
6506 ipf_outobj(softc, data, ptr, type)
6507         ipf_main_softc_t *softc;
6508         void *data;
6509         void *ptr;
6510         int type;
6511 {
6512         ipfobj_t obj;
6513         int error;
6514
6515         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6516                 IPFERROR(67);
6517                 return EINVAL;
6518         }
6519
6520         error = BCOPYIN(data, &obj, sizeof(obj));
6521         if (error != 0) {
6522                 IPFERROR(126);
6523                 return EFAULT;
6524         }
6525
6526         if (obj.ipfo_type != type) {
6527                 IPFERROR(68);
6528                 return EINVAL;
6529         }
6530
6531         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6532                 if ((ipf_objbytes[type][0] & 1) != 0) {
6533                         if (obj.ipfo_size < ipf_objbytes[type][1]) {
6534                                 IPFERROR(69);
6535                                 return EINVAL;
6536                         }
6537                 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6538                         IPFERROR(70);
6539                         return EINVAL;
6540                 }
6541
6542                 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6543                 if (error != 0) {
6544                         IPFERROR(73);
6545                         error = EFAULT;
6546                 }
6547         } else {
6548 #ifdef  IPFILTER_COMPAT
6549                 error = ipf_out_compat(softc, &obj, ptr);
6550 #else
6551                 IPFERROR(72);
6552                 error = EINVAL;
6553 #endif
6554         }
6555         return error;
6556 }
6557
6558
6559 /* ------------------------------------------------------------------------ */
6560 /* Function:    ipf_outobjk                                                 */
6561 /* Returns:     int     - 0 = success, else failure                         */
6562 /* Parameters:  obj(I)  - pointer to data description structure             */
6563 /*              ptr(I)  - pointer to kernel data to copy out                */
6564 /*                                                                          */
6565 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6566 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6567 /* already populated with information and now we just need to use it.       */
6568 /* There is no need for this function to have a "type" parameter as there   */
6569 /* is no point in validating information that comes from the kernel with    */
6570 /* itself.                                                                  */
6571 /* ------------------------------------------------------------------------ */
6572 int
6573 ipf_outobjk(softc, obj, ptr)
6574         ipf_main_softc_t *softc;
6575         ipfobj_t *obj;
6576         void *ptr;
6577 {
6578         int type = obj->ipfo_type;
6579         int error;
6580
6581         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6582                 IPFERROR(147);
6583                 return EINVAL;
6584         }
6585
6586         if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6587                 if ((ipf_objbytes[type][0] & 1) != 0) {
6588                         if (obj->ipfo_size < ipf_objbytes[type][1]) {
6589                                 IPFERROR(148);
6590                                 return EINVAL;
6591                         }
6592
6593                 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6594                         IPFERROR(149);
6595                         return EINVAL;
6596                 }
6597
6598                 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6599                 if (error != 0) {
6600                         IPFERROR(150);
6601                         error = EFAULT;
6602                 }
6603         } else {
6604 #ifdef  IPFILTER_COMPAT
6605                 error = ipf_out_compat(softc, obj, ptr);
6606 #else
6607                 IPFERROR(151);
6608                 error = EINVAL;
6609 #endif
6610         }
6611         return error;
6612 }
6613
6614
6615 /* ------------------------------------------------------------------------ */
6616 /* Function:    ipf_checkl4sum                                              */
6617 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6618 /* Parameters:  fin(I) - pointer to packet information                      */
6619 /*                                                                          */
6620 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6621 /* not possible, return without indicating a failure or success but in a    */
6622 /* way that is ditinguishable. This function should only be called by the   */
6623 /* ipf_checkv6sum() for each platform.                                      */
6624 /* ------------------------------------------------------------------------ */
6625 INLINE int
6626 ipf_checkl4sum(fin)
6627         fr_info_t *fin;
6628 {
6629         u_short sum, hdrsum, *csump;
6630         udphdr_t *udp;
6631         int dosum;
6632
6633         /*
6634          * If the TCP packet isn't a fragment, isn't too short and otherwise
6635          * isn't already considered "bad", then validate the checksum.  If
6636          * this check fails then considered the packet to be "bad".
6637          */
6638         if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6639                 return 1;
6640
6641         DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6642         if (fin->fin_out == 1) {
6643                 fin->fin_cksum = FI_CK_SUMOK;
6644                 return 0;
6645         }
6646
6647         csump = NULL;
6648         hdrsum = 0;
6649         dosum = 0;
6650         sum = 0;
6651
6652         switch (fin->fin_p)
6653         {
6654         case IPPROTO_TCP :
6655                 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6656                 dosum = 1;
6657                 break;
6658
6659         case IPPROTO_UDP :
6660                 udp = fin->fin_dp;
6661                 if (udp->uh_sum != 0) {
6662                         csump = &udp->uh_sum;
6663                         dosum = 1;
6664                 }
6665                 break;
6666
6667 #ifdef USE_INET6
6668         case IPPROTO_ICMPV6 :
6669                 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6670                 dosum = 1;
6671                 break;
6672 #endif
6673
6674         case IPPROTO_ICMP :
6675                 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6676                 dosum = 1;
6677                 break;
6678
6679         default :
6680                 return 1;
6681                 /*NOTREACHED*/
6682         }
6683
6684         if (csump != NULL)
6685                 hdrsum = *csump;
6686
6687         if (dosum) {
6688                 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6689         }
6690 #if !defined(_KERNEL)
6691         if (sum == hdrsum) {
6692                 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6693         } else {
6694                 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6695         }
6696 #endif
6697         DT2(l4sums, u_short, hdrsum, u_short, sum);
6698 #ifdef USE_INET6
6699         if (hdrsum == sum || (sum == 0 && fin->fin_p == IPPROTO_ICMPV6)) {
6700 #else
6701         if (hdrsum == sum) {
6702 #endif
6703                 fin->fin_cksum = FI_CK_SUMOK;
6704                 return 0;
6705         }
6706         fin->fin_cksum = FI_CK_BAD;
6707         return -1;
6708 }
6709
6710
6711 /* ------------------------------------------------------------------------ */
6712 /* Function:    ipf_ifpfillv4addr                                           */
6713 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6714 /* Parameters:  atype(I)   - type of network address update to perform      */
6715 /*              sin(I)     - pointer to source of address information       */
6716 /*              mask(I)    - pointer to source of netmask information       */
6717 /*              inp(I)     - pointer to destination address store           */
6718 /*              inpmask(I) - pointer to destination netmask store           */
6719 /*                                                                          */
6720 /* Given a type of network address update (atype) to perform, copy          */
6721 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6722 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6723 /* which case the operation fails.  For all values of atype other than      */
6724 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6725 /* value.                                                                   */
6726 /* ------------------------------------------------------------------------ */
6727 int
6728 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6729         int atype;
6730         struct sockaddr_in *sin, *mask;
6731         struct in_addr *inp, *inpmask;
6732 {
6733         if (inpmask != NULL && atype != FRI_NETMASKED)
6734                 inpmask->s_addr = 0xffffffff;
6735
6736         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6737                 if (atype == FRI_NETMASKED) {
6738                         if (inpmask == NULL)
6739                                 return -1;
6740                         inpmask->s_addr = mask->sin_addr.s_addr;
6741                 }
6742                 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6743         } else {
6744                 inp->s_addr = sin->sin_addr.s_addr;
6745         }
6746         return 0;
6747 }
6748
6749
6750 #ifdef  USE_INET6
6751 /* ------------------------------------------------------------------------ */
6752 /* Function:    ipf_ifpfillv6addr                                           */
6753 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6754 /* Parameters:  atype(I)   - type of network address update to perform      */
6755 /*              sin(I)     - pointer to source of address information       */
6756 /*              mask(I)    - pointer to source of netmask information       */
6757 /*              inp(I)     - pointer to destination address store           */
6758 /*              inpmask(I) - pointer to destination netmask store           */
6759 /*                                                                          */
6760 /* Given a type of network address update (atype) to perform, copy          */
6761 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6762 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6763 /* which case the operation fails.  For all values of atype other than      */
6764 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6765 /* value.                                                                   */
6766 /* ------------------------------------------------------------------------ */
6767 int
6768 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6769         int atype;
6770         struct sockaddr_in6 *sin, *mask;
6771         i6addr_t *inp, *inpmask;
6772 {
6773         i6addr_t *src, *and;
6774
6775         src = (i6addr_t *)&sin->sin6_addr;
6776         and = (i6addr_t *)&mask->sin6_addr;
6777
6778         if (inpmask != NULL && atype != FRI_NETMASKED) {
6779                 inpmask->i6[0] = 0xffffffff;
6780                 inpmask->i6[1] = 0xffffffff;
6781                 inpmask->i6[2] = 0xffffffff;
6782                 inpmask->i6[3] = 0xffffffff;
6783         }
6784
6785         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6786                 if (atype == FRI_NETMASKED) {
6787                         if (inpmask == NULL)
6788                                 return -1;
6789                         inpmask->i6[0] = and->i6[0];
6790                         inpmask->i6[1] = and->i6[1];
6791                         inpmask->i6[2] = and->i6[2];
6792                         inpmask->i6[3] = and->i6[3];
6793                 }
6794
6795                 inp->i6[0] = src->i6[0] & and->i6[0];
6796                 inp->i6[1] = src->i6[1] & and->i6[1];
6797                 inp->i6[2] = src->i6[2] & and->i6[2];
6798                 inp->i6[3] = src->i6[3] & and->i6[3];
6799         } else {
6800                 inp->i6[0] = src->i6[0];
6801                 inp->i6[1] = src->i6[1];
6802                 inp->i6[2] = src->i6[2];
6803                 inp->i6[3] = src->i6[3];
6804         }
6805         return 0;
6806 }
6807 #endif
6808
6809
6810 /* ------------------------------------------------------------------------ */
6811 /* Function:    ipf_matchtag                                                */
6812 /* Returns:     0 == mismatch, 1 == match.                                  */
6813 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6814 /*              tag2(I) - pointer to second tag to compare                  */
6815 /*                                                                          */
6816 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6817 /* considered to be a match or not match, respectively.  The tag is 16      */
6818 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6819 /* compare the ints instead, for speed. tag1 is the master of the           */
6820 /* comparison.  This function should only be called with both tag1 and tag2 */
6821 /* as non-NULL pointers.                                                    */
6822 /* ------------------------------------------------------------------------ */
6823 int
6824 ipf_matchtag(tag1, tag2)
6825         ipftag_t *tag1, *tag2;
6826 {
6827         if (tag1 == tag2)
6828                 return 1;
6829
6830         if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6831                 return 1;
6832
6833         if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6834             (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6835             (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6836             (tag1->ipt_num[3] == tag2->ipt_num[3]))
6837                 return 1;
6838         return 0;
6839 }
6840
6841
6842 /* ------------------------------------------------------------------------ */
6843 /* Function:    ipf_coalesce                                                */
6844 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6845 /* Parameters:  fin(I) - pointer to packet information                      */
6846 /*                                                                          */
6847 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6848 /* If this call returns a failure then the buffers have also been freed.    */
6849 /* ------------------------------------------------------------------------ */
6850 int
6851 ipf_coalesce(fin)
6852         fr_info_t *fin;
6853 {
6854
6855         if ((fin->fin_flx & FI_COALESCE) != 0)
6856                 return 1;
6857
6858         /*
6859          * If the mbuf pointers indicate that there is no mbuf to work with,
6860          * return but do not indicate success or failure.
6861          */
6862         if (fin->fin_m == NULL || fin->fin_mp == NULL)
6863                 return 0;
6864
6865 #if defined(_KERNEL)
6866         if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6867                 ipf_main_softc_t *softc = fin->fin_main_soft;
6868
6869                 DT1(frb_coalesce, fr_info_t *, fin);
6870                 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6871 # ifdef MENTAT
6872                 FREE_MB_T(*fin->fin_mp);
6873 # endif
6874                 fin->fin_reason = FRB_COALESCE;
6875                 *fin->fin_mp = NULL;
6876                 fin->fin_m = NULL;
6877                 return -1;
6878         }
6879 #else
6880         fin = fin;      /* LINT */
6881 #endif
6882         return 1;
6883 }
6884
6885
6886 /*
6887  * The following table lists all of the tunable variables that can be
6888  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6889  * in the table below is as follows:
6890  *
6891  * pointer to value, name of value, minimum, maximum, size of the value's
6892  *     container, value attribute flags
6893  *
6894  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6895  * means the value can only be written to when IPFilter is loaded but disabled.
6896  * The obvious implication is if neither of these are set then the value can be
6897  * changed at any time without harm.
6898  */
6899
6900
6901 /* ------------------------------------------------------------------------ */
6902 /* Function:    ipf_tune_findbycookie                                       */
6903 /* Returns:     NULL = search failed, else pointer to tune struct           */
6904 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6905 /*              next(O)   - pointer to place to store the cookie for the    */
6906 /*                          "next" tuneable, if it is desired.              */
6907 /*                                                                          */
6908 /* This function is used to walk through all of the existing tunables with  */
6909 /* successive calls.  It searches the known tunables for the one which has  */
6910 /* a matching value for "cookie" - ie its address.  When returning a match, */
6911 /* the next one to be found may be returned inside next.                    */
6912 /* ------------------------------------------------------------------------ */
6913 static ipftuneable_t *
6914 ipf_tune_findbycookie(ptop, cookie, next)
6915         ipftuneable_t **ptop;
6916         void *cookie, **next;
6917 {
6918         ipftuneable_t *ta, **tap;
6919
6920         for (ta = *ptop; ta->ipft_name != NULL; ta++)
6921                 if (ta == cookie) {
6922                         if (next != NULL) {
6923                                 /*
6924                                  * If the next entry in the array has a name
6925                                  * present, then return a pointer to it for
6926                                  * where to go next, else return a pointer to
6927                                  * the dynaminc list as a key to search there
6928                                  * next.  This facilitates a weak linking of
6929                                  * the two "lists" together.
6930                                  */
6931                                 if ((ta + 1)->ipft_name != NULL)
6932                                         *next = ta + 1;
6933                                 else
6934                                         *next = ptop;
6935                         }
6936                         return ta;
6937                 }
6938
6939         for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6940                 if (tap == cookie) {
6941                         if (next != NULL)
6942                                 *next = &ta->ipft_next;
6943                         return ta;
6944                 }
6945
6946         if (next != NULL)
6947                 *next = NULL;
6948         return NULL;
6949 }
6950
6951
6952 /* ------------------------------------------------------------------------ */
6953 /* Function:    ipf_tune_findbyname                                         */
6954 /* Returns:     NULL = search failed, else pointer to tune struct           */
6955 /* Parameters:  name(I) - name of the tuneable entry to find.               */
6956 /*                                                                          */
6957 /* Search the static array of tuneables and the list of dynamic tuneables   */
6958 /* for an entry with a matching name.  If we can find one, return a pointer */
6959 /* to the matching structure.                                               */
6960 /* ------------------------------------------------------------------------ */
6961 static ipftuneable_t *
6962 ipf_tune_findbyname(top, name)
6963         ipftuneable_t *top;
6964         const char *name;
6965 {
6966         ipftuneable_t *ta;
6967
6968         for (ta = top; ta != NULL; ta = ta->ipft_next)
6969                 if (!strcmp(ta->ipft_name, name)) {
6970                         return ta;
6971                 }
6972
6973         return NULL;
6974 }
6975
6976
6977 /* ------------------------------------------------------------------------ */
6978 /* Function:    ipf_tune_add_array                                          */
6979 /* Returns:     int - 0 == success, else failure                            */
6980 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
6981 /*                                                                          */
6982 /* Appends tune structures from the array passed in (newtune) to the end of */
6983 /* the current list of "dynamic" tuneable parameters.                       */
6984 /* If any entry to be added is already present (by name) then the operation */
6985 /* is aborted - entries that have been added are removed before returning.  */
6986 /* An entry with no name (NULL) is used as the indication that the end of   */
6987 /* the array has been reached.                                              */
6988 /* ------------------------------------------------------------------------ */
6989 int
6990 ipf_tune_add_array(softc, newtune)
6991         ipf_main_softc_t *softc;
6992         ipftuneable_t *newtune;
6993 {
6994         ipftuneable_t *nt, *dt;
6995         int error = 0;
6996
6997         for (nt = newtune; nt->ipft_name != NULL; nt++) {
6998                 error = ipf_tune_add(softc, nt);
6999                 if (error != 0) {
7000                         for (dt = newtune; dt != nt; dt++) {
7001                                 (void) ipf_tune_del(softc, dt);
7002                         }
7003                 }
7004         }
7005
7006         return error;
7007 }
7008
7009
7010 /* ------------------------------------------------------------------------ */
7011 /* Function:    ipf_tune_array_link                                         */
7012 /* Returns:     0 == success, -1 == failure                                 */
7013 /* Parameters:  softc(I) - soft context pointerto work with                 */
7014 /*              array(I) - pointer to an array of tuneables                 */
7015 /*                                                                          */
7016 /* Given an array of tunables (array), append them to the current list of   */
7017 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7018 /* the array for being appended to the list, initialise all of the next     */
7019 /* pointers so we don't need to walk parts of it with ++ and others with    */
7020 /* next. The array is expected to have an entry with a NULL name as the     */
7021 /* terminator. Trying to add an array with no non-NULL names will return as */
7022 /* a failure.                                                               */
7023 /* ------------------------------------------------------------------------ */
7024 int
7025 ipf_tune_array_link(softc, array)
7026         ipf_main_softc_t *softc;
7027         ipftuneable_t *array;
7028 {
7029         ipftuneable_t *t, **p;
7030
7031         t = array;
7032         if (t->ipft_name == NULL)
7033                 return -1;
7034
7035         for (; t[1].ipft_name != NULL; t++)
7036                 t[0].ipft_next = &t[1];
7037         t->ipft_next = NULL;
7038
7039         /*
7040          * Since a pointer to the last entry isn't kept, we need to find it
7041          * each time we want to add new variables to the list.
7042          */
7043         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7044                 if (t->ipft_name == NULL)
7045                         break;
7046         *p = array;
7047
7048         return 0;
7049 }
7050
7051
7052 /* ------------------------------------------------------------------------ */
7053 /* Function:    ipf_tune_array_unlink                                       */
7054 /* Returns:     0 == success, -1 == failure                                 */
7055 /* Parameters:  softc(I) - soft context pointerto work with                 */
7056 /*              array(I) - pointer to an array of tuneables                 */
7057 /*                                                                          */
7058 /* ------------------------------------------------------------------------ */
7059 int
7060 ipf_tune_array_unlink(softc, array)
7061         ipf_main_softc_t *softc;
7062         ipftuneable_t *array;
7063 {
7064         ipftuneable_t *t, **p;
7065
7066         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7067                 if (t == array)
7068                         break;
7069         if (t == NULL)
7070                 return -1;
7071
7072         for (; t[1].ipft_name != NULL; t++)
7073                 ;
7074
7075         *p = t->ipft_next;
7076
7077         return 0;
7078 }
7079
7080
7081 /* ------------------------------------------------------------------------ */
7082 /* Function:   ipf_tune_array_copy                                          */
7083 /* Returns:    NULL = failure, else pointer to new array                    */
7084 /* Parameters: base(I)     - pointer to structure base                      */
7085 /*             size(I)     - size of the array at template                  */
7086 /*             template(I) - original array to copy                         */
7087 /*                                                                          */
7088 /* Allocate memory for a new set of tuneable values and copy everything     */
7089 /* from template into the new region of memory.  The new region is full of  */
7090 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7091 /*                                                                          */
7092 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7093 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
7094 /* location of the tuneable value inside the structure pointed to by base.  */
7095 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7096 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7097 /* ipftp_void that points to the stored value.                              */
7098 /* ------------------------------------------------------------------------ */
7099 ipftuneable_t *
7100 ipf_tune_array_copy(base, size, template)
7101         void *base;
7102         size_t size;
7103         ipftuneable_t *template;
7104 {
7105         ipftuneable_t *copy;
7106         int i;
7107
7108
7109         KMALLOCS(copy, ipftuneable_t *, size);
7110         if (copy == NULL) {
7111                 return NULL;
7112         }
7113         bcopy(template, copy, size);
7114
7115         for (i = 0; copy[i].ipft_name; i++) {
7116                 copy[i].ipft_una.ipftp_offset += (u_long)base;
7117                 copy[i].ipft_next = copy + i + 1;
7118         }
7119
7120         return copy;
7121 }
7122
7123
7124 /* ------------------------------------------------------------------------ */
7125 /* Function:    ipf_tune_add                                                */
7126 /* Returns:     int - 0 == success, else failure                            */
7127 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7128 /*                                                                          */
7129 /* Appends tune structures from the array passed in (newtune) to the end of */
7130 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
7131 /* owner of the object is not expected to ever change "ipft_next".          */
7132 /* ------------------------------------------------------------------------ */
7133 int
7134 ipf_tune_add(softc, newtune)
7135         ipf_main_softc_t *softc;
7136         ipftuneable_t *newtune;
7137 {
7138         ipftuneable_t *ta, **tap;
7139
7140         ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7141         if (ta != NULL) {
7142                 IPFERROR(74);
7143                 return EEXIST;
7144         }
7145
7146         for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7147                 ;
7148
7149         newtune->ipft_next = NULL;
7150         *tap = newtune;
7151         return 0;
7152 }
7153
7154
7155 /* ------------------------------------------------------------------------ */
7156 /* Function:    ipf_tune_del                                                */
7157 /* Returns:     int - 0 == success, else failure                            */
7158 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7159 /*                        current dynamic tuneables                         */
7160 /*                                                                          */
7161 /* Search for the tune structure, by pointer, in the list of those that are */
7162 /* dynamically added at run time.  If found, adjust the list so that this   */
7163 /* structure is no longer part of it.                                       */
7164 /* ------------------------------------------------------------------------ */
7165 int
7166 ipf_tune_del(softc, oldtune)
7167         ipf_main_softc_t *softc;
7168         ipftuneable_t *oldtune;
7169 {
7170         ipftuneable_t *ta, **tap;
7171         int error = 0;
7172
7173         for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7174              tap = &ta->ipft_next) {
7175                 if (ta == oldtune) {
7176                         *tap = oldtune->ipft_next;
7177                         oldtune->ipft_next = NULL;
7178                         break;
7179                 }
7180         }
7181
7182         if (ta == NULL) {
7183                 error = ESRCH;
7184                 IPFERROR(75);
7185         }
7186         return error;
7187 }
7188
7189
7190 /* ------------------------------------------------------------------------ */
7191 /* Function:    ipf_tune_del_array                                          */
7192 /* Returns:     int - 0 == success, else failure                            */
7193 /* Parameters:  oldtune - pointer to tuneables array                        */
7194 /*                                                                          */
7195 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7196 /* tunables.  If one entry should fail to be found, an error will be        */
7197 /* returned and no further ones removed.                                    */
7198 /* An entry with a NULL name is used as the indicator of the last entry in  */
7199 /* the array.                                                               */
7200 /* ------------------------------------------------------------------------ */
7201 int
7202 ipf_tune_del_array(softc, oldtune)
7203         ipf_main_softc_t *softc;
7204         ipftuneable_t *oldtune;
7205 {
7206         ipftuneable_t *ot;
7207         int error = 0;
7208
7209         for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7210                 error = ipf_tune_del(softc, ot);
7211                 if (error != 0)
7212                         break;
7213         }
7214
7215         return error;
7216
7217 }
7218
7219
7220 /* ------------------------------------------------------------------------ */
7221 /* Function:    ipf_tune                                                    */
7222 /* Returns:     int - 0 == success, else failure                            */
7223 /* Parameters:  cmd(I)  - ioctl command number                              */
7224 /*              data(I) - pointer to ioctl data structure                   */
7225 /*                                                                          */
7226 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7227 /* three ioctls provide the means to access and control global variables    */
7228 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7229 /* changed without rebooting, reloading or recompiling.  The initialisation */
7230 /* and 'destruction' routines of the various components of ipfilter are all */
7231 /* each responsible for handling their own values being too big.            */
7232 /* ------------------------------------------------------------------------ */
7233 int
7234 ipf_ipftune(softc, cmd, data)
7235         ipf_main_softc_t *softc;
7236         ioctlcmd_t cmd;
7237         void *data;
7238 {
7239         ipftuneable_t *ta;
7240         ipftune_t tu;
7241         void *cookie;
7242         int error;
7243
7244         error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7245         if (error != 0)
7246                 return error;
7247
7248         tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7249         cookie = tu.ipft_cookie;
7250         ta = NULL;
7251
7252         switch (cmd)
7253         {
7254         case SIOCIPFGETNEXT :
7255                 /*
7256                  * If cookie is non-NULL, assume it to be a pointer to the last
7257                  * entry we looked at, so find it (if possible) and return a
7258                  * pointer to the next one after it.  The last entry in the
7259                  * the table is a NULL entry, so when we get to it, set cookie
7260                  * to NULL and return that, indicating end of list, erstwhile
7261                  * if we come in with cookie set to NULL, we are starting anew
7262                  * at the front of the list.
7263                  */
7264                 if (cookie != NULL) {
7265                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7266                                                    cookie, &tu.ipft_cookie);
7267                 } else {
7268                         ta = softc->ipf_tuners;
7269                         tu.ipft_cookie = ta + 1;
7270                 }
7271                 if (ta != NULL) {
7272                         /*
7273                          * Entry found, but does the data pointed to by that
7274                          * row fit in what we can return?
7275                          */
7276                         if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7277                                 IPFERROR(76);
7278                                 return EINVAL;
7279                         }
7280
7281                         tu.ipft_vlong = 0;
7282                         if (ta->ipft_sz == sizeof(u_long))
7283                                 tu.ipft_vlong = *ta->ipft_plong;
7284                         else if (ta->ipft_sz == sizeof(u_int))
7285                                 tu.ipft_vint = *ta->ipft_pint;
7286                         else if (ta->ipft_sz == sizeof(u_short))
7287                                 tu.ipft_vshort = *ta->ipft_pshort;
7288                         else if (ta->ipft_sz == sizeof(u_char))
7289                                 tu.ipft_vchar = *ta->ipft_pchar;
7290
7291                         tu.ipft_sz = ta->ipft_sz;
7292                         tu.ipft_min = ta->ipft_min;
7293                         tu.ipft_max = ta->ipft_max;
7294                         tu.ipft_flags = ta->ipft_flags;
7295                         bcopy(ta->ipft_name, tu.ipft_name,
7296                               MIN(sizeof(tu.ipft_name),
7297                                   strlen(ta->ipft_name) + 1));
7298                 }
7299                 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7300                 break;
7301
7302         case SIOCIPFGET :
7303         case SIOCIPFSET :
7304                 /*
7305                  * Search by name or by cookie value for a particular entry
7306                  * in the tuning paramter table.
7307                  */
7308                 IPFERROR(77);
7309                 error = ESRCH;
7310                 if (cookie != NULL) {
7311                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7312                                                    cookie, NULL);
7313                         if (ta != NULL)
7314                                 error = 0;
7315                 } else if (tu.ipft_name[0] != '\0') {
7316                         ta = ipf_tune_findbyname(softc->ipf_tuners,
7317                                                  tu.ipft_name);
7318                         if (ta != NULL)
7319                                 error = 0;
7320                 }
7321                 if (error != 0)
7322                         break;
7323
7324                 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7325                         /*
7326                          * Fetch the tuning parameters for a particular value
7327                          */
7328                         tu.ipft_vlong = 0;
7329                         if (ta->ipft_sz == sizeof(u_long))
7330                                 tu.ipft_vlong = *ta->ipft_plong;
7331                         else if (ta->ipft_sz == sizeof(u_int))
7332                                 tu.ipft_vint = *ta->ipft_pint;
7333                         else if (ta->ipft_sz == sizeof(u_short))
7334                                 tu.ipft_vshort = *ta->ipft_pshort;
7335                         else if (ta->ipft_sz == sizeof(u_char))
7336                                 tu.ipft_vchar = *ta->ipft_pchar;
7337                         tu.ipft_cookie = ta;
7338                         tu.ipft_sz = ta->ipft_sz;
7339                         tu.ipft_min = ta->ipft_min;
7340                         tu.ipft_max = ta->ipft_max;
7341                         tu.ipft_flags = ta->ipft_flags;
7342                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7343
7344                 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7345                         /*
7346                          * Set an internal parameter.  The hard part here is
7347                          * getting the new value safely and correctly out of
7348                          * the kernel (given we only know its size, not type.)
7349                          */
7350                         u_long in;
7351
7352                         if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7353                             (softc->ipf_running > 0)) {
7354                                 IPFERROR(78);
7355                                 error = EBUSY;
7356                                 break;
7357                         }
7358
7359                         in = tu.ipft_vlong;
7360                         if (in < ta->ipft_min || in > ta->ipft_max) {
7361                                 IPFERROR(79);
7362                                 error = EINVAL;
7363                                 break;
7364                         }
7365
7366                         if (ta->ipft_func != NULL) {
7367                                 SPL_INT(s);
7368
7369                                 SPL_NET(s);
7370                                 error = (*ta->ipft_func)(softc, ta,
7371                                                          &tu.ipft_un);
7372                                 SPL_X(s);
7373
7374                         } else if (ta->ipft_sz == sizeof(u_long)) {
7375                                 tu.ipft_vlong = *ta->ipft_plong;
7376                                 *ta->ipft_plong = in;
7377
7378                         } else if (ta->ipft_sz == sizeof(u_int)) {
7379                                 tu.ipft_vint = *ta->ipft_pint;
7380                                 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7381
7382                         } else if (ta->ipft_sz == sizeof(u_short)) {
7383                                 tu.ipft_vshort = *ta->ipft_pshort;
7384                                 *ta->ipft_pshort = (u_short)(in & 0xffff);
7385
7386                         } else if (ta->ipft_sz == sizeof(u_char)) {
7387                                 tu.ipft_vchar = *ta->ipft_pchar;
7388                                 *ta->ipft_pchar = (u_char)(in & 0xff);
7389                         }
7390                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7391                 }
7392                 break;
7393
7394         default :
7395                 IPFERROR(80);
7396                 error = EINVAL;
7397                 break;
7398         }
7399
7400         return error;
7401 }
7402
7403
7404 /* ------------------------------------------------------------------------ */
7405 /* Function:    ipf_zerostats                                               */
7406 /* Returns:     int - 0 = success, else failure                             */
7407 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7408 /*                                                                          */
7409 /* Copies the current statistics out to userspace and then zero's the       */
7410 /* current ones in the kernel. The lock is only held across the bzero() as  */
7411 /* the copyout may result in paging (ie network activity.)                  */
7412 /* ------------------------------------------------------------------------ */
7413 int
7414 ipf_zerostats(softc, data)
7415         ipf_main_softc_t *softc;
7416         caddr_t data;
7417 {
7418         friostat_t fio;
7419         ipfobj_t obj;
7420         int error;
7421
7422         error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7423         if (error != 0)
7424                 return error;
7425         ipf_getstat(softc, &fio, obj.ipfo_rev);
7426         error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7427         if (error != 0)
7428                 return error;
7429
7430         WRITE_ENTER(&softc->ipf_mutex);
7431         bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7432         RWLOCK_EXIT(&softc->ipf_mutex);
7433
7434         return 0;
7435 }
7436
7437
7438 /* ------------------------------------------------------------------------ */
7439 /* Function:    ipf_resolvedest                                             */
7440 /* Returns:     Nil                                                         */
7441 /* Parameters:  softc(I) - pointer to soft context main structure           */
7442 /*              base(I)  - where strings are stored                         */
7443 /*              fdp(IO)  - pointer to destination information to resolve    */
7444 /*              v(I)     - IP protocol version to match                     */
7445 /*                                                                          */
7446 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7447 /* if a matching name can be found for the particular IP protocol version   */
7448 /* then store the interface pointer in the frdest struct.  If no match is   */
7449 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7450 /* indicate there is no information at all in the structure.                */
7451 /* ------------------------------------------------------------------------ */
7452 int
7453 ipf_resolvedest(softc, base, fdp, v)
7454         ipf_main_softc_t *softc;
7455         char *base;
7456         frdest_t *fdp;
7457         int v;
7458 {
7459         int errval = 0;
7460         void *ifp;
7461
7462         ifp = NULL;
7463
7464         if (fdp->fd_name != -1) {
7465                 if (fdp->fd_type == FRD_DSTLIST) {
7466                         ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7467                                                   IPLT_DSTLIST,
7468                                                   base + fdp->fd_name,
7469                                                   NULL);
7470                         if (ifp == NULL) {
7471                                 IPFERROR(144);
7472                                 errval = ESRCH;
7473                         }
7474                 } else {
7475                         ifp = GETIFP(base + fdp->fd_name, v);
7476                         if (ifp == NULL)
7477                                 ifp = (void *)-1;
7478                 }
7479         }
7480         fdp->fd_ptr = ifp;
7481
7482         return errval;
7483 }
7484
7485
7486 /* ------------------------------------------------------------------------ */
7487 /* Function:    ipf_resolvenic                                              */
7488 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7489 /*                      pointer to interface structure for NIC              */
7490 /* Parameters:  softc(I)- pointer to soft context main structure            */
7491 /*              name(I) - complete interface name                           */
7492 /*              v(I)    - IP protocol version                               */
7493 /*                                                                          */
7494 /* Look for a network interface structure that firstly has a matching name  */
7495 /* to that passed in and that is also being used for that IP protocol       */
7496 /* version (necessary on some platforms where there are separate listings   */
7497 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7498 /* ------------------------------------------------------------------------ */
7499 void *
7500 ipf_resolvenic(softc, name, v)
7501         ipf_main_softc_t *softc;
7502         char *name;
7503         int v;
7504 {
7505         void *nic;
7506
7507         softc = softc;  /* gcc -Wextra */
7508         if (name[0] == '\0')
7509                 return NULL;
7510
7511         if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7512                 return NULL;
7513         }
7514
7515         nic = GETIFP(name, v);
7516         if (nic == NULL)
7517                 nic = (void *)-1;
7518         return nic;
7519 }
7520
7521
7522 /* ------------------------------------------------------------------------ */
7523 /* Function:    ipf_token_expire                                            */
7524 /* Returns:     None.                                                       */
7525 /* Parameters:  softc(I) - pointer to soft context main structure           */
7526 /*                                                                          */
7527 /* This function is run every ipf tick to see if there are any tokens that  */
7528 /* have been held for too long and need to be freed up.                     */
7529 /* ------------------------------------------------------------------------ */
7530 void
7531 ipf_token_expire(softc)
7532         ipf_main_softc_t *softc;
7533 {
7534         ipftoken_t *it;
7535
7536         WRITE_ENTER(&softc->ipf_tokens);
7537         while ((it = softc->ipf_token_head) != NULL) {
7538                 if (it->ipt_die > softc->ipf_ticks)
7539                         break;
7540
7541                 ipf_token_deref(softc, it);
7542         }
7543         RWLOCK_EXIT(&softc->ipf_tokens);
7544 }
7545
7546
7547 /* ------------------------------------------------------------------------ */
7548 /* Function:    ipf_token_flush                                             */
7549 /* Returns:     None.                                                       */
7550 /* Parameters:  softc(I) - pointer to soft context main structure           */
7551 /*                                                                          */
7552 /* Loop through all of the existing tokens and call deref to see if they    */
7553 /* can be freed. Normally a function like this might just loop on           */
7554 /* ipf_token_head but there is a chance that a token might have a ref count */
7555 /* of greater than one and in that case the the reference would drop twice  */
7556 /* by code that is only entitled to drop it once.                           */
7557 /* ------------------------------------------------------------------------ */
7558 static void
7559 ipf_token_flush(softc)
7560         ipf_main_softc_t *softc;
7561 {
7562         ipftoken_t *it, *next;
7563
7564         WRITE_ENTER(&softc->ipf_tokens);
7565         for (it = softc->ipf_token_head; it != NULL; it = next) {
7566                 next = it->ipt_next;
7567                 (void) ipf_token_deref(softc, it);
7568         }
7569         RWLOCK_EXIT(&softc->ipf_tokens);
7570 }
7571
7572
7573 /* ------------------------------------------------------------------------ */
7574 /* Function:    ipf_token_del                                               */
7575 /* Returns:     int     - 0 = success, else error                           */
7576 /* Parameters:  softc(I)- pointer to soft context main structure            */
7577 /*              type(I) - the token type to match                           */
7578 /*              uid(I)  - uid owning the token                              */
7579 /*              ptr(I)  - context pointer for the token                     */
7580 /*                                                                          */
7581 /* This function looks for a a token in the current list that matches up    */
7582 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7583 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7584 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7585 /* enables debugging to distinguish between the two paths that ultimately   */
7586 /* lead to a token to be deleted.                                           */
7587 /* ------------------------------------------------------------------------ */
7588 int
7589 ipf_token_del(softc, type, uid, ptr)
7590         ipf_main_softc_t *softc;
7591         int type, uid;
7592         void *ptr;
7593 {
7594         ipftoken_t *it;
7595         int error;
7596
7597         IPFERROR(82);
7598         error = ESRCH;
7599
7600         WRITE_ENTER(&softc->ipf_tokens);
7601         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7602                 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7603                     uid == it->ipt_uid) {
7604                         it->ipt_complete = 2;
7605                         ipf_token_deref(softc, it);
7606                         error = 0;
7607                         break;
7608                 }
7609         }
7610         RWLOCK_EXIT(&softc->ipf_tokens);
7611
7612         return error;
7613 }
7614
7615
7616 /* ------------------------------------------------------------------------ */
7617 /* Function:    ipf_token_mark_complete                                     */
7618 /* Returns:     None.                                                       */
7619 /* Parameters:  token(I) - pointer to token structure                       */
7620 /*                                                                          */
7621 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7622 /* ------------------------------------------------------------------------ */
7623 void
7624 ipf_token_mark_complete(token)
7625         ipftoken_t *token;
7626 {
7627         if (token->ipt_complete == 0)
7628                 token->ipt_complete = 1;
7629 }
7630
7631
7632 /* ------------------------------------------------------------------------ */
7633 /* Function:    ipf_token_find                                               */
7634 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7635 /* Parameters:  softc(I)- pointer to soft context main structure            */
7636 /*              type(I) - the token type to match                           */
7637 /*              uid(I)  - uid owning the token                              */
7638 /*              ptr(I)  - context pointer for the token                     */
7639 /*                                                                          */
7640 /* This function looks for a live token in the list of current tokens that  */
7641 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7642 /* allocated.  If one is found then it is moved to the top of the list of   */
7643 /* currently active tokens.                                                 */
7644 /* ------------------------------------------------------------------------ */
7645 ipftoken_t *
7646 ipf_token_find(softc, type, uid, ptr)
7647         ipf_main_softc_t *softc;
7648         int type, uid;
7649         void *ptr;
7650 {
7651         ipftoken_t *it, *new;
7652
7653         KMALLOC(new, ipftoken_t *);
7654         if (new != NULL)
7655                 bzero((char *)new, sizeof(*new));
7656
7657         WRITE_ENTER(&softc->ipf_tokens);
7658         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7659                 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7660                     (uid == it->ipt_uid) && (it->ipt_complete < 2))
7661                         break;
7662         }
7663
7664         if (it == NULL) {
7665                 it = new;
7666                 new = NULL;
7667                 if (it == NULL) {
7668                         RWLOCK_EXIT(&softc->ipf_tokens);
7669                         return NULL;
7670                 }
7671                 it->ipt_ctx = ptr;
7672                 it->ipt_uid = uid;
7673                 it->ipt_type = type;
7674                 it->ipt_ref = 1;
7675         } else {
7676                 if (new != NULL) {
7677                         KFREE(new);
7678                         new = NULL;
7679                 }
7680
7681                 if (it->ipt_complete > 0)
7682                         it = NULL;
7683                 else
7684                         ipf_token_unlink(softc, it);
7685         }
7686
7687         if (it != NULL) {
7688                 it->ipt_pnext = softc->ipf_token_tail;
7689                 *softc->ipf_token_tail = it;
7690                 softc->ipf_token_tail = &it->ipt_next;
7691                 it->ipt_next = NULL;
7692                 it->ipt_ref++;
7693
7694                 it->ipt_die = softc->ipf_ticks + 20;
7695         }
7696
7697         RWLOCK_EXIT(&softc->ipf_tokens);
7698
7699         return it;
7700 }
7701
7702
7703 /* ------------------------------------------------------------------------ */
7704 /* Function:    ipf_token_unlink                                            */
7705 /* Returns:     None.                                                       */
7706 /* Parameters:  softc(I) - pointer to soft context main structure           */
7707 /*              token(I) - pointer to token structure                       */
7708 /* Write Locks: ipf_tokens                                                  */
7709 /*                                                                          */
7710 /* This function unlinks a token structure from the linked list of tokens   */
7711 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7712 /* but the tail does due to the linked list implementation.                 */
7713 /* ------------------------------------------------------------------------ */
7714 static void
7715 ipf_token_unlink(softc, token)
7716         ipf_main_softc_t *softc;
7717         ipftoken_t *token;
7718 {
7719
7720         if (softc->ipf_token_tail == &token->ipt_next)
7721                 softc->ipf_token_tail = token->ipt_pnext;
7722
7723         *token->ipt_pnext = token->ipt_next;
7724         if (token->ipt_next != NULL)
7725                 token->ipt_next->ipt_pnext = token->ipt_pnext;
7726         token->ipt_next = NULL;
7727         token->ipt_pnext = NULL;
7728 }
7729
7730
7731 /* ------------------------------------------------------------------------ */
7732 /* Function:    ipf_token_deref                                             */
7733 /* Returns:     int      - 0 == token freed, else reference count           */
7734 /* Parameters:  softc(I) - pointer to soft context main structure           */
7735 /*              token(I) - pointer to token structure                       */
7736 /* Write Locks: ipf_tokens                                                  */
7737 /*                                                                          */
7738 /* Drop the reference count on the token structure and if it drops to zero, */
7739 /* call the dereference function for the token type because it is then      */
7740 /* possible to free the token data structure.                               */
7741 /* ------------------------------------------------------------------------ */
7742 int
7743 ipf_token_deref(softc, token)
7744         ipf_main_softc_t *softc;
7745         ipftoken_t *token;
7746 {
7747         void *data, **datap;
7748
7749         ASSERT(token->ipt_ref > 0);
7750         token->ipt_ref--;
7751         if (token->ipt_ref > 0)
7752                 return token->ipt_ref;
7753
7754         data = token->ipt_data;
7755         datap = &data;
7756
7757         if ((data != NULL) && (data != (void *)-1)) {
7758                 switch (token->ipt_type)
7759                 {
7760                 case IPFGENITER_IPF :
7761                         (void) ipf_derefrule(softc, (frentry_t **)datap);
7762                         break;
7763                 case IPFGENITER_IPNAT :
7764                         WRITE_ENTER(&softc->ipf_nat);
7765                         ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7766                         RWLOCK_EXIT(&softc->ipf_nat);
7767                         break;
7768                 case IPFGENITER_NAT :
7769                         ipf_nat_deref(softc, (nat_t **)datap);
7770                         break;
7771                 case IPFGENITER_STATE :
7772                         ipf_state_deref(softc, (ipstate_t **)datap);
7773                         break;
7774                 case IPFGENITER_FRAG :
7775                         ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7776                         break;
7777                 case IPFGENITER_NATFRAG :
7778                         ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7779                         break;
7780                 case IPFGENITER_HOSTMAP :
7781                         WRITE_ENTER(&softc->ipf_nat);
7782                         ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7783                         RWLOCK_EXIT(&softc->ipf_nat);
7784                         break;
7785                 default :
7786                         ipf_lookup_iterderef(softc, token->ipt_type, data);
7787                         break;
7788                 }
7789         }
7790
7791         ipf_token_unlink(softc, token);
7792         KFREE(token);
7793         return 0;
7794 }
7795
7796
7797 /* ------------------------------------------------------------------------ */
7798 /* Function:    ipf_nextrule                                                */
7799 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7800 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7801 /*              fr(I)       - pointer to filter rule                        */
7802 /*              out(I)      - 1 == out rules, 0 == input rules              */
7803 /*                                                                          */
7804 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7805 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7806 /* last rule in the list. When walking rule lists, it is either input or    */
7807 /* output rules that are returned, never both.                              */
7808 /* ------------------------------------------------------------------------ */
7809 static frentry_t *
7810 ipf_nextrule(softc, active, unit, fr, out)
7811         ipf_main_softc_t *softc;
7812         int active, unit;
7813         frentry_t *fr;
7814         int out;
7815 {
7816         frentry_t *next;
7817         frgroup_t *fg;
7818
7819         if (fr != NULL && fr->fr_group != -1) {
7820                 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7821                                    unit, active, NULL);
7822                 if (fg != NULL)
7823                         fg = fg->fg_next;
7824         } else {
7825                 fg = softc->ipf_groups[unit][active];
7826         }
7827
7828         while (fg != NULL) {
7829                 next = fg->fg_start;
7830                 while (next != NULL) {
7831                         if (out) {
7832                                 if (next->fr_flags & FR_OUTQUE)
7833                                         return next;
7834                         } else if (next->fr_flags & FR_INQUE) {
7835                                 return next;
7836                         }
7837                         next = next->fr_next;
7838                 }
7839                 if (next == NULL)
7840                         fg = fg->fg_next;
7841         }
7842
7843         return NULL;
7844 }
7845
7846 /* ------------------------------------------------------------------------ */
7847 /* Function:    ipf_getnextrule                                             */
7848 /* Returns:     int - 0 = success, else error                               */
7849 /* Parameters:  softc(I)- pointer to soft context main structure            */
7850 /*              t(I)   - pointer to destination information to resolve      */
7851 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7852 /*                                                                          */
7853 /* This function's first job is to bring in the ipfruleiter_t structure via */
7854 /* the ipfobj_t structure to determine what should be the next rule to      */
7855 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7856 /* find the 'next rule'.  This may include searching rule group lists or    */
7857 /* just be as simple as looking at the 'next' field in the rule structure.  */
7858 /* When we have found the rule to return, increase its reference count and  */
7859 /* if we used an existing rule to get here, decrease its reference count.   */
7860 /* ------------------------------------------------------------------------ */
7861 int
7862 ipf_getnextrule(softc, t, ptr)
7863         ipf_main_softc_t *softc;
7864         ipftoken_t *t;
7865         void *ptr;
7866 {
7867         frentry_t *fr, *next, zero;
7868         ipfruleiter_t it;
7869         int error, out;
7870         frgroup_t *fg;
7871         ipfobj_t obj;
7872         int predict;
7873         char *dst;
7874         int unit;
7875
7876         if (t == NULL || ptr == NULL) {
7877                 IPFERROR(84);
7878                 return EFAULT;
7879         }
7880
7881         error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7882         if (error != 0)
7883                 return error;
7884
7885         if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7886                 IPFERROR(85);
7887                 return EINVAL;
7888         }
7889         if ((it.iri_active != 0) && (it.iri_active != 1)) {
7890                 IPFERROR(86);
7891                 return EINVAL;
7892         }
7893         if (it.iri_nrules == 0) {
7894                 IPFERROR(87);
7895                 return ENOSPC;
7896         }
7897         if (it.iri_rule == NULL) {
7898                 IPFERROR(88);
7899                 return EFAULT;
7900         }
7901
7902         fg = NULL;
7903         fr = t->ipt_data;
7904         if ((it.iri_inout & F_OUT) != 0)
7905                 out = 1;
7906         else
7907                 out = 0;
7908         if ((it.iri_inout & F_ACIN) != 0)
7909                 unit = IPL_LOGCOUNT;
7910         else
7911                 unit = IPL_LOGIPF;
7912
7913         READ_ENTER(&softc->ipf_mutex);
7914         if (fr == NULL) {
7915                 if (*it.iri_group == '\0') {
7916                         if (unit == IPL_LOGCOUNT) {
7917                                 next = softc->ipf_acct[out][it.iri_active];
7918                         } else {
7919                                 next = softc->ipf_rules[out][it.iri_active];
7920                         }
7921                         if (next == NULL)
7922                                 next = ipf_nextrule(softc, it.iri_active,
7923                                                     unit, NULL, out);
7924                 } else {
7925                         fg = ipf_findgroup(softc, it.iri_group, unit,
7926                                            it.iri_active, NULL);
7927                         if (fg != NULL)
7928                                 next = fg->fg_start;
7929                         else
7930                                 next = NULL;
7931                 }
7932         } else {
7933                 next = fr->fr_next;
7934                 if (next == NULL)
7935                         next = ipf_nextrule(softc, it.iri_active, unit,
7936                                             fr, out);
7937         }
7938
7939         if (next != NULL && next->fr_next != NULL)
7940                 predict = 1;
7941         else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7942                 predict = 1;
7943         else
7944                 predict = 0;
7945
7946         if (fr != NULL)
7947                 (void) ipf_derefrule(softc, &fr);
7948
7949         obj.ipfo_type = IPFOBJ_FRENTRY;
7950         dst = (char *)it.iri_rule;
7951
7952         if (next != NULL) {
7953                 obj.ipfo_size = next->fr_size;
7954                 MUTEX_ENTER(&next->fr_lock);
7955                 next->fr_ref++;
7956                 MUTEX_EXIT(&next->fr_lock);
7957                 t->ipt_data = next;
7958         } else {
7959                 obj.ipfo_size = sizeof(frentry_t);
7960                 bzero(&zero, sizeof(zero));
7961                 next = &zero;
7962                 t->ipt_data = NULL;
7963         }
7964         it.iri_rule = predict ? next : NULL;
7965         if (predict == 0)
7966                 ipf_token_mark_complete(t);
7967
7968         RWLOCK_EXIT(&softc->ipf_mutex);
7969
7970         obj.ipfo_ptr = dst;
7971         error = ipf_outobjk(softc, &obj, next);
7972         if (error == 0 && t->ipt_data != NULL) {
7973                 dst += obj.ipfo_size;
7974                 if (next->fr_data != NULL) {
7975                         ipfobj_t dobj;
7976
7977                         if (next->fr_type == FR_T_IPFEXPR)
7978                                 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7979                         else
7980                                 dobj.ipfo_type = IPFOBJ_FRIPF;
7981                         dobj.ipfo_size = next->fr_dsize;
7982                         dobj.ipfo_rev = obj.ipfo_rev;
7983                         dobj.ipfo_ptr = dst;
7984                         error = ipf_outobjk(softc, &dobj, next->fr_data);
7985                 }
7986         }
7987
7988         if ((fr != NULL) && (next == &zero))
7989                 (void) ipf_derefrule(softc, &fr);
7990
7991         return error;
7992 }
7993
7994
7995 /* ------------------------------------------------------------------------ */
7996 /* Function:    ipf_frruleiter                                              */
7997 /* Returns:     int - 0 = success, else error                               */
7998 /* Parameters:  softc(I)- pointer to soft context main structure            */
7999 /*              data(I) - the token type to match                           */
8000 /*              uid(I)  - uid owning the token                              */
8001 /*              ptr(I)  - context pointer for the token                     */
8002 /*                                                                          */
8003 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8004 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8005 /* the process doing the ioctl and use that to ask for the next rule.       */
8006 /* ------------------------------------------------------------------------ */
8007 static int
8008 ipf_frruleiter(softc, data, uid, ctx)
8009         ipf_main_softc_t *softc;
8010         void *data, *ctx;
8011         int uid;
8012 {
8013         ipftoken_t *token;
8014         ipfruleiter_t it;
8015         ipfobj_t obj;
8016         int error;
8017
8018         token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8019         if (token != NULL) {
8020                 error = ipf_getnextrule(softc, token, data);
8021                 WRITE_ENTER(&softc->ipf_tokens);
8022                 ipf_token_deref(softc, token);
8023                 RWLOCK_EXIT(&softc->ipf_tokens);
8024         } else {
8025                 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8026                 if (error != 0)
8027                         return error;
8028                 it.iri_rule = NULL;
8029                 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8030         }
8031
8032         return error;
8033 }
8034
8035
8036 /* ------------------------------------------------------------------------ */
8037 /* Function:    ipf_geniter                                                 */
8038 /* Returns:     int - 0 = success, else error                               */
8039 /* Parameters:  softc(I) - pointer to soft context main structure           */
8040 /*              token(I) - pointer to ipftoken_t structure                  */
8041 /*              itp(I)   - pointer to iterator data                         */
8042 /*                                                                          */
8043 /* Decide which iterator function to call using information passed through  */
8044 /* the ipfgeniter_t structure at itp.                                       */
8045 /* ------------------------------------------------------------------------ */
8046 static int
8047 ipf_geniter(softc, token, itp)
8048         ipf_main_softc_t *softc;
8049         ipftoken_t *token;
8050         ipfgeniter_t *itp;
8051 {
8052         int error;
8053
8054         switch (itp->igi_type)
8055         {
8056         case IPFGENITER_FRAG :
8057                 error = ipf_frag_pkt_next(softc, token, itp);
8058                 break;
8059         default :
8060                 IPFERROR(92);
8061                 error = EINVAL;
8062                 break;
8063         }
8064
8065         return error;
8066 }
8067
8068
8069 /* ------------------------------------------------------------------------ */
8070 /* Function:    ipf_genericiter                                             */
8071 /* Returns:     int - 0 = success, else error                               */
8072 /* Parameters:  softc(I)- pointer to soft context main structure            */
8073 /*              data(I) - the token type to match                           */
8074 /*              uid(I)  - uid owning the token                              */
8075 /*              ptr(I)  - context pointer for the token                     */
8076 /*                                                                          */
8077 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8078 /* ------------------------------------------------------------------------ */
8079 int
8080 ipf_genericiter(softc, data, uid, ctx)
8081         ipf_main_softc_t *softc;
8082         void *data, *ctx;
8083         int uid;
8084 {
8085         ipftoken_t *token;
8086         ipfgeniter_t iter;
8087         int error;
8088
8089         error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8090         if (error != 0)
8091                 return error;
8092
8093         token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8094         if (token != NULL) {
8095                 token->ipt_subtype = iter.igi_type;
8096                 error = ipf_geniter(softc, token, &iter);
8097                 WRITE_ENTER(&softc->ipf_tokens);
8098                 ipf_token_deref(softc, token);
8099                 RWLOCK_EXIT(&softc->ipf_tokens);
8100         } else {
8101                 IPFERROR(93);
8102                 error = 0;
8103         }
8104
8105         return error;
8106 }
8107
8108
8109 /* ------------------------------------------------------------------------ */
8110 /* Function:    ipf_ipf_ioctl                                               */
8111 /* Returns:     int - 0 = success, else error                               */
8112 /* Parameters:  softc(I)- pointer to soft context main structure           */
8113 /*              data(I) - the token type to match                           */
8114 /*              cmd(I)  - the ioctl command number                          */
8115 /*              mode(I) - mode flags for the ioctl                          */
8116 /*              uid(I)  - uid owning the token                              */
8117 /*              ptr(I)  - context pointer for the token                     */
8118 /*                                                                          */
8119 /* This function handles all of the ioctl command that are actually isssued */
8120 /* to the /dev/ipl device.                                                  */
8121 /* ------------------------------------------------------------------------ */
8122 int
8123 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8124         ipf_main_softc_t *softc;
8125         caddr_t data;
8126         ioctlcmd_t cmd;
8127         int mode, uid;
8128         void *ctx;
8129 {
8130         friostat_t fio;
8131         int error, tmp;
8132         ipfobj_t obj;
8133         SPL_INT(s);
8134
8135         switch (cmd)
8136         {
8137         case SIOCFRENB :
8138                 if (!(mode & FWRITE)) {
8139                         IPFERROR(94);
8140                         error = EPERM;
8141                 } else {
8142                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8143                         if (error != 0) {
8144                                 IPFERROR(95);
8145                                 error = EFAULT;
8146                                 break;
8147                         }
8148
8149                         WRITE_ENTER(&softc->ipf_global);
8150                         if (tmp) {
8151                                 if (softc->ipf_running > 0)
8152                                         error = 0;
8153                                 else
8154                                         error = ipfattach(softc);
8155                                 if (error == 0)
8156                                         softc->ipf_running = 1;
8157                                 else
8158                                         (void) ipfdetach(softc);
8159                         } else {
8160                                 if (softc->ipf_running == 1)
8161                                         error = ipfdetach(softc);
8162                                 else
8163                                         error = 0;
8164                                 if (error == 0)
8165                                         softc->ipf_running = -1;
8166                         }
8167                         RWLOCK_EXIT(&softc->ipf_global);
8168                 }
8169                 break;
8170
8171         case SIOCIPFSET :
8172                 if (!(mode & FWRITE)) {
8173                         IPFERROR(96);
8174                         error = EPERM;
8175                         break;
8176                 }
8177                 /* FALLTHRU */
8178         case SIOCIPFGETNEXT :
8179         case SIOCIPFGET :
8180                 error = ipf_ipftune(softc, cmd, (void *)data);
8181                 break;
8182
8183         case SIOCSETFF :
8184                 if (!(mode & FWRITE)) {
8185                         IPFERROR(97);
8186                         error = EPERM;
8187                 } else {
8188                         error = BCOPYIN(data, &softc->ipf_flags,
8189                                         sizeof(softc->ipf_flags));
8190                         if (error != 0) {
8191                                 IPFERROR(98);
8192                                 error = EFAULT;
8193                         }
8194                 }
8195                 break;
8196
8197         case SIOCGETFF :
8198                 error = BCOPYOUT(&softc->ipf_flags, data,
8199                                  sizeof(softc->ipf_flags));
8200                 if (error != 0) {
8201                         IPFERROR(99);
8202                         error = EFAULT;
8203                 }
8204                 break;
8205
8206         case SIOCFUNCL :
8207                 error = ipf_resolvefunc(softc, (void *)data);
8208                 break;
8209
8210         case SIOCINAFR :
8211         case SIOCRMAFR :
8212         case SIOCADAFR :
8213         case SIOCZRLST :
8214                 if (!(mode & FWRITE)) {
8215                         IPFERROR(100);
8216                         error = EPERM;
8217                 } else {
8218                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8219                                           softc->ipf_active, 1);
8220                 }
8221                 break;
8222
8223         case SIOCINIFR :
8224         case SIOCRMIFR :
8225         case SIOCADIFR :
8226                 if (!(mode & FWRITE)) {
8227                         IPFERROR(101);
8228                         error = EPERM;
8229                 } else {
8230                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8231                                           1 - softc->ipf_active, 1);
8232                 }
8233                 break;
8234
8235         case SIOCSWAPA :
8236                 if (!(mode & FWRITE)) {
8237                         IPFERROR(102);
8238                         error = EPERM;
8239                 } else {
8240                         WRITE_ENTER(&softc->ipf_mutex);
8241                         error = BCOPYOUT(&softc->ipf_active, data,
8242                                          sizeof(softc->ipf_active));
8243                         if (error != 0) {
8244                                 IPFERROR(103);
8245                                 error = EFAULT;
8246                         } else {
8247                                 softc->ipf_active = 1 - softc->ipf_active;
8248                         }
8249                         RWLOCK_EXIT(&softc->ipf_mutex);
8250                 }
8251                 break;
8252
8253         case SIOCGETFS :
8254                 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8255                                   IPFOBJ_IPFSTAT);
8256                 if (error != 0)
8257                         break;
8258                 ipf_getstat(softc, &fio, obj.ipfo_rev);
8259                 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8260                 break;
8261
8262         case SIOCFRZST :
8263                 if (!(mode & FWRITE)) {
8264                         IPFERROR(104);
8265                         error = EPERM;
8266                 } else
8267                         error = ipf_zerostats(softc, (caddr_t)data);
8268                 break;
8269
8270         case SIOCIPFFL :
8271                 if (!(mode & FWRITE)) {
8272                         IPFERROR(105);
8273                         error = EPERM;
8274                 } else {
8275                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8276                         if (!error) {
8277                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8278                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8279                                 if (error != 0) {
8280                                         IPFERROR(106);
8281                                         error = EFAULT;
8282                                 }
8283                         } else {
8284                                 IPFERROR(107);
8285                                 error = EFAULT;
8286                         }
8287                 }
8288                 break;
8289
8290 #ifdef USE_INET6
8291         case SIOCIPFL6 :
8292                 if (!(mode & FWRITE)) {
8293                         IPFERROR(108);
8294                         error = EPERM;
8295                 } else {
8296                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8297                         if (!error) {
8298                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8299                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8300                                 if (error != 0) {
8301                                         IPFERROR(109);
8302                                         error = EFAULT;
8303                                 }
8304                         } else {
8305                                 IPFERROR(110);
8306                                 error = EFAULT;
8307                         }
8308                 }
8309                 break;
8310 #endif
8311
8312         case SIOCSTLCK :
8313                 if (!(mode & FWRITE)) {
8314                         IPFERROR(122);
8315                         error = EPERM;
8316                 } else {
8317                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8318                         if (error == 0) {
8319                                 ipf_state_setlock(softc->ipf_state_soft, tmp);
8320                                 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8321                                 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8322                                 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8323                         } else {
8324                                 IPFERROR(111);
8325                                 error = EFAULT;
8326                         }
8327                 }
8328                 break;
8329
8330 #ifdef  IPFILTER_LOG
8331         case SIOCIPFFB :
8332                 if (!(mode & FWRITE)) {
8333                         IPFERROR(112);
8334                         error = EPERM;
8335                 } else {
8336                         tmp = ipf_log_clear(softc, IPL_LOGIPF);
8337                         error = BCOPYOUT(&tmp, data, sizeof(tmp));
8338                         if (error) {
8339                                 IPFERROR(113);
8340                                 error = EFAULT;
8341                         }
8342                 }
8343                 break;
8344 #endif /* IPFILTER_LOG */
8345
8346         case SIOCFRSYN :
8347                 if (!(mode & FWRITE)) {
8348                         IPFERROR(114);
8349                         error = EPERM;
8350                 } else {
8351                         WRITE_ENTER(&softc->ipf_global);
8352 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8353                         error = ipfsync();
8354 #else
8355                         ipf_sync(softc, NULL);
8356                         error = 0;
8357 #endif
8358                         RWLOCK_EXIT(&softc->ipf_global);
8359
8360                 }
8361                 break;
8362
8363         case SIOCGFRST :
8364                 error = ipf_outobj(softc, (void *)data,
8365                                    ipf_frag_stats(softc->ipf_frag_soft),
8366                                    IPFOBJ_FRAGSTAT);
8367                 break;
8368
8369 #ifdef  IPFILTER_LOG
8370         case FIONREAD :
8371                 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8372                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8373                 break;
8374 #endif
8375
8376         case SIOCIPFITER :
8377                 SPL_SCHED(s);
8378                 error = ipf_frruleiter(softc, data, uid, ctx);
8379                 SPL_X(s);
8380                 break;
8381
8382         case SIOCGENITER :
8383                 SPL_SCHED(s);
8384                 error = ipf_genericiter(softc, data, uid, ctx);
8385                 SPL_X(s);
8386                 break;
8387
8388         case SIOCIPFDELTOK :
8389                 error = BCOPYIN(data, &tmp, sizeof(tmp));
8390                 if (error == 0) {
8391                         SPL_SCHED(s);
8392                         error = ipf_token_del(softc, tmp, uid, ctx);
8393                         SPL_X(s);
8394                 }
8395                 break;
8396
8397         default :
8398                 IPFERROR(115);
8399                 error = EINVAL;
8400                 break;
8401         }
8402
8403         return error;
8404 }
8405
8406
8407 /* ------------------------------------------------------------------------ */
8408 /* Function:    ipf_decaps                                                  */
8409 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8410 /*                           flags indicating packet filtering decision.    */
8411 /* Parameters:  fin(I)     - pointer to packet information                  */
8412 /*              pass(I)    - IP protocol version to match                   */
8413 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8414 /*                                                                          */
8415 /* This function is called for packets that are wrapt up in other packets,  */
8416 /* for example, an IP packet that is the entire data segment for another IP */
8417 /* packet.  If the basic constraints for this are satisfied, change the     */
8418 /* buffer to point to the start of the inner packet and start processing    */
8419 /* rules belonging to the head group this rule specifies.                   */
8420 /* ------------------------------------------------------------------------ */
8421 u_32_t
8422 ipf_decaps(fin, pass, l5proto)
8423         fr_info_t *fin;
8424         u_32_t pass;
8425         int l5proto;
8426 {
8427         fr_info_t fin2, *fino = NULL;
8428         int elen, hlen, nh;
8429         grehdr_t gre;
8430         ip_t *ip;
8431         mb_t *m;
8432
8433         if ((fin->fin_flx & FI_COALESCE) == 0)
8434                 if (ipf_coalesce(fin) == -1)
8435                         goto cantdecaps;
8436
8437         m = fin->fin_m;
8438         hlen = fin->fin_hlen;
8439
8440         switch (fin->fin_p)
8441         {
8442         case IPPROTO_UDP :
8443                 /*
8444                  * In this case, the specific protocol being decapsulated
8445                  * inside UDP frames comes from the rule.
8446                  */
8447                 nh = fin->fin_fr->fr_icode;
8448                 break;
8449
8450         case IPPROTO_GRE :      /* 47 */
8451                 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8452                 hlen += sizeof(grehdr_t);
8453                 if (gre.gr_R|gre.gr_s)
8454                         goto cantdecaps;
8455                 if (gre.gr_C)
8456                         hlen += 4;
8457                 if (gre.gr_K)
8458                         hlen += 4;
8459                 if (gre.gr_S)
8460                         hlen += 4;
8461
8462                 nh = IPPROTO_IP;
8463
8464                 /*
8465                  * If the routing options flag is set, validate that it is
8466                  * there and bounce over it.
8467                  */
8468 #if 0
8469                 /* This is really heavy weight and lots of room for error, */
8470                 /* so for now, put it off and get the simple stuff right.  */
8471                 if (gre.gr_R) {
8472                         u_char off, len, *s;
8473                         u_short af;
8474                         int end;
8475
8476                         end = 0;
8477                         s = fin->fin_dp;
8478                         s += hlen;
8479                         aplen = fin->fin_plen - hlen;
8480                         while (aplen > 3) {
8481                                 af = (s[0] << 8) | s[1];
8482                                 off = s[2];
8483                                 len = s[3];
8484                                 aplen -= 4;
8485                                 s += 4;
8486                                 if (af == 0 && len == 0) {
8487                                         end = 1;
8488                                         break;
8489                                 }
8490                                 if (aplen < len)
8491                                         break;
8492                                 s += len;
8493                                 aplen -= len;
8494                         }
8495                         if (end != 1)
8496                                 goto cantdecaps;
8497                         hlen = s - (u_char *)fin->fin_dp;
8498                 }
8499 #endif
8500                 break;
8501
8502 #ifdef IPPROTO_IPIP
8503         case IPPROTO_IPIP :     /* 4 */
8504 #endif
8505                 nh = IPPROTO_IP;
8506                 break;
8507
8508         default :       /* Includes ESP, AH is special for IPv4 */
8509                 goto cantdecaps;
8510         }
8511
8512         switch (nh)
8513         {
8514         case IPPROTO_IP :
8515         case IPPROTO_IPV6 :
8516                 break;
8517         default :
8518                 goto cantdecaps;
8519         }
8520
8521         bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8522         fino = fin;
8523         fin = &fin2;
8524         elen = hlen;
8525 #if defined(MENTAT) && defined(_KERNEL)
8526         m->b_rptr += elen;
8527 #else
8528         m->m_data += elen;
8529         m->m_len -= elen;
8530 #endif
8531         fin->fin_plen -= elen;
8532
8533         ip = (ip_t *)((char *)fin->fin_ip + elen);
8534
8535         /*
8536          * Make sure we have at least enough data for the network layer
8537          * header.
8538          */
8539         if (IP_V(ip) == 4)
8540                 hlen = IP_HL(ip) << 2;
8541 #ifdef USE_INET6
8542         else if (IP_V(ip) == 6)
8543                 hlen = sizeof(ip6_t);
8544 #endif
8545         else
8546                 goto cantdecaps2;
8547
8548         if (fin->fin_plen < hlen)
8549                 goto cantdecaps2;
8550
8551         fin->fin_dp = (char *)ip + hlen;
8552
8553         if (IP_V(ip) == 4) {
8554                 /*
8555                  * Perform IPv4 header checksum validation.
8556                  */
8557                 if (ipf_cksum((u_short *)ip, hlen))
8558                         goto cantdecaps2;
8559         }
8560
8561         if (ipf_makefrip(hlen, ip, fin) == -1) {
8562 cantdecaps2:
8563                 if (m != NULL) {
8564 #if defined(MENTAT) && defined(_KERNEL)
8565                         m->b_rptr -= elen;
8566 #else
8567                         m->m_data -= elen;
8568                         m->m_len += elen;
8569 #endif
8570                 }
8571 cantdecaps:
8572                 DT1(frb_decapfrip, fr_info_t *, fin);
8573                 pass &= ~FR_CMDMASK;
8574                 pass |= FR_BLOCK|FR_QUICK;
8575                 fin->fin_reason = FRB_DECAPFRIP;
8576                 return -1;
8577         }
8578
8579         pass = ipf_scanlist(fin, pass);
8580
8581         /*
8582          * Copy the packet filter "result" fields out of the fr_info_t struct
8583          * that is local to the decapsulation processing and back into the
8584          * one we were called with.
8585          */
8586         fino->fin_flx = fin->fin_flx;
8587         fino->fin_rev = fin->fin_rev;
8588         fino->fin_icode = fin->fin_icode;
8589         fino->fin_rule = fin->fin_rule;
8590         (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8591         fino->fin_fr = fin->fin_fr;
8592         fino->fin_error = fin->fin_error;
8593         fino->fin_mp = fin->fin_mp;
8594         fino->fin_m = fin->fin_m;
8595         m = fin->fin_m;
8596         if (m != NULL) {
8597 #if defined(MENTAT) && defined(_KERNEL)
8598                 m->b_rptr -= elen;
8599 #else
8600                 m->m_data -= elen;
8601                 m->m_len += elen;
8602 #endif
8603         }
8604         return pass;
8605 }
8606
8607
8608 /* ------------------------------------------------------------------------ */
8609 /* Function:    ipf_matcharray_load                                         */
8610 /* Returns:     int         - 0 = success, else error                       */
8611 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8612 /*              data(I)     - pointer to ioctl data                         */
8613 /*              objp(I)     - ipfobj_t structure to load data into          */
8614 /*              arrayptr(I) - pointer to location to store array pointer    */
8615 /*                                                                          */
8616 /* This function loads in a mathing array through the ipfobj_t struct that  */
8617 /* describes it.  Sanity checking and array size limitations are enforced   */
8618 /* in this function to prevent userspace from trying to load in something   */
8619 /* that is insanely big.  Once the size of the array is known, the memory   */
8620 /* required is malloc'd and returned through changing *arrayptr.  The       */
8621 /* contents of the array are verified before returning.  Only in the event  */
8622 /* of a successful call is the caller required to free up the malloc area.  */
8623 /* ------------------------------------------------------------------------ */
8624 int
8625 ipf_matcharray_load(softc, data, objp, arrayptr)
8626         ipf_main_softc_t *softc;
8627         caddr_t data;
8628         ipfobj_t *objp;
8629         int **arrayptr;
8630 {
8631         int arraysize, *array, error;
8632
8633         *arrayptr = NULL;
8634
8635         error = BCOPYIN(data, objp, sizeof(*objp));
8636         if (error != 0) {
8637                 IPFERROR(116);
8638                 return EFAULT;
8639         }
8640
8641         if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8642                 IPFERROR(117);
8643                 return EINVAL;
8644         }
8645
8646         if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8647             (objp->ipfo_size > 1024)) {
8648                 IPFERROR(118);
8649                 return EINVAL;
8650         }
8651
8652         arraysize = objp->ipfo_size * sizeof(*array);
8653         KMALLOCS(array, int *, arraysize);
8654         if (array == NULL) {
8655                 IPFERROR(119);
8656                 return ENOMEM;
8657         }
8658
8659         error = COPYIN(objp->ipfo_ptr, array, arraysize);
8660         if (error != 0) {
8661                 KFREES(array, arraysize);
8662                 IPFERROR(120);
8663                 return EFAULT;
8664         }
8665
8666         if (ipf_matcharray_verify(array, arraysize) != 0) {
8667                 KFREES(array, arraysize);
8668                 IPFERROR(121);
8669                 return EINVAL;
8670         }
8671
8672         *arrayptr = array;
8673         return 0;
8674 }
8675
8676
8677 /* ------------------------------------------------------------------------ */
8678 /* Function:    ipf_matcharray_verify                                       */
8679 /* Returns:     Nil                                                         */
8680 /* Parameters:  array(I)     - pointer to matching array                    */
8681 /*              arraysize(I) - number of elements in the array              */
8682 /*                                                                          */
8683 /* Verify the contents of a matching array by stepping through each element */
8684 /* in it.  The actual commands in the array are not verified for            */
8685 /* correctness, only that all of the sizes are correctly within limits.     */
8686 /* ------------------------------------------------------------------------ */
8687 int
8688 ipf_matcharray_verify(array, arraysize)
8689         int *array, arraysize;
8690 {
8691         int i, nelem, maxidx;
8692         ipfexp_t *e;
8693
8694         nelem = arraysize / sizeof(*array);
8695
8696         /*
8697          * Currently, it makes no sense to have an array less than 6
8698          * elements long - the initial size at the from, a single operation
8699          * (minimum 4 in length) and a trailer, for a total of 6.
8700          */
8701         if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8702                 return -1;
8703         }
8704
8705         /*
8706          * Verify the size of data pointed to by array with how long
8707          * the array claims to be itself.
8708          */
8709         if (array[0] * sizeof(*array) != arraysize) {
8710                 return -1;
8711         }
8712
8713         maxidx = nelem - 1;
8714         /*
8715          * The last opcode in this array should be an IPF_EXP_END.
8716          */
8717         if (array[maxidx] != IPF_EXP_END) {
8718                 return -1;
8719         }
8720
8721         for (i = 1; i < maxidx; ) {
8722                 e = (ipfexp_t *)(array + i);
8723
8724                 /*
8725                  * The length of the bits to check must be at least 1
8726                  * (or else there is nothing to comapre with!) and it
8727                  * cannot exceed the length of the data present.
8728                  */
8729                 if ((e->ipfe_size < 1 ) ||
8730                     (e->ipfe_size + i > maxidx)) {
8731                         return -1;
8732                 }
8733                 i += e->ipfe_size;
8734         }
8735         return 0;
8736 }
8737
8738
8739 /* ------------------------------------------------------------------------ */
8740 /* Function:    ipf_fr_matcharray                                           */
8741 /* Returns:     int      - 0 = match failed, else positive match            */
8742 /* Parameters:  fin(I)   - pointer to packet information                    */
8743 /*              array(I) - pointer to matching array                        */
8744 /*                                                                          */
8745 /* This function is used to apply a matching array against a packet and     */
8746 /* return an indication of whether or not the packet successfully matches   */
8747 /* all of the commands in it.                                               */
8748 /* ------------------------------------------------------------------------ */
8749 static int
8750 ipf_fr_matcharray(fin, array)
8751         fr_info_t *fin;
8752         int *array;
8753 {
8754         int i, n, *x, rv, p;
8755         ipfexp_t *e;
8756
8757         rv = 0;
8758         n = array[0];
8759         x = array + 1;
8760
8761         for (; n > 0; x += 3 + x[3], rv = 0) {
8762                 e = (ipfexp_t *)x;
8763                 if (e->ipfe_cmd == IPF_EXP_END)
8764                         break;
8765                 n -= e->ipfe_size;
8766
8767                 /*
8768                  * The upper 16 bits currently store the protocol value.
8769                  * This is currently used with TCP and UDP port compares and
8770                  * allows "tcp.port = 80" without requiring an explicit
8771                  " "ip.pr = tcp" first.
8772                  */
8773                 p = e->ipfe_cmd >> 16;
8774                 if ((p != 0) && (p != fin->fin_p))
8775                         break;
8776
8777                 switch (e->ipfe_cmd)
8778                 {
8779                 case IPF_EXP_IP_PR :
8780                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8781                                 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8782                         }
8783                         break;
8784
8785                 case IPF_EXP_IP_SRCADDR :
8786                         if (fin->fin_v != 4)
8787                                 break;
8788                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8789                                 rv |= ((fin->fin_saddr &
8790                                         e->ipfe_arg0[i * 2 + 1]) ==
8791                                        e->ipfe_arg0[i * 2]);
8792                         }
8793                         break;
8794
8795                 case IPF_EXP_IP_DSTADDR :
8796                         if (fin->fin_v != 4)
8797                                 break;
8798                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8799                                 rv |= ((fin->fin_daddr &
8800                                         e->ipfe_arg0[i * 2 + 1]) ==
8801                                        e->ipfe_arg0[i * 2]);
8802                         }
8803                         break;
8804
8805                 case IPF_EXP_IP_ADDR :
8806                         if (fin->fin_v != 4)
8807                                 break;
8808                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8809                                 rv |= ((fin->fin_saddr &
8810                                         e->ipfe_arg0[i * 2 + 1]) ==
8811                                        e->ipfe_arg0[i * 2]) ||
8812                                       ((fin->fin_daddr &
8813                                         e->ipfe_arg0[i * 2 + 1]) ==
8814                                        e->ipfe_arg0[i * 2]);
8815                         }
8816                         break;
8817
8818 #ifdef USE_INET6
8819                 case IPF_EXP_IP6_SRCADDR :
8820                         if (fin->fin_v != 6)
8821                                 break;
8822                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8823                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8824                                                  &e->ipfe_arg0[i * 8 + 4],
8825                                                  &e->ipfe_arg0[i * 8]);
8826                         }
8827                         break;
8828
8829                 case IPF_EXP_IP6_DSTADDR :
8830                         if (fin->fin_v != 6)
8831                                 break;
8832                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8833                                 rv |= IP6_MASKEQ(&fin->fin_dst6,
8834                                                  &e->ipfe_arg0[i * 8 + 4],
8835                                                  &e->ipfe_arg0[i * 8]);
8836                         }
8837                         break;
8838
8839                 case IPF_EXP_IP6_ADDR :
8840                         if (fin->fin_v != 6)
8841                                 break;
8842                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8843                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8844                                                  &e->ipfe_arg0[i * 8 + 4],
8845                                                  &e->ipfe_arg0[i * 8]) ||
8846                                       IP6_MASKEQ(&fin->fin_dst6,
8847                                                  &e->ipfe_arg0[i * 8 + 4],
8848                                                  &e->ipfe_arg0[i * 8]);
8849                         }
8850                         break;
8851 #endif
8852
8853                 case IPF_EXP_UDP_PORT :
8854                 case IPF_EXP_TCP_PORT :
8855                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8856                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8857                                       (fin->fin_dport == e->ipfe_arg0[i]);
8858                         }
8859                         break;
8860
8861                 case IPF_EXP_UDP_SPORT :
8862                 case IPF_EXP_TCP_SPORT :
8863                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8864                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8865                         }
8866                         break;
8867
8868                 case IPF_EXP_UDP_DPORT :
8869                 case IPF_EXP_TCP_DPORT :
8870                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8871                                 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8872                         }
8873                         break;
8874
8875                 case IPF_EXP_TCP_FLAGS :
8876                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8877                                 rv |= ((fin->fin_tcpf &
8878                                         e->ipfe_arg0[i * 2 + 1]) ==
8879                                        e->ipfe_arg0[i * 2]);
8880                         }
8881                         break;
8882                 }
8883                 rv ^= e->ipfe_not;
8884
8885                 if (rv == 0)
8886                         break;
8887         }
8888
8889         return rv;
8890 }
8891
8892
8893 /* ------------------------------------------------------------------------ */
8894 /* Function:    ipf_queueflush                                              */
8895 /* Returns:     int - number of entries flushed (0 = none)                  */
8896 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8897 /*              deletefn(I) - function to call to delete entry              */
8898 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8899 /*              userqs(I)   - top of the list of user defined timeouts      */
8900 /*                                                                          */
8901 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8902 /* need to try a bit harder to free up some space.  The algorithm used here */
8903 /* split into two parts but both halves have the same goal: to reduce the   */
8904 /* number of connections considered to be "active" to the low watermark.    */
8905 /* There are two steps in doing this:                                       */
8906 /* 1) Remove any TCP connections that are already considered to be "closed" */
8907 /*    but have not yet been removed from the state table.  The two states   */
8908 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8909 /*    candidates for this style of removal.  If freeing up entries in       */
8910 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8911 /*    we do not go on to step 2.                                            */
8912 /*                                                                          */
8913 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8914 /*    they are within the given window we are considering.  Where the       */
8915 /*    window starts and the steps taken to increase its size depend upon    */
8916 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8917 /*    last 30 seconds is not touched.                                       */
8918 /*                                              touched                     */
8919 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8920 /*           |          |        |           |     |     |                  */
8921 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8922 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8923 /*                                                                          */
8924 /* Points to note:                                                          */
8925 /* - tqe_die is the time, in the future, when entries die.                  */
8926 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8927 /*   ticks.                                                                 */
8928 /* - tqe_touched is when the entry was last used by NAT/state               */
8929 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8930 /*   ipf_ticks any given timeout queue and vice versa.                      */
8931 /* - both tqe_die and tqe_touched increase over time                        */
8932 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8933 /*   bottom and therefore the smallest values of each are at the top        */
8934 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8935 /*   queues representing each of the TCP states                             */
8936 /*                                                                          */
8937 /* We start by setting up a maximum range to scan for things to move of     */
8938 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8939 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8940 /* we start again with a new value for "iend" and "istart".  This is        */
8941 /* continued until we either finish the scan of 30 second intervals or the  */
8942 /* low water mark is reached.                                               */
8943 /* ------------------------------------------------------------------------ */
8944 int
8945 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
8946         ipf_main_softc_t *softc;
8947         ipftq_delete_fn_t deletefn;
8948         ipftq_t *ipfqs, *userqs;
8949         u_int *activep;
8950         int size, low;
8951 {
8952         u_long interval, istart, iend;
8953         ipftq_t *ifq, *ifqnext;
8954         ipftqent_t *tqe, *tqn;
8955         int removed = 0;
8956
8957         for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8958                 tqn = tqe->tqe_next;
8959                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8960                         removed++;
8961         }
8962         if ((*activep * 100 / size) > low) {
8963                 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8964                      ((tqe = tqn) != NULL); ) {
8965                         tqn = tqe->tqe_next;
8966                         if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8967                                 removed++;
8968                 }
8969         }
8970
8971         if ((*activep * 100 / size) <= low) {
8972                 return removed;
8973         }
8974
8975         /*
8976          * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8977          *       used then the operations are upgraded to floating point
8978          *       and kernels don't like floating point...
8979          */
8980         if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8981                 istart = IPF_TTLVAL(86400 * 4);
8982                 interval = IPF_TTLVAL(43200);
8983         } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8984                 istart = IPF_TTLVAL(43200);
8985                 interval = IPF_TTLVAL(1800);
8986         } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8987                 istart = IPF_TTLVAL(1800);
8988                 interval = IPF_TTLVAL(30);
8989         } else {
8990                 return 0;
8991         }
8992         if (istart > softc->ipf_ticks) {
8993                 if (softc->ipf_ticks - interval < interval)
8994                         istart = interval;
8995                 else
8996                         istart = (softc->ipf_ticks / interval) * interval;
8997         }
8998
8999         iend = softc->ipf_ticks - interval;
9000
9001         while ((*activep * 100 / size) > low) {
9002                 u_long try;
9003
9004                 try = softc->ipf_ticks - istart;
9005
9006                 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9007                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9008                                 if (try < tqe->tqe_touched)
9009                                         break;
9010                                 tqn = tqe->tqe_next;
9011                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9012                                         removed++;
9013                         }
9014                 }
9015
9016                 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9017                         ifqnext = ifq->ifq_next;
9018
9019                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9020                                 if (try < tqe->tqe_touched)
9021                                         break;
9022                                 tqn = tqe->tqe_next;
9023                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9024                                         removed++;
9025                         }
9026                 }
9027
9028                 if (try >= iend) {
9029                         if (interval == IPF_TTLVAL(43200)) {
9030                                 interval = IPF_TTLVAL(1800);
9031                         } else if (interval == IPF_TTLVAL(1800)) {
9032                                 interval = IPF_TTLVAL(30);
9033                         } else {
9034                                 break;
9035                         }
9036                         if (interval >= softc->ipf_ticks)
9037                                 break;
9038
9039                         iend = softc->ipf_ticks - interval;
9040                 }
9041                 istart -= interval;
9042         }
9043
9044         return removed;
9045 }
9046
9047
9048 /* ------------------------------------------------------------------------ */
9049 /* Function:    ipf_deliverlocal                                            */
9050 /* Returns:     int - 1 = local address, 0 = non-local address              */
9051 /* Parameters:  softc(I)     - pointer to soft context main structure       */
9052 /*              ipversion(I) - IP protocol version (4 or 6)                 */
9053 /*              ifp(I)       - network interface pointer                    */
9054 /*              ipaddr(I)    - IPv4/6 destination address                   */
9055 /*                                                                          */
9056 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
9057 /* the network interface represented by ifp.                                */
9058 /* ------------------------------------------------------------------------ */
9059 int
9060 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9061         ipf_main_softc_t *softc;
9062         int ipversion;
9063         void *ifp;
9064         i6addr_t *ipaddr;
9065 {
9066         i6addr_t addr;
9067         int islocal = 0;
9068
9069         if (ipversion == 4) {
9070                 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9071                         if (addr.in4.s_addr == ipaddr->in4.s_addr)
9072                                 islocal = 1;
9073                 }
9074
9075 #ifdef USE_INET6
9076         } else if (ipversion == 6) {
9077                 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9078                         if (IP6_EQ(&addr, ipaddr))
9079                                 islocal = 1;
9080                 }
9081 #endif
9082         }
9083
9084         return islocal;
9085 }
9086
9087
9088 /* ------------------------------------------------------------------------ */
9089 /* Function:    ipf_settimeout                                              */
9090 /* Returns:     int - 0 = success, -1 = failure                             */
9091 /* Parameters:  softc(I) - pointer to soft context main structure           */
9092 /*              t(I)     - pointer to tuneable array entry                  */
9093 /*              p(I)     - pointer to values passed in to apply             */
9094 /*                                                                          */
9095 /* This function is called to set the timeout values for each distinct      */
9096 /* queue timeout that is available.  When called, it calls into both the    */
9097 /* state and NAT code, telling them to update their timeout queues.         */
9098 /* ------------------------------------------------------------------------ */
9099 static int
9100 ipf_settimeout(softc, t, p)
9101         struct ipf_main_softc_s *softc;
9102         ipftuneable_t *t;
9103         ipftuneval_t *p;
9104 {
9105
9106         /*
9107          * ipf_interror should be set by the functions called here, not
9108          * by this function - it's just a middle man.
9109          */
9110         if (ipf_state_settimeout(softc, t, p) == -1)
9111                 return -1;
9112         if (ipf_nat_settimeout(softc, t, p) == -1)
9113                 return -1;
9114         return 0;
9115 }
9116
9117
9118 /* ------------------------------------------------------------------------ */
9119 /* Function:    ipf_apply_timeout                                           */
9120 /* Returns:     int - 0 = success, -1 = failure                             */
9121 /* Parameters:  head(I)    - pointer to tuneable array entry                */
9122 /*              seconds(I) - pointer to values passed in to apply           */
9123 /*                                                                          */
9124 /* This function applies a timeout of "seconds" to the timeout queue that   */
9125 /* is pointed to by "head".  All entries on this list have an expiration    */
9126 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
9127 /* function should only be called when the delta is non-zero, the task is   */
9128 /* to walk the entire list and apply the change.  The sort order will not   */
9129 /* change.  The only catch is that this is O(n) across the list, so if the  */
9130 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9131 /* could take a relatively long time to work through them all.              */
9132 /* ------------------------------------------------------------------------ */
9133 void
9134 ipf_apply_timeout(head, seconds)
9135         ipftq_t *head;
9136         u_int seconds;
9137 {
9138         u_int oldtimeout, newtimeout;
9139         ipftqent_t *tqe;
9140         int delta;
9141
9142         MUTEX_ENTER(&head->ifq_lock);
9143         oldtimeout = head->ifq_ttl;
9144         newtimeout = IPF_TTLVAL(seconds);
9145         delta = oldtimeout - newtimeout;
9146
9147         head->ifq_ttl = newtimeout;
9148
9149         for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9150                 tqe->tqe_die += delta;
9151         }
9152         MUTEX_EXIT(&head->ifq_lock);
9153 }
9154
9155
9156 /* ------------------------------------------------------------------------ */
9157 /* Function:   ipf_settimeout_tcp                                           */
9158 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
9159 /* Parameters: t(I)   - pointer to tuneable to change                       */
9160 /*             p(I)   - pointer to new timeout information                  */
9161 /*             tab(I) - pointer to table of TCP queues                      */
9162 /*                                                                          */
9163 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
9164 /* updates all of the entries on the relevant timeout queue by calling      */
9165 /* ipf_apply_timeout().                                                     */
9166 /* ------------------------------------------------------------------------ */
9167 int
9168 ipf_settimeout_tcp(t, p, tab)
9169         ipftuneable_t *t;
9170         ipftuneval_t *p;
9171         ipftq_t *tab;
9172 {
9173         if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9174             !strcmp(t->ipft_name, "tcp_established")) {
9175                 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9176         } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9177                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9178         } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9179                 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9180         } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9181                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9182                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9183                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9184         } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9185                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9186         } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9187                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9188         } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9189                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9190         } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9191                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9192         } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9193                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9194         } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9195                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9196         } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9197                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9198         } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9199                 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9200         } else {
9201                 /*
9202                  * ipf_interror isn't set here because it should be set
9203                  * by whatever called this function.
9204                  */
9205                 return -1;
9206         }
9207         return 0;
9208 }
9209
9210
9211 /* ------------------------------------------------------------------------ */
9212 /* Function:   ipf_main_soft_create                                         */
9213 /* Returns:    NULL = failure, else success                                 */
9214 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9215 /*                                                                          */
9216 /* Create the foundation soft context structure. In circumstances where it  */
9217 /* is not required to dynamically allocate the context, a pointer can be    */
9218 /* passed in (rather than NULL) to a structure to be initialised.           */
9219 /* The main thing of interest is that a number of locks are initialised     */
9220 /* here instead of in the where might be expected - in the relevant create  */
9221 /* function elsewhere.  This is done because the current locking design has */
9222 /* some areas where these locks are used outside of their module.           */
9223 /* Possibly the most important exercise that is done here is setting of all */
9224 /* the timeout values, allowing them to be changed before init().           */
9225 /* ------------------------------------------------------------------------ */
9226 void *
9227 ipf_main_soft_create(arg)
9228         void *arg;
9229 {
9230         ipf_main_softc_t *softc;
9231
9232         if (arg == NULL) {
9233                 KMALLOC(softc, ipf_main_softc_t *);
9234                 if (softc == NULL)
9235                         return NULL;
9236         } else {
9237                 softc = arg;
9238         }
9239
9240         bzero((char *)softc, sizeof(*softc));
9241
9242         /*
9243          * This serves as a flag as to whether or not the softc should be
9244          * free'd when _destroy is called.
9245          */
9246         softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9247
9248         softc->ipf_tuners = ipf_tune_array_copy(softc,
9249                                                 sizeof(ipf_main_tuneables),
9250                                                 ipf_main_tuneables);
9251         if (softc->ipf_tuners == NULL) {
9252                 ipf_main_soft_destroy(softc);
9253                 return NULL;
9254         }
9255
9256         MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9257         MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9258         RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9259         RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9260         RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9261         RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9262         RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9263         RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9264         RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9265
9266         softc->ipf_token_head = NULL;
9267         softc->ipf_token_tail = &softc->ipf_token_head;
9268
9269         softc->ipf_tcpidletimeout = FIVE_DAYS;
9270         softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9271         softc->ipf_tcplastack = IPF_TTLVAL(30);
9272         softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9273         softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9274         softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9275         softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9276         softc->ipf_tcpclosed = IPF_TTLVAL(30);
9277         softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9278         softc->ipf_udptimeout = IPF_TTLVAL(120);
9279         softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9280         softc->ipf_icmptimeout = IPF_TTLVAL(60);
9281         softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9282         softc->ipf_iptimeout = IPF_TTLVAL(60);
9283
9284 #if defined(IPFILTER_DEFAULT_BLOCK)
9285         softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9286 #else
9287         softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9288 #endif
9289         softc->ipf_minttl = 4;
9290         softc->ipf_icmpminfragmtu = 68;
9291         softc->ipf_flags = IPF_LOGGING;
9292
9293         return softc;
9294 }
9295
9296 /* ------------------------------------------------------------------------ */
9297 /* Function:   ipf_main_soft_init                                           */
9298 /* Returns:    0 = success, -1 = failure                                    */
9299 /* Parameters: softc(I) - pointer to soft context main structure            */
9300 /*                                                                          */
9301 /* A null-op function that exists as a placeholder so that the flow in      */
9302 /* other functions is obvious.                                              */
9303 /* ------------------------------------------------------------------------ */
9304 /*ARGSUSED*/
9305 int
9306 ipf_main_soft_init(softc)
9307         ipf_main_softc_t *softc;
9308 {
9309         return 0;
9310 }
9311
9312
9313 /* ------------------------------------------------------------------------ */
9314 /* Function:   ipf_main_soft_destroy                                        */
9315 /* Returns:    void                                                         */
9316 /* Parameters: softc(I) - pointer to soft context main structure            */
9317 /*                                                                          */
9318 /* Undo everything that we did in ipf_main_soft_create.                     */
9319 /*                                                                          */
9320 /* The most important check that needs to be made here is whether or not    */
9321 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9322 /* value is stored in ipf_dynamic_main.                                     */
9323 /* ------------------------------------------------------------------------ */
9324 /*ARGSUSED*/
9325 void
9326 ipf_main_soft_destroy(softc)
9327         ipf_main_softc_t *softc;
9328 {
9329
9330         RW_DESTROY(&softc->ipf_frag);
9331         RW_DESTROY(&softc->ipf_poolrw);
9332         RW_DESTROY(&softc->ipf_nat);
9333         RW_DESTROY(&softc->ipf_state);
9334         RW_DESTROY(&softc->ipf_tokens);
9335         RW_DESTROY(&softc->ipf_mutex);
9336         RW_DESTROY(&softc->ipf_global);
9337         MUTEX_DESTROY(&softc->ipf_timeoutlock);
9338         MUTEX_DESTROY(&softc->ipf_rw);
9339
9340         if (softc->ipf_tuners != NULL) {
9341                 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9342         }
9343         if (softc->ipf_dynamic_softc == 1) {
9344                 KFREE(softc);
9345         }
9346 }
9347
9348
9349 /* ------------------------------------------------------------------------ */
9350 /* Function:   ipf_main_soft_fini                                           */
9351 /* Returns:    0 = success, -1 = failure                                    */
9352 /* Parameters: softc(I) - pointer to soft context main structure            */
9353 /*                                                                          */
9354 /* Clean out the rules which have been added since _init was last called,   */
9355 /* the only dynamic part of the mainline.                                   */
9356 /* ------------------------------------------------------------------------ */
9357 int
9358 ipf_main_soft_fini(softc)
9359         ipf_main_softc_t *softc;
9360 {
9361         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9362         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9363         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9364         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9365
9366         return 0;
9367 }
9368
9369
9370 /* ------------------------------------------------------------------------ */
9371 /* Function:   ipf_main_load                                                */
9372 /* Returns:    0 = success, -1 = failure                                    */
9373 /* Parameters: none                                                         */
9374 /*                                                                          */
9375 /* Handle global initialisation that needs to be done for the base part of  */
9376 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9377 /* arrays that get used by the state/NAT code.                              */
9378 /* ------------------------------------------------------------------------ */
9379 int
9380 ipf_main_load()
9381 {
9382         int i;
9383
9384         /* fill icmp reply type table */
9385         for (i = 0; i <= ICMP_MAXTYPE; i++)
9386                 icmpreplytype4[i] = -1;
9387         icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9388         icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9389         icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9390         icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9391
9392 #ifdef  USE_INET6
9393         /* fill icmp reply type table */
9394         for (i = 0; i <= ICMP6_MAXTYPE; i++)
9395                 icmpreplytype6[i] = -1;
9396         icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9397         icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9398         icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9399         icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9400         icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9401 #endif
9402
9403         return 0;
9404 }
9405
9406
9407 /* ------------------------------------------------------------------------ */
9408 /* Function:   ipf_main_unload                                              */
9409 /* Returns:    0 = success, -1 = failure                                    */
9410 /* Parameters: none                                                         */
9411 /*                                                                          */
9412 /* A null-op function that exists as a placeholder so that the flow in      */
9413 /* other functions is obvious.                                              */
9414 /* ------------------------------------------------------------------------ */
9415 int
9416 ipf_main_unload()
9417 {
9418         return 0;
9419 }
9420
9421
9422 /* ------------------------------------------------------------------------ */
9423 /* Function:   ipf_load_all                                                 */
9424 /* Returns:    0 = success, -1 = failure                                    */
9425 /* Parameters: none                                                         */
9426 /*                                                                          */
9427 /* Work through all of the subsystems inside IPFilter and call the load     */
9428 /* function for each in an order that won't lead to a crash :)              */
9429 /* ------------------------------------------------------------------------ */
9430 int
9431 ipf_load_all()
9432 {
9433         if (ipf_main_load() == -1)
9434                 return -1;
9435
9436         if (ipf_state_main_load() == -1)
9437                 return -1;
9438
9439         if (ipf_nat_main_load() == -1)
9440                 return -1;
9441
9442         if (ipf_frag_main_load() == -1)
9443                 return -1;
9444
9445         if (ipf_auth_main_load() == -1)
9446                 return -1;
9447
9448         if (ipf_proxy_main_load() == -1)
9449                 return -1;
9450
9451         return 0;
9452 }
9453
9454
9455 /* ------------------------------------------------------------------------ */
9456 /* Function:   ipf_unload_all                                               */
9457 /* Returns:    0 = success, -1 = failure                                    */
9458 /* Parameters: none                                                         */
9459 /*                                                                          */
9460 /* Work through all of the subsystems inside IPFilter and call the unload   */
9461 /* function for each in an order that won't lead to a crash :)              */
9462 /* ------------------------------------------------------------------------ */
9463 int
9464 ipf_unload_all()
9465 {
9466         if (ipf_proxy_main_unload() == -1)
9467                 return -1;
9468
9469         if (ipf_auth_main_unload() == -1)
9470                 return -1;
9471
9472         if (ipf_frag_main_unload() == -1)
9473                 return -1;
9474
9475         if (ipf_nat_main_unload() == -1)
9476                 return -1;
9477
9478         if (ipf_state_main_unload() == -1)
9479                 return -1;
9480
9481         if (ipf_main_unload() == -1)
9482                 return -1;
9483
9484         return 0;
9485 }
9486
9487
9488 /* ------------------------------------------------------------------------ */
9489 /* Function:   ipf_create_all                                               */
9490 /* Returns:    NULL = failure, else success                                 */
9491 /* Parameters: arg(I) - pointer to soft context main structure              */
9492 /*                                                                          */
9493 /* Work through all of the subsystems inside IPFilter and call the create   */
9494 /* function for each in an order that won't lead to a crash :)              */
9495 /* ------------------------------------------------------------------------ */
9496 ipf_main_softc_t *
9497 ipf_create_all(arg)
9498         void *arg;
9499 {
9500         ipf_main_softc_t *softc;
9501
9502         softc = ipf_main_soft_create(arg);
9503         if (softc == NULL)
9504                 return NULL;
9505
9506 #ifdef IPFILTER_LOG
9507         softc->ipf_log_soft = ipf_log_soft_create(softc);
9508         if (softc->ipf_log_soft == NULL) {
9509                 ipf_destroy_all(softc);
9510                 return NULL;
9511         }
9512 #endif
9513
9514         softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9515         if (softc->ipf_lookup_soft == NULL) {
9516                 ipf_destroy_all(softc);
9517                 return NULL;
9518         }
9519
9520         softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9521         if (softc->ipf_sync_soft == NULL) {
9522                 ipf_destroy_all(softc);
9523                 return NULL;
9524         }
9525
9526         softc->ipf_state_soft = ipf_state_soft_create(softc);
9527         if (softc->ipf_state_soft == NULL) {
9528                 ipf_destroy_all(softc);
9529                 return NULL;
9530         }
9531
9532         softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9533         if (softc->ipf_nat_soft == NULL) {
9534                 ipf_destroy_all(softc);
9535                 return NULL;
9536         }
9537
9538         softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9539         if (softc->ipf_frag_soft == NULL) {
9540                 ipf_destroy_all(softc);
9541                 return NULL;
9542         }
9543
9544         softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9545         if (softc->ipf_auth_soft == NULL) {
9546                 ipf_destroy_all(softc);
9547                 return NULL;
9548         }
9549
9550         softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9551         if (softc->ipf_proxy_soft == NULL) {
9552                 ipf_destroy_all(softc);
9553                 return NULL;
9554         }
9555
9556         return softc;
9557 }
9558
9559
9560 /* ------------------------------------------------------------------------ */
9561 /* Function:   ipf_destroy_all                                              */
9562 /* Returns:    void                                                         */
9563 /* Parameters: softc(I) - pointer to soft context main structure            */
9564 /*                                                                          */
9565 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9566 /* function for each in an order that won't lead to a crash :)              */
9567 /*                                                                          */
9568 /* Every one of these functions is expected to succeed, so there is no      */
9569 /* checking of return values.                                               */
9570 /* ------------------------------------------------------------------------ */
9571 void
9572 ipf_destroy_all(softc)
9573         ipf_main_softc_t *softc;
9574 {
9575
9576         if (softc->ipf_state_soft != NULL) {
9577                 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9578                 softc->ipf_state_soft = NULL;
9579         }
9580
9581         if (softc->ipf_nat_soft != NULL) {
9582                 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9583                 softc->ipf_nat_soft = NULL;
9584         }
9585
9586         if (softc->ipf_frag_soft != NULL) {
9587                 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9588                 softc->ipf_frag_soft = NULL;
9589         }
9590
9591         if (softc->ipf_auth_soft != NULL) {
9592                 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9593                 softc->ipf_auth_soft = NULL;
9594         }
9595
9596         if (softc->ipf_proxy_soft != NULL) {
9597                 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9598                 softc->ipf_proxy_soft = NULL;
9599         }
9600
9601         if (softc->ipf_sync_soft != NULL) {
9602                 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9603                 softc->ipf_sync_soft = NULL;
9604         }
9605
9606         if (softc->ipf_lookup_soft != NULL) {
9607                 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9608                 softc->ipf_lookup_soft = NULL;
9609         }
9610
9611 #ifdef IPFILTER_LOG
9612         if (softc->ipf_log_soft != NULL) {
9613                 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9614                 softc->ipf_log_soft = NULL;
9615         }
9616 #endif
9617
9618         ipf_main_soft_destroy(softc);
9619 }
9620
9621
9622 /* ------------------------------------------------------------------------ */
9623 /* Function:   ipf_init_all                                                 */
9624 /* Returns:    0 = success, -1 = failure                                    */
9625 /* Parameters: softc(I) - pointer to soft context main structure            */
9626 /*                                                                          */
9627 /* Work through all of the subsystems inside IPFilter and call the init     */
9628 /* function for each in an order that won't lead to a crash :)              */
9629 /* ------------------------------------------------------------------------ */
9630 int
9631 ipf_init_all(softc)
9632         ipf_main_softc_t *softc;
9633 {
9634
9635         if (ipf_main_soft_init(softc) == -1)
9636                 return -1;
9637
9638 #ifdef IPFILTER_LOG
9639         if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9640                 return -1;
9641 #endif
9642
9643         if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9644                 return -1;
9645
9646         if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9647                 return -1;
9648
9649         if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9650                 return -1;
9651
9652         if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9653                 return -1;
9654
9655         if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9656                 return -1;
9657
9658         if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9659                 return -1;
9660
9661         if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9662                 return -1;
9663
9664         return 0;
9665 }
9666
9667
9668 /* ------------------------------------------------------------------------ */
9669 /* Function:   ipf_fini_all                                                 */
9670 /* Returns:    0 = success, -1 = failure                                    */
9671 /* Parameters: softc(I) - pointer to soft context main structure            */
9672 /*                                                                          */
9673 /* Work through all of the subsystems inside IPFilter and call the fini     */
9674 /* function for each in an order that won't lead to a crash :)              */
9675 /* ------------------------------------------------------------------------ */
9676 int
9677 ipf_fini_all(softc)
9678         ipf_main_softc_t *softc;
9679 {
9680
9681         ipf_token_flush(softc);
9682
9683         if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9684                 return -1;
9685
9686         if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9687                 return -1;
9688
9689         if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9690                 return -1;
9691
9692         if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9693                 return -1;
9694
9695         if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9696                 return -1;
9697
9698         if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9699                 return -1;
9700
9701         if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9702                 return -1;
9703
9704 #ifdef IPFILTER_LOG
9705         if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9706                 return -1;
9707 #endif
9708
9709         if (ipf_main_soft_fini(softc) == -1)
9710                 return -1;
9711
9712         return 0;
9713 }
9714
9715
9716 /* ------------------------------------------------------------------------ */
9717 /* Function:    ipf_rule_expire                                             */
9718 /* Returns:     Nil                                                         */
9719 /* Parameters:  softc(I) - pointer to soft context main structure           */
9720 /*                                                                          */
9721 /* At present this function exists just to support temporary addition of    */
9722 /* firewall rules. Both inactive and active lists are scanned for items to  */
9723 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9724 /* loaded in.                                                               */
9725 /* ------------------------------------------------------------------------ */
9726 void
9727 ipf_rule_expire(softc)
9728         ipf_main_softc_t *softc;
9729 {
9730         frentry_t *fr;
9731
9732         if ((softc->ipf_rule_explist[0] == NULL) &&
9733             (softc->ipf_rule_explist[1] == NULL))
9734                 return;
9735
9736         WRITE_ENTER(&softc->ipf_mutex);
9737
9738         while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9739                 /*
9740                  * Because the list is kept sorted on insertion, the fist
9741                  * one that dies in the future means no more work to do.
9742                  */
9743                 if (fr->fr_die > softc->ipf_ticks)
9744                         break;
9745                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9746         }
9747
9748         while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9749                 /*
9750                  * Because the list is kept sorted on insertion, the fist
9751                  * one that dies in the future means no more work to do.
9752                  */
9753                 if (fr->fr_die > softc->ipf_ticks)
9754                         break;
9755                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9756         }
9757
9758         RWLOCK_EXIT(&softc->ipf_mutex);
9759 }
9760
9761
9762 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9763 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9764                                       i6addr_t *));
9765
9766 host_node_t RBI_ZERO(ipf_rb);
9767 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9768
9769
9770 /* ------------------------------------------------------------------------ */
9771 /* Function:    ipf_ht_node_cmp                                             */
9772 /* Returns:     int   - 0 == nodes are the same, ..                         */
9773 /* Parameters:  k1(I) - pointer to first key to compare                     */
9774 /*              k2(I) - pointer to second key to compare                    */
9775 /*                                                                          */
9776 /* The "key" for the node is a combination of two fields: the address       */
9777 /* family and the address itself.                                           */
9778 /*                                                                          */
9779 /* Because we're not actually interpreting the address data, it isn't       */
9780 /* necessary to convert them to/from network/host byte order. The mask is   */
9781 /* just used to remove bits that aren't significant - it doesn't matter     */
9782 /* where they are, as long as they're always in the same place.             */
9783 /*                                                                          */
9784 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9785 /* this is where individual ones will differ the most - but not true for    */
9786 /* for /48's, etc.                                                          */
9787 /* ------------------------------------------------------------------------ */
9788 static int
9789 ipf_ht_node_cmp(k1, k2)
9790         struct host_node_s *k1, *k2;
9791 {
9792         int i;
9793
9794         i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9795         if (i != 0)
9796                 return i;
9797
9798         if (k1->hn_addr.adf_family == AF_INET)
9799                 return (k2->hn_addr.adf_addr.in4.s_addr -
9800                         k1->hn_addr.adf_addr.in4.s_addr);
9801
9802         i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9803         if (i != 0)
9804                 return i;
9805         i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9806         if (i != 0)
9807                 return i;
9808         i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9809         if (i != 0)
9810                 return i;
9811         i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9812         return i;
9813 }
9814
9815
9816 /* ------------------------------------------------------------------------ */
9817 /* Function:    ipf_ht_node_make_key                                        */
9818 /* Returns:     Nil                                                         */
9819 /* parameters:  htp(I)    - pointer to address tracking structure           */
9820 /*              key(I)    - where to store masked address for lookup        */
9821 /*              family(I) - protocol family of address                      */
9822 /*              addr(I)   - pointer to network address                      */
9823 /*                                                                          */
9824 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9825 /* copy the address passed in into the key structure whilst masking out the */
9826 /* bits that we don't want.                                                 */
9827 /*                                                                          */
9828 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9829 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9830 /* have to be wary of that and not allow 32-128 to happen.                  */
9831 /* ------------------------------------------------------------------------ */
9832 static void
9833 ipf_ht_node_make_key(htp, key, family, addr)
9834         host_track_t *htp;
9835         host_node_t *key;
9836         int family;
9837         i6addr_t *addr;
9838 {
9839         key->hn_addr.adf_family = family;
9840         if (family == AF_INET) {
9841                 u_32_t mask;
9842                 int bits;
9843
9844                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9845                 bits = htp->ht_netmask;
9846                 if (bits >= 32) {
9847                         mask = 0xffffffff;
9848                 } else {
9849                         mask = htonl(0xffffffff << (32 - bits));
9850                 }
9851                 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9852 #ifdef USE_INET6
9853         } else {
9854                 int bits = htp->ht_netmask;
9855
9856                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9857                 if (bits > 96) {
9858                         key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9859                                              htonl(0xffffffff << (128 - bits));
9860                         key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9861                         key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9862                         key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9863                 } else if (bits > 64) {
9864                         key->hn_addr.adf_addr.i6[3] = 0;
9865                         key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9866                                              htonl(0xffffffff << (96 - bits));
9867                         key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9868                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9869                 } else if (bits > 32) {
9870                         key->hn_addr.adf_addr.i6[3] = 0;
9871                         key->hn_addr.adf_addr.i6[2] = 0;
9872                         key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9873                                              htonl(0xffffffff << (64 - bits));
9874                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9875                 } else {
9876                         key->hn_addr.adf_addr.i6[3] = 0;
9877                         key->hn_addr.adf_addr.i6[2] = 0;
9878                         key->hn_addr.adf_addr.i6[1] = 0;
9879                         key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9880                                              htonl(0xffffffff << (32 - bits));
9881                 }
9882 #endif
9883         }
9884 }
9885
9886
9887 /* ------------------------------------------------------------------------ */
9888 /* Function:    ipf_ht_node_add                                             */
9889 /* Returns:     int       - 0 == success,  -1 == failure                    */
9890 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9891 /*              htp(I)    - pointer to address tracking structure           */
9892 /*              family(I) - protocol family of address                      */
9893 /*              addr(I)   - pointer to network address                      */
9894 /*                                                                          */
9895 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9896 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9897 /*                                                                          */
9898 /* After preparing the key with the address information to find, look in    */
9899 /* the red-black tree to see if the address is known. A successful call to  */
9900 /* this function can mean one of two things: a new node was added to the    */
9901 /* tree or a matching node exists and we're able to bump up its activity.   */
9902 /* ------------------------------------------------------------------------ */
9903 int
9904 ipf_ht_node_add(softc, htp, family, addr)
9905         ipf_main_softc_t *softc;
9906         host_track_t *htp;
9907         int family;
9908         i6addr_t *addr;
9909 {
9910         host_node_t *h;
9911         host_node_t k;
9912
9913         ipf_ht_node_make_key(htp, &k, family, addr);
9914
9915         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9916         if (h == NULL) {
9917                 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9918                         return -1;
9919                 KMALLOC(h, host_node_t *);
9920                 if (h == NULL) {
9921                         DT(ipf_rb_no_mem);
9922                         LBUMP(ipf_rb_no_mem);
9923                         return -1;
9924                 }
9925
9926                 /*
9927                  * If there was a macro to initialise the RB node then that
9928                  * would get used here, but there isn't...
9929                  */
9930                 bzero((char *)h, sizeof(*h));
9931                 h->hn_addr = k.hn_addr;
9932                 h->hn_addr.adf_family = k.hn_addr.adf_family;
9933                 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9934                 htp->ht_cur_nodes++;
9935         } else {
9936                 if ((htp->ht_max_per_node != 0) &&
9937                     (h->hn_active >= htp->ht_max_per_node)) {
9938                         DT(ipf_rb_node_max);
9939                         LBUMP(ipf_rb_node_max);
9940                         return -1;
9941                 }
9942         }
9943
9944         h->hn_active++;
9945
9946         return 0;
9947 }
9948
9949
9950 /* ------------------------------------------------------------------------ */
9951 /* Function:    ipf_ht_node_del                                             */
9952 /* Returns:     int       - 0 == success,  -1 == failure                    */
9953 /* parameters:  htp(I)    - pointer to address tracking structure           */
9954 /*              family(I) - protocol family of address                      */
9955 /*              addr(I)   - pointer to network address                      */
9956 /*                                                                          */
9957 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9958 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9959 /*                                                                          */
9960 /* Try and find the address passed in amongst the leavese on this tree to   */
9961 /* be friend. If found then drop the active account for that node drops by  */
9962 /* one. If that count reaches 0, it is time to free it all up.              */
9963 /* ------------------------------------------------------------------------ */
9964 int
9965 ipf_ht_node_del(htp, family, addr)
9966         host_track_t *htp;
9967         int family;
9968         i6addr_t *addr;
9969 {
9970         host_node_t *h;
9971         host_node_t k;
9972
9973         ipf_ht_node_make_key(htp, &k, family, addr);
9974
9975         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9976         if (h == NULL) {
9977                 return -1;
9978         } else {
9979                 h->hn_active--;
9980                 if (h->hn_active == 0) {
9981                         (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9982                         htp->ht_cur_nodes--;
9983                         KFREE(h);
9984                 }
9985         }
9986
9987         return 0;
9988 }
9989
9990
9991 /* ------------------------------------------------------------------------ */
9992 /* Function:    ipf_rb_ht_init                                              */
9993 /* Returns:     Nil                                                         */
9994 /* Parameters:  head(I) - pointer to host tracking structure                */
9995 /*                                                                          */
9996 /* Initialise the host tracking structure to be ready for use above.        */
9997 /* ------------------------------------------------------------------------ */
9998 void
9999 ipf_rb_ht_init(head)
10000         host_track_t *head;
10001 {
10002         RBI_INIT(ipf_rb, &head->ht_root);
10003 }
10004
10005
10006 /* ------------------------------------------------------------------------ */
10007 /* Function:    ipf_rb_ht_freenode                                          */
10008 /* Returns:     Nil                                                         */
10009 /* Parameters:  head(I) - pointer to host tracking structure                */
10010 /*              arg(I)  - additional argument from walk caller              */
10011 /*                                                                          */
10012 /* Free an actual host_node_t structure.                                    */
10013 /* ------------------------------------------------------------------------ */
10014 void
10015 ipf_rb_ht_freenode(node, arg)
10016         host_node_t *node;
10017         void *arg;
10018 {
10019         KFREE(node);
10020 }
10021
10022
10023 /* ------------------------------------------------------------------------ */
10024 /* Function:    ipf_rb_ht_flush                                             */
10025 /* Returns:     Nil                                                         */
10026 /* Parameters:  head(I) - pointer to host tracking structure                */
10027 /*                                                                          */
10028 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10029 /* and free'ing each one.                                                   */
10030 /* ------------------------------------------------------------------------ */
10031 void
10032 ipf_rb_ht_flush(head)
10033         host_track_t *head;
10034 {
10035         RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10036 }
10037
10038
10039 /* ------------------------------------------------------------------------ */
10040 /* Function:    ipf_slowtimer                                               */
10041 /* Returns:     Nil                                                         */
10042 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10043 /*                                                                          */
10044 /* Slowly expire held state for fragments.  Timeouts are set * in           */
10045 /* expectation of this being called twice per second.                       */
10046 /* ------------------------------------------------------------------------ */
10047 void
10048 ipf_slowtimer(softc)
10049         ipf_main_softc_t *softc;
10050 {
10051
10052         ipf_token_expire(softc);
10053         ipf_frag_expire(softc);
10054         ipf_state_expire(softc);
10055         ipf_nat_expire(softc);
10056         ipf_auth_expire(softc);
10057         ipf_lookup_expire(softc);
10058         ipf_rule_expire(softc);
10059         ipf_sync_expire(softc);
10060         softc->ipf_ticks++;
10061 }
10062
10063
10064 /* ------------------------------------------------------------------------ */
10065 /* Function:    ipf_inet_mask_add                                           */
10066 /* Returns:     Nil                                                         */
10067 /* Parameters:  bits(I) - pointer to nat context information                */
10068 /*              mtab(I) - pointer to mask hash table structure              */
10069 /*                                                                          */
10070 /* When called, bits represents the mask of a new NAT rule that has just    */
10071 /* been added. This function inserts a bitmask into the array of masks to   */
10072 /* search when searching for a matching NAT rule for a packet.              */
10073 /* Prevention of duplicate masks is achieved by checking the use count for  */
10074 /* a given netmask.                                                         */
10075 /* ------------------------------------------------------------------------ */
10076 void
10077 ipf_inet_mask_add(bits, mtab)
10078         int bits;
10079         ipf_v4_masktab_t *mtab;
10080 {
10081         u_32_t mask;
10082         int i, j;
10083
10084         mtab->imt4_masks[bits]++;
10085         if (mtab->imt4_masks[bits] > 1)
10086                 return;
10087
10088         if (bits == 0)
10089                 mask = 0;
10090         else
10091                 mask = 0xffffffff << (32 - bits);
10092
10093         for (i = 0; i < 33; i++) {
10094                 if (ntohl(mtab->imt4_active[i]) < mask) {
10095                         for (j = 32; j > i; j--)
10096                                 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10097                         mtab->imt4_active[i] = htonl(mask);
10098                         break;
10099                 }
10100         }
10101         mtab->imt4_max++;
10102 }
10103
10104
10105 /* ------------------------------------------------------------------------ */
10106 /* Function:    ipf_inet_mask_del                                           */
10107 /* Returns:     Nil                                                         */
10108 /* Parameters:  bits(I) - number of bits set in the netmask                 */
10109 /*              mtab(I) - pointer to mask hash table structure              */
10110 /*                                                                          */
10111 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
10112 /* netmasks stored inside of mtab.                                          */
10113 /* ------------------------------------------------------------------------ */
10114 void
10115 ipf_inet_mask_del(bits, mtab)
10116         int bits;
10117         ipf_v4_masktab_t *mtab;
10118 {
10119         u_32_t mask;
10120         int i, j;
10121
10122         mtab->imt4_masks[bits]--;
10123         if (mtab->imt4_masks[bits] > 0)
10124                 return;
10125
10126         mask = htonl(0xffffffff << (32 - bits));
10127         for (i = 0; i < 33; i++) {
10128                 if (mtab->imt4_active[i] == mask) {
10129                         for (j = i + 1; j < 33; j++)
10130                                 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10131                         break;
10132                 }
10133         }
10134         mtab->imt4_max--;
10135         ASSERT(mtab->imt4_max >= 0);
10136 }
10137
10138
10139 #ifdef USE_INET6
10140 /* ------------------------------------------------------------------------ */
10141 /* Function:    ipf_inet6_mask_add                                          */
10142 /* Returns:     Nil                                                         */
10143 /* Parameters:  bits(I) - number of bits set in mask                        */
10144 /*              mask(I) - pointer to mask to add                            */
10145 /*              mtab(I) - pointer to mask hash table structure              */
10146 /*                                                                          */
10147 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10148 /* has just been added. This function inserts a bitmask into the array of   */
10149 /* masks to search when searching for a matching NAT rule for a packet.     */
10150 /* Prevention of duplicate masks is achieved by checking the use count for  */
10151 /* a given netmask.                                                         */
10152 /* ------------------------------------------------------------------------ */
10153 void
10154 ipf_inet6_mask_add(bits, mask, mtab)
10155         int bits;
10156         i6addr_t *mask;
10157         ipf_v6_masktab_t *mtab;
10158 {
10159         i6addr_t zero;
10160         int i, j;
10161
10162         mtab->imt6_masks[bits]++;
10163         if (mtab->imt6_masks[bits] > 1)
10164                 return;
10165
10166         if (bits == 0) {
10167                 mask = &zero;
10168                 zero.i6[0] = 0;
10169                 zero.i6[1] = 0;
10170                 zero.i6[2] = 0;
10171                 zero.i6[3] = 0;
10172         }
10173
10174         for (i = 0; i < 129; i++) {
10175                 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10176                         for (j = 128; j > i; j--)
10177                                 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10178                         mtab->imt6_active[i] = *mask;
10179                         break;
10180                 }
10181         }
10182         mtab->imt6_max++;
10183 }
10184
10185
10186 /* ------------------------------------------------------------------------ */
10187 /* Function:    ipf_inet6_mask_del                                          */
10188 /* Returns:     Nil                                                         */
10189 /* Parameters:  bits(I) - number of bits set in mask                        */
10190 /*              mask(I) - pointer to mask to remove                         */
10191 /*              mtab(I) - pointer to mask hash table structure              */
10192 /*                                                                          */
10193 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
10194 /* netmasks stored inside of mtab.                                          */
10195 /* ------------------------------------------------------------------------ */
10196 void
10197 ipf_inet6_mask_del(bits, mask, mtab)
10198         int bits;
10199         i6addr_t *mask;
10200         ipf_v6_masktab_t *mtab;
10201 {
10202         i6addr_t zero;
10203         int i, j;
10204
10205         mtab->imt6_masks[bits]--;
10206         if (mtab->imt6_masks[bits] > 0)
10207                 return;
10208
10209         if (bits == 0)
10210                 mask = &zero;
10211         zero.i6[0] = 0;
10212         zero.i6[1] = 0;
10213         zero.i6[2] = 0;
10214         zero.i6[3] = 0;
10215
10216         for (i = 0; i < 129; i++) {
10217                 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10218                         for (j = i + 1; j < 129; j++) {
10219                                 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10220                                 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10221                                         break;
10222                         }
10223                         break;
10224                 }
10225         }
10226         mtab->imt6_max--;
10227         ASSERT(mtab->imt6_max >= 0);
10228 }
10229 #endif