]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/ipfilter/netinet/fil.c
Upgrade LDNS to 1.7.0.
[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     (__FreeBSD_version >= 220000)
25 # if (__FreeBSD_version >= 400000)
26 #  if !defined(IPFILTER_LKM)
27 #   include "opt_inet6.h"
28 #  endif
29 #  if (__FreeBSD_version == 400019)
30 #   define CSUM_DELAY_DATA
31 #  endif
32 # endif
33 # include <sys/filio.h>
34 #else
35 # include <sys/ioctl.h>
36 #endif
37 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
38 # include <sys/filio.h>
39 #endif
40 #if !defined(_AIX51)
41 # include <sys/fcntl.h>
42 #endif
43 #if defined(_KERNEL)
44 # include <sys/systm.h>
45 # include <sys/file.h>
46 #else
47 # include <stdio.h>
48 # include <string.h>
49 # include <stdlib.h>
50 # include <stddef.h>
51 # include <sys/file.h>
52 # define _KERNEL
53 # ifdef __OpenBSD__
54 struct file;
55 # endif
56 # include <sys/uio.h>
57 # undef _KERNEL
58 #endif
59 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
60     !defined(linux)
61 # include <sys/mbuf.h>
62 #else
63 # if !defined(linux)
64 #  include <sys/byteorder.h>
65 # endif
66 # if (SOLARIS2 < 5) && defined(sun)
67 #  include <sys/dditypes.h>
68 # endif
69 #endif
70 #ifdef __hpux
71 # define _NET_ROUTE_INCLUDED
72 #endif
73 #if !defined(linux)
74 # include <sys/protosw.h>
75 #endif
76 #include <sys/socket.h>
77 #include <net/if.h>
78 #ifdef sun
79 # include <net/af.h>
80 #endif
81 #include <netinet/in.h>
82 #include <netinet/in_systm.h>
83 #include <netinet/ip.h>
84 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
85 # include <sys/hashing.h>
86 # include <netinet/in_var.h>
87 #endif
88 #include <netinet/tcp.h>
89 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
90 # include <netinet/udp.h>
91 # include <netinet/ip_icmp.h>
92 #endif
93 #ifdef __hpux
94 # undef _NET_ROUTE_INCLUDED
95 #endif
96 #ifdef __osf__
97 # undef _RADIX_H_
98 #endif
99 #include "netinet/ip_compat.h"
100 #ifdef  USE_INET6
101 # include <netinet/icmp6.h>
102 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
103 #  include <netinet6/in6_var.h>
104 # endif
105 #endif
106 #include "netinet/ip_fil.h"
107 #include "netinet/ip_nat.h"
108 #include "netinet/ip_frag.h"
109 #include "netinet/ip_state.h"
110 #include "netinet/ip_proxy.h"
111 #include "netinet/ip_auth.h"
112 #ifdef IPFILTER_SCAN
113 # include "netinet/ip_scan.h"
114 #endif
115 #include "netinet/ip_sync.h"
116 #include "netinet/ip_lookup.h"
117 #include "netinet/ip_pool.h"
118 #include "netinet/ip_htable.h"
119 #ifdef IPFILTER_COMPILED
120 # include "netinet/ip_rules.h"
121 #endif
122 #if defined(IPFILTER_BPF) && defined(_KERNEL)
123 # include <net/bpf.h>
124 #endif
125 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
126 # include <sys/malloc.h>
127 #endif
128 #include "netinet/ipl.h"
129
130 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
131 # include <sys/callout.h>
132 extern struct callout ipf_slowtimer_ch;
133 #endif
134 #if defined(__OpenBSD__)
135 # include <sys/timeout.h>
136 extern struct timeout ipf_slowtimer_ch;
137 #endif
138 /* END OF INCLUDES */
139
140 #if !defined(lint)
141 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
142 static const char rcsid[] = "@(#)$FreeBSD$";
143 /* static const char rcsid[] = "@(#)$Id: fil.c,v 2.243.2.125 2007/10/10 09:27:20 darrenr Exp $"; */
144 #endif
145
146 #ifndef _KERNEL
147 # include "ipf.h"
148 # include "ipt.h"
149 extern  int     opts;
150 extern  int     blockreason;
151 #endif /* _KERNEL */
152
153 #define LBUMP(x)        softc->x++
154 #define LBUMPD(x, y)    do { softc->x.y++; DT(y); } while (0)
155
156 static  INLINE int      ipf_check_ipf __P((fr_info_t *, frentry_t *, int));
157 static  u_32_t          ipf_checkcipso __P((fr_info_t *, u_char *, int));
158 static  u_32_t          ipf_checkripso __P((u_char *));
159 static  u_32_t          ipf_decaps __P((fr_info_t *, u_32_t, int));
160 #ifdef IPFILTER_LOG
161 static  frentry_t       *ipf_dolog __P((fr_info_t *, u_32_t *));
162 #endif
163 static  int             ipf_flushlist __P((ipf_main_softc_t *, int *,
164                                            frentry_t **));
165 static  int             ipf_flush_groups __P((ipf_main_softc_t *, frgroup_t **,
166                                               int));
167 static  ipfunc_t        ipf_findfunc __P((ipfunc_t));
168 static  void            *ipf_findlookup __P((ipf_main_softc_t *, int,
169                                              frentry_t *,
170                                              i6addr_t *, i6addr_t *));
171 static  frentry_t       *ipf_firewall __P((fr_info_t *, u_32_t *));
172 static  int             ipf_fr_matcharray __P((fr_info_t *, int *));
173 static  int             ipf_frruleiter __P((ipf_main_softc_t *, void *, int,
174                                             void *));
175 static  void            ipf_funcfini __P((ipf_main_softc_t *, frentry_t *));
176 static  int             ipf_funcinit __P((ipf_main_softc_t *, frentry_t *));
177 static  int             ipf_geniter __P((ipf_main_softc_t *, ipftoken_t *,
178                                          ipfgeniter_t *));
179 static  void            ipf_getstat __P((ipf_main_softc_t *,
180                                          struct friostat *, int));
181 static  int             ipf_group_flush __P((ipf_main_softc_t *, frgroup_t *));
182 static  void            ipf_group_free __P((frgroup_t *));
183 static  int             ipf_grpmapfini __P((struct ipf_main_softc_s *,
184                                             frentry_t *));
185 static  int             ipf_grpmapinit __P((struct ipf_main_softc_s *,
186                                             frentry_t *));
187 static  frentry_t       *ipf_nextrule __P((ipf_main_softc_t *, int, int,
188                                            frentry_t *, int));
189 static  int             ipf_portcheck __P((frpcmp_t *, u_32_t));
190 static  INLINE int      ipf_pr_ah __P((fr_info_t *));
191 static  INLINE void     ipf_pr_esp __P((fr_info_t *));
192 static  INLINE void     ipf_pr_gre __P((fr_info_t *));
193 static  INLINE void     ipf_pr_udp __P((fr_info_t *));
194 static  INLINE void     ipf_pr_tcp __P((fr_info_t *));
195 static  INLINE void     ipf_pr_icmp __P((fr_info_t *));
196 static  INLINE void     ipf_pr_ipv4hdr __P((fr_info_t *));
197 static  INLINE void     ipf_pr_short __P((fr_info_t *, int));
198 static  INLINE int      ipf_pr_tcpcommon __P((fr_info_t *));
199 static  INLINE int      ipf_pr_udpcommon __P((fr_info_t *));
200 static  void            ipf_rule_delete __P((ipf_main_softc_t *, frentry_t *f,
201                                              int, int));
202 static  void            ipf_rule_expire_insert __P((ipf_main_softc_t *,
203                                                     frentry_t *, int));
204 static  int             ipf_synclist __P((ipf_main_softc_t *, frentry_t *,
205                                           void *));
206 static  void            ipf_token_flush __P((ipf_main_softc_t *));
207 static  void            ipf_token_unlink __P((ipf_main_softc_t *,
208                                               ipftoken_t *));
209 static  ipftuneable_t   *ipf_tune_findbyname __P((ipftuneable_t *,
210                                                   const char *));
211 static  ipftuneable_t   *ipf_tune_findbycookie __P((ipftuneable_t **, void *,
212                                                     void **));
213 static  int             ipf_updateipid __P((fr_info_t *));
214 static  int             ipf_settimeout __P((struct ipf_main_softc_s *,
215                                             struct ipftuneable *,
216                                             ipftuneval_t *));
217 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
218      !defined(__FreeBSD__)) || \
219     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
220     OPENBSD_LT_REV(200006)
221 static  int             ppsratecheck(struct timeval *, int *, int);
222 #endif
223
224
225 /*
226  * bit values for identifying presence of individual IP options
227  * All of these tables should be ordered by increasing key value on the left
228  * hand side to allow for binary searching of the array and include a trailer
229  * with a 0 for the bitmask for linear searches to easily find the end with.
230  */
231 static const    struct  optlist ipopts[20] = {
232         { IPOPT_NOP,    0x000001 },
233         { IPOPT_RR,     0x000002 },
234         { IPOPT_ZSU,    0x000004 },
235         { IPOPT_MTUP,   0x000008 },
236         { IPOPT_MTUR,   0x000010 },
237         { IPOPT_ENCODE, 0x000020 },
238         { IPOPT_TS,     0x000040 },
239         { IPOPT_TR,     0x000080 },
240         { IPOPT_SECURITY, 0x000100 },
241         { IPOPT_LSRR,   0x000200 },
242         { IPOPT_E_SEC,  0x000400 },
243         { IPOPT_CIPSO,  0x000800 },
244         { IPOPT_SATID,  0x001000 },
245         { IPOPT_SSRR,   0x002000 },
246         { IPOPT_ADDEXT, 0x004000 },
247         { IPOPT_VISA,   0x008000 },
248         { IPOPT_IMITD,  0x010000 },
249         { IPOPT_EIP,    0x020000 },
250         { IPOPT_FINN,   0x040000 },
251         { 0,            0x000000 }
252 };
253
254 #ifdef USE_INET6
255 static const struct optlist ip6exthdr[] = {
256         { IPPROTO_HOPOPTS,              0x000001 },
257         { IPPROTO_IPV6,                 0x000002 },
258         { IPPROTO_ROUTING,              0x000004 },
259         { IPPROTO_FRAGMENT,             0x000008 },
260         { IPPROTO_ESP,                  0x000010 },
261         { IPPROTO_AH,                   0x000020 },
262         { IPPROTO_NONE,                 0x000040 },
263         { IPPROTO_DSTOPTS,              0x000080 },
264         { IPPROTO_MOBILITY,             0x000100 },
265         { 0,                            0 }
266 };
267 #endif
268
269 /*
270  * bit values for identifying presence of individual IP security options
271  */
272 static const    struct  optlist secopt[8] = {
273         { IPSO_CLASS_RES4,      0x01 },
274         { IPSO_CLASS_TOPS,      0x02 },
275         { IPSO_CLASS_SECR,      0x04 },
276         { IPSO_CLASS_RES3,      0x08 },
277         { IPSO_CLASS_CONF,      0x10 },
278         { IPSO_CLASS_UNCL,      0x20 },
279         { IPSO_CLASS_RES2,      0x40 },
280         { IPSO_CLASS_RES1,      0x80 }
281 };
282
283 char    ipfilter_version[] = IPL_VERSION;
284
285 int     ipf_features = 0
286 #ifdef  IPFILTER_LKM
287                 | IPF_FEAT_LKM
288 #endif
289 #ifdef  IPFILTER_LOG
290                 | IPF_FEAT_LOG
291 #endif
292                 | IPF_FEAT_LOOKUP
293 #ifdef  IPFILTER_BPF
294                 | IPF_FEAT_BPF
295 #endif
296 #ifdef  IPFILTER_COMPILED
297                 | IPF_FEAT_COMPILED
298 #endif
299 #ifdef  IPFILTER_CKSUM
300                 | IPF_FEAT_CKSUM
301 #endif
302                 | IPF_FEAT_SYNC
303 #ifdef  IPFILTER_SCAN
304                 | IPF_FEAT_SCAN
305 #endif
306 #ifdef  USE_INET6
307                 | IPF_FEAT_IPV6
308 #endif
309         ;
310
311
312 /*
313  * Table of functions available for use with call rules.
314  */
315 static ipfunc_resolve_t ipf_availfuncs[] = {
316         { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
317         { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
318         { "",         NULL,           NULL,           NULL }
319 };
320
321 static ipftuneable_t ipf_main_tuneables[] = {
322         { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
323                 "ipf_flags",            0,      0xffffffff,
324                 stsizeof(ipf_main_softc_t, ipf_flags),
325                 0,                      NULL,   NULL },
326         { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
327                 "active",               0,      0,
328                 stsizeof(ipf_main_softc_t, ipf_active),
329                 IPFT_RDONLY,            NULL,   NULL },
330         { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
331                 "control_forwarding",   0, 1,
332                 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
333                 0,                      NULL,   NULL },
334         { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
335                 "update_ipid",          0,      1,
336                 stsizeof(ipf_main_softc_t, ipf_update_ipid),
337                 0,                      NULL,   NULL },
338         { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
339                 "chksrc",               0,      1,
340                 stsizeof(ipf_main_softc_t, ipf_chksrc),
341                 0,                      NULL,   NULL },
342         { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
343                 "min_ttl",              0,      1,
344                 stsizeof(ipf_main_softc_t, ipf_minttl),
345                 0,                      NULL,   NULL },
346         { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
347                 "icmp_minfragmtu",      0,      1,
348                 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
349                 0,                      NULL,   NULL },
350         { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
351                 "default_pass",         0,      0xffffffff,
352                 stsizeof(ipf_main_softc_t, ipf_pass),
353                 0,                      NULL,   NULL },
354         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
355                 "tcp_idle_timeout",     1,      0x7fffffff,
356                 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
357                 0,                      NULL,   ipf_settimeout },
358         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
359                 "tcp_close_wait",       1,      0x7fffffff,
360                 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
361                 0,                      NULL,   ipf_settimeout },
362         { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
363                 "tcp_last_ack",         1,      0x7fffffff,
364                 stsizeof(ipf_main_softc_t, ipf_tcplastack),
365                 0,                      NULL,   ipf_settimeout },
366         { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
367                 "tcp_timeout",          1,      0x7fffffff,
368                 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
369                 0,                      NULL,   ipf_settimeout },
370         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
371                 "tcp_syn_sent",         1,      0x7fffffff,
372                 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
373                 0,                      NULL,   ipf_settimeout },
374         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
375                 "tcp_syn_received",     1,      0x7fffffff,
376                 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
377                 0,                      NULL,   ipf_settimeout },
378         { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
379                 "tcp_closed",           1,      0x7fffffff,
380                 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
381                 0,                      NULL,   ipf_settimeout },
382         { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
383                 "tcp_half_closed",      1,      0x7fffffff,
384                 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
385                 0,                      NULL,   ipf_settimeout },
386         { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
387                 "tcp_time_wait",        1,      0x7fffffff,
388                 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
389                 0,                      NULL,   ipf_settimeout },
390         { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
391                 "udp_timeout",          1,      0x7fffffff,
392                 stsizeof(ipf_main_softc_t, ipf_udptimeout),
393                 0,                      NULL,   ipf_settimeout },
394         { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
395                 "udp_ack_timeout",      1,      0x7fffffff,
396                 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
397                 0,                      NULL,   ipf_settimeout },
398         { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
399                 "icmp_timeout",         1,      0x7fffffff,
400                 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
401                 0,                      NULL,   ipf_settimeout },
402         { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
403                 "icmp_ack_timeout",     1,      0x7fffffff,
404                 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
405                 0,                      NULL,   ipf_settimeout },
406         { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
407                 "ip_timeout",           1,      0x7fffffff,
408                 stsizeof(ipf_main_softc_t, ipf_iptimeout),
409                 0,                      NULL,   ipf_settimeout },
410 #if defined(INSTANCES) && defined(_KERNEL)
411         { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
412                 "intercept_loopback",   0,      1,
413                 stsizeof(ipf_main_softc_t, ipf_get_loopback),
414                 0,                      NULL,   ipf_set_loopback },
415 #endif
416         { { 0 },
417                 NULL,                   0,      0,
418                 0,
419                 0,                      NULL,   NULL }
420 };
421
422
423 /*
424  * The next section of code is a collection of small routines that set
425  * fields in the fr_info_t structure passed based on properties of the
426  * current packet.  There are different routines for the same protocol
427  * for each of IPv4 and IPv6.  Adding a new protocol, for which there
428  * will "special" inspection for setup, is now more easily done by adding
429  * a new routine and expanding the ipf_pr_ipinit*() function rather than by
430  * adding more code to a growing switch statement.
431  */
432 #ifdef USE_INET6
433 static  INLINE int      ipf_pr_ah6 __P((fr_info_t *));
434 static  INLINE void     ipf_pr_esp6 __P((fr_info_t *));
435 static  INLINE void     ipf_pr_gre6 __P((fr_info_t *));
436 static  INLINE void     ipf_pr_udp6 __P((fr_info_t *));
437 static  INLINE void     ipf_pr_tcp6 __P((fr_info_t *));
438 static  INLINE void     ipf_pr_icmp6 __P((fr_info_t *));
439 static  INLINE void     ipf_pr_ipv6hdr __P((fr_info_t *));
440 static  INLINE void     ipf_pr_short6 __P((fr_info_t *, int));
441 static  INLINE int      ipf_pr_hopopts6 __P((fr_info_t *));
442 static  INLINE int      ipf_pr_mobility6 __P((fr_info_t *));
443 static  INLINE int      ipf_pr_routing6 __P((fr_info_t *));
444 static  INLINE int      ipf_pr_dstopts6 __P((fr_info_t *));
445 static  INLINE int      ipf_pr_fragment6 __P((fr_info_t *));
446 static  INLINE struct ip6_ext *ipf_pr_ipv6exthdr __P((fr_info_t *, int, int));
447
448
449 /* ------------------------------------------------------------------------ */
450 /* Function:    ipf_pr_short6                                               */
451 /* Returns:     void                                                        */
452 /* Parameters:  fin(I)  - pointer to packet information                     */
453 /*              xmin(I) - minimum header size                               */
454 /*                                                                          */
455 /* IPv6 Only                                                                */
456 /* This is function enforces the 'is a packet too short to be legit' rule   */
457 /* for IPv6 and marks the packet with FI_SHORT if so.  See function comment */
458 /* for ipf_pr_short() for more details.                                     */
459 /* ------------------------------------------------------------------------ */
460 static INLINE void
461 ipf_pr_short6(fin, xmin)
462         fr_info_t *fin;
463         int xmin;
464 {
465
466         if (fin->fin_dlen < xmin)
467                 fin->fin_flx |= FI_SHORT;
468 }
469
470
471 /* ------------------------------------------------------------------------ */
472 /* Function:    ipf_pr_ipv6hdr                                              */
473 /* Returns:     void                                                        */
474 /* Parameters:  fin(I) - pointer to packet information                      */
475 /*                                                                          */
476 /* IPv6 Only                                                                */
477 /* Copy values from the IPv6 header into the fr_info_t struct and call the  */
478 /* per-protocol analyzer if it exists.  In validating the packet, a protocol*/
479 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
480 /* of that possibility arising.                                             */
481 /* ------------------------------------------------------------------------ */
482 static INLINE void
483 ipf_pr_ipv6hdr(fin)
484         fr_info_t *fin;
485 {
486         ip6_t *ip6 = (ip6_t *)fin->fin_ip;
487         int p, go = 1, i, hdrcount;
488         fr_ip_t *fi = &fin->fin_fi;
489
490         fin->fin_off = 0;
491
492         fi->fi_tos = 0;
493         fi->fi_optmsk = 0;
494         fi->fi_secmsk = 0;
495         fi->fi_auth = 0;
496
497         p = ip6->ip6_nxt;
498         fin->fin_crc = p;
499         fi->fi_ttl = ip6->ip6_hlim;
500         fi->fi_src.in6 = ip6->ip6_src;
501         fin->fin_crc += fi->fi_src.i6[0];
502         fin->fin_crc += fi->fi_src.i6[1];
503         fin->fin_crc += fi->fi_src.i6[2];
504         fin->fin_crc += fi->fi_src.i6[3];
505         fi->fi_dst.in6 = ip6->ip6_dst;
506         fin->fin_crc += fi->fi_dst.i6[0];
507         fin->fin_crc += fi->fi_dst.i6[1];
508         fin->fin_crc += fi->fi_dst.i6[2];
509         fin->fin_crc += fi->fi_dst.i6[3];
510         fin->fin_id = 0;
511         if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
512                 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
513
514         hdrcount = 0;
515         while (go && !(fin->fin_flx & FI_SHORT)) {
516                 switch (p)
517                 {
518                 case IPPROTO_UDP :
519                         ipf_pr_udp6(fin);
520                         go = 0;
521                         break;
522
523                 case IPPROTO_TCP :
524                         ipf_pr_tcp6(fin);
525                         go = 0;
526                         break;
527
528                 case IPPROTO_ICMPV6 :
529                         ipf_pr_icmp6(fin);
530                         go = 0;
531                         break;
532
533                 case IPPROTO_GRE :
534                         ipf_pr_gre6(fin);
535                         go = 0;
536                         break;
537
538                 case IPPROTO_HOPOPTS :
539                         p = ipf_pr_hopopts6(fin);
540                         break;
541
542                 case IPPROTO_MOBILITY :
543                         p = ipf_pr_mobility6(fin);
544                         break;
545
546                 case IPPROTO_DSTOPTS :
547                         p = ipf_pr_dstopts6(fin);
548                         break;
549
550                 case IPPROTO_ROUTING :
551                         p = ipf_pr_routing6(fin);
552                         break;
553
554                 case IPPROTO_AH :
555                         p = ipf_pr_ah6(fin);
556                         break;
557
558                 case IPPROTO_ESP :
559                         ipf_pr_esp6(fin);
560                         go = 0;
561                         break;
562
563                 case IPPROTO_IPV6 :
564                         for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
565                                 if (ip6exthdr[i].ol_val == p) {
566                                         fin->fin_flx |= ip6exthdr[i].ol_bit;
567                                         break;
568                                 }
569                         go = 0;
570                         break;
571
572                 case IPPROTO_NONE :
573                         go = 0;
574                         break;
575
576                 case IPPROTO_FRAGMENT :
577                         p = ipf_pr_fragment6(fin);
578                         /*
579                          * Given that the only fragments we want to let through
580                          * (where fin_off != 0) are those where the non-first
581                          * fragments only have data, we can safely stop looking
582                          * at headers if this is a non-leading fragment.
583                          */
584                         if (fin->fin_off != 0)
585                                 go = 0;
586                         break;
587
588                 default :
589                         go = 0;
590                         break;
591                 }
592                 hdrcount++;
593
594                 /*
595                  * It is important to note that at this point, for the
596                  * extension headers (go != 0), the entire header may not have
597                  * been pulled up when the code gets to this point.  This is
598                  * only done for "go != 0" because the other header handlers
599                  * will all pullup their complete header.  The other indicator
600                  * of an incomplete packet is that this was just an extension
601                  * header.
602                  */
603                 if ((go != 0) && (p != IPPROTO_NONE) &&
604                     (ipf_pr_pullup(fin, 0) == -1)) {
605                         p = IPPROTO_NONE;
606                         break;
607                 }
608         }
609
610         /*
611          * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
612          * and destroy whatever packet was here.  The caller of this function
613          * expects us to return if there is a problem with ipf_pullup.
614          */
615         if (fin->fin_m == NULL) {
616                 ipf_main_softc_t *softc = fin->fin_main_soft;
617
618                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
619                 return;
620         }
621
622         fi->fi_p = p;
623
624         /*
625          * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
626          * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
627          */
628         if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
629                 ipf_main_softc_t *softc = fin->fin_main_soft;
630
631                 fin->fin_flx |= FI_BAD;
632                 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
633                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
634                 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
635         }
636 }
637
638
639 /* ------------------------------------------------------------------------ */
640 /* Function:    ipf_pr_ipv6exthdr                                           */
641 /* Returns:     struct ip6_ext * - pointer to the start of the next header  */
642 /*                                 or NULL if there is a prolblem.          */
643 /* Parameters:  fin(I)      - pointer to packet information                 */
644 /*              multiple(I) - flag indicating yes/no if multiple occurances */
645 /*                            of this extension header are allowed.         */
646 /*              proto(I)    - protocol number for this extension header     */
647 /*                                                                          */
648 /* IPv6 Only                                                                */
649 /* This function embodies a number of common checks that all IPv6 extension */
650 /* headers must be subjected to.  For example, making sure the packet is    */
651 /* big enough for it to be in, checking if it is repeated and setting a     */
652 /* flag to indicate its presence.                                           */
653 /* ------------------------------------------------------------------------ */
654 static INLINE struct ip6_ext *
655 ipf_pr_ipv6exthdr(fin, multiple, proto)
656         fr_info_t *fin;
657         int multiple, proto;
658 {
659         ipf_main_softc_t *softc = fin->fin_main_soft;
660         struct ip6_ext *hdr;
661         u_short shift;
662         int i;
663
664         fin->fin_flx |= FI_V6EXTHDR;
665
666                                 /* 8 is default length of extension hdr */
667         if ((fin->fin_dlen - 8) < 0) {
668                 fin->fin_flx |= FI_SHORT;
669                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
670                 return NULL;
671         }
672
673         if (ipf_pr_pullup(fin, 8) == -1) {
674                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
675                 return NULL;
676         }
677
678         hdr = fin->fin_dp;
679         switch (proto)
680         {
681         case IPPROTO_FRAGMENT :
682                 shift = 8;
683                 break;
684         default :
685                 shift = 8 + (hdr->ip6e_len << 3);
686                 break;
687         }
688
689         if (shift > fin->fin_dlen) {    /* Nasty extension header length? */
690                 fin->fin_flx |= FI_BAD;
691                 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
692                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
693                 return NULL;
694         }
695
696         fin->fin_dp = (char *)fin->fin_dp + shift;
697         fin->fin_dlen -= shift;
698
699         /*
700          * If we have seen a fragment header, do not set any flags to indicate
701          * the presence of this extension header as it has no impact on the
702          * end result until after it has been defragmented.
703          */
704         if (fin->fin_flx & FI_FRAG)
705                 return hdr;
706
707         for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
708                 if (ip6exthdr[i].ol_val == proto) {
709                         /*
710                          * Most IPv6 extension headers are only allowed once.
711                          */
712                         if ((multiple == 0) &&
713                             ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
714                                 fin->fin_flx |= FI_BAD;
715                                 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
716                         } else
717                                 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
718                         break;
719                 }
720
721         return hdr;
722 }
723
724
725 /* ------------------------------------------------------------------------ */
726 /* Function:    ipf_pr_hopopts6                                             */
727 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
728 /* Parameters:  fin(I) - pointer to packet information                      */
729 /*                                                                          */
730 /* IPv6 Only                                                                */
731 /* This is function checks pending hop by hop options extension header      */
732 /* ------------------------------------------------------------------------ */
733 static INLINE int
734 ipf_pr_hopopts6(fin)
735         fr_info_t *fin;
736 {
737         struct ip6_ext *hdr;
738
739         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
740         if (hdr == NULL)
741                 return IPPROTO_NONE;
742         return hdr->ip6e_nxt;
743 }
744
745
746 /* ------------------------------------------------------------------------ */
747 /* Function:    ipf_pr_mobility6                                            */
748 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
749 /* Parameters:  fin(I) - pointer to packet information                      */
750 /*                                                                          */
751 /* IPv6 Only                                                                */
752 /* This is function checks the IPv6 mobility extension header               */
753 /* ------------------------------------------------------------------------ */
754 static INLINE int
755 ipf_pr_mobility6(fin)
756         fr_info_t *fin;
757 {
758         struct ip6_ext *hdr;
759
760         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
761         if (hdr == NULL)
762                 return IPPROTO_NONE;
763         return hdr->ip6e_nxt;
764 }
765
766
767 /* ------------------------------------------------------------------------ */
768 /* Function:    ipf_pr_routing6                                             */
769 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
770 /* Parameters:  fin(I) - pointer to packet information                      */
771 /*                                                                          */
772 /* IPv6 Only                                                                */
773 /* This is function checks pending routing extension header                 */
774 /* ------------------------------------------------------------------------ */
775 static INLINE int
776 ipf_pr_routing6(fin)
777         fr_info_t *fin;
778 {
779         struct ip6_routing *hdr;
780
781         hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
782         if (hdr == NULL)
783                 return IPPROTO_NONE;
784
785         switch (hdr->ip6r_type)
786         {
787         case 0 :
788                 /*
789                  * Nasty extension header length?
790                  */
791                 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
792                     (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
793                         ipf_main_softc_t *softc = fin->fin_main_soft;
794
795                         fin->fin_flx |= FI_BAD;
796                         DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
797                         LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
798                         return IPPROTO_NONE;
799                 }
800                 break;
801
802         default :
803                 break;
804         }
805
806         return hdr->ip6r_nxt;
807 }
808
809
810 /* ------------------------------------------------------------------------ */
811 /* Function:    ipf_pr_fragment6                                            */
812 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
813 /* Parameters:  fin(I) - pointer to packet information                      */
814 /*                                                                          */
815 /* IPv6 Only                                                                */
816 /* Examine the IPv6 fragment header and extract fragment offset information.*/
817 /*                                                                          */
818 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
819 /* so than in IPv4.  There are 5 cases of fragments with IPv6 that all      */
820 /* packets with a fragment header can fit into.  They are as follows:       */
821 /*                                                                          */
822 /* 1.  [IPv6][0-n EH][FH][0-n EH] (no L4HDR present)                        */
823 /* 2.  [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short)                       */
824 /* 3.  [IPV6][0-n EH][FH][L4HDR part][0-n data] (short)                     */
825 /* 4.  [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data]                          */
826 /* 5.  [IPV6][0-n EH][FH][data]                                             */
827 /*                                                                          */
828 /* IPV6 = IPv6 header, FH = Fragment Header,                                */
829 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
830 /*                                                                          */
831 /* Packets that match 1, 2, 3 will be dropped as the only reasonable        */
832 /* scenario in which they happen is in extreme circumstances that are most  */
833 /* likely to be an indication of an attack rather than normal traffic.      */
834 /* A type 3 packet may be sent by an attacked after a type 4 packet.  There */
835 /* are two rules that can be used to guard against type 3 packets: L4       */
836 /* headers must always be in a packet that has the offset field set to 0    */
837 /* and no packet is allowed to overlay that where offset = 0.               */
838 /* ------------------------------------------------------------------------ */
839 static INLINE int
840 ipf_pr_fragment6(fin)
841         fr_info_t *fin;
842 {
843         ipf_main_softc_t *softc = fin->fin_main_soft;
844         struct ip6_frag *frag;
845
846         fin->fin_flx |= FI_FRAG;
847
848         frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
849         if (frag == NULL) {
850                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
851                 return IPPROTO_NONE;
852         }
853
854         if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
855                 /*
856                  * Any fragment that isn't the last fragment must have its
857                  * length as a multiple of 8.
858                  */
859                 if ((fin->fin_plen & 7) != 0) {
860                         fin->fin_flx |= FI_BAD;
861                         DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
862                 }
863         }
864
865         fin->fin_fraghdr = frag;
866         fin->fin_id = frag->ip6f_ident;
867         fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
868         if (fin->fin_off != 0)
869                 fin->fin_flx |= FI_FRAGBODY;
870
871         /*
872          * Jumbograms aren't handled, so the max. length is 64k
873          */
874         if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
875                   fin->fin_flx |= FI_BAD;
876                   DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
877         }
878
879         /*
880          * We don't know where the transport layer header (or whatever is next
881          * is), as it could be behind destination options (amongst others) so
882          * return the fragment header as the type of packet this is.  Note that
883          * this effectively disables the fragment cache for > 1 protocol at a
884          * time.
885          */
886         return frag->ip6f_nxt;
887 }
888
889
890 /* ------------------------------------------------------------------------ */
891 /* Function:    ipf_pr_dstopts6                                             */
892 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
893 /* Parameters:  fin(I) - pointer to packet information                      */
894 /*                                                                          */
895 /* IPv6 Only                                                                */
896 /* This is function checks pending destination options extension header     */
897 /* ------------------------------------------------------------------------ */
898 static INLINE int
899 ipf_pr_dstopts6(fin)
900         fr_info_t *fin;
901 {
902         ipf_main_softc_t *softc = fin->fin_main_soft;
903         struct ip6_ext *hdr;
904
905         hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
906         if (hdr == NULL) {
907                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
908                 return IPPROTO_NONE;
909         }
910         return hdr->ip6e_nxt;
911 }
912
913
914 /* ------------------------------------------------------------------------ */
915 /* Function:    ipf_pr_icmp6                                                */
916 /* Returns:     void                                                        */
917 /* Parameters:  fin(I) - pointer to packet information                      */
918 /*                                                                          */
919 /* IPv6 Only                                                                */
920 /* This routine is mainly concerned with determining the minimum valid size */
921 /* for an ICMPv6 packet.                                                    */
922 /* ------------------------------------------------------------------------ */
923 static INLINE void
924 ipf_pr_icmp6(fin)
925         fr_info_t *fin;
926 {
927         int minicmpsz = sizeof(struct icmp6_hdr);
928         struct icmp6_hdr *icmp6;
929
930         if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
931                 ipf_main_softc_t *softc = fin->fin_main_soft;
932
933                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
934                 return;
935         }
936
937         if (fin->fin_dlen > 1) {
938                 ip6_t *ip6;
939
940                 icmp6 = fin->fin_dp;
941
942                 fin->fin_data[0] = *(u_short *)icmp6;
943
944                 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
945                         fin->fin_flx |= FI_ICMPQUERY;
946
947                 switch (icmp6->icmp6_type)
948                 {
949                 case ICMP6_ECHO_REPLY :
950                 case ICMP6_ECHO_REQUEST :
951                         if (fin->fin_dlen >= 6)
952                                 fin->fin_data[1] = icmp6->icmp6_id;
953                         minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
954                         break;
955
956                 case ICMP6_DST_UNREACH :
957                 case ICMP6_PACKET_TOO_BIG :
958                 case ICMP6_TIME_EXCEEDED :
959                 case ICMP6_PARAM_PROB :
960                         fin->fin_flx |= FI_ICMPERR;
961                         minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
962                         if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
963                                 break;
964
965                         if (M_LEN(fin->fin_m) < fin->fin_plen) {
966                                 if (ipf_coalesce(fin) != 1)
967                                         return;
968                         }
969
970                         if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
971                                 return;
972
973                         /*
974                          * If the destination of this packet doesn't match the
975                          * source of the original packet then this packet is
976                          * not correct.
977                          */
978                         icmp6 = fin->fin_dp;
979                         ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
980                         if (IP6_NEQ(&fin->fin_fi.fi_dst,
981                                     (i6addr_t *)&ip6->ip6_src)) {
982                                 fin->fin_flx |= FI_BAD;
983                                 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
984                         }
985                         break;
986                 default :
987                         break;
988                 }
989         }
990
991         ipf_pr_short6(fin, minicmpsz);
992         if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
993                 u_char p = fin->fin_p;
994
995                 fin->fin_p = IPPROTO_ICMPV6;
996                 ipf_checkv6sum(fin);
997                 fin->fin_p = p;
998         }
999 }
1000
1001
1002 /* ------------------------------------------------------------------------ */
1003 /* Function:    ipf_pr_udp6                                                 */
1004 /* Returns:     void                                                        */
1005 /* Parameters:  fin(I) - pointer to packet information                      */
1006 /*                                                                          */
1007 /* IPv6 Only                                                                */
1008 /* Analyse the packet for IPv6/UDP properties.                              */
1009 /* Is not expected to be called for fragmented packets.                     */
1010 /* ------------------------------------------------------------------------ */
1011 static INLINE void
1012 ipf_pr_udp6(fin)
1013         fr_info_t *fin;
1014 {
1015
1016         if (ipf_pr_udpcommon(fin) == 0) {
1017                 u_char p = fin->fin_p;
1018
1019                 fin->fin_p = IPPROTO_UDP;
1020                 ipf_checkv6sum(fin);
1021                 fin->fin_p = p;
1022         }
1023 }
1024
1025
1026 /* ------------------------------------------------------------------------ */
1027 /* Function:    ipf_pr_tcp6                                                 */
1028 /* Returns:     void                                                        */
1029 /* Parameters:  fin(I) - pointer to packet information                      */
1030 /*                                                                          */
1031 /* IPv6 Only                                                                */
1032 /* Analyse the packet for IPv6/TCP properties.                              */
1033 /* Is not expected to be called for fragmented packets.                     */
1034 /* ------------------------------------------------------------------------ */
1035 static INLINE void
1036 ipf_pr_tcp6(fin)
1037         fr_info_t *fin;
1038 {
1039
1040         if (ipf_pr_tcpcommon(fin) == 0) {
1041                 u_char p = fin->fin_p;
1042
1043                 fin->fin_p = IPPROTO_TCP;
1044                 ipf_checkv6sum(fin);
1045                 fin->fin_p = p;
1046         }
1047 }
1048
1049
1050 /* ------------------------------------------------------------------------ */
1051 /* Function:    ipf_pr_esp6                                                 */
1052 /* Returns:     void                                                        */
1053 /* Parameters:  fin(I) - pointer to packet information                      */
1054 /*                                                                          */
1055 /* IPv6 Only                                                                */
1056 /* Analyse the packet for ESP properties.                                   */
1057 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1058 /* even though the newer ESP packets must also have a sequence number that  */
1059 /* is 32bits as well, it is not possible(?) to determine the version from a */
1060 /* simple packet header.                                                    */
1061 /* ------------------------------------------------------------------------ */
1062 static INLINE void
1063 ipf_pr_esp6(fin)
1064         fr_info_t *fin;
1065 {
1066
1067         if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1068                 ipf_main_softc_t *softc = fin->fin_main_soft;
1069
1070                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1071                 return;
1072         }
1073 }
1074
1075
1076 /* ------------------------------------------------------------------------ */
1077 /* Function:    ipf_pr_ah6                                                  */
1078 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1079 /* Parameters:  fin(I) - pointer to packet information                      */
1080 /*                                                                          */
1081 /* IPv6 Only                                                                */
1082 /* Analyse the packet for AH properties.                                    */
1083 /* The minimum length is taken to be the combination of all fields in the   */
1084 /* header being present and no authentication data (null algorithm used.)   */
1085 /* ------------------------------------------------------------------------ */
1086 static INLINE int
1087 ipf_pr_ah6(fin)
1088         fr_info_t *fin;
1089 {
1090         authhdr_t *ah;
1091
1092         fin->fin_flx |= FI_AH;
1093
1094         ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1095         if (ah == NULL) {
1096                 ipf_main_softc_t *softc = fin->fin_main_soft;
1097
1098                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1099                 return IPPROTO_NONE;
1100         }
1101
1102         ipf_pr_short6(fin, sizeof(*ah));
1103
1104         /*
1105          * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1106          * enough data to satisfy ah_next (the very first one.)
1107          */
1108         return ah->ah_next;
1109 }
1110
1111
1112 /* ------------------------------------------------------------------------ */
1113 /* Function:    ipf_pr_gre6                                                 */
1114 /* Returns:     void                                                        */
1115 /* Parameters:  fin(I) - pointer to packet information                      */
1116 /*                                                                          */
1117 /* Analyse the packet for GRE properties.                                   */
1118 /* ------------------------------------------------------------------------ */
1119 static INLINE void
1120 ipf_pr_gre6(fin)
1121         fr_info_t *fin;
1122 {
1123         grehdr_t *gre;
1124
1125         if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1126                 ipf_main_softc_t *softc = fin->fin_main_soft;
1127
1128                 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1129                 return;
1130         }
1131
1132         gre = fin->fin_dp;
1133         if (GRE_REV(gre->gr_flags) == 1)
1134                 fin->fin_data[0] = gre->gr_call;
1135 }
1136 #endif  /* USE_INET6 */
1137
1138
1139 /* ------------------------------------------------------------------------ */
1140 /* Function:    ipf_pr_pullup                                               */
1141 /* Returns:     int     - 0 == pullup succeeded, -1 == failure              */
1142 /* Parameters:  fin(I)  - pointer to packet information                     */
1143 /*              plen(I) - length (excluding L3 header) to pullup            */
1144 /*                                                                          */
1145 /* Short inline function to cut down on code duplication to perform a call  */
1146 /* to ipf_pullup to ensure there is the required amount of data,            */
1147 /* consecutively in the packet buffer.                                      */
1148 /*                                                                          */
1149 /* This function pulls up 'extra' data at the location of fin_dp.  fin_dp   */
1150 /* points to the first byte after the complete layer 3 header, which will   */
1151 /* include all of the known extension headers for IPv6 or options for IPv4. */
1152 /*                                                                          */
1153 /* Since fr_pullup() expects the total length of bytes to be pulled up, it  */
1154 /* is necessary to add those we can already assume to be pulled up (fin_dp  */
1155 /* - fin_ip) to what is passed through.                                     */
1156 /* ------------------------------------------------------------------------ */
1157 int
1158 ipf_pr_pullup(fin, plen)
1159         fr_info_t *fin;
1160         int plen;
1161 {
1162         ipf_main_softc_t *softc = fin->fin_main_soft;
1163
1164         if (fin->fin_m != NULL) {
1165                 if (fin->fin_dp != NULL)
1166                         plen += (char *)fin->fin_dp -
1167                                 ((char *)fin->fin_ip + fin->fin_hlen);
1168                 plen += fin->fin_hlen;
1169                 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1170 #if defined(_KERNEL)
1171                         if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1172                                 DT(ipf_pullup_fail);
1173                                 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1174                                 return -1;
1175                         }
1176                         LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1177 #else
1178                         LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1179                         /*
1180                          * Fake ipf_pullup failing
1181                          */
1182                         fin->fin_reason = FRB_PULLUP;
1183                         *fin->fin_mp = NULL;
1184                         fin->fin_m = NULL;
1185                         fin->fin_ip = NULL;
1186                         return -1;
1187 #endif
1188                 }
1189         }
1190         return 0;
1191 }
1192
1193
1194 /* ------------------------------------------------------------------------ */
1195 /* Function:    ipf_pr_short                                                */
1196 /* Returns:     void                                                        */
1197 /* Parameters:  fin(I)  - pointer to packet information                     */
1198 /*              xmin(I) - minimum header size                               */
1199 /*                                                                          */
1200 /* Check if a packet is "short" as defined by xmin.  The rule we are        */
1201 /* applying here is that the packet must not be fragmented within the layer */
1202 /* 4 header.  That is, it must not be a fragment that has its offset set to */
1203 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the    */
1204 /* entire layer 4 header must be present (min).                             */
1205 /* ------------------------------------------------------------------------ */
1206 static INLINE void
1207 ipf_pr_short(fin, xmin)
1208         fr_info_t *fin;
1209         int xmin;
1210 {
1211
1212         if (fin->fin_off == 0) {
1213                 if (fin->fin_dlen < xmin)
1214                         fin->fin_flx |= FI_SHORT;
1215         } else if (fin->fin_off < xmin) {
1216                 fin->fin_flx |= FI_SHORT;
1217         }
1218 }
1219
1220
1221 /* ------------------------------------------------------------------------ */
1222 /* Function:    ipf_pr_icmp                                                 */
1223 /* Returns:     void                                                        */
1224 /* Parameters:  fin(I) - pointer to packet information                      */
1225 /*                                                                          */
1226 /* IPv4 Only                                                                */
1227 /* Do a sanity check on the packet for ICMP (v4).  In nearly all cases,     */
1228 /* except extrememly bad packets, both type and code will be present.       */
1229 /* The expected minimum size of an ICMP packet is very much dependent on    */
1230 /* the type of it.                                                          */
1231 /*                                                                          */
1232 /* XXX - other ICMP sanity checks?                                          */
1233 /* ------------------------------------------------------------------------ */
1234 static INLINE void
1235 ipf_pr_icmp(fin)
1236         fr_info_t *fin;
1237 {
1238         ipf_main_softc_t *softc = fin->fin_main_soft;
1239         int minicmpsz = sizeof(struct icmp);
1240         icmphdr_t *icmp;
1241         ip_t *oip;
1242
1243         ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1244
1245         if (fin->fin_off != 0) {
1246                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1247                 return;
1248         }
1249
1250         if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1251                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1252                 return;
1253         }
1254
1255         icmp = fin->fin_dp;
1256
1257         fin->fin_data[0] = *(u_short *)icmp;
1258         fin->fin_data[1] = icmp->icmp_id;
1259
1260         switch (icmp->icmp_type)
1261         {
1262         case ICMP_ECHOREPLY :
1263         case ICMP_ECHO :
1264         /* Router discovery messaes - RFC 1256 */
1265         case ICMP_ROUTERADVERT :
1266         case ICMP_ROUTERSOLICIT :
1267                 fin->fin_flx |= FI_ICMPQUERY;
1268                 minicmpsz = ICMP_MINLEN;
1269                 break;
1270         /*
1271          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1272          * 3 * timestamp(3 * 4)
1273          */
1274         case ICMP_TSTAMP :
1275         case ICMP_TSTAMPREPLY :
1276                 fin->fin_flx |= FI_ICMPQUERY;
1277                 minicmpsz = 20;
1278                 break;
1279         /*
1280          * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1281          * mask(4)
1282          */
1283         case ICMP_IREQ :
1284         case ICMP_IREQREPLY :
1285         case ICMP_MASKREQ :
1286         case ICMP_MASKREPLY :
1287                 fin->fin_flx |= FI_ICMPQUERY;
1288                 minicmpsz = 12;
1289                 break;
1290         /*
1291          * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1292          */
1293         case ICMP_UNREACH :
1294 #ifdef icmp_nextmtu
1295                 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1296                         if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1297                                 fin->fin_flx |= FI_BAD;
1298                                 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1299                         }
1300                 }
1301 #endif
1302                 /* FALLTHROUGH */
1303         case ICMP_SOURCEQUENCH :
1304         case ICMP_REDIRECT :
1305         case ICMP_TIMXCEED :
1306         case ICMP_PARAMPROB :
1307                 fin->fin_flx |= FI_ICMPERR;
1308                 if (ipf_coalesce(fin) != 1) {
1309                         LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1310                         return;
1311                 }
1312
1313                 /*
1314                  * ICMP error packets should not be generated for IP
1315                  * packets that are a fragment that isn't the first
1316                  * fragment.
1317                  */
1318                 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1319                 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1320                         fin->fin_flx |= FI_BAD;
1321                         DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1322                 }
1323
1324                 /*
1325                  * If the destination of this packet doesn't match the
1326                  * source of the original packet then this packet is
1327                  * not correct.
1328                  */
1329                 if (oip->ip_src.s_addr != fin->fin_daddr) {
1330                         fin->fin_flx |= FI_BAD;
1331                         DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1332                 }
1333                 break;
1334         default :
1335                 break;
1336         }
1337
1338         ipf_pr_short(fin, minicmpsz);
1339
1340         ipf_checkv4sum(fin);
1341 }
1342
1343
1344 /* ------------------------------------------------------------------------ */
1345 /* Function:    ipf_pr_tcpcommon                                            */
1346 /* Returns:     int    - 0 = header ok, 1 = bad packet, -1 = buffer error   */
1347 /* Parameters:  fin(I) - pointer to packet information                      */
1348 /*                                                                          */
1349 /* TCP header sanity checking.  Look for bad combinations of TCP flags,     */
1350 /* and make some checks with how they interact with other fields.           */
1351 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is     */
1352 /* valid and mark the packet as bad if not.                                 */
1353 /* ------------------------------------------------------------------------ */
1354 static INLINE int
1355 ipf_pr_tcpcommon(fin)
1356         fr_info_t *fin;
1357 {
1358         ipf_main_softc_t *softc = fin->fin_main_soft;
1359         int flags, tlen;
1360         tcphdr_t *tcp;
1361
1362         fin->fin_flx |= FI_TCPUDP;
1363         if (fin->fin_off != 0) {
1364                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1365                 return 0;
1366         }
1367
1368         if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1369                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1370                 return -1;
1371         }
1372
1373         tcp = fin->fin_dp;
1374         if (fin->fin_dlen > 3) {
1375                 fin->fin_sport = ntohs(tcp->th_sport);
1376                 fin->fin_dport = ntohs(tcp->th_dport);
1377         }
1378
1379         if ((fin->fin_flx & FI_SHORT) != 0) {
1380                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1381                 return 1;
1382         }
1383
1384         /*
1385          * Use of the TCP data offset *must* result in a value that is at
1386          * least the same size as the TCP header.
1387          */
1388         tlen = TCP_OFF(tcp) << 2;
1389         if (tlen < sizeof(tcphdr_t)) {
1390                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1391                 fin->fin_flx |= FI_BAD;
1392                 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1393                 return 1;
1394         }
1395
1396         flags = tcp->th_flags;
1397         fin->fin_tcpf = tcp->th_flags;
1398
1399         /*
1400          * If the urgent flag is set, then the urgent pointer must
1401          * also be set and vice versa.  Good TCP packets do not have
1402          * just one of these set.
1403          */
1404         if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1405                 fin->fin_flx |= FI_BAD;
1406                 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1407 #if 0
1408         } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1409                 /*
1410                  * Ignore this case (#if 0) as it shows up in "real"
1411                  * traffic with bogus values in the urgent pointer field.
1412                  */
1413                 fin->fin_flx |= FI_BAD;
1414                 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1415 #endif
1416         } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1417                    ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1418                 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1419                 fin->fin_flx |= FI_BAD;
1420                 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1421 #if 1
1422         } else if (((flags & TH_SYN) != 0) &&
1423                    ((flags & (TH_URG|TH_PUSH)) != 0)) {
1424                 /*
1425                  * SYN with URG and PUSH set is not for normal TCP but it is
1426                  * possible(?) with T/TCP...but who uses T/TCP?
1427                  */
1428                 fin->fin_flx |= FI_BAD;
1429                 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1430 #endif
1431         } else if (!(flags & TH_ACK)) {
1432                 /*
1433                  * If the ack bit isn't set, then either the SYN or
1434                  * RST bit must be set.  If the SYN bit is set, then
1435                  * we expect the ACK field to be 0.  If the ACK is
1436                  * not set and if URG, PSH or FIN are set, consdier
1437                  * that to indicate a bad TCP packet.
1438                  */
1439                 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1440                         /*
1441                          * Cisco PIX sets the ACK field to a random value.
1442                          * In light of this, do not set FI_BAD until a patch
1443                          * is available from Cisco to ensure that
1444                          * interoperability between existing systems is
1445                          * achieved.
1446                          */
1447                         /*fin->fin_flx |= FI_BAD*/;
1448                         /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1449                 } else if (!(flags & (TH_RST|TH_SYN))) {
1450                         fin->fin_flx |= FI_BAD;
1451                         DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1452                 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1453                         fin->fin_flx |= FI_BAD;
1454                         DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
1455                 }
1456         }
1457         if (fin->fin_flx & FI_BAD) {
1458                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1459                 return 1;
1460         }
1461
1462         /*
1463          * At this point, it's not exactly clear what is to be gained by
1464          * marking up which TCP options are and are not present.  The one we
1465          * are most interested in is the TCP window scale.  This is only in
1466          * a SYN packet [RFC1323] so we don't need this here...?
1467          * Now if we were to analyse the header for passive fingerprinting,
1468          * then that might add some weight to adding this...
1469          */
1470         if (tlen == sizeof(tcphdr_t)) {
1471                 return 0;
1472         }
1473
1474         if (ipf_pr_pullup(fin, tlen) == -1) {
1475                 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1476                 return -1;
1477         }
1478
1479 #if 0
1480         tcp = fin->fin_dp;
1481         ip = fin->fin_ip;
1482         s = (u_char *)(tcp + 1);
1483         off = IP_HL(ip) << 2;
1484 # ifdef _KERNEL
1485         if (fin->fin_mp != NULL) {
1486                 mb_t *m = *fin->fin_mp;
1487
1488                 if (off + tlen > M_LEN(m))
1489                         return;
1490         }
1491 # endif
1492         for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1493                 opt = *s;
1494                 if (opt == '\0')
1495                         break;
1496                 else if (opt == TCPOPT_NOP)
1497                         ol = 1;
1498                 else {
1499                         if (tlen < 2)
1500                                 break;
1501                         ol = (int)*(s + 1);
1502                         if (ol < 2 || ol > tlen)
1503                                 break;
1504                 }
1505
1506                 for (i = 9, mv = 4; mv >= 0; ) {
1507                         op = ipopts + i;
1508                         if (opt == (u_char)op->ol_val) {
1509                                 optmsk |= op->ol_bit;
1510                                 break;
1511                         }
1512                 }
1513                 tlen -= ol;
1514                 s += ol;
1515         }
1516 #endif /* 0 */
1517
1518         return 0;
1519 }
1520
1521
1522
1523 /* ------------------------------------------------------------------------ */
1524 /* Function:    ipf_pr_udpcommon                                            */
1525 /* Returns:     int    - 0 = header ok, 1 = bad packet                      */
1526 /* Parameters:  fin(I) - pointer to packet information                      */
1527 /*                                                                          */
1528 /* Extract the UDP source and destination ports, if present.  If compiled   */
1529 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid.          */
1530 /* ------------------------------------------------------------------------ */
1531 static INLINE int
1532 ipf_pr_udpcommon(fin)
1533         fr_info_t *fin;
1534 {
1535         udphdr_t *udp;
1536
1537         fin->fin_flx |= FI_TCPUDP;
1538
1539         if (!fin->fin_off && (fin->fin_dlen > 3)) {
1540                 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1541                         ipf_main_softc_t *softc = fin->fin_main_soft;
1542
1543                         fin->fin_flx |= FI_SHORT;
1544                         LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1545                         return 1;
1546                 }
1547
1548                 udp = fin->fin_dp;
1549
1550                 fin->fin_sport = ntohs(udp->uh_sport);
1551                 fin->fin_dport = ntohs(udp->uh_dport);
1552         }
1553
1554         return 0;
1555 }
1556
1557
1558 /* ------------------------------------------------------------------------ */
1559 /* Function:    ipf_pr_tcp                                                  */
1560 /* Returns:     void                                                        */
1561 /* Parameters:  fin(I) - pointer to packet information                      */
1562 /*                                                                          */
1563 /* IPv4 Only                                                                */
1564 /* Analyse the packet for IPv4/TCP properties.                              */
1565 /* ------------------------------------------------------------------------ */
1566 static INLINE void
1567 ipf_pr_tcp(fin)
1568         fr_info_t *fin;
1569 {
1570
1571         ipf_pr_short(fin, sizeof(tcphdr_t));
1572
1573         if (ipf_pr_tcpcommon(fin) == 0)
1574                 ipf_checkv4sum(fin);
1575 }
1576
1577
1578 /* ------------------------------------------------------------------------ */
1579 /* Function:    ipf_pr_udp                                                  */
1580 /* Returns:     void                                                        */
1581 /* Parameters:  fin(I) - pointer to packet information                      */
1582 /*                                                                          */
1583 /* IPv4 Only                                                                */
1584 /* Analyse the packet for IPv4/UDP properties.                              */
1585 /* ------------------------------------------------------------------------ */
1586 static INLINE void
1587 ipf_pr_udp(fin)
1588         fr_info_t *fin;
1589 {
1590
1591         ipf_pr_short(fin, sizeof(udphdr_t));
1592
1593         if (ipf_pr_udpcommon(fin) == 0)
1594                 ipf_checkv4sum(fin);
1595 }
1596
1597
1598 /* ------------------------------------------------------------------------ */
1599 /* Function:    ipf_pr_esp                                                  */
1600 /* Returns:     void                                                        */
1601 /* Parameters:  fin(I) - pointer to packet information                      */
1602 /*                                                                          */
1603 /* Analyse the packet for ESP properties.                                   */
1604 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits)  */
1605 /* even though the newer ESP packets must also have a sequence number that  */
1606 /* is 32bits as well, it is not possible(?) to determine the version from a */
1607 /* simple packet header.                                                    */
1608 /* ------------------------------------------------------------------------ */
1609 static INLINE void
1610 ipf_pr_esp(fin)
1611         fr_info_t *fin;
1612 {
1613
1614         if (fin->fin_off == 0) {
1615                 ipf_pr_short(fin, 8);
1616                 if (ipf_pr_pullup(fin, 8) == -1) {
1617                         ipf_main_softc_t *softc = fin->fin_main_soft;
1618
1619                         LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1620                 }
1621         }
1622 }
1623
1624
1625 /* ------------------------------------------------------------------------ */
1626 /* Function:    ipf_pr_ah                                                   */
1627 /* Returns:     int    - value of the next header or IPPROTO_NONE if error  */
1628 /* Parameters:  fin(I) - pointer to packet information                      */
1629 /*                                                                          */
1630 /* Analyse the packet for AH properties.                                    */
1631 /* The minimum length is taken to be the combination of all fields in the   */
1632 /* header being present and no authentication data (null algorithm used.)   */
1633 /* ------------------------------------------------------------------------ */
1634 static INLINE int
1635 ipf_pr_ah(fin)
1636         fr_info_t *fin;
1637 {
1638         ipf_main_softc_t *softc = fin->fin_main_soft;
1639         authhdr_t *ah;
1640         int len;
1641
1642         fin->fin_flx |= FI_AH;
1643         ipf_pr_short(fin, sizeof(*ah));
1644
1645         if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1646                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1647                 return IPPROTO_NONE;
1648         }
1649
1650         if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1651                 DT(fr_v4_ah_pullup_1);
1652                 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1653                 return IPPROTO_NONE;
1654         }
1655
1656         ah = (authhdr_t *)fin->fin_dp;
1657
1658         len = (ah->ah_plen + 2) << 2;
1659         ipf_pr_short(fin, len);
1660         if (ipf_pr_pullup(fin, len) == -1) {
1661                 DT(fr_v4_ah_pullup_2);
1662                 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1663                 return IPPROTO_NONE;
1664         }
1665
1666         /*
1667          * Adjust fin_dp and fin_dlen for skipping over the authentication
1668          * header.
1669          */
1670         fin->fin_dp = (char *)fin->fin_dp + len;
1671         fin->fin_dlen -= len;
1672         return ah->ah_next;
1673 }
1674
1675
1676 /* ------------------------------------------------------------------------ */
1677 /* Function:    ipf_pr_gre                                                  */
1678 /* Returns:     void                                                        */
1679 /* Parameters:  fin(I) - pointer to packet information                      */
1680 /*                                                                          */
1681 /* Analyse the packet for GRE properties.                                   */
1682 /* ------------------------------------------------------------------------ */
1683 static INLINE void
1684 ipf_pr_gre(fin)
1685         fr_info_t *fin;
1686 {
1687         ipf_main_softc_t *softc = fin->fin_main_soft;
1688         grehdr_t *gre;
1689
1690         ipf_pr_short(fin, sizeof(grehdr_t));
1691
1692         if (fin->fin_off != 0) {
1693                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1694                 return;
1695         }
1696
1697         if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1698                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1699                 return;
1700         }
1701
1702         gre = fin->fin_dp;
1703         if (GRE_REV(gre->gr_flags) == 1)
1704                 fin->fin_data[0] = gre->gr_call;
1705 }
1706
1707
1708 /* ------------------------------------------------------------------------ */
1709 /* Function:    ipf_pr_ipv4hdr                                              */
1710 /* Returns:     void                                                        */
1711 /* Parameters:  fin(I) - pointer to packet information                      */
1712 /*                                                                          */
1713 /* IPv4 Only                                                                */
1714 /* Analyze the IPv4 header and set fields in the fr_info_t structure.       */
1715 /* Check all options present and flag their presence if any exist.          */
1716 /* ------------------------------------------------------------------------ */
1717 static INLINE void
1718 ipf_pr_ipv4hdr(fin)
1719         fr_info_t *fin;
1720 {
1721         u_short optmsk = 0, secmsk = 0, auth = 0;
1722         int hlen, ol, mv, p, i;
1723         const struct optlist *op;
1724         u_char *s, opt;
1725         u_short off;
1726         fr_ip_t *fi;
1727         ip_t *ip;
1728
1729         fi = &fin->fin_fi;
1730         hlen = fin->fin_hlen;
1731
1732         ip = fin->fin_ip;
1733         p = ip->ip_p;
1734         fi->fi_p = p;
1735         fin->fin_crc = p;
1736         fi->fi_tos = ip->ip_tos;
1737         fin->fin_id = ip->ip_id;
1738         off = ntohs(ip->ip_off);
1739
1740         /* Get both TTL and protocol */
1741         fi->fi_p = ip->ip_p;
1742         fi->fi_ttl = ip->ip_ttl;
1743
1744         /* Zero out bits not used in IPv6 address */
1745         fi->fi_src.i6[1] = 0;
1746         fi->fi_src.i6[2] = 0;
1747         fi->fi_src.i6[3] = 0;
1748         fi->fi_dst.i6[1] = 0;
1749         fi->fi_dst.i6[2] = 0;
1750         fi->fi_dst.i6[3] = 0;
1751
1752         fi->fi_saddr = ip->ip_src.s_addr;
1753         fin->fin_crc += fi->fi_saddr;
1754         fi->fi_daddr = ip->ip_dst.s_addr;
1755         fin->fin_crc += fi->fi_daddr;
1756         if (IN_CLASSD(ntohl(fi->fi_daddr)))
1757                 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1758
1759         /*
1760          * set packet attribute flags based on the offset and
1761          * calculate the byte offset that it represents.
1762          */
1763         off &= IP_MF|IP_OFFMASK;
1764         if (off != 0) {
1765                 int morefrag = off & IP_MF;
1766
1767                 fi->fi_flx |= FI_FRAG;
1768                 off &= IP_OFFMASK;
1769                 if (off != 0) {
1770                         fin->fin_flx |= FI_FRAGBODY;
1771                         off <<= 3;
1772                         if ((off + fin->fin_dlen > 65535) ||
1773                             (fin->fin_dlen == 0) ||
1774                             ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1775                                 /*
1776                                  * The length of the packet, starting at its
1777                                  * offset cannot exceed 65535 (0xffff) as the
1778                                  * length of an IP packet is only 16 bits.
1779                                  *
1780                                  * Any fragment that isn't the last fragment
1781                                  * must have a length greater than 0 and it
1782                                  * must be an even multiple of 8.
1783                                  */
1784                                 fi->fi_flx |= FI_BAD;
1785                                 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1786                         }
1787                 }
1788         }
1789         fin->fin_off = off;
1790
1791         /*
1792          * Call per-protocol setup and checking
1793          */
1794         if (p == IPPROTO_AH) {
1795                 /*
1796                  * Treat AH differently because we expect there to be another
1797                  * layer 4 header after it.
1798                  */
1799                 p = ipf_pr_ah(fin);
1800         }
1801
1802         switch (p)
1803         {
1804         case IPPROTO_UDP :
1805                 ipf_pr_udp(fin);
1806                 break;
1807         case IPPROTO_TCP :
1808                 ipf_pr_tcp(fin);
1809                 break;
1810         case IPPROTO_ICMP :
1811                 ipf_pr_icmp(fin);
1812                 break;
1813         case IPPROTO_ESP :
1814                 ipf_pr_esp(fin);
1815                 break;
1816         case IPPROTO_GRE :
1817                 ipf_pr_gre(fin);
1818                 break;
1819         }
1820
1821         ip = fin->fin_ip;
1822         if (ip == NULL)
1823                 return;
1824
1825         /*
1826          * If it is a standard IP header (no options), set the flag fields
1827          * which relate to options to 0.
1828          */
1829         if (hlen == sizeof(*ip)) {
1830                 fi->fi_optmsk = 0;
1831                 fi->fi_secmsk = 0;
1832                 fi->fi_auth = 0;
1833                 return;
1834         }
1835
1836         /*
1837          * So the IP header has some IP options attached.  Walk the entire
1838          * list of options present with this packet and set flags to indicate
1839          * which ones are here and which ones are not.  For the somewhat out
1840          * of date and obscure security classification options, set a flag to
1841          * represent which classification is present.
1842          */
1843         fi->fi_flx |= FI_OPTIONS;
1844
1845         for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1846                 opt = *s;
1847                 if (opt == '\0')
1848                         break;
1849                 else if (opt == IPOPT_NOP)
1850                         ol = 1;
1851                 else {
1852                         if (hlen < 2)
1853                                 break;
1854                         ol = (int)*(s + 1);
1855                         if (ol < 2 || ol > hlen)
1856                                 break;
1857                 }
1858                 for (i = 9, mv = 4; mv >= 0; ) {
1859                         op = ipopts + i;
1860
1861                         if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1862                                 u_32_t doi;
1863
1864                                 switch (opt)
1865                                 {
1866                                 case IPOPT_SECURITY :
1867                                         if (optmsk & op->ol_bit) {
1868                                                 fin->fin_flx |= FI_BAD;
1869                                                 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1870                                         } else {
1871                                                 doi = ipf_checkripso(s);
1872                                                 secmsk = doi >> 16;
1873                                                 auth = doi & 0xffff;
1874                                         }
1875                                         break;
1876
1877                                 case IPOPT_CIPSO :
1878
1879                                         if (optmsk & op->ol_bit) {
1880                                                 fin->fin_flx |= FI_BAD;
1881                                                 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1882                                         } else {
1883                                                 doi = ipf_checkcipso(fin,
1884                                                                      s, ol);
1885                                                 secmsk = doi >> 16;
1886                                                 auth = doi & 0xffff;
1887                                         }
1888                                         break;
1889                                 }
1890                                 optmsk |= op->ol_bit;
1891                         }
1892
1893                         if (opt < op->ol_val)
1894                                 i -= mv;
1895                         else
1896                                 i += mv;
1897                         mv--;
1898                 }
1899                 hlen -= ol;
1900                 s += ol;
1901         }
1902
1903         /*
1904          *
1905          */
1906         if (auth && !(auth & 0x0100))
1907                 auth &= 0xff00;
1908         fi->fi_optmsk = optmsk;
1909         fi->fi_secmsk = secmsk;
1910         fi->fi_auth = auth;
1911 }
1912
1913
1914 /* ------------------------------------------------------------------------ */
1915 /* Function:    ipf_checkripso                                              */
1916 /* Returns:     void                                                        */
1917 /* Parameters:  s(I)   - pointer to start of RIPSO option                   */
1918 /*                                                                          */
1919 /* ------------------------------------------------------------------------ */
1920 static u_32_t
1921 ipf_checkripso(s)
1922         u_char *s;
1923 {
1924         const struct optlist *sp;
1925         u_short secmsk = 0, auth = 0;
1926         u_char sec;
1927         int j, m;
1928
1929         sec = *(s + 2); /* classification */
1930         for (j = 3, m = 2; m >= 0; ) {
1931                 sp = secopt + j;
1932                 if (sec == sp->ol_val) {
1933                         secmsk |= sp->ol_bit;
1934                         auth = *(s + 3);
1935                         auth *= 256;
1936                         auth += *(s + 4);
1937                         break;
1938                 }
1939                 if (sec < sp->ol_val)
1940                         j -= m;
1941                 else
1942                         j += m;
1943                 m--;
1944         }
1945
1946         return (secmsk << 16) | auth;
1947 }
1948
1949
1950 /* ------------------------------------------------------------------------ */
1951 /* Function:    ipf_checkcipso                                              */
1952 /* Returns:     u_32_t  - 0 = failure, else the doi from the header         */
1953 /* Parameters:  fin(IO) - pointer to packet information                     */
1954 /*              s(I)    - pointer to start of CIPSO option                  */
1955 /*              ol(I)   - length of CIPSO option field                      */
1956 /*                                                                          */
1957 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1958 /* header and returns that whilst also storing the highest sensitivity      */
1959 /* value found in the fr_info_t structure.                                  */
1960 /*                                                                          */
1961 /* No attempt is made to extract the category bitmaps as these are defined  */
1962 /* by the user (rather than the protocol) and can be rather numerous on the */
1963 /* end nodes.                                                               */
1964 /* ------------------------------------------------------------------------ */
1965 static u_32_t
1966 ipf_checkcipso(fin, s, ol)
1967         fr_info_t *fin;
1968         u_char *s;
1969         int ol;
1970 {
1971         ipf_main_softc_t *softc = fin->fin_main_soft;
1972         fr_ip_t *fi;
1973         u_32_t doi;
1974         u_char *t, tag, tlen, sensitivity;
1975         int len;
1976
1977         if (ol < 6 || ol > 40) {
1978                 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1979                 fin->fin_flx |= FI_BAD;
1980                 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1981                 return 0;
1982         }
1983
1984         fi = &fin->fin_fi;
1985         fi->fi_sensitivity = 0;
1986         /*
1987          * The DOI field MUST be there.
1988          */
1989         bcopy(s + 2, &doi, sizeof(doi));
1990
1991         t = (u_char *)s + 6;
1992         for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1993                 tag = *t;
1994                 tlen = *(t + 1);
1995                 if (tlen > len || tlen < 4 || tlen > 34) {
1996                         LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1997                         fin->fin_flx |= FI_BAD;
1998                         DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1999                         return 0;
2000                 }
2001
2002                 sensitivity = 0;
2003                 /*
2004                  * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
2005                  * draft (16 July 1992) that has expired.
2006                  */
2007                 if (tag == 0) {
2008                         fin->fin_flx |= FI_BAD;
2009                         DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
2010                         continue;
2011                 } else if (tag == 1) {
2012                         if (*(t + 2) != 0) {
2013                                 fin->fin_flx |= FI_BAD;
2014                                 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
2015                                 continue;
2016                         }
2017                         sensitivity = *(t + 3);
2018                         /* Category bitmap for categories 0-239 */
2019
2020                 } else if (tag == 4) {
2021                         if (*(t + 2) != 0) {
2022                                 fin->fin_flx |= FI_BAD;
2023                                 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
2024                                 continue;
2025                         }
2026                         sensitivity = *(t + 3);
2027                         /* Enumerated categories, 16bits each, upto 15 */
2028
2029                 } else if (tag == 5) {
2030                         if (*(t + 2) != 0) {
2031                                 fin->fin_flx |= FI_BAD;
2032                                 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
2033                                 continue;
2034                         }
2035                         sensitivity = *(t + 3);
2036                         /* Range of categories (2*16bits), up to 7 pairs */
2037
2038                 } else if (tag > 127) {
2039                         /* Custom defined DOI */
2040                         ;
2041                 } else {
2042                         fin->fin_flx |= FI_BAD;
2043                         DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
2044                         continue;
2045                 }
2046
2047                 if (sensitivity > fi->fi_sensitivity)
2048                         fi->fi_sensitivity = sensitivity;
2049         }
2050
2051         return doi;
2052 }
2053
2054
2055 /* ------------------------------------------------------------------------ */
2056 /* Function:    ipf_makefrip                                                */
2057 /* Returns:     int     - 0 == packet ok, -1 == packet freed                */
2058 /* Parameters:  hlen(I) - length of IP packet header                        */
2059 /*              ip(I)   - pointer to the IP header                          */
2060 /*              fin(IO) - pointer to packet information                     */
2061 /*                                                                          */
2062 /* Compact the IP header into a structure which contains just the info.     */
2063 /* which is useful for comparing IP headers with and store this information */
2064 /* in the fr_info_t structure pointer to by fin.  At present, it is assumed */
2065 /* this function will be called with either an IPv4 or IPv6 packet.         */
2066 /* ------------------------------------------------------------------------ */
2067 int
2068 ipf_makefrip(hlen, ip, fin)
2069         int hlen;
2070         ip_t *ip;
2071         fr_info_t *fin;
2072 {
2073         ipf_main_softc_t *softc = fin->fin_main_soft;
2074         int v;
2075
2076         fin->fin_depth = 0;
2077         fin->fin_hlen = (u_short)hlen;
2078         fin->fin_ip = ip;
2079         fin->fin_rule = 0xffffffff;
2080         fin->fin_group[0] = -1;
2081         fin->fin_group[1] = '\0';
2082         fin->fin_dp = (char *)ip + hlen;
2083
2084         v = fin->fin_v;
2085         if (v == 4) {
2086                 fin->fin_plen = ntohs(ip->ip_len);
2087                 fin->fin_dlen = fin->fin_plen - hlen;
2088                 ipf_pr_ipv4hdr(fin);
2089 #ifdef  USE_INET6
2090         } else if (v == 6) {
2091                 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2092                 fin->fin_dlen = fin->fin_plen;
2093                 fin->fin_plen += hlen;
2094
2095                 ipf_pr_ipv6hdr(fin);
2096 #endif
2097         }
2098         if (fin->fin_ip == NULL) {
2099                 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2100                 return -1;
2101         }
2102         return 0;
2103 }
2104
2105
2106 /* ------------------------------------------------------------------------ */
2107 /* Function:    ipf_portcheck                                               */
2108 /* Returns:     int - 1 == port matched, 0 == port match failed             */
2109 /* Parameters:  frp(I) - pointer to port check `expression'                 */
2110 /*              pop(I) - port number to evaluate                            */
2111 /*                                                                          */
2112 /* Perform a comparison of a port number against some other(s), using a     */
2113 /* structure with compare information stored in it.                         */
2114 /* ------------------------------------------------------------------------ */
2115 static INLINE int
2116 ipf_portcheck(frp, pop)
2117         frpcmp_t *frp;
2118         u_32_t pop;
2119 {
2120         int err = 1;
2121         u_32_t po;
2122
2123         po = frp->frp_port;
2124
2125         /*
2126          * Do opposite test to that required and continue if that succeeds.
2127          */
2128         switch (frp->frp_cmp)
2129         {
2130         case FR_EQUAL :
2131                 if (pop != po) /* EQUAL */
2132                         err = 0;
2133                 break;
2134         case FR_NEQUAL :
2135                 if (pop == po) /* NOTEQUAL */
2136                         err = 0;
2137                 break;
2138         case FR_LESST :
2139                 if (pop >= po) /* LESSTHAN */
2140                         err = 0;
2141                 break;
2142         case FR_GREATERT :
2143                 if (pop <= po) /* GREATERTHAN */
2144                         err = 0;
2145                 break;
2146         case FR_LESSTE :
2147                 if (pop > po) /* LT or EQ */
2148                         err = 0;
2149                 break;
2150         case FR_GREATERTE :
2151                 if (pop < po) /* GT or EQ */
2152                         err = 0;
2153                 break;
2154         case FR_OUTRANGE :
2155                 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2156                         err = 0;
2157                 break;
2158         case FR_INRANGE :
2159                 if (pop <= po || pop >= frp->frp_top) /* In range */
2160                         err = 0;
2161                 break;
2162         case FR_INCRANGE :
2163                 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2164                         err = 0;
2165                 break;
2166         default :
2167                 break;
2168         }
2169         return err;
2170 }
2171
2172
2173 /* ------------------------------------------------------------------------ */
2174 /* Function:    ipf_tcpudpchk                                               */
2175 /* Returns:     int - 1 == protocol matched, 0 == check failed              */
2176 /* Parameters:  fda(I) - pointer to packet information                      */
2177 /*              ft(I)  - pointer to structure with comparison data          */
2178 /*                                                                          */
2179 /* Compares the current pcket (assuming it is TCP/UDP) information with a   */
2180 /* structure containing information that we want to match against.          */
2181 /* ------------------------------------------------------------------------ */
2182 int
2183 ipf_tcpudpchk(fi, ft)
2184         fr_ip_t *fi;
2185         frtuc_t *ft;
2186 {
2187         int err = 1;
2188
2189         /*
2190          * Both ports should *always* be in the first fragment.
2191          * So far, I cannot find any cases where they can not be.
2192          *
2193          * compare destination ports
2194          */
2195         if (ft->ftu_dcmp)
2196                 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2197
2198         /*
2199          * compare source ports
2200          */
2201         if (err && ft->ftu_scmp)
2202                 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2203
2204         /*
2205          * If we don't have all the TCP/UDP header, then how can we
2206          * expect to do any sort of match on it ?  If we were looking for
2207          * TCP flags, then NO match.  If not, then match (which should
2208          * satisfy the "short" class too).
2209          */
2210         if (err && (fi->fi_p == IPPROTO_TCP)) {
2211                 if (fi->fi_flx & FI_SHORT)
2212                         return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2213                 /*
2214                  * Match the flags ?  If not, abort this match.
2215                  */
2216                 if (ft->ftu_tcpfm &&
2217                     ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2218                         FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2219                                  ft->ftu_tcpfm, ft->ftu_tcpf));
2220                         err = 0;
2221                 }
2222         }
2223         return err;
2224 }
2225
2226
2227 /* ------------------------------------------------------------------------ */
2228 /* Function:    ipf_check_ipf                                               */
2229 /* Returns:     int - 0 == match, else no match                             */
2230 /* Parameters:  fin(I)     - pointer to packet information                  */
2231 /*              fr(I)      - pointer to filter rule                         */
2232 /*              portcmp(I) - flag indicating whether to attempt matching on */
2233 /*                           TCP/UDP port data.                             */
2234 /*                                                                          */
2235 /* Check to see if a packet matches an IPFilter rule.  Checks of addresses, */
2236 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2237 /* this function.                                                           */
2238 /* ------------------------------------------------------------------------ */
2239 static INLINE int
2240 ipf_check_ipf(fin, fr, portcmp)
2241         fr_info_t *fin;
2242         frentry_t *fr;
2243         int portcmp;
2244 {
2245         u_32_t  *ld, *lm, *lip;
2246         fripf_t *fri;
2247         fr_ip_t *fi;
2248         int i;
2249
2250         fi = &fin->fin_fi;
2251         fri = fr->fr_ipf;
2252         lip = (u_32_t *)fi;
2253         lm = (u_32_t *)&fri->fri_mip;
2254         ld = (u_32_t *)&fri->fri_ip;
2255
2256         /*
2257          * first 32 bits to check coversion:
2258          * IP version, TOS, TTL, protocol
2259          */
2260         i = ((*lip & *lm) != *ld);
2261         FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2262                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2263         if (i)
2264                 return 1;
2265
2266         /*
2267          * Next 32 bits is a constructed bitmask indicating which IP options
2268          * are present (if any) in this packet.
2269          */
2270         lip++, lm++, ld++;
2271         i = ((*lip & *lm) != *ld);
2272         FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2273                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2274         if (i != 0)
2275                 return 1;
2276
2277         lip++, lm++, ld++;
2278         /*
2279          * Unrolled loops (4 each, for 32 bits) for address checks.
2280          */
2281         /*
2282          * Check the source address.
2283          */
2284         if (fr->fr_satype == FRI_LOOKUP) {
2285                 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2286                                       fi->fi_v, lip, fin->fin_plen);
2287                 if (i == -1)
2288                         return 1;
2289                 lip += 3;
2290                 lm += 3;
2291                 ld += 3;
2292         } else {
2293                 i = ((*lip & *lm) != *ld);
2294                 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2295                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2296                 if (fi->fi_v == 6) {
2297                         lip++, lm++, ld++;
2298                         i |= ((*lip & *lm) != *ld);
2299                         FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2300                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2301                         lip++, lm++, ld++;
2302                         i |= ((*lip & *lm) != *ld);
2303                         FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2304                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2305                         lip++, lm++, ld++;
2306                         i |= ((*lip & *lm) != *ld);
2307                         FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2308                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2309                 } else {
2310                         lip += 3;
2311                         lm += 3;
2312                         ld += 3;
2313                 }
2314         }
2315         i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2316         if (i != 0)
2317                 return 1;
2318
2319         /*
2320          * Check the destination address.
2321          */
2322         lip++, lm++, ld++;
2323         if (fr->fr_datype == FRI_LOOKUP) {
2324                 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2325                                       fi->fi_v, lip, fin->fin_plen);
2326                 if (i == -1)
2327                         return 1;
2328                 lip += 3;
2329                 lm += 3;
2330                 ld += 3;
2331         } else {
2332                 i = ((*lip & *lm) != *ld);
2333                 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2334                            ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2335                 if (fi->fi_v == 6) {
2336                         lip++, lm++, ld++;
2337                         i |= ((*lip & *lm) != *ld);
2338                         FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2339                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2340                         lip++, lm++, ld++;
2341                         i |= ((*lip & *lm) != *ld);
2342                         FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2343                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2344                         lip++, lm++, ld++;
2345                         i |= ((*lip & *lm) != *ld);
2346                         FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2347                                    ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2348                 } else {
2349                         lip += 3;
2350                         lm += 3;
2351                         ld += 3;
2352                 }
2353         }
2354         i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2355         if (i != 0)
2356                 return 1;
2357         /*
2358          * IP addresses matched.  The next 32bits contains:
2359          * mast of old IP header security & authentication bits.
2360          */
2361         lip++, lm++, ld++;
2362         i = (*ld - (*lip & *lm));
2363         FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2364
2365         /*
2366          * Next we have 32 bits of packet flags.
2367          */
2368         lip++, lm++, ld++;
2369         i |= (*ld - (*lip & *lm));
2370         FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2371
2372         if (i == 0) {
2373                 /*
2374                  * If a fragment, then only the first has what we're
2375                  * looking for here...
2376                  */
2377                 if (portcmp) {
2378                         if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2379                                 i = 1;
2380                 } else {
2381                         if (fr->fr_dcmp || fr->fr_scmp ||
2382                             fr->fr_tcpf || fr->fr_tcpfm)
2383                                 i = 1;
2384                         if (fr->fr_icmpm || fr->fr_icmp) {
2385                                 if (((fi->fi_p != IPPROTO_ICMP) &&
2386                                      (fi->fi_p != IPPROTO_ICMPV6)) ||
2387                                     fin->fin_off || (fin->fin_dlen < 2))
2388                                         i = 1;
2389                                 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2390                                          fr->fr_icmp) {
2391                                         FR_DEBUG(("i. %#x & %#x != %#x\n",
2392                                                  fin->fin_data[0],
2393                                                  fr->fr_icmpm, fr->fr_icmp));
2394                                         i = 1;
2395                                 }
2396                         }
2397                 }
2398         }
2399         return i;
2400 }
2401
2402
2403 /* ------------------------------------------------------------------------ */
2404 /* Function:    ipf_scanlist                                                */
2405 /* Returns:     int - result flags of scanning filter list                  */
2406 /* Parameters:  fin(I) - pointer to packet information                      */
2407 /*              pass(I) - default result to return for filtering            */
2408 /*                                                                          */
2409 /* Check the input/output list of rules for a match to the current packet.  */
2410 /* If a match is found, the value of fr_flags from the rule becomes the     */
2411 /* return value and fin->fin_fr points to the matched rule.                 */
2412 /*                                                                          */
2413 /* This function may be called recusively upto 16 times (limit inbuilt.)    */
2414 /* When unwinding, it should finish up with fin_depth as 0.                 */
2415 /*                                                                          */
2416 /* Could be per interface, but this gets real nasty when you don't have,    */
2417 /* or can't easily change, the kernel source code to .                      */
2418 /* ------------------------------------------------------------------------ */
2419 int
2420 ipf_scanlist(fin, pass)
2421         fr_info_t *fin;
2422         u_32_t pass;
2423 {
2424         ipf_main_softc_t *softc = fin->fin_main_soft;
2425         int rulen, portcmp, off, skip;
2426         struct frentry *fr, *fnext;
2427         u_32_t passt, passo;
2428
2429         /*
2430          * Do not allow nesting deeper than 16 levels.
2431          */
2432         if (fin->fin_depth >= 16)
2433                 return pass;
2434
2435         fr = fin->fin_fr;
2436
2437         /*
2438          * If there are no rules in this list, return now.
2439          */
2440         if (fr == NULL)
2441                 return pass;
2442
2443         skip = 0;
2444         portcmp = 0;
2445         fin->fin_depth++;
2446         fin->fin_fr = NULL;
2447         off = fin->fin_off;
2448
2449         if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2450                 portcmp = 1;
2451
2452         for (rulen = 0; fr; fr = fnext, rulen++) {
2453                 fnext = fr->fr_next;
2454                 if (skip != 0) {
2455                         FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2456                         skip--;
2457                         continue;
2458                 }
2459
2460                 /*
2461                  * In all checks below, a null (zero) value in the
2462                  * filter struture is taken to mean a wildcard.
2463                  *
2464                  * check that we are working for the right interface
2465                  */
2466 #ifdef  _KERNEL
2467                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2468                         continue;
2469 #else
2470                 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2471                         printf("\n");
2472                 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2473                                   FR_ISPASS(pass) ? 'p' :
2474                                   FR_ISACCOUNT(pass) ? 'A' :
2475                                   FR_ISAUTH(pass) ? 'a' :
2476                                   (pass & FR_NOMATCH) ? 'n' :'b'));
2477                 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2478                         continue;
2479                 FR_VERBOSE((":i"));
2480 #endif
2481
2482                 switch (fr->fr_type)
2483                 {
2484                 case FR_T_IPF :
2485                 case FR_T_IPF_BUILTIN :
2486                         if (ipf_check_ipf(fin, fr, portcmp))
2487                                 continue;
2488                         break;
2489 #if defined(IPFILTER_BPF)
2490                 case FR_T_BPFOPC :
2491                 case FR_T_BPFOPC_BUILTIN :
2492                     {
2493                         u_char *mc;
2494                         int wlen;
2495
2496                         if (*fin->fin_mp == NULL)
2497                                 continue;
2498                         if (fin->fin_family != fr->fr_family)
2499                                 continue;
2500                         mc = (u_char *)fin->fin_m;
2501                         wlen = fin->fin_dlen + fin->fin_hlen;
2502                         if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2503                                 continue;
2504                         break;
2505                     }
2506 #endif
2507                 case FR_T_CALLFUNC_BUILTIN :
2508                     {
2509                         frentry_t *f;
2510
2511                         f = (*fr->fr_func)(fin, &pass);
2512                         if (f != NULL)
2513                                 fr = f;
2514                         else
2515                                 continue;
2516                         break;
2517                     }
2518
2519                 case FR_T_IPFEXPR :
2520                 case FR_T_IPFEXPR_BUILTIN :
2521                         if (fin->fin_family != fr->fr_family)
2522                                 continue;
2523                         if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2524                                 continue;
2525                         break;
2526
2527                 default :
2528                         break;
2529                 }
2530
2531                 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2532                         if (fin->fin_nattag == NULL)
2533                                 continue;
2534                         if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2535                                 continue;
2536                 }
2537                 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2538
2539                 passt = fr->fr_flags;
2540
2541                 /*
2542                  * If the rule is a "call now" rule, then call the function
2543                  * in the rule, if it exists and use the results from that.
2544                  * If the function pointer is bad, just make like we ignore
2545                  * it, except for increasing the hit counter.
2546                  */
2547                 if ((passt & FR_CALLNOW) != 0) {
2548                         frentry_t *frs;
2549
2550                         ATOMIC_INC64(fr->fr_hits);
2551                         if ((fr->fr_func == NULL) ||
2552                             (fr->fr_func == (ipfunc_t)-1))
2553                                 continue;
2554
2555                         frs = fin->fin_fr;
2556                         fin->fin_fr = fr;
2557                         fr = (*fr->fr_func)(fin, &passt);
2558                         if (fr == NULL) {
2559                                 fin->fin_fr = frs;
2560                                 continue;
2561                         }
2562                         passt = fr->fr_flags;
2563                 }
2564                 fin->fin_fr = fr;
2565
2566 #ifdef  IPFILTER_LOG
2567                 /*
2568                  * Just log this packet...
2569                  */
2570                 if ((passt & FR_LOGMASK) == FR_LOG) {
2571                         if (ipf_log_pkt(fin, passt) == -1) {
2572                                 if (passt & FR_LOGORBLOCK) {
2573                                         DT(frb_logfail);
2574                                         passt &= ~FR_CMDMASK;
2575                                         passt |= FR_BLOCK|FR_QUICK;
2576                                         fin->fin_reason = FRB_LOGFAIL;
2577                                 }
2578                         }
2579                 }
2580 #endif /* IPFILTER_LOG */
2581
2582                 MUTEX_ENTER(&fr->fr_lock);
2583                 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2584                 fr->fr_hits++;
2585                 MUTEX_EXIT(&fr->fr_lock);
2586                 fin->fin_rule = rulen;
2587
2588                 passo = pass;
2589                 if (FR_ISSKIP(passt)) {
2590                         skip = fr->fr_arg;
2591                         continue;
2592                 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2593                            ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2594                         pass = passt;
2595                 }
2596
2597                 if (passt & (FR_RETICMP|FR_FAKEICMP))
2598                         fin->fin_icode = fr->fr_icode;
2599
2600                 if (fr->fr_group != -1) {
2601                         (void) strncpy(fin->fin_group,
2602                                        FR_NAME(fr, fr_group),
2603                                        strlen(FR_NAME(fr, fr_group)));
2604                 } else {
2605                         fin->fin_group[0] = '\0';
2606                 }
2607
2608                 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2609
2610                 if (fr->fr_grphead != NULL) {
2611                         fin->fin_fr = fr->fr_grphead->fg_start;
2612                         FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2613
2614                         if (FR_ISDECAPS(passt))
2615                                 passt = ipf_decaps(fin, pass, fr->fr_icode);
2616                         else
2617                                 passt = ipf_scanlist(fin, pass);
2618
2619                         if (fin->fin_fr == NULL) {
2620                                 fin->fin_rule = rulen;
2621                                 if (fr->fr_group != -1)
2622                                         (void) strncpy(fin->fin_group,
2623                                                        fr->fr_names +
2624                                                        fr->fr_group,
2625                                                        strlen(fr->fr_names +
2626                                                               fr->fr_group));
2627                                 fin->fin_fr = fr;
2628                                 passt = pass;
2629                         }
2630                         pass = passt;
2631                 }
2632
2633                 if (pass & FR_QUICK) {
2634                         /*
2635                          * Finally, if we've asked to track state for this
2636                          * packet, set it up.  Add state for "quick" rules
2637                          * here so that if the action fails we can consider
2638                          * the rule to "not match" and keep on processing
2639                          * filter rules.
2640                          */
2641                         if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2642                             !(fin->fin_flx & FI_STATE)) {
2643                                 int out = fin->fin_out;
2644
2645                                 fin->fin_fr = fr;
2646                                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2647                                         LBUMPD(ipf_stats[out], fr_ads);
2648                                 } else {
2649                                         LBUMPD(ipf_stats[out], fr_bads);
2650                                         pass = passo;
2651                                         continue;
2652                                 }
2653                         }
2654                         break;
2655                 }
2656         }
2657         fin->fin_depth--;
2658         return pass;
2659 }
2660
2661
2662 /* ------------------------------------------------------------------------ */
2663 /* Function:    ipf_acctpkt                                                 */
2664 /* Returns:     frentry_t* - always returns NULL                            */
2665 /* Parameters:  fin(I) - pointer to packet information                      */
2666 /*              passp(IO) - pointer to current/new filter decision (unused) */
2667 /*                                                                          */
2668 /* Checks a packet against accounting rules, if there are any for the given */
2669 /* IP protocol version.                                                     */
2670 /*                                                                          */
2671 /* N.B.: this function returns NULL to match the prototype used by other    */
2672 /* functions called from the IPFilter "mainline" in ipf_check().            */
2673 /* ------------------------------------------------------------------------ */
2674 frentry_t *
2675 ipf_acctpkt(fin, passp)
2676         fr_info_t *fin;
2677         u_32_t *passp;
2678 {
2679         ipf_main_softc_t *softc = fin->fin_main_soft;
2680         char group[FR_GROUPLEN];
2681         frentry_t *fr, *frsave;
2682         u_32_t pass, rulen;
2683
2684         passp = passp;
2685         fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2686
2687         if (fr != NULL) {
2688                 frsave = fin->fin_fr;
2689                 bcopy(fin->fin_group, group, FR_GROUPLEN);
2690                 rulen = fin->fin_rule;
2691                 fin->fin_fr = fr;
2692                 pass = ipf_scanlist(fin, FR_NOMATCH);
2693                 if (FR_ISACCOUNT(pass)) {
2694                         LBUMPD(ipf_stats[0], fr_acct);
2695                 }
2696                 fin->fin_fr = frsave;
2697                 bcopy(group, fin->fin_group, FR_GROUPLEN);
2698                 fin->fin_rule = rulen;
2699         }
2700         return NULL;
2701 }
2702
2703
2704 /* ------------------------------------------------------------------------ */
2705 /* Function:    ipf_firewall                                                */
2706 /* Returns:     frentry_t* - returns pointer to matched rule, if no matches */
2707 /*                           were found, returns NULL.                      */
2708 /* Parameters:  fin(I) - pointer to packet information                      */
2709 /*              passp(IO) - pointer to current/new filter decision (unused) */
2710 /*                                                                          */
2711 /* Applies an appropriate set of firewall rules to the packet, to see if    */
2712 /* there are any matches.  The first check is to see if a match can be seen */
2713 /* in the cache.  If not, then search an appropriate list of rules.  Once a */
2714 /* matching rule is found, take any appropriate actions as defined by the   */
2715 /* rule - except logging.                                                   */
2716 /* ------------------------------------------------------------------------ */
2717 static frentry_t *
2718 ipf_firewall(fin, passp)
2719         fr_info_t *fin;
2720         u_32_t *passp;
2721 {
2722         ipf_main_softc_t *softc = fin->fin_main_soft;
2723         frentry_t *fr;
2724         u_32_t pass;
2725         int out;
2726
2727         out = fin->fin_out;
2728         pass = *passp;
2729
2730         /*
2731          * This rule cache will only affect packets that are not being
2732          * statefully filtered.
2733          */
2734         fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2735         if (fin->fin_fr != NULL)
2736                 pass = ipf_scanlist(fin, softc->ipf_pass);
2737
2738         if ((pass & FR_NOMATCH)) {
2739                 LBUMPD(ipf_stats[out], fr_nom);
2740         }
2741         fr = fin->fin_fr;
2742
2743         /*
2744          * Apply packets per second rate-limiting to a rule as required.
2745          */
2746         if ((fr != NULL) && (fr->fr_pps != 0) &&
2747             !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2748                 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2749                 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2750                 pass |= FR_BLOCK;
2751                 LBUMPD(ipf_stats[out], fr_ppshit);
2752                 fin->fin_reason = FRB_PPSRATE;
2753         }
2754
2755         /*
2756          * If we fail to add a packet to the authorization queue, then we
2757          * drop the packet later.  However, if it was added then pretend
2758          * we've dropped it already.
2759          */
2760         if (FR_ISAUTH(pass)) {
2761                 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2762                         DT1(frb_authnew, fr_info_t *, fin);
2763                         fin->fin_m = *fin->fin_mp = NULL;
2764                         fin->fin_reason = FRB_AUTHNEW;
2765                         fin->fin_error = 0;
2766                 } else {
2767                         IPFERROR(1);
2768                         fin->fin_error = ENOSPC;
2769                 }
2770         }
2771
2772         if ((fr != NULL) && (fr->fr_func != NULL) &&
2773             (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2774                 (void) (*fr->fr_func)(fin, &pass);
2775
2776         /*
2777          * If a rule is a pre-auth rule, check again in the list of rules
2778          * loaded for authenticated use.  It does not particulary matter
2779          * if this search fails because a "preauth" result, from a rule,
2780          * is treated as "not a pass", hence the packet is blocked.
2781          */
2782         if (FR_ISPREAUTH(pass)) {
2783                 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2784         }
2785
2786         /*
2787          * If the rule has "keep frag" and the packet is actually a fragment,
2788          * then create a fragment state entry.
2789          */
2790         if (pass & FR_KEEPFRAG) {
2791                 if (fin->fin_flx & FI_FRAG) {
2792                         if (ipf_frag_new(softc, fin, pass) == -1) {
2793                                 LBUMP(ipf_stats[out].fr_bnfr);
2794                         } else {
2795                                 LBUMP(ipf_stats[out].fr_nfr);
2796                         }
2797                 } else {
2798                         LBUMP(ipf_stats[out].fr_cfr);
2799                 }
2800         }
2801
2802         fr = fin->fin_fr;
2803         *passp = pass;
2804
2805         return fr;
2806 }
2807
2808
2809 /* ------------------------------------------------------------------------ */
2810 /* Function:    ipf_check                                                   */
2811 /* Returns:     int -  0 == packet allowed through,                         */
2812 /*              User space:                                                 */
2813 /*                    -1 == packet blocked                                  */
2814 /*                     1 == packet not matched                              */
2815 /*                    -2 == requires authentication                         */
2816 /*              Kernel:                                                     */
2817 /*                   > 0 == filter error # for packet                       */
2818 /* Parameters: ip(I)   - pointer to start of IPv4/6 packet                  */
2819 /*             hlen(I) - length of header                                   */
2820 /*             ifp(I)  - pointer to interface this packet is on             */
2821 /*             out(I)  - 0 == packet going in, 1 == packet going out        */
2822 /*             mp(IO)  - pointer to caller's buffer pointer that holds this */
2823 /*                       IP packet.                                         */
2824 /* Solaris & HP-UX ONLY :                                                   */
2825 /*             qpi(I)  - pointer to STREAMS queue information for this      */
2826 /*                       interface & direction.                             */
2827 /*                                                                          */
2828 /* ipf_check() is the master function for all IPFilter packet processing.   */
2829 /* It orchestrates: Network Address Translation (NAT), checking for packet  */
2830 /* authorisation (or pre-authorisation), presence of related state info.,   */
2831 /* generating log entries, IP packet accounting, routing of packets as      */
2832 /* directed by firewall rules and of course whether or not to allow the     */
2833 /* packet to be further processed by the kernel.                            */
2834 /*                                                                          */
2835 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer  */
2836 /* freed.  Packets passed may be returned with the pointer pointed to by    */
2837 /* by "mp" changed to a new buffer.                                         */
2838 /* ------------------------------------------------------------------------ */
2839 int
2840 ipf_check(ctx, ip, hlen, ifp, out
2841 #if defined(_KERNEL) && defined(MENTAT)
2842         , qif, mp)
2843         void *qif;
2844 #else
2845         , mp)
2846 #endif
2847         mb_t **mp;
2848         ip_t *ip;
2849         int hlen;
2850         void *ifp;
2851         int out;
2852         void *ctx;
2853 {
2854         /*
2855          * The above really sucks, but short of writing a diff
2856          */
2857         ipf_main_softc_t *softc = ctx;
2858         fr_info_t frinfo;
2859         fr_info_t *fin = &frinfo;
2860         u_32_t pass = softc->ipf_pass;
2861         frentry_t *fr = NULL;
2862         int v = IP_V(ip);
2863         mb_t *mc = NULL;
2864         mb_t *m;
2865         /*
2866          * The first part of ipf_check() deals with making sure that what goes
2867          * into the filtering engine makes some sense.  Information about the
2868          * the packet is distilled, collected into a fr_info_t structure and
2869          * the an attempt to ensure the buffer the packet is in is big enough
2870          * to hold all the required packet headers.
2871          */
2872 #ifdef  _KERNEL
2873 # ifdef MENTAT
2874         qpktinfo_t *qpi = qif;
2875
2876 #  ifdef __sparc
2877         if ((u_int)ip & 0x3)
2878                 return 2;
2879 #  endif
2880 # else
2881         SPL_INT(s);
2882 # endif
2883
2884         if (softc->ipf_running <= 0) {
2885                 return 0;
2886         }
2887
2888         bzero((char *)fin, sizeof(*fin));
2889
2890 # ifdef MENTAT
2891         if (qpi->qpi_flags & QF_BROADCAST)
2892                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2893         if (qpi->qpi_flags & QF_MULTICAST)
2894                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2895         m = qpi->qpi_m;
2896         fin->fin_qfm = m;
2897         fin->fin_qpi = qpi;
2898 # else /* MENTAT */
2899
2900         m = *mp;
2901
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 #  ifdef M_CANFASTFWD
2915         /*
2916          * XXX For now, IP Filter and fast-forwarding of cached flows
2917          * XXX are mutually exclusive.  Eventually, IP Filter should
2918          * XXX get a "can-fast-forward" filter rule.
2919          */
2920         m->m_flags &= ~M_CANFASTFWD;
2921 #  endif /* M_CANFASTFWD */
2922 #  if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2923                                    (__FreeBSD_version < 501108))
2924         /*
2925          * disable delayed checksums.
2926          */
2927         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2928                 in_delayed_cksum(m);
2929                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2930         }
2931 #  endif /* CSUM_DELAY_DATA */
2932 # endif /* MENTAT */
2933 #else
2934         bzero((char *)fin, sizeof(*fin));
2935         m = *mp;
2936 # if defined(M_MCAST)
2937         if ((m->m_flags & M_MCAST) != 0)
2938                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2939 # endif
2940 # if defined(M_MLOOP)
2941         if ((m->m_flags & M_MLOOP) != 0)
2942                 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2943 # endif
2944 # if defined(M_BCAST)
2945         if ((m->m_flags & M_BCAST) != 0)
2946                 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2947 # endif
2948 #endif /* _KERNEL */
2949
2950         fin->fin_v = v;
2951         fin->fin_m = m;
2952         fin->fin_ip = ip;
2953         fin->fin_mp = mp;
2954         fin->fin_out = out;
2955         fin->fin_ifp = ifp;
2956         fin->fin_error = ENETUNREACH;
2957         fin->fin_hlen = (u_short)hlen;
2958         fin->fin_dp = (char *)ip + hlen;
2959         fin->fin_main_soft = softc;
2960
2961         fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2962
2963         SPL_NET(s);
2964
2965 #ifdef  USE_INET6
2966         if (v == 6) {
2967                 LBUMP(ipf_stats[out].fr_ipv6);
2968                 /*
2969                  * Jumbo grams are quite likely too big for internal buffer
2970                  * structures to handle comfortably, for now, so just drop
2971                  * them.
2972                  */
2973                 if (((ip6_t *)ip)->ip6_plen == 0) {
2974                         DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2975                         pass = FR_BLOCK|FR_NOMATCH;
2976                         fin->fin_reason = FRB_JUMBO;
2977                         goto finished;
2978                 }
2979                 fin->fin_family = AF_INET6;
2980         } else
2981 #endif
2982         {
2983                 fin->fin_family = AF_INET;
2984         }
2985
2986         if (ipf_makefrip(hlen, ip, fin) == -1) {
2987                 DT1(frb_makefrip, fr_info_t *, fin);
2988                 pass = FR_BLOCK|FR_NOMATCH;
2989                 fin->fin_reason = FRB_MAKEFRIP;
2990                 goto finished;
2991         }
2992
2993         /*
2994          * For at least IPv6 packets, if a m_pullup() fails then this pointer
2995          * becomes NULL and so we have no packet to free.
2996          */
2997         if (*fin->fin_mp == NULL)
2998                 goto finished;
2999
3000         if (!out) {
3001                 if (v == 4) {
3002                         if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
3003                                 LBUMPD(ipf_stats[0], fr_v4_badsrc);
3004                                 fin->fin_flx |= FI_BADSRC;
3005                         }
3006                         if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
3007                                 LBUMPD(ipf_stats[0], fr_v4_badttl);
3008                                 fin->fin_flx |= FI_LOWTTL;
3009                         }
3010                 }
3011 #ifdef USE_INET6
3012                 else  if (v == 6) {
3013                         if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
3014                                 LBUMPD(ipf_stats[0], fr_v6_badttl);
3015                                 fin->fin_flx |= FI_LOWTTL;
3016                         }
3017                 }
3018 #endif
3019         }
3020
3021         if (fin->fin_flx & FI_SHORT) {
3022                 LBUMPD(ipf_stats[out], fr_short);
3023         }
3024
3025         READ_ENTER(&softc->ipf_mutex);
3026
3027         if (!out) {
3028                 switch (fin->fin_v)
3029                 {
3030                 case 4 :
3031                         if (ipf_nat_checkin(fin, &pass) == -1) {
3032                                 goto filterdone;
3033                         }
3034                         break;
3035 #ifdef USE_INET6
3036                 case 6 :
3037                         if (ipf_nat6_checkin(fin, &pass) == -1) {
3038                                 goto filterdone;
3039                         }
3040                         break;
3041 #endif
3042                 default :
3043                         break;
3044                 }
3045         }
3046         /*
3047          * Check auth now.
3048          * If a packet is found in the auth table, then skip checking
3049          * the access lists for permission but we do need to consider
3050          * the result as if it were from the ACL's.  In addition, being
3051          * found in the auth table means it has been seen before, so do
3052          * not pass it through accounting (again), lest it be counted twice.
3053          */
3054         fr = ipf_auth_check(fin, &pass);
3055         if (!out && (fr == NULL))
3056                 (void) ipf_acctpkt(fin, NULL);
3057
3058         if (fr == NULL) {
3059                 if ((fin->fin_flx & FI_FRAG) != 0)
3060                         fr = ipf_frag_known(fin, &pass);
3061
3062                 if (fr == NULL)
3063                         fr = ipf_state_check(fin, &pass);
3064         }
3065
3066         if ((pass & FR_NOMATCH) || (fr == NULL))
3067                 fr = ipf_firewall(fin, &pass);
3068
3069         /*
3070          * If we've asked to track state for this packet, set it up.
3071          * Here rather than ipf_firewall because ipf_checkauth may decide
3072          * to return a packet for "keep state"
3073          */
3074         if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
3075             !(fin->fin_flx & FI_STATE)) {
3076                 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
3077                         LBUMP(ipf_stats[out].fr_ads);
3078                 } else {
3079                         LBUMP(ipf_stats[out].fr_bads);
3080                         if (FR_ISPASS(pass)) {
3081                                 DT(frb_stateadd);
3082                                 pass &= ~FR_CMDMASK;
3083                                 pass |= FR_BLOCK;
3084                                 fin->fin_reason = FRB_STATEADD;
3085                         }
3086                 }
3087         }
3088
3089         fin->fin_fr = fr;
3090         if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
3091                 fin->fin_dif = &fr->fr_dif;
3092                 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3093         }
3094
3095         /*
3096          * Only count/translate packets which will be passed on, out the
3097          * interface.
3098          */
3099         if (out && FR_ISPASS(pass)) {
3100                 (void) ipf_acctpkt(fin, NULL);
3101
3102                 switch (fin->fin_v)
3103                 {
3104                 case 4 :
3105                         if (ipf_nat_checkout(fin, &pass) == -1) {
3106                                 ;
3107                         } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3108                                 if (ipf_updateipid(fin) == -1) {
3109                                         DT(frb_updateipid);
3110                                         LBUMP(ipf_stats[1].fr_ipud);
3111                                         pass &= ~FR_CMDMASK;
3112                                         pass |= FR_BLOCK;
3113                                         fin->fin_reason = FRB_UPDATEIPID;
3114                                 } else {
3115                                         LBUMP(ipf_stats[0].fr_ipud);
3116                                 }
3117                         }
3118                         break;
3119 #ifdef USE_INET6
3120                 case 6 :
3121                         (void) ipf_nat6_checkout(fin, &pass);
3122                         break;
3123 #endif
3124                 default :
3125                         break;
3126                 }
3127         }
3128
3129 filterdone:
3130 #ifdef  IPFILTER_LOG
3131         if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3132                 (void) ipf_dolog(fin, &pass);
3133         }
3134 #endif
3135
3136         /*
3137          * The FI_STATE flag is cleared here so that calling ipf_state_check
3138          * will work when called from inside of fr_fastroute.  Although
3139          * there is a similar flag, FI_NATED, for NAT, it does have the same
3140          * impact on code execution.
3141          */
3142         fin->fin_flx &= ~FI_STATE;
3143
3144 #if defined(FASTROUTE_RECURSION)
3145         /*
3146          * Up the reference on fr_lock and exit ipf_mutex. The generation of
3147          * a packet below can sometimes cause a recursive call into IPFilter.
3148          * On those platforms where that does happen, we need to hang onto
3149          * the filter rule just in case someone decides to remove or flush it
3150          * in the meantime.
3151          */
3152         if (fr != NULL) {
3153                 MUTEX_ENTER(&fr->fr_lock);
3154                 fr->fr_ref++;
3155                 MUTEX_EXIT(&fr->fr_lock);
3156         }
3157
3158         RWLOCK_EXIT(&softc->ipf_mutex);
3159 #endif
3160
3161         if ((pass & FR_RETMASK) != 0) {
3162                 /*
3163                  * Should we return an ICMP packet to indicate error
3164                  * status passing through the packet filter ?
3165                  * WARNING: ICMP error packets AND TCP RST packets should
3166                  * ONLY be sent in repsonse to incoming packets.  Sending
3167                  * them in response to outbound packets can result in a
3168                  * panic on some operating systems.
3169                  */
3170                 if (!out) {
3171                         if (pass & FR_RETICMP) {
3172                                 int dst;
3173
3174                                 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3175                                         dst = 1;
3176                                 else
3177                                         dst = 0;
3178                                 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3179                                                          dst);
3180                                 LBUMP(ipf_stats[0].fr_ret);
3181                         } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3182                                    !(fin->fin_flx & FI_SHORT)) {
3183                                 if (((fin->fin_flx & FI_OOW) != 0) ||
3184                                     (ipf_send_reset(fin) == 0)) {
3185                                         LBUMP(ipf_stats[1].fr_ret);
3186                                 }
3187                         }
3188
3189                         /*
3190                          * When using return-* with auth rules, the auth code
3191                          * takes over disposing of this packet.
3192                          */
3193                         if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3194                                 DT1(frb_authcapture, fr_info_t *, fin);
3195                                 fin->fin_m = *fin->fin_mp = NULL;
3196                                 fin->fin_reason = FRB_AUTHCAPTURE;
3197                                 m = NULL;
3198                         }
3199                 } else {
3200                         if (pass & FR_RETRST) {
3201                                 fin->fin_error = ECONNRESET;
3202                         }
3203                 }
3204         }
3205
3206         /*
3207          * After the above so that ICMP unreachables and TCP RSTs get
3208          * created properly.
3209          */
3210         if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3211                 ipf_nat_uncreate(fin);
3212
3213         /*
3214          * If we didn't drop off the bottom of the list of rules (and thus
3215          * the 'current' rule fr is not NULL), then we may have some extra
3216          * instructions about what to do with a packet.
3217          * Once we're finished return to our caller, freeing the packet if
3218          * we are dropping it.
3219          */
3220         if (fr != NULL) {
3221                 frdest_t *fdp;
3222
3223                 /*
3224                  * Generate a duplicated packet first because ipf_fastroute
3225                  * can lead to fin_m being free'd... not good.
3226                  */
3227                 fdp = fin->fin_dif;
3228                 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3229                     (fdp->fd_ptr != (void *)-1)) {
3230                         mc = M_COPY(fin->fin_m);
3231                         if (mc != NULL)
3232                                 ipf_fastroute(mc, &mc, fin, fdp);
3233                 }
3234
3235                 fdp = fin->fin_tif;
3236                 if (!out && (pass & FR_FASTROUTE)) {
3237                         /*
3238                          * For fastroute rule, no destination interface defined
3239                          * so pass NULL as the frdest_t parameter
3240                          */
3241                         (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3242                         m = *mp = NULL;
3243                 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3244                            (fdp->fd_ptr != (struct ifnet *)-1)) {
3245                         /* this is for to rules: */
3246                         ipf_fastroute(fin->fin_m, mp, fin, fdp);
3247                         m = *mp = NULL;
3248                 }
3249
3250 #if defined(FASTROUTE_RECURSION)
3251                 (void) ipf_derefrule(softc, &fr);
3252 #endif
3253         }
3254 #if !defined(FASTROUTE_RECURSION)
3255         RWLOCK_EXIT(&softc->ipf_mutex);
3256 #endif
3257
3258 finished:
3259         if (!FR_ISPASS(pass)) {
3260                 LBUMP(ipf_stats[out].fr_block);
3261                 if (*mp != NULL) {
3262 #ifdef _KERNEL
3263                         FREE_MB_T(*mp);
3264 #endif
3265                         m = *mp = NULL;
3266                 }
3267         } else {
3268                 LBUMP(ipf_stats[out].fr_pass);
3269 #if defined(_KERNEL) && defined(__sgi)
3270                 if ((fin->fin_hbuf != NULL) &&
3271                     (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3272                         COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3273                 }
3274 #endif
3275         }
3276
3277         SPL_X(s);
3278
3279 #ifdef _KERNEL
3280         if (FR_ISPASS(pass))
3281                 return 0;
3282         LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3283         return fin->fin_error;
3284 #else /* _KERNEL */
3285         if (*mp != NULL)
3286                 (*mp)->mb_ifp = fin->fin_ifp;
3287         blockreason = fin->fin_reason;
3288         FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3289         /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3290                 if ((pass & FR_NOMATCH) != 0)
3291                         return 1;
3292
3293         if ((pass & FR_RETMASK) != 0)
3294                 switch (pass & FR_RETMASK)
3295                 {
3296                 case FR_RETRST :
3297                         return 3;
3298                 case FR_RETICMP :
3299                         return 4;
3300                 case FR_FAKEICMP :
3301                         return 5;
3302                 }
3303
3304         switch (pass & FR_CMDMASK)
3305         {
3306         case FR_PASS :
3307                 return 0;
3308         case FR_BLOCK :
3309                 return -1;
3310         case FR_AUTH :
3311                 return -2;
3312         case FR_ACCOUNT :
3313                 return -3;
3314         case FR_PREAUTH :
3315                 return -4;
3316         }
3317         return 2;
3318 #endif /* _KERNEL */
3319 }
3320
3321
3322 #ifdef  IPFILTER_LOG
3323 /* ------------------------------------------------------------------------ */
3324 /* Function:    ipf_dolog                                                   */
3325 /* Returns:     frentry_t* - returns contents of fin_fr (no change made)    */
3326 /* Parameters:  fin(I) - pointer to packet information                      */
3327 /*              passp(IO) - pointer to current/new filter decision (unused) */
3328 /*                                                                          */
3329 /* Checks flags set to see how a packet should be logged, if it is to be    */
3330 /* logged.  Adjust statistics based on its success or not.                  */
3331 /* ------------------------------------------------------------------------ */
3332 frentry_t *
3333 ipf_dolog(fin, passp)
3334         fr_info_t *fin;
3335         u_32_t *passp;
3336 {
3337         ipf_main_softc_t *softc = fin->fin_main_soft;
3338         u_32_t pass;
3339         int out;
3340
3341         out = fin->fin_out;
3342         pass = *passp;
3343
3344         if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3345                 pass |= FF_LOGNOMATCH;
3346                 LBUMPD(ipf_stats[out], fr_npkl);
3347                 goto logit;
3348
3349         } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3350             (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3351                 if ((pass & FR_LOGMASK) != FR_LOGP)
3352                         pass |= FF_LOGPASS;
3353                 LBUMPD(ipf_stats[out], fr_ppkl);
3354                 goto logit;
3355
3356         } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3357                    (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3358                 if ((pass & FR_LOGMASK) != FR_LOGB)
3359                         pass |= FF_LOGBLOCK;
3360                 LBUMPD(ipf_stats[out], fr_bpkl);
3361
3362 logit:
3363                 if (ipf_log_pkt(fin, pass) == -1) {
3364                         /*
3365                          * If the "or-block" option has been used then
3366                          * block the packet if we failed to log it.
3367                          */
3368                         if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3369                                 DT1(frb_logfail2, u_int, pass);
3370                                 pass &= ~FR_CMDMASK;
3371                                 pass |= FR_BLOCK;
3372                                 fin->fin_reason = FRB_LOGFAIL2;
3373                         }
3374                 }
3375                 *passp = pass;
3376         }
3377
3378         return fin->fin_fr;
3379 }
3380 #endif /* IPFILTER_LOG */
3381
3382
3383 /* ------------------------------------------------------------------------ */
3384 /* Function:    ipf_cksum                                                   */
3385 /* Returns:     u_short - IP header checksum                                */
3386 /* Parameters:  addr(I) - pointer to start of buffer to checksum            */
3387 /*              len(I)  - length of buffer in bytes                         */
3388 /*                                                                          */
3389 /* Calculate the two's complement 16 bit checksum of the buffer passed.     */
3390 /*                                                                          */
3391 /* N.B.: addr should be 16bit aligned.                                      */
3392 /* ------------------------------------------------------------------------ */
3393 u_short
3394 ipf_cksum(addr, len)
3395         u_short *addr;
3396         int len;
3397 {
3398         u_32_t sum = 0;
3399
3400         for (sum = 0; len > 1; len -= 2)
3401                 sum += *addr++;
3402
3403         /* mop up an odd byte, if necessary */
3404         if (len == 1)
3405                 sum += *(u_char *)addr;
3406
3407         /*
3408          * add back carry outs from top 16 bits to low 16 bits
3409          */
3410         sum = (sum >> 16) + (sum & 0xffff);     /* add hi 16 to low 16 */
3411         sum += (sum >> 16);                     /* add carry */
3412         return (u_short)(~sum);
3413 }
3414
3415
3416 /* ------------------------------------------------------------------------ */
3417 /* Function:    fr_cksum                                                    */
3418 /* Returns:     u_short - layer 4 checksum                                  */
3419 /* Parameters:  fin(I)     - pointer to packet information                  */
3420 /*              ip(I)      - pointer to IP header                           */
3421 /*              l4proto(I) - protocol to caclulate checksum for             */
3422 /*              l4hdr(I)   - pointer to layer 4 header                      */
3423 /*                                                                          */
3424 /* Calculates the TCP checksum for the packet held in "m", using the data   */
3425 /* in the IP header "ip" to seed it.                                        */
3426 /*                                                                          */
3427 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3428 /* and the TCP header.  We also assume that data blocks aren't allocated in */
3429 /* odd sizes.                                                               */
3430 /*                                                                          */
3431 /* Expects ip_len and ip_off to be in network byte order when called.       */
3432 /* ------------------------------------------------------------------------ */
3433 u_short
3434 fr_cksum(fin, ip, l4proto, l4hdr)
3435         fr_info_t *fin;
3436         ip_t *ip;
3437         int l4proto;
3438         void *l4hdr;
3439 {
3440         u_short *sp, slen, sumsave, *csump;
3441         u_int sum, sum2;
3442         int hlen;
3443         int off;
3444 #ifdef  USE_INET6
3445         ip6_t *ip6;
3446 #endif
3447
3448         csump = NULL;
3449         sumsave = 0;
3450         sp = NULL;
3451         slen = 0;
3452         hlen = 0;
3453         sum = 0;
3454
3455         sum = htons((u_short)l4proto);
3456         /*
3457          * Add up IP Header portion
3458          */
3459 #ifdef  USE_INET6
3460         if (IP_V(ip) == 4) {
3461 #endif
3462                 hlen = IP_HL(ip) << 2;
3463                 off = hlen;
3464                 sp = (u_short *)&ip->ip_src;
3465                 sum += *sp++;   /* ip_src */
3466                 sum += *sp++;
3467                 sum += *sp++;   /* ip_dst */
3468                 sum += *sp++;
3469 #ifdef  USE_INET6
3470         } else if (IP_V(ip) == 6) {
3471                 ip6 = (ip6_t *)ip;
3472                 hlen = sizeof(*ip6);
3473                 off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3474                 sp = (u_short *)&ip6->ip6_src;
3475                 sum += *sp++;   /* ip6_src */
3476                 sum += *sp++;
3477                 sum += *sp++;
3478                 sum += *sp++;
3479                 sum += *sp++;
3480                 sum += *sp++;
3481                 sum += *sp++;
3482                 sum += *sp++;
3483                 /* This needs to be routing header aware. */
3484                 sum += *sp++;   /* ip6_dst */
3485                 sum += *sp++;
3486                 sum += *sp++;
3487                 sum += *sp++;
3488                 sum += *sp++;
3489                 sum += *sp++;
3490                 sum += *sp++;
3491                 sum += *sp++;
3492         } else {
3493                 return 0xffff;
3494         }
3495 #endif
3496         slen = fin->fin_plen - off;
3497         sum += htons(slen);
3498
3499         switch (l4proto)
3500         {
3501         case IPPROTO_UDP :
3502                 csump = &((udphdr_t *)l4hdr)->uh_sum;
3503                 break;
3504
3505         case IPPROTO_TCP :
3506                 csump = &((tcphdr_t *)l4hdr)->th_sum;
3507                 break;
3508         case IPPROTO_ICMP :
3509                 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3510                 sum = 0;        /* Pseudo-checksum is not included */
3511                 break;
3512 #ifdef USE_INET6
3513         case IPPROTO_ICMPV6 :
3514                 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3515                 break;
3516 #endif
3517         default :
3518                 break;
3519         }
3520
3521         if (csump != NULL) {
3522                 sumsave = *csump;
3523                 *csump = 0;
3524         }
3525
3526         sum2 = ipf_pcksum(fin, off, sum);
3527         if (csump != NULL)
3528                 *csump = sumsave;
3529         return sum2;
3530 }
3531
3532
3533 /* ------------------------------------------------------------------------ */
3534 /* Function:    ipf_findgroup                                               */
3535 /* Returns:     frgroup_t * - NULL = group not found, else pointer to group */
3536 /* Parameters:  softc(I) - pointer to soft context main structure           */
3537 /*              group(I) - group name to search for                         */
3538 /*              unit(I)  - device to which this group belongs               */
3539 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3540 /*              fgpp(O)  - pointer to place to store pointer to the pointer */
3541 /*                         to where to add the next (last) group or where   */
3542 /*                         to delete group from.                            */
3543 /*                                                                          */
3544 /* Search amongst the defined groups for a particular group number.         */
3545 /* ------------------------------------------------------------------------ */
3546 frgroup_t *
3547 ipf_findgroup(softc, group, unit, set, fgpp)
3548         ipf_main_softc_t *softc;
3549         char *group;
3550         minor_t unit;
3551         int set;
3552         frgroup_t ***fgpp;
3553 {
3554         frgroup_t *fg, **fgp;
3555
3556         /*
3557          * Which list of groups to search in is dependent on which list of
3558          * rules are being operated on.
3559          */
3560         fgp = &softc->ipf_groups[unit][set];
3561
3562         while ((fg = *fgp) != NULL) {
3563                 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3564                         break;
3565                 else
3566                         fgp = &fg->fg_next;
3567         }
3568         if (fgpp != NULL)
3569                 *fgpp = fgp;
3570         return fg;
3571 }
3572
3573
3574 /* ------------------------------------------------------------------------ */
3575 /* Function:    ipf_group_add                                               */
3576 /* Returns:     frgroup_t * - NULL == did not create group,                 */
3577 /*                            != NULL == pointer to the group               */
3578 /* Parameters:  softc(I) - pointer to soft context main structure           */
3579 /*              num(I)   - group number to add                              */
3580 /*              head(I)  - rule pointer that is using this as the head      */
3581 /*              flags(I) - rule flags which describe the type of rule it is */
3582 /*              unit(I)  - device to which this group will belong to        */
3583 /*              set(I)   - which set of rules (inactive/inactive) this is   */
3584 /* Write Locks: ipf_mutex                                                   */
3585 /*                                                                          */
3586 /* Add a new group head, or if it already exists, increase the reference    */
3587 /* count to it.                                                             */
3588 /* ------------------------------------------------------------------------ */
3589 frgroup_t *
3590 ipf_group_add(softc, group, head, flags, unit, set)
3591         ipf_main_softc_t *softc;
3592         char *group;
3593         void *head;
3594         u_32_t flags;
3595         minor_t unit;
3596         int set;
3597 {
3598         frgroup_t *fg, **fgp;
3599         u_32_t gflags;
3600
3601         if (group == NULL)
3602                 return NULL;
3603
3604         if (unit == IPL_LOGIPF && *group == '\0')
3605                 return NULL;
3606
3607         fgp = NULL;
3608         gflags = flags & FR_INOUT;
3609
3610         fg = ipf_findgroup(softc, group, unit, set, &fgp);
3611         if (fg != NULL) {
3612                 if (fg->fg_head == NULL && head != NULL)
3613                         fg->fg_head = head;
3614                 if (fg->fg_flags == 0)
3615                         fg->fg_flags = gflags;
3616                 else if (gflags != fg->fg_flags)
3617                         return NULL;
3618                 fg->fg_ref++;
3619                 return fg;
3620         }
3621
3622         KMALLOC(fg, frgroup_t *);
3623         if (fg != NULL) {
3624                 fg->fg_head = head;
3625                 fg->fg_start = NULL;
3626                 fg->fg_next = *fgp;
3627                 bcopy(group, fg->fg_name, strlen(group) + 1);
3628                 fg->fg_flags = gflags;
3629                 fg->fg_ref = 1;
3630                 fg->fg_set = &softc->ipf_groups[unit][set];
3631                 *fgp = fg;
3632         }
3633         return fg;
3634 }
3635
3636
3637 /* ------------------------------------------------------------------------ */
3638 /* Function:    ipf_group_del                                               */
3639 /* Returns:     int      - number of rules deleted                          */
3640 /* Parameters:  softc(I) - pointer to soft context main structure           */
3641 /*              group(I) - group name to delete                             */
3642 /*              fr(I)    - filter rule from which group is referenced       */
3643 /* Write Locks: ipf_mutex                                                   */
3644 /*                                                                          */
3645 /* This function is called whenever a reference to a group is to be dropped */
3646 /* and thus its reference count needs to be lowered and the group free'd if */
3647 /* the reference count reaches zero. Passing in fr is really for the sole   */
3648 /* purpose of knowing when the head rule is being deleted.                  */
3649 /* ------------------------------------------------------------------------ */
3650 void
3651 ipf_group_del(softc, group, fr)
3652         ipf_main_softc_t *softc;
3653         frgroup_t *group;
3654         frentry_t *fr;
3655 {
3656
3657         if (group->fg_head == fr)
3658                 group->fg_head = NULL;
3659
3660         group->fg_ref--;
3661         if ((group->fg_ref == 0) && (group->fg_start == NULL))
3662                 ipf_group_free(group);
3663 }
3664
3665
3666 /* ------------------------------------------------------------------------ */
3667 /* Function:    ipf_group_free                                              */
3668 /* Returns:     Nil                                                         */
3669 /* Parameters:  group(I) - pointer to filter rule group                     */
3670 /*                                                                          */
3671 /* Remove the group from the list of groups and free it.                    */
3672 /* ------------------------------------------------------------------------ */
3673 static void
3674 ipf_group_free(group)
3675         frgroup_t *group;
3676 {
3677         frgroup_t **gp;
3678
3679         for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3680                 if (*gp == group) {
3681                         *gp = group->fg_next;
3682                         break;
3683                 }
3684         }
3685         KFREE(group);
3686 }
3687
3688
3689 /* ------------------------------------------------------------------------ */
3690 /* Function:    ipf_group_flush                                             */
3691 /* Returns:     int      - number of rules flush from group                 */
3692 /* Parameters:  softc(I) - pointer to soft context main structure           */
3693 /* Parameters:  group(I) - pointer to filter rule group                     */
3694 /*                                                                          */
3695 /* Remove all of the rules that currently are listed under the given group. */
3696 /* ------------------------------------------------------------------------ */
3697 static int
3698 ipf_group_flush(softc, group)
3699         ipf_main_softc_t *softc;
3700         frgroup_t *group;
3701 {
3702         int gone = 0;
3703
3704         (void) ipf_flushlist(softc, &gone, &group->fg_start);
3705
3706         return gone;
3707 }
3708
3709
3710 /* ------------------------------------------------------------------------ */
3711 /* Function:    ipf_getrulen                                                */
3712 /* Returns:     frentry_t * - NULL == not found, else pointer to rule n     */
3713 /* Parameters:  softc(I) - pointer to soft context main structure           */
3714 /* Parameters:  unit(I)  - device for which to count the rule's number      */
3715 /*              flags(I) - which set of rules to find the rule in           */
3716 /*              group(I) - group name                                       */
3717 /*              n(I)     - rule number to find                              */
3718 /*                                                                          */
3719 /* Find rule # n in group # g and return a pointer to it.  Return NULl if   */
3720 /* group # g doesn't exist or there are less than n rules in the group.     */
3721 /* ------------------------------------------------------------------------ */
3722 frentry_t *
3723 ipf_getrulen(softc, unit, group, n)
3724         ipf_main_softc_t *softc;
3725         int unit;
3726         char *group;
3727         u_32_t n;
3728 {
3729         frentry_t *fr;
3730         frgroup_t *fg;
3731
3732         fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3733         if (fg == NULL)
3734                 return NULL;
3735         for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3736                 ;
3737         if (n != 0)
3738                 return NULL;
3739         return fr;
3740 }
3741
3742
3743 /* ------------------------------------------------------------------------ */
3744 /* Function:    ipf_flushlist                                               */
3745 /* Returns:     int - >= 0 - number of flushed rules                        */
3746 /* Parameters:  softc(I)   - pointer to soft context main structure         */
3747 /*              nfreedp(O) - pointer to int where flush count is stored     */
3748 /*              listp(I)   - pointer to list to flush pointer               */
3749 /* Write Locks: ipf_mutex                                                   */
3750 /*                                                                          */
3751 /* Recursively flush rules from the list, descending groups as they are     */
3752 /* encountered.  if a rule is the head of a group and it has lost all its   */
3753 /* group members, then also delete the group reference.  nfreedp is needed  */
3754 /* to store the accumulating count of rules removed, whereas the returned   */
3755 /* value is just the number removed from the current list.  The latter is   */
3756 /* needed to correctly adjust reference counts on rules that define groups. */
3757 /*                                                                          */
3758 /* NOTE: Rules not loaded from user space cannot be flushed.                */
3759 /* ------------------------------------------------------------------------ */
3760 static int
3761 ipf_flushlist(softc, nfreedp, listp)
3762         ipf_main_softc_t *softc;
3763         int *nfreedp;
3764         frentry_t **listp;
3765 {
3766         int freed = 0;
3767         frentry_t *fp;
3768
3769         while ((fp = *listp) != NULL) {
3770                 if ((fp->fr_type & FR_T_BUILTIN) ||
3771                     !(fp->fr_flags & FR_COPIED)) {
3772                         listp = &fp->fr_next;
3773                         continue;
3774                 }
3775                 *listp = fp->fr_next;
3776                 if (fp->fr_next != NULL)
3777                         fp->fr_next->fr_pnext = fp->fr_pnext;
3778                 fp->fr_pnext = NULL;
3779
3780                 if (fp->fr_grphead != NULL) {
3781                         freed += ipf_group_flush(softc, fp->fr_grphead);
3782                         fp->fr_names[fp->fr_grhead] = '\0';
3783                 }
3784
3785                 if (fp->fr_icmpgrp != NULL) {
3786                         freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3787                         fp->fr_names[fp->fr_icmphead] = '\0';
3788                 }
3789
3790                 if (fp->fr_srctrack.ht_max_nodes)
3791                         ipf_rb_ht_flush(&fp->fr_srctrack);
3792
3793                 fp->fr_next = NULL;
3794
3795                 ASSERT(fp->fr_ref > 0);
3796                 if (ipf_derefrule(softc, &fp) == 0)
3797                         freed++;
3798         }
3799         *nfreedp += freed;
3800         return freed;
3801 }
3802
3803
3804 /* ------------------------------------------------------------------------ */
3805 /* Function:    ipf_flush                                                   */
3806 /* Returns:     int - >= 0 - number of flushed rules                        */
3807 /* Parameters:  softc(I) - pointer to soft context main structure           */
3808 /*              unit(I)  - device for which to flush rules                  */
3809 /*              flags(I) - which set of rules to flush                      */
3810 /*                                                                          */
3811 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3812 /* and IPv6) as defined by the value of flags.                              */
3813 /* ------------------------------------------------------------------------ */
3814 int
3815 ipf_flush(softc, unit, flags)
3816         ipf_main_softc_t *softc;
3817         minor_t unit;
3818         int flags;
3819 {
3820         int flushed = 0, set;
3821
3822         WRITE_ENTER(&softc->ipf_mutex);
3823
3824         set = softc->ipf_active;
3825         if ((flags & FR_INACTIVE) == FR_INACTIVE)
3826                 set = 1 - set;
3827
3828         if (flags & FR_OUTQUE) {
3829                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3830                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3831         }
3832         if (flags & FR_INQUE) {
3833                 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3834                 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3835         }
3836
3837         flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3838                                     flags & (FR_INQUE|FR_OUTQUE));
3839
3840         RWLOCK_EXIT(&softc->ipf_mutex);
3841
3842         if (unit == IPL_LOGIPF) {
3843                 int tmp;
3844
3845                 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3846                 if (tmp >= 0)
3847                         flushed += tmp;
3848         }
3849         return flushed;
3850 }
3851
3852
3853 /* ------------------------------------------------------------------------ */
3854 /* Function:    ipf_flush_groups                                            */
3855 /* Returns:     int - >= 0 - number of flushed rules                        */
3856 /* Parameters:  softc(I)  - soft context pointerto work with                */
3857 /*              grhead(I) - pointer to the start of the group list to flush */
3858 /*              flags(I)  - which set of rules to flush                     */
3859 /*                                                                          */
3860 /* Walk through all of the groups under the given group head and remove all */
3861 /* of those that match the flags passed in. The for loop here is bit more   */
3862 /* complicated than usual because the removal of a rule with ipf_derefrule  */
3863 /* may end up removing not only the structure pointed to by "fg" but also   */
3864 /* what is fg_next and fg_next after that. So if a filter rule is actually  */
3865 /* removed from the group then it is necessary to start again.              */
3866 /* ------------------------------------------------------------------------ */
3867 static int
3868 ipf_flush_groups(softc, grhead, flags)
3869         ipf_main_softc_t *softc;
3870         frgroup_t **grhead;
3871         int flags;
3872 {
3873         frentry_t *fr, **frp;
3874         frgroup_t *fg, **fgp;
3875         int flushed = 0;
3876         int removed = 0;
3877
3878         for (fgp = grhead; (fg = *fgp) != NULL; ) {
3879                 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3880                         fg = fg->fg_next;
3881                 if (fg == NULL)
3882                         break;
3883                 removed = 0;
3884                 frp = &fg->fg_start;
3885                 while ((removed == 0) && ((fr = *frp) != NULL)) {
3886                         if ((fr->fr_flags & flags) == 0) {
3887                                 frp = &fr->fr_next;
3888                         } else {
3889                                 if (fr->fr_next != NULL)
3890                                         fr->fr_next->fr_pnext = fr->fr_pnext;
3891                                 *frp = fr->fr_next;
3892                                 fr->fr_pnext = NULL;
3893                                 fr->fr_next = NULL;
3894                                 (void) ipf_derefrule(softc, &fr);
3895                                 flushed++;
3896                                 removed++;
3897                         }
3898                 }
3899                 if (removed == 0)
3900                         fgp = &fg->fg_next;
3901         }
3902         return flushed;
3903 }
3904
3905
3906 /* ------------------------------------------------------------------------ */
3907 /* Function:    memstr                                                      */
3908 /* Returns:     char *  - NULL if failed, != NULL pointer to matching bytes */
3909 /* Parameters:  src(I)  - pointer to byte sequence to match                 */
3910 /*              dst(I)  - pointer to byte sequence to search                */
3911 /*              slen(I) - match length                                      */
3912 /*              dlen(I) - length available to search in                     */
3913 /*                                                                          */
3914 /* Search dst for a sequence of bytes matching those at src and extend for  */
3915 /* slen bytes.                                                              */
3916 /* ------------------------------------------------------------------------ */
3917 char *
3918 memstr(src, dst, slen, dlen)
3919         const char *src;
3920         char *dst;
3921         size_t slen, dlen;
3922 {
3923         char *s = NULL;
3924
3925         while (dlen >= slen) {
3926                 if (bcmp(src, dst, slen) == 0) {
3927                         s = dst;
3928                         break;
3929                 }
3930                 dst++;
3931                 dlen--;
3932         }
3933         return s;
3934 }
3935 /* ------------------------------------------------------------------------ */
3936 /* Function:    ipf_fixskip                                                 */
3937 /* Returns:     Nil                                                         */
3938 /* Parameters:  listp(IO)    - pointer to start of list with skip rule      */
3939 /*              rp(I)        - rule added/removed with skip in it.          */
3940 /*              addremove(I) - adjustment (-1/+1) to make to skip count,    */
3941 /*                             depending on whether a rule was just added   */
3942 /*                             or removed.                                  */
3943 /*                                                                          */
3944 /* Adjust all the rules in a list which would have skip'd past the position */
3945 /* where we are inserting to skip to the right place given the change.      */
3946 /* ------------------------------------------------------------------------ */
3947 void
3948 ipf_fixskip(listp, rp, addremove)
3949         frentry_t **listp, *rp;
3950         int addremove;
3951 {
3952         int rules, rn;
3953         frentry_t *fp;
3954
3955         rules = 0;
3956         for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3957                 rules++;
3958
3959         if (!fp)
3960                 return;
3961
3962         for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3963                 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3964                         fp->fr_arg += addremove;
3965 }
3966
3967
3968 #ifdef  _KERNEL
3969 /* ------------------------------------------------------------------------ */
3970 /* Function:    count4bits                                                  */
3971 /* Returns:     int - >= 0 - number of consecutive bits in input            */
3972 /* Parameters:  ip(I) - 32bit IP address                                    */
3973 /*                                                                          */
3974 /* IPv4 ONLY                                                                */
3975 /* count consecutive 1's in bit mask.  If the mask generated by counting    */
3976 /* consecutive 1's is different to that passed, return -1, else return #    */
3977 /* of bits.                                                                 */
3978 /* ------------------------------------------------------------------------ */
3979 int
3980 count4bits(ip)
3981         u_32_t  ip;
3982 {
3983         u_32_t  ipn;
3984         int     cnt = 0, i, j;
3985
3986         ip = ipn = ntohl(ip);
3987         for (i = 32; i; i--, ipn *= 2)
3988                 if (ipn & 0x80000000)
3989                         cnt++;
3990                 else
3991                         break;
3992         ipn = 0;
3993         for (i = 32, j = cnt; i; i--, j--) {
3994                 ipn *= 2;
3995                 if (j > 0)
3996                         ipn++;
3997         }
3998         if (ipn == ip)
3999                 return cnt;
4000         return -1;
4001 }
4002
4003
4004 /* ------------------------------------------------------------------------ */
4005 /* Function:    count6bits                                                  */
4006 /* Returns:     int - >= 0 - number of consecutive bits in input            */
4007 /* Parameters:  msk(I) - pointer to start of IPv6 bitmask                   */
4008 /*                                                                          */
4009 /* IPv6 ONLY                                                                */
4010 /* count consecutive 1's in bit mask.                                       */
4011 /* ------------------------------------------------------------------------ */
4012 # ifdef USE_INET6
4013 int
4014 count6bits(msk)
4015         u_32_t *msk;
4016 {
4017         int i = 0, k;
4018         u_32_t j;
4019
4020         for (k = 3; k >= 0; k--)
4021                 if (msk[k] == 0xffffffff)
4022                         i += 32;
4023                 else {
4024                         for (j = msk[k]; j; j <<= 1)
4025                                 if (j & 0x80000000)
4026                                         i++;
4027                 }
4028         return i;
4029 }
4030 # endif
4031 #endif /* _KERNEL */
4032
4033
4034 /* ------------------------------------------------------------------------ */
4035 /* Function:    ipf_synclist                                                */
4036 /* Returns:     int    - 0 = no failures, else indication of first failure  */
4037 /* Parameters:  fr(I)  - start of filter list to sync interface names for   */
4038 /*              ifp(I) - interface pointer for limiting sync lookups        */
4039 /* Write Locks: ipf_mutex                                                   */
4040 /*                                                                          */
4041 /* Walk through a list of filter rules and resolve any interface names into */
4042 /* pointers.  Where dynamic addresses are used, also update the IP address  */
4043 /* used in the rule.  The interface pointer is used to limit the lookups to */
4044 /* a specific set of matching names if it is non-NULL.                      */
4045 /* Errors can occur when resolving the destination name of to/dup-to fields */
4046 /* when the name points to a pool and that pool doest not exist. If this    */
4047 /* does happen then it is necessary to check if there are any lookup refs   */
4048 /* that need to be dropped before returning with an error.                  */
4049 /* ------------------------------------------------------------------------ */
4050 static int
4051 ipf_synclist(softc, fr, ifp)
4052         ipf_main_softc_t *softc;
4053         frentry_t *fr;
4054         void *ifp;
4055 {
4056         frentry_t *frt, *start = fr;
4057         frdest_t *fdp;
4058         char *name;
4059         int error;
4060         void *ifa;
4061         int v, i;
4062
4063         error = 0;
4064
4065         for (; fr; fr = fr->fr_next) {
4066                 if (fr->fr_family == AF_INET)
4067                         v = 4;
4068                 else if (fr->fr_family == AF_INET6)
4069                         v = 6;
4070                 else
4071                         v = 0;
4072
4073                 /*
4074                  * Lookup all the interface names that are part of the rule.
4075                  */
4076                 for (i = 0; i < 4; i++) {
4077                         if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
4078                                 continue;
4079                         if (fr->fr_ifnames[i] == -1)
4080                                 continue;
4081                         name = FR_NAME(fr, fr_ifnames[i]);
4082                         fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
4083                 }
4084
4085                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
4086                         if (fr->fr_satype != FRI_NORMAL &&
4087                             fr->fr_satype != FRI_LOOKUP) {
4088                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4089                                                      fr->fr_sifpidx, v);
4090                                 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
4091                                             &fr->fr_src6, &fr->fr_smsk6);
4092                         }
4093                         if (fr->fr_datype != FRI_NORMAL &&
4094                             fr->fr_datype != FRI_LOOKUP) {
4095                                 ifa = ipf_resolvenic(softc, fr->fr_names +
4096                                                      fr->fr_sifpidx, v);
4097                                 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
4098                                             &fr->fr_dst6, &fr->fr_dmsk6);
4099                         }
4100                 }
4101
4102                 fdp = &fr->fr_tifs[0];
4103                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4104                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4105                         if (error != 0)
4106                                 goto unwind;
4107                 }
4108
4109                 fdp = &fr->fr_tifs[1];
4110                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4111                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4112                         if (error != 0)
4113                                 goto unwind;
4114                 }
4115
4116                 fdp = &fr->fr_dif;
4117                 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
4118                         error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
4119                         if (error != 0)
4120                                 goto unwind;
4121                 }
4122
4123                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4124                     (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
4125                         fr->fr_srcptr = ipf_lookup_res_num(softc,
4126                                                            fr->fr_srctype,
4127                                                            IPL_LOGIPF,
4128                                                            fr->fr_srcnum,
4129                                                            &fr->fr_srcfunc);
4130                 }
4131                 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4132                     (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
4133                         fr->fr_dstptr = ipf_lookup_res_num(softc,
4134                                                            fr->fr_dsttype,
4135                                                            IPL_LOGIPF,
4136                                                            fr->fr_dstnum,
4137                                                            &fr->fr_dstfunc);
4138                 }
4139         }
4140         return 0;
4141
4142 unwind:
4143         for (frt = start; frt != fr; fr = fr->fr_next) {
4144                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4145                     (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4146                                 ipf_lookup_deref(softc, frt->fr_srctype,
4147                                                  frt->fr_srcptr);
4148                 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4149                     (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4150                                 ipf_lookup_deref(softc, frt->fr_dsttype,
4151                                                  frt->fr_dstptr);
4152         }
4153         return error;
4154 }
4155
4156
4157 /* ------------------------------------------------------------------------ */
4158 /* Function:    ipf_sync                                                    */
4159 /* Returns:     void                                                        */
4160 /* Parameters:  Nil                                                         */
4161 /*                                                                          */
4162 /* ipf_sync() is called when we suspect that the interface list or          */
4163 /* information about interfaces (like IP#) has changed.  Go through all     */
4164 /* filter rules, NAT entries and the state table and check if anything      */
4165 /* needs to be changed/updated.                                             */
4166 /* ------------------------------------------------------------------------ */
4167 int
4168 ipf_sync(softc, ifp)
4169         ipf_main_softc_t *softc;
4170         void *ifp;
4171 {
4172         int i;
4173
4174 # if !SOLARIS
4175         ipf_nat_sync(softc, ifp);
4176         ipf_state_sync(softc, ifp);
4177         ipf_lookup_sync(softc, ifp);
4178 # endif
4179
4180         WRITE_ENTER(&softc->ipf_mutex);
4181         (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4182         (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4183         (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4184         (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4185
4186         for (i = 0; i < IPL_LOGSIZE; i++) {
4187                 frgroup_t *g;
4188
4189                 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4190                         (void) ipf_synclist(softc, g->fg_start, ifp);
4191                 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4192                         (void) ipf_synclist(softc, g->fg_start, ifp);
4193         }
4194         RWLOCK_EXIT(&softc->ipf_mutex);
4195
4196         return 0;
4197 }
4198
4199
4200 /*
4201  * In the functions below, bcopy() is called because the pointer being
4202  * copied _from_ in this instance is a pointer to a char buf (which could
4203  * end up being unaligned) and on the kernel's local stack.
4204  */
4205 /* ------------------------------------------------------------------------ */
4206 /* Function:    copyinptr                                                   */
4207 /* Returns:     int - 0 = success, else failure                             */
4208 /* Parameters:  src(I)  - pointer to the source address                     */
4209 /*              dst(I)  - destination address                               */
4210 /*              size(I) - number of bytes to copy                           */
4211 /*                                                                          */
4212 /* Copy a block of data in from user space, given a pointer to the pointer  */
4213 /* to start copying from (src) and a pointer to where to store it (dst).    */
4214 /* NB: src - pointer to user space pointer, dst - kernel space pointer      */
4215 /* ------------------------------------------------------------------------ */
4216 int
4217 copyinptr(softc, src, dst, size)
4218         ipf_main_softc_t *softc;
4219         void *src, *dst;
4220         size_t size;
4221 {
4222         caddr_t ca;
4223         int error;
4224
4225 # if SOLARIS
4226         error = COPYIN(src, &ca, sizeof(ca));
4227         if (error != 0)
4228                 return error;
4229 # else
4230         bcopy(src, (caddr_t)&ca, sizeof(ca));
4231 # endif
4232         error = COPYIN(ca, dst, size);
4233         if (error != 0) {
4234                 IPFERROR(3);
4235                 error = EFAULT;
4236         }
4237         return error;
4238 }
4239
4240
4241 /* ------------------------------------------------------------------------ */
4242 /* Function:    copyoutptr                                                  */
4243 /* Returns:     int - 0 = success, else failure                             */
4244 /* Parameters:  src(I)  - pointer to the source address                     */
4245 /*              dst(I)  - destination address                               */
4246 /*              size(I) - number of bytes to copy                           */
4247 /*                                                                          */
4248 /* Copy a block of data out to user space, given a pointer to the pointer   */
4249 /* to start copying from (src) and a pointer to where to store it (dst).    */
4250 /* NB: src - kernel space pointer, dst - pointer to user space pointer.     */
4251 /* ------------------------------------------------------------------------ */
4252 int
4253 copyoutptr(softc, src, dst, size)
4254         ipf_main_softc_t *softc;
4255         void *src, *dst;
4256         size_t size;
4257 {
4258         caddr_t ca;
4259         int error;
4260
4261         bcopy(dst, (caddr_t)&ca, sizeof(ca));
4262         error = COPYOUT(src, ca, size);
4263         if (error != 0) {
4264                 IPFERROR(4);
4265                 error = EFAULT;
4266         }
4267         return error;
4268 }
4269 #ifdef  _KERNEL
4270 #endif
4271
4272
4273 /* ------------------------------------------------------------------------ */
4274 /* Function:    ipf_lock                                                    */
4275 /* Returns:     int      - 0 = success, else error                          */
4276 /* Parameters:  data(I)  - pointer to lock value to set                     */
4277 /*              lockp(O) - pointer to location to store old lock value      */
4278 /*                                                                          */
4279 /* Get the new value for the lock integer, set it and return the old value  */
4280 /* in *lockp.                                                               */
4281 /* ------------------------------------------------------------------------ */
4282 int
4283 ipf_lock(data, lockp)
4284         caddr_t data;
4285         int *lockp;
4286 {
4287         int arg, err;
4288
4289         err = BCOPYIN(data, &arg, sizeof(arg));
4290         if (err != 0)
4291                 return EFAULT;
4292         err = BCOPYOUT(lockp, data, sizeof(*lockp));
4293         if (err != 0)
4294                 return EFAULT;
4295         *lockp = arg;
4296         return 0;
4297 }
4298
4299
4300 /* ------------------------------------------------------------------------ */
4301 /* Function:    ipf_getstat                                                 */
4302 /* Returns:     Nil                                                         */
4303 /* Parameters:  softc(I) - pointer to soft context main structure           */
4304 /*              fiop(I)  - pointer to ipfilter stats structure              */
4305 /*              rev(I)   - version claim by program doing ioctl             */
4306 /*                                                                          */
4307 /* Stores a copy of current pointers, counters, etc, in the friostat        */
4308 /* structure.                                                               */
4309 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the    */
4310 /* program is looking for. This ensure that validation of the version it    */
4311 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will      */
4312 /* allow older binaries to work but kernels without it will not.            */
4313 /* ------------------------------------------------------------------------ */
4314 /*ARGSUSED*/
4315 static void
4316 ipf_getstat(softc, fiop, rev)
4317         ipf_main_softc_t *softc;
4318         friostat_t *fiop;
4319         int rev;
4320 {
4321         int i;
4322
4323         bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4324               sizeof(ipf_statistics_t) * 2);
4325         fiop->f_locks[IPL_LOGSTATE] = -1;
4326         fiop->f_locks[IPL_LOGNAT] = -1;
4327         fiop->f_locks[IPL_LOGIPF] = -1;
4328         fiop->f_locks[IPL_LOGAUTH] = -1;
4329
4330         fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4331         fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4332         fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4333         fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4334         fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4335         fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4336         fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4337         fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4338
4339         fiop->f_ticks = softc->ipf_ticks;
4340         fiop->f_active = softc->ipf_active;
4341         fiop->f_froute[0] = softc->ipf_frouteok[0];
4342         fiop->f_froute[1] = softc->ipf_frouteok[1];
4343         fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4344         fiop->f_rb_node_max = softc->ipf_rb_node_max;
4345
4346         fiop->f_running = softc->ipf_running;
4347         for (i = 0; i < IPL_LOGSIZE; i++) {
4348                 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4349                 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4350         }
4351 #ifdef  IPFILTER_LOG
4352         fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4353         fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4354         fiop->f_logging = 1;
4355 #else
4356         fiop->f_log_ok = 0;
4357         fiop->f_log_fail = 0;
4358         fiop->f_logging = 0;
4359 #endif
4360         fiop->f_defpass = softc->ipf_pass;
4361         fiop->f_features = ipf_features;
4362
4363 #ifdef IPFILTER_COMPAT
4364         sprintf(fiop->f_version, "IP Filter: v%d.%d.%d",
4365                 (rev / 1000000) % 100,
4366                 (rev / 10000) % 100,
4367                 (rev / 100) % 100);
4368 #else
4369         rev = rev;
4370         (void) strncpy(fiop->f_version, ipfilter_version,
4371                        sizeof(fiop->f_version));
4372 #endif
4373 }
4374
4375
4376 #ifdef  USE_INET6
4377 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4378         ICMP6_ECHO_REPLY,       /* 0: ICMP_ECHOREPLY */
4379         -1,                     /* 1: UNUSED */
4380         -1,                     /* 2: UNUSED */
4381         ICMP6_DST_UNREACH,      /* 3: ICMP_UNREACH */
4382         -1,                     /* 4: ICMP_SOURCEQUENCH */
4383         ND_REDIRECT,            /* 5: ICMP_REDIRECT */
4384         -1,                     /* 6: UNUSED */
4385         -1,                     /* 7: UNUSED */
4386         ICMP6_ECHO_REQUEST,     /* 8: ICMP_ECHO */
4387         -1,                     /* 9: UNUSED */
4388         -1,                     /* 10: UNUSED */
4389         ICMP6_TIME_EXCEEDED,    /* 11: ICMP_TIMXCEED */
4390         ICMP6_PARAM_PROB,       /* 12: ICMP_PARAMPROB */
4391         -1,                     /* 13: ICMP_TSTAMP */
4392         -1,                     /* 14: ICMP_TSTAMPREPLY */
4393         -1,                     /* 15: ICMP_IREQ */
4394         -1,                     /* 16: ICMP_IREQREPLY */
4395         -1,                     /* 17: ICMP_MASKREQ */
4396         -1,                     /* 18: ICMP_MASKREPLY */
4397 };
4398
4399
4400 int     icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4401         ICMP6_DST_UNREACH_ADDR,         /* 0: ICMP_UNREACH_NET */
4402         ICMP6_DST_UNREACH_ADDR,         /* 1: ICMP_UNREACH_HOST */
4403         -1,                             /* 2: ICMP_UNREACH_PROTOCOL */
4404         ICMP6_DST_UNREACH_NOPORT,       /* 3: ICMP_UNREACH_PORT */
4405         -1,                             /* 4: ICMP_UNREACH_NEEDFRAG */
4406         ICMP6_DST_UNREACH_NOTNEIGHBOR,  /* 5: ICMP_UNREACH_SRCFAIL */
4407         ICMP6_DST_UNREACH_ADDR,         /* 6: ICMP_UNREACH_NET_UNKNOWN */
4408         ICMP6_DST_UNREACH_ADDR,         /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4409         -1,                             /* 8: ICMP_UNREACH_ISOLATED */
4410         ICMP6_DST_UNREACH_ADMIN,        /* 9: ICMP_UNREACH_NET_PROHIB */
4411         ICMP6_DST_UNREACH_ADMIN,        /* 10: ICMP_UNREACH_HOST_PROHIB */
4412         -1,                             /* 11: ICMP_UNREACH_TOSNET */
4413         -1,                             /* 12: ICMP_UNREACH_TOSHOST */
4414         ICMP6_DST_UNREACH_ADMIN,        /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4415 };
4416 int     icmpreplytype6[ICMP6_MAXTYPE + 1];
4417 #endif
4418
4419 int     icmpreplytype4[ICMP_MAXTYPE + 1];
4420
4421
4422 /* ------------------------------------------------------------------------ */
4423 /* Function:    ipf_matchicmpqueryreply                                     */
4424 /* Returns:     int - 1 if "icmp" is a valid reply to "ic" else 0.          */
4425 /* Parameters:  v(I)    - IP protocol version (4 or 6)                      */
4426 /*              ic(I)   - ICMP information                                  */
4427 /*              icmp(I) - ICMP packet header                                */
4428 /*              rev(I)  - direction (0 = forward/1 = reverse) of packet     */
4429 /*                                                                          */
4430 /* Check if the ICMP packet defined by the header pointed to by icmp is a   */
4431 /* reply to one as described by what's in ic.  If it is a match, return 1,  */
4432 /* else return 0 for no match.                                              */
4433 /* ------------------------------------------------------------------------ */
4434 int
4435 ipf_matchicmpqueryreply(v, ic, icmp, rev)
4436         int v;
4437         icmpinfo_t *ic;
4438         icmphdr_t *icmp;
4439         int rev;
4440 {
4441         int ictype;
4442
4443         ictype = ic->ici_type;
4444
4445         if (v == 4) {
4446                 /*
4447                  * If we matched its type on the way in, then when going out
4448                  * it will still be the same type.
4449                  */
4450                 if ((!rev && (icmp->icmp_type == ictype)) ||
4451                     (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4452                         if (icmp->icmp_type != ICMP_ECHOREPLY)
4453                                 return 1;
4454                         if (icmp->icmp_id == ic->ici_id)
4455                                 return 1;
4456                 }
4457         }
4458 #ifdef  USE_INET6
4459         else if (v == 6) {
4460                 if ((!rev && (icmp->icmp_type == ictype)) ||
4461                     (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4462                         if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4463                                 return 1;
4464                         if (icmp->icmp_id == ic->ici_id)
4465                                 return 1;
4466                 }
4467         }
4468 #endif
4469         return 0;
4470 }
4471
4472
4473 /* ------------------------------------------------------------------------ */
4474 /* Function:    ipf_rule_compare                                            */
4475 /* Parameters:  fr1(I) - first rule structure to compare                    */
4476 /*              fr2(I) - second rule structure to compare                   */
4477 /* Returns:     int    - 0 == rules are the same, else mismatch             */
4478 /*                                                                          */
4479 /* Compare two rules and return 0 if they match or a number indicating      */
4480 /* which of the individual checks failed.                                   */
4481 /* ------------------------------------------------------------------------ */
4482 static int
4483 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4484 {
4485         if (fr1->fr_cksum != fr2->fr_cksum)
4486                 return 1;
4487         if (fr1->fr_size != fr2->fr_size)
4488                 return 2;
4489         if (fr1->fr_dsize != fr2->fr_dsize)
4490                 return 3;
4491         if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func,
4492                  fr1->fr_size - offsetof(struct frentry, fr_func)) != 0)
4493                 return 4;
4494         if (fr1->fr_data && !fr2->fr_data)
4495                 return 5;
4496         if (!fr1->fr_data && fr2->fr_data)
4497                 return 6;
4498         if (fr1->fr_data) {
4499                 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize))
4500                         return 7;
4501         }
4502         return 0;
4503 }
4504
4505
4506 /* ------------------------------------------------------------------------ */
4507 /* Function:    frrequest                                                   */
4508 /* Returns:     int - 0 == success, > 0 == errno value                      */
4509 /* Parameters:  unit(I)     - device for which this is for                  */
4510 /*              req(I)      - ioctl command (SIOC*)                         */
4511 /*              data(I)     - pointr to ioctl data                          */
4512 /*              set(I)      - 1 or 0 (filter set)                           */
4513 /*              makecopy(I) - flag indicating whether data points to a rule */
4514 /*                            in kernel space & hence doesn't need copying. */
4515 /*                                                                          */
4516 /* This function handles all the requests which operate on the list of      */
4517 /* filter rules.  This includes adding, deleting, insertion.  It is also    */
4518 /* responsible for creating groups when a "head" rule is loaded.  Interface */
4519 /* names are resolved here and other sanity checks are made on the content  */
4520 /* of the rule structure being loaded.  If a rule has user defined timeouts */
4521 /* then make sure they are created and initialised before exiting.          */
4522 /* ------------------------------------------------------------------------ */
4523 int
4524 frrequest(softc, unit, req, data, set, makecopy)
4525         ipf_main_softc_t *softc;
4526         int unit;
4527         ioctlcmd_t req;
4528         int set, makecopy;
4529         caddr_t data;
4530 {
4531         int error = 0, in, family, addrem, need_free = 0;
4532         frentry_t frd, *fp, *f, **fprev, **ftail;
4533         void *ptr, *uptr, *cptr;
4534         u_int *p, *pp;
4535         frgroup_t *fg;
4536         char *group;
4537
4538         ptr = NULL;
4539         cptr = NULL;
4540         fg = NULL;
4541         fp = &frd;
4542         if (makecopy != 0) {
4543                 bzero(fp, sizeof(frd));
4544                 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4545                 if (error) {
4546                         return error;
4547                 }
4548                 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4549                         IPFERROR(6);
4550                         return EINVAL;
4551                 }
4552                 KMALLOCS(f, frentry_t *, fp->fr_size);
4553                 if (f == NULL) {
4554                         IPFERROR(131);
4555                         return ENOMEM;
4556                 }
4557                 bzero(f, fp->fr_size);
4558                 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4559                                     fp->fr_size);
4560                 if (error) {
4561                         KFREES(f, fp->fr_size);
4562                         return error;
4563                 }
4564
4565                 fp = f;
4566                 f = NULL;
4567                 fp->fr_next = NULL;
4568                 fp->fr_dnext = NULL;
4569                 fp->fr_pnext = NULL;
4570                 fp->fr_pdnext = NULL;
4571                 fp->fr_grp = NULL;
4572                 fp->fr_grphead = NULL;
4573                 fp->fr_icmpgrp = NULL;
4574                 fp->fr_isc = (void *)-1;
4575                 fp->fr_ptr = NULL;
4576                 fp->fr_ref = 0;
4577                 fp->fr_flags |= FR_COPIED;
4578         } else {
4579                 fp = (frentry_t *)data;
4580                 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4581                         IPFERROR(7);
4582                         return EINVAL;
4583                 }
4584                 fp->fr_flags &= ~FR_COPIED;
4585         }
4586
4587         if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4588             ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4589                 IPFERROR(8);
4590                 error = EINVAL;
4591                 goto donenolock;
4592         }
4593
4594         family = fp->fr_family;
4595         uptr = fp->fr_data;
4596
4597         if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4598             req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4599                 addrem = 0;
4600         else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4601                 addrem = 1;
4602         else if (req == (ioctlcmd_t)SIOCZRLST)
4603                 addrem = 2;
4604         else {
4605                 IPFERROR(9);
4606                 error = EINVAL;
4607                 goto donenolock;
4608         }
4609
4610         /*
4611          * Only filter rules for IPv4 or IPv6 are accepted.
4612          */
4613         if (family == AF_INET) {
4614                 /*EMPTY*/;
4615 #ifdef  USE_INET6
4616         } else if (family == AF_INET6) {
4617                 /*EMPTY*/;
4618 #endif
4619         } else if (family != 0) {
4620                 IPFERROR(10);
4621                 error = EINVAL;
4622                 goto donenolock;
4623         }
4624
4625         /*
4626          * If the rule is being loaded from user space, i.e. we had to copy it
4627          * into kernel space, then do not trust the function pointer in the
4628          * rule.
4629          */
4630         if ((makecopy == 1) && (fp->fr_func != NULL)) {
4631                 if (ipf_findfunc(fp->fr_func) == NULL) {
4632                         IPFERROR(11);
4633                         error = ESRCH;
4634                         goto donenolock;
4635                 }
4636
4637                 if (addrem == 0) {
4638                         error = ipf_funcinit(softc, fp);
4639                         if (error != 0)
4640                                 goto donenolock;
4641                 }
4642         }
4643         if ((fp->fr_flags & FR_CALLNOW) &&
4644             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4645                 IPFERROR(142);
4646                 error = ESRCH;
4647                 goto donenolock;
4648         }
4649         if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4650             ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4651                 IPFERROR(143);
4652                 error = ESRCH;
4653                 goto donenolock;
4654         }
4655
4656         ptr = NULL;
4657         cptr = NULL;
4658
4659         if (FR_ISACCOUNT(fp->fr_flags))
4660                 unit = IPL_LOGCOUNT;
4661
4662         /*
4663          * Check that each group name in the rule has a start index that
4664          * is valid.
4665          */
4666         if (fp->fr_icmphead != -1) {
4667                 if ((fp->fr_icmphead < 0) ||
4668                     (fp->fr_icmphead >= fp->fr_namelen)) {
4669                         IPFERROR(136);
4670                         error = EINVAL;
4671                         goto donenolock;
4672                 }
4673                 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4674                         fp->fr_names[fp->fr_icmphead] = '\0';
4675         }
4676
4677         if (fp->fr_grhead != -1) {
4678                 if ((fp->fr_grhead < 0) ||
4679                     (fp->fr_grhead >= fp->fr_namelen)) {
4680                         IPFERROR(137);
4681                         error = EINVAL;
4682                         goto donenolock;
4683                 }
4684                 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4685                         fp->fr_names[fp->fr_grhead] = '\0';
4686         }
4687
4688         if (fp->fr_group != -1) {
4689                 if ((fp->fr_group < 0) ||
4690                     (fp->fr_group >= fp->fr_namelen)) {
4691                         IPFERROR(138);
4692                         error = EINVAL;
4693                         goto donenolock;
4694                 }
4695                 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4696                         /*
4697                          * Allow loading rules that are in groups to cause
4698                          * them to be created if they don't already exit.
4699                          */
4700                         group = FR_NAME(fp, fr_group);
4701                         if (addrem == 0) {
4702                                 fg = ipf_group_add(softc, group, NULL,
4703                                                    fp->fr_flags, unit, set);
4704                                 fp->fr_grp = fg;
4705                         } else {
4706                                 fg = ipf_findgroup(softc, group, unit,
4707                                                    set, NULL);
4708                                 if (fg == NULL) {
4709                                         IPFERROR(12);
4710                                         error = ESRCH;
4711                                         goto donenolock;
4712                                 }
4713                         }
4714
4715                         if (fg->fg_flags == 0) {
4716                                 fg->fg_flags = fp->fr_flags & FR_INOUT;
4717                         } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4718                                 IPFERROR(13);
4719                                 error = ESRCH;
4720                                 goto donenolock;
4721                         }
4722                 }
4723         } else {
4724                 /*
4725                  * If a rule is going to be part of a group then it does
4726                  * not matter whether it is an in or out rule, but if it
4727                  * isn't in a group, then it does...
4728                  */
4729                 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4730                         IPFERROR(14);
4731                         error = EINVAL;
4732                         goto donenolock;
4733                 }
4734         }
4735         in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4736
4737         /*
4738          * Work out which rule list this change is being applied to.
4739          */
4740         ftail = NULL;
4741         fprev = NULL;
4742         if (unit == IPL_LOGAUTH) {
4743                 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4744                     (fp->fr_tifs[1].fd_ptr != NULL) ||
4745                     (fp->fr_dif.fd_ptr != NULL) ||
4746                     (fp->fr_flags & FR_FASTROUTE)) {
4747                         softc->ipf_interror = 145;
4748                         error = EINVAL;
4749                         goto donenolock;
4750                 }
4751                 fprev = ipf_auth_rulehead(softc);
4752         } else {
4753                 if (FR_ISACCOUNT(fp->fr_flags))
4754                         fprev = &softc->ipf_acct[in][set];
4755                 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4756                         fprev = &softc->ipf_rules[in][set];
4757         }
4758         if (fprev == NULL) {
4759                 IPFERROR(15);
4760                 error = ESRCH;
4761                 goto donenolock;
4762         }
4763
4764         if (fg != NULL)
4765                 fprev = &fg->fg_start;
4766
4767         /*
4768          * Copy in extra data for the rule.
4769          */
4770         if (fp->fr_dsize != 0) {
4771                 if (makecopy != 0) {
4772                         KMALLOCS(ptr, void *, fp->fr_dsize);
4773                         if (ptr == NULL) {
4774                                 IPFERROR(16);
4775                                 error = ENOMEM;
4776                                 goto donenolock;
4777                         }
4778
4779                         /*
4780                          * The bcopy case is for when the data is appended
4781                          * to the rule by ipf_in_compat().
4782                          */
4783                         if (uptr >= (void *)fp &&
4784                             uptr < (void *)((char *)fp + fp->fr_size)) {
4785                                 bcopy(uptr, ptr, fp->fr_dsize);
4786                                 error = 0;
4787                         } else {
4788                                 error = COPYIN(uptr, ptr, fp->fr_dsize);
4789                                 if (error != 0) {
4790                                         IPFERROR(17);
4791                                         error = EFAULT;
4792                                         goto donenolock;
4793                                 }
4794                         }
4795                 } else {
4796                         ptr = uptr;
4797                 }
4798                 fp->fr_data = ptr;
4799         } else {
4800                 fp->fr_data = NULL;
4801         }
4802
4803         /*
4804          * Perform per-rule type sanity checks of their members.
4805          * All code after this needs to be aware that allocated memory
4806          * may need to be free'd before exiting.
4807          */
4808         switch (fp->fr_type & ~FR_T_BUILTIN)
4809         {
4810 #if defined(IPFILTER_BPF)
4811         case FR_T_BPFOPC :
4812                 if (fp->fr_dsize == 0) {
4813                         IPFERROR(19);
4814                         error = EINVAL;
4815                         break;
4816                 }
4817                 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4818                         IPFERROR(20);
4819                         error = EINVAL;
4820                         break;
4821                 }
4822                 break;
4823 #endif
4824         case FR_T_IPF :
4825                 /*
4826                  * Preparation for error case at the bottom of this function.
4827                  */
4828                 if (fp->fr_datype == FRI_LOOKUP)
4829                         fp->fr_dstptr = NULL;
4830                 if (fp->fr_satype == FRI_LOOKUP)
4831                         fp->fr_srcptr = NULL;
4832
4833                 if (fp->fr_dsize != sizeof(fripf_t)) {
4834                         IPFERROR(21);
4835                         error = EINVAL;
4836                         break;
4837                 }
4838
4839                 /*
4840                  * Allowing a rule with both "keep state" and "with oow" is
4841                  * pointless because adding a state entry to the table will
4842                  * fail with the out of window (oow) flag set.
4843                  */
4844                 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4845                         IPFERROR(22);
4846                         error = EINVAL;
4847                         break;
4848                 }
4849
4850                 switch (fp->fr_satype)
4851                 {
4852                 case FRI_BROADCAST :
4853                 case FRI_DYNAMIC :
4854                 case FRI_NETWORK :
4855                 case FRI_NETMASKED :
4856                 case FRI_PEERADDR :
4857                         if (fp->fr_sifpidx < 0) {
4858                                 IPFERROR(23);
4859                                 error = EINVAL;
4860                         }
4861                         break;
4862                 case FRI_LOOKUP :
4863                         fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4864                                                        &fp->fr_src6,
4865                                                        &fp->fr_smsk6);
4866                         if (fp->fr_srcfunc == NULL) {
4867                                 IPFERROR(132);
4868                                 error = ESRCH;
4869                                 break;
4870                         }
4871                         break;
4872                 case FRI_NORMAL :
4873                         break;
4874                 default :
4875                         IPFERROR(133);
4876                         error = EINVAL;
4877                         break;
4878                 }
4879                 if (error != 0)
4880                         break;
4881
4882                 switch (fp->fr_datype)
4883                 {
4884                 case FRI_BROADCAST :
4885                 case FRI_DYNAMIC :
4886                 case FRI_NETWORK :
4887                 case FRI_NETMASKED :
4888                 case FRI_PEERADDR :
4889                         if (fp->fr_difpidx < 0) {
4890                                 IPFERROR(24);
4891                                 error = EINVAL;
4892                         }
4893                         break;
4894                 case FRI_LOOKUP :
4895                         fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4896                                                        &fp->fr_dst6,
4897                                                        &fp->fr_dmsk6);
4898                         if (fp->fr_dstfunc == NULL) {
4899                                 IPFERROR(134);
4900                                 error = ESRCH;
4901                         }
4902                         break;
4903                 case FRI_NORMAL :
4904                         break;
4905                 default :
4906                         IPFERROR(135);
4907                         error = EINVAL;
4908                 }
4909                 break;
4910
4911         case FR_T_NONE :
4912         case FR_T_CALLFUNC :
4913         case FR_T_COMPIPF :
4914                 break;
4915
4916         case FR_T_IPFEXPR :
4917                 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4918                         IPFERROR(25);
4919                         error = EINVAL;
4920                 }
4921                 break;
4922
4923         default :
4924                 IPFERROR(26);
4925                 error = EINVAL;
4926                 break;
4927         }
4928         if (error != 0)
4929                 goto donenolock;
4930
4931         if (fp->fr_tif.fd_name != -1) {
4932                 if ((fp->fr_tif.fd_name < 0) ||
4933                     (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4934                         IPFERROR(139);
4935                         error = EINVAL;
4936                         goto donenolock;
4937                 }
4938         }
4939
4940         if (fp->fr_dif.fd_name != -1) {
4941                 if ((fp->fr_dif.fd_name < 0) ||
4942                     (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4943                         IPFERROR(140);
4944                         error = EINVAL;
4945                         goto donenolock;
4946                 }
4947         }
4948
4949         if (fp->fr_rif.fd_name != -1) {
4950                 if ((fp->fr_rif.fd_name < 0) ||
4951                     (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4952                         IPFERROR(141);
4953                         error = EINVAL;
4954                         goto donenolock;
4955                 }
4956         }
4957
4958         /*
4959          * Lookup all the interface names that are part of the rule.
4960          */
4961         error = ipf_synclist(softc, fp, NULL);
4962         if (error != 0)
4963                 goto donenolock;
4964         fp->fr_statecnt = 0;
4965         if (fp->fr_srctrack.ht_max_nodes != 0)
4966                 ipf_rb_ht_init(&fp->fr_srctrack);
4967
4968         /*
4969          * Look for an existing matching filter rule, but don't include the
4970          * next or interface pointer in the comparison (fr_next, fr_ifa).
4971          * This elminates rules which are indentical being loaded.  Checksum
4972          * the constant part of the filter rule to make comparisons quicker
4973          * (this meaning no pointers are included).
4974          */
4975         for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4976              p < pp; p++)
4977                 fp->fr_cksum += *p;
4978         pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4979         for (p = (u_int *)fp->fr_data; p < pp; p++)
4980                 fp->fr_cksum += *p;
4981
4982         WRITE_ENTER(&softc->ipf_mutex);
4983
4984         /*
4985          * Now that the filter rule lists are locked, we can walk the
4986          * chain of them without fear.
4987          */
4988         ftail = fprev;
4989         for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4990                 if (fp->fr_collect <= f->fr_collect) {
4991                         ftail = fprev;
4992                         f = NULL;
4993                         break;
4994                 }
4995                 fprev = ftail;
4996         }
4997
4998         for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4999                 if (ipf_rule_compare(fp, f) == 0)
5000                         break;
5001         }
5002
5003         /*
5004          * If zero'ing statistics, copy current to caller and zero.
5005          */
5006         if (addrem == 2) {
5007                 if (f == NULL) {
5008                         IPFERROR(27);
5009                         error = ESRCH;
5010                 } else {
5011                         /*
5012                          * Copy and reduce lock because of impending copyout.
5013                          * Well we should, but if we do then the atomicity of
5014                          * this call and the correctness of fr_hits and
5015                          * fr_bytes cannot be guaranteed.  As it is, this code
5016                          * only resets them to 0 if they are successfully
5017                          * copied out into user space.
5018                          */
5019                         bcopy((char *)f, (char *)fp, f->fr_size);
5020                         /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
5021
5022                         /*
5023                          * When we copy this rule back out, set the data
5024                          * pointer to be what it was in user space.
5025                          */
5026                         fp->fr_data = uptr;
5027                         error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
5028
5029                         if (error == 0) {
5030                                 if ((f->fr_dsize != 0) && (uptr != NULL))
5031                                         error = COPYOUT(f->fr_data, uptr,
5032                                                         f->fr_dsize);
5033                                         if (error != 0) {
5034                                                 IPFERROR(28);
5035                                                 error = EFAULT;
5036                                         }
5037                                 if (error == 0) {
5038                                         f->fr_hits = 0;
5039                                         f->fr_bytes = 0;
5040                                 }
5041                         }
5042                 }
5043
5044                 if (makecopy != 0) {
5045                         if (ptr != NULL) {
5046                                 KFREES(ptr, fp->fr_dsize);
5047                         }
5048                         KFREES(fp, fp->fr_size);
5049                 }
5050                 RWLOCK_EXIT(&softc->ipf_mutex);
5051                 return error;
5052         }
5053
5054         if (!f) {
5055                 /*
5056                  * At the end of this, ftail must point to the place where the
5057                  * new rule is to be saved/inserted/added.
5058                  * For SIOCAD*FR, this should be the last rule in the group of
5059                  * rules that have equal fr_collect fields.
5060                  * For SIOCIN*FR, ...
5061                  */
5062                 if (req == (ioctlcmd_t)SIOCADAFR ||
5063                     req == (ioctlcmd_t)SIOCADIFR) {
5064
5065                         for (ftail = fprev; (f = *ftail) != NULL; ) {
5066                                 if (f->fr_collect > fp->fr_collect)
5067                                         break;
5068                                 ftail = &f->fr_next;
5069                                 fprev = ftail;
5070                         }
5071                         ftail = fprev;
5072                         f = NULL;
5073                         ptr = NULL;
5074                 } else if (req == (ioctlcmd_t)SIOCINAFR ||
5075                            req == (ioctlcmd_t)SIOCINIFR) {
5076                         while ((f = *fprev) != NULL) {
5077                                 if (f->fr_collect >= fp->fr_collect)
5078                                         break;
5079                                 fprev = &f->fr_next;
5080                         }
5081                         ftail = fprev;
5082                         if (fp->fr_hits != 0) {
5083                                 while (fp->fr_hits && (f = *ftail)) {
5084                                         if (f->fr_collect != fp->fr_collect)
5085                                                 break;
5086                                         fprev = ftail;
5087                                         ftail = &f->fr_next;
5088                                         fp->fr_hits--;
5089                                 }
5090                         }
5091                         f = NULL;
5092                         ptr = NULL;
5093                 }
5094         }
5095
5096         /*
5097          * Request to remove a rule.
5098          */
5099         if (addrem == 1) {
5100                 if (!f) {
5101                         IPFERROR(29);
5102                         error = ESRCH;
5103                 } else {
5104                         /*
5105                          * Do not allow activity from user space to interfere
5106                          * with rules not loaded that way.
5107                          */
5108                         if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5109                                 IPFERROR(30);
5110                                 error = EPERM;
5111                                 goto done;
5112                         }
5113
5114                         /*
5115                          * Return EBUSY if the rule is being reference by
5116                          * something else (eg state information.)
5117                          */
5118                         if (f->fr_ref > 1) {
5119                                 IPFERROR(31);
5120                                 error = EBUSY;
5121                                 goto done;
5122                         }
5123 #ifdef  IPFILTER_SCAN
5124                         if (f->fr_isctag != -1 &&
5125                             (f->fr_isc != (struct ipscan *)-1))
5126                                 ipf_scan_detachfr(f);
5127 #endif
5128
5129                         if (unit == IPL_LOGAUTH) {
5130                                 error = ipf_auth_precmd(softc, req, f, ftail);
5131                                 goto done;
5132                         }
5133
5134                         ipf_rule_delete(softc, f, unit, set);
5135
5136                         need_free = makecopy;
5137                 }
5138         } else {
5139                 /*
5140                  * Not removing, so we must be adding/inserting a rule.
5141                  */
5142                 if (f != NULL) {
5143                         IPFERROR(32);
5144                         error = EEXIST;
5145                         goto done;
5146                 }
5147                 if (unit == IPL_LOGAUTH) {
5148                         error = ipf_auth_precmd(softc, req, fp, ftail);
5149                         goto done;
5150                 }
5151
5152                 MUTEX_NUKE(&fp->fr_lock);
5153                 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5154                 if (fp->fr_die != 0)
5155                         ipf_rule_expire_insert(softc, fp, set);
5156
5157                 fp->fr_hits = 0;
5158                 if (makecopy != 0)
5159                         fp->fr_ref = 1;
5160                 fp->fr_pnext = ftail;
5161                 fp->fr_next = *ftail;
5162                 if (fp->fr_next != NULL)
5163                         fp->fr_next->fr_pnext = &fp->fr_next;
5164                 *ftail = fp;
5165                 if (addrem == 0)
5166                         ipf_fixskip(ftail, fp, 1);
5167
5168                 fp->fr_icmpgrp = NULL;
5169                 if (fp->fr_icmphead != -1) {
5170                         group = FR_NAME(fp, fr_icmphead);
5171                         fg = ipf_group_add(softc, group, fp, 0, unit, set);
5172                         fp->fr_icmpgrp = fg;
5173                 }
5174
5175                 fp->fr_grphead = NULL;
5176                 if (fp->fr_grhead != -1) {
5177                         group = FR_NAME(fp, fr_grhead);
5178                         fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5179                                            unit, set);
5180                         fp->fr_grphead = fg;
5181                 }
5182         }
5183 done:
5184         RWLOCK_EXIT(&softc->ipf_mutex);
5185 donenolock:
5186         if (need_free || (error != 0)) {
5187                 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5188                         if ((fp->fr_satype == FRI_LOOKUP) &&
5189                             (fp->fr_srcptr != NULL))
5190                                 ipf_lookup_deref(softc, fp->fr_srctype,
5191                                                  fp->fr_srcptr);
5192                         if ((fp->fr_datype == FRI_LOOKUP) &&
5193                             (fp->fr_dstptr != NULL))
5194                                 ipf_lookup_deref(softc, fp->fr_dsttype,
5195                                                  fp->fr_dstptr);
5196                 }
5197                 if (fp->fr_grp != NULL) {
5198                         WRITE_ENTER(&softc->ipf_mutex);
5199                         ipf_group_del(softc, fp->fr_grp, fp);
5200                         RWLOCK_EXIT(&softc->ipf_mutex);
5201                 }
5202                 if ((ptr != NULL) && (makecopy != 0)) {
5203                         KFREES(ptr, fp->fr_dsize);
5204                 }
5205                 KFREES(fp, fp->fr_size);
5206         }
5207         return (error);
5208 }
5209
5210
5211 /* ------------------------------------------------------------------------ */
5212 /* Function:   ipf_rule_delete                                              */
5213 /* Returns:    Nil                                                          */
5214 /* Parameters: softc(I) - pointer to soft context main structure            */
5215 /*             f(I)     - pointer to the rule being deleted                 */
5216 /*             ftail(I) - pointer to the pointer to f                       */
5217 /*             unit(I)  - device for which this is for                      */
5218 /*             set(I)   - 1 or 0 (filter set)                               */
5219 /*                                                                          */
5220 /* This function attempts to do what it can to delete a filter rule: remove */
5221 /* it from any linked lists and remove any groups it is responsible for.    */
5222 /* But in the end, removing a rule can only drop the reference count - we   */
5223 /* must use that as the guide for whether or not it can be freed.           */
5224 /* ------------------------------------------------------------------------ */
5225 static void
5226 ipf_rule_delete(softc, f, unit, set)
5227         ipf_main_softc_t *softc;
5228         frentry_t *f;
5229         int unit, set;
5230 {
5231
5232         /*
5233          * If fr_pdnext is set, then the rule is on the expire list, so
5234          * remove it from there.
5235          */
5236         if (f->fr_pdnext != NULL) {
5237                 *f->fr_pdnext = f->fr_dnext;
5238                 if (f->fr_dnext != NULL)
5239                         f->fr_dnext->fr_pdnext = f->fr_pdnext;
5240                 f->fr_pdnext = NULL;
5241                 f->fr_dnext = NULL;
5242         }
5243
5244         ipf_fixskip(f->fr_pnext, f, -1);
5245         if (f->fr_pnext != NULL)
5246                 *f->fr_pnext = f->fr_next;
5247         if (f->fr_next != NULL)
5248                 f->fr_next->fr_pnext = f->fr_pnext;
5249         f->fr_pnext = NULL;
5250         f->fr_next = NULL;
5251
5252         (void) ipf_derefrule(softc, &f);
5253 }
5254
5255 /* ------------------------------------------------------------------------ */
5256 /* Function:   ipf_rule_expire_insert                                       */
5257 /* Returns:    Nil                                                          */
5258 /* Parameters: softc(I) - pointer to soft context main structure            */
5259 /*             f(I)     - pointer to rule to be added to expire list        */
5260 /*             set(I)   - 1 or 0 (filter set)                               */
5261 /*                                                                          */
5262 /* If the new rule has a given expiration time, insert it into the list of  */
5263 /* expiring rules with the ones to be removed first added to the front of   */
5264 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5265 /* expiration interval checks.                                              */
5266 /* ------------------------------------------------------------------------ */
5267 static void
5268 ipf_rule_expire_insert(softc, f, set)
5269         ipf_main_softc_t *softc;
5270         frentry_t *f;
5271         int set;
5272 {
5273         frentry_t *fr;
5274
5275         /*
5276          */
5277
5278         f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5279         for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5280              fr = fr->fr_dnext) {
5281                 if (f->fr_die < fr->fr_die)
5282                         break;
5283                 if (fr->fr_dnext == NULL) {
5284                         /*
5285                          * We've got to the last rule and everything
5286                          * wanted to be expired before this new node,
5287                          * so we have to tack it on the end...
5288                          */
5289                         fr->fr_dnext = f;
5290                         f->fr_pdnext = &fr->fr_dnext;
5291                         fr = NULL;
5292                         break;
5293                 }
5294         }
5295
5296         if (softc->ipf_rule_explist[set] == NULL) {
5297                 softc->ipf_rule_explist[set] = f;
5298                 f->fr_pdnext = &softc->ipf_rule_explist[set];
5299         } else if (fr != NULL) {
5300                 f->fr_dnext = fr;
5301                 f->fr_pdnext = fr->fr_pdnext;
5302                 fr->fr_pdnext = &f->fr_dnext;
5303         }
5304 }
5305
5306
5307 /* ------------------------------------------------------------------------ */
5308 /* Function:   ipf_findlookup                                               */
5309 /* Returns:    NULL = failure, else success                                 */
5310 /* Parameters: softc(I) - pointer to soft context main structure            */
5311 /*             unit(I)  - ipf device we want to find match for              */
5312 /*             fp(I)    - rule for which lookup is for                      */
5313 /*             addrp(I) - pointer to lookup information in address struct   */
5314 /*             maskp(O) - pointer to lookup information for storage         */
5315 /*                                                                          */
5316 /* When using pools and hash tables to store addresses for matching in      */
5317 /* rules, it is necessary to resolve both the object referred to by the     */
5318 /* name or address (and return that pointer) and also provide the means by  */
5319 /* which to determine if an address belongs to that object to make the      */
5320 /* packet matching quicker.                                                 */
5321 /* ------------------------------------------------------------------------ */
5322 static void *
5323 ipf_findlookup(softc, unit, fr, addrp, maskp)
5324         ipf_main_softc_t *softc;
5325         int unit;
5326         frentry_t *fr;
5327         i6addr_t *addrp, *maskp;
5328 {
5329         void *ptr = NULL;
5330
5331         switch (addrp->iplookupsubtype)
5332         {
5333         case 0 :
5334                 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5335                                          addrp->iplookupnum,
5336                                          &maskp->iplookupfunc);
5337                 break;
5338         case 1 :
5339                 if (addrp->iplookupname < 0)
5340                         break;
5341                 if (addrp->iplookupname >= fr->fr_namelen)
5342                         break;
5343                 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5344                                           fr->fr_names + addrp->iplookupname,
5345                                           &maskp->iplookupfunc);
5346                 break;
5347         default :
5348                 break;
5349         }
5350
5351         return ptr;
5352 }
5353
5354
5355 /* ------------------------------------------------------------------------ */
5356 /* Function:    ipf_funcinit                                                */
5357 /* Returns:     int - 0 == success, else ESRCH: cannot resolve rule details */
5358 /* Parameters:  softc(I) - pointer to soft context main structure           */
5359 /*              fr(I)    - pointer to filter rule                           */
5360 /*                                                                          */
5361 /* If a rule is a call rule, then check if the function it points to needs  */
5362 /* an init function to be called now the rule has been loaded.              */
5363 /* ------------------------------------------------------------------------ */
5364 static int
5365 ipf_funcinit(softc, fr)
5366         ipf_main_softc_t *softc;
5367         frentry_t *fr;
5368 {
5369         ipfunc_resolve_t *ft;
5370         int err;
5371
5372         IPFERROR(34);
5373         err = ESRCH;
5374
5375         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5376                 if (ft->ipfu_addr == fr->fr_func) {
5377                         err = 0;
5378                         if (ft->ipfu_init != NULL)
5379                                 err = (*ft->ipfu_init)(softc, fr);
5380                         break;
5381                 }
5382         return err;
5383 }
5384
5385
5386 /* ------------------------------------------------------------------------ */
5387 /* Function:    ipf_funcfini                                                */
5388 /* Returns:     Nil                                                         */
5389 /* Parameters:  softc(I) - pointer to soft context main structure           */
5390 /*              fr(I)    - pointer to filter rule                           */
5391 /*                                                                          */
5392 /* For a given filter rule, call the matching "fini" function if the rule   */
5393 /* is using a known function that would have resulted in the "init" being   */
5394 /* called for ealier.                                                       */
5395 /* ------------------------------------------------------------------------ */
5396 static void
5397 ipf_funcfini(softc, fr)
5398         ipf_main_softc_t *softc;
5399         frentry_t *fr;
5400 {
5401         ipfunc_resolve_t *ft;
5402
5403         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5404                 if (ft->ipfu_addr == fr->fr_func) {
5405                         if (ft->ipfu_fini != NULL)
5406                                 (void) (*ft->ipfu_fini)(softc, fr);
5407                         break;
5408                 }
5409 }
5410
5411
5412 /* ------------------------------------------------------------------------ */
5413 /* Function:    ipf_findfunc                                                */
5414 /* Returns:     ipfunc_t - pointer to function if found, else NULL          */
5415 /* Parameters:  funcptr(I) - function pointer to lookup                     */
5416 /*                                                                          */
5417 /* Look for a function in the table of known functions.                     */
5418 /* ------------------------------------------------------------------------ */
5419 static ipfunc_t
5420 ipf_findfunc(funcptr)
5421         ipfunc_t funcptr;
5422 {
5423         ipfunc_resolve_t *ft;
5424
5425         for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5426                 if (ft->ipfu_addr == funcptr)
5427                         return funcptr;
5428         return NULL;
5429 }
5430
5431
5432 /* ------------------------------------------------------------------------ */
5433 /* Function:    ipf_resolvefunc                                             */
5434 /* Returns:     int - 0 == success, else error                              */
5435 /* Parameters:  data(IO) - ioctl data pointer to ipfunc_resolve_t struct    */
5436 /*                                                                          */
5437 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5438 /* This will either be the function name (if the pointer is set) or the     */
5439 /* function pointer if the name is set.  When found, fill in the other one  */
5440 /* so that the entire, complete, structure can be copied back to user space.*/
5441 /* ------------------------------------------------------------------------ */
5442 int
5443 ipf_resolvefunc(softc, data)
5444         ipf_main_softc_t *softc;
5445         void *data;
5446 {
5447         ipfunc_resolve_t res, *ft;
5448         int error;
5449
5450         error = BCOPYIN(data, &res, sizeof(res));
5451         if (error != 0) {
5452                 IPFERROR(123);
5453                 return EFAULT;
5454         }
5455
5456         if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5457                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5458                         if (strncmp(res.ipfu_name, ft->ipfu_name,
5459                                     sizeof(res.ipfu_name)) == 0) {
5460                                 res.ipfu_addr = ft->ipfu_addr;
5461                                 res.ipfu_init = ft->ipfu_init;
5462                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5463                                         IPFERROR(35);
5464                                         return EFAULT;
5465                                 }
5466                                 return 0;
5467                         }
5468         }
5469         if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5470                 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5471                         if (ft->ipfu_addr == res.ipfu_addr) {
5472                                 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5473                                                sizeof(res.ipfu_name));
5474                                 res.ipfu_init = ft->ipfu_init;
5475                                 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5476                                         IPFERROR(36);
5477                                         return EFAULT;
5478                                 }
5479                                 return 0;
5480                         }
5481         }
5482         IPFERROR(37);
5483         return ESRCH;
5484 }
5485
5486
5487 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5488      !defined(__FreeBSD__)) || \
5489     FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5490     OPENBSD_LT_REV(200006)
5491 /*
5492  * From: NetBSD
5493  * ppsratecheck(): packets (or events) per second limitation.
5494  */
5495 int
5496 ppsratecheck(lasttime, curpps, maxpps)
5497         struct timeval *lasttime;
5498         int *curpps;
5499         int maxpps;     /* maximum pps allowed */
5500 {
5501         struct timeval tv, delta;
5502         int rv;
5503
5504         GETKTIME(&tv);
5505
5506         delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5507         delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5508         if (delta.tv_usec < 0) {
5509                 delta.tv_sec--;
5510                 delta.tv_usec += 1000000;
5511         }
5512
5513         /*
5514          * check for 0,0 is so that the message will be seen at least once.
5515          * if more than one second have passed since the last update of
5516          * lasttime, reset the counter.
5517          *
5518          * we do increment *curpps even in *curpps < maxpps case, as some may
5519          * try to use *curpps for stat purposes as well.
5520          */
5521         if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5522             delta.tv_sec >= 1) {
5523                 *lasttime = tv;
5524                 *curpps = 0;
5525                 rv = 1;
5526         } else if (maxpps < 0)
5527                 rv = 1;
5528         else if (*curpps < maxpps)
5529                 rv = 1;
5530         else
5531                 rv = 0;
5532         *curpps = *curpps + 1;
5533
5534         return (rv);
5535 }
5536 #endif
5537
5538
5539 /* ------------------------------------------------------------------------ */
5540 /* Function:    ipf_derefrule                                               */
5541 /* Returns:     int   - 0 == rule freed up, else rule not freed             */
5542 /* Parameters:  fr(I) - pointer to filter rule                              */
5543 /*                                                                          */
5544 /* Decrement the reference counter to a rule by one.  If it reaches zero,   */
5545 /* free it and any associated storage space being used by it.               */
5546 /* ------------------------------------------------------------------------ */
5547 int
5548 ipf_derefrule(softc, frp)
5549         ipf_main_softc_t *softc;
5550         frentry_t **frp;
5551 {
5552         frentry_t *fr;
5553         frdest_t *fdp;
5554
5555         fr = *frp;
5556         *frp = NULL;
5557
5558         MUTEX_ENTER(&fr->fr_lock);
5559         fr->fr_ref--;
5560         if (fr->fr_ref == 0) {
5561                 MUTEX_EXIT(&fr->fr_lock);
5562                 MUTEX_DESTROY(&fr->fr_lock);
5563
5564                 ipf_funcfini(softc, fr);
5565
5566                 fdp = &fr->fr_tif;
5567                 if (fdp->fd_type == FRD_DSTLIST)
5568                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5569
5570                 fdp = &fr->fr_rif;
5571                 if (fdp->fd_type == FRD_DSTLIST)
5572                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5573
5574                 fdp = &fr->fr_dif;
5575                 if (fdp->fd_type == FRD_DSTLIST)
5576                         ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5577
5578                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5579                     fr->fr_satype == FRI_LOOKUP)
5580                         ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5581                 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5582                     fr->fr_datype == FRI_LOOKUP)
5583                         ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5584
5585                 if (fr->fr_grp != NULL)
5586                         ipf_group_del(softc, fr->fr_grp, fr);
5587
5588                 if (fr->fr_grphead != NULL)
5589                         ipf_group_del(softc, fr->fr_grphead, fr);
5590
5591                 if (fr->fr_icmpgrp != NULL)
5592                         ipf_group_del(softc, fr->fr_icmpgrp, fr);
5593
5594                 if ((fr->fr_flags & FR_COPIED) != 0) {
5595                         if (fr->fr_dsize) {
5596                                 KFREES(fr->fr_data, fr->fr_dsize);
5597                         }
5598                         KFREES(fr, fr->fr_size);
5599                         return 0;
5600                 }
5601                 return 1;
5602         } else {
5603                 MUTEX_EXIT(&fr->fr_lock);
5604         }
5605         return -1;
5606 }
5607
5608
5609 /* ------------------------------------------------------------------------ */
5610 /* Function:    ipf_grpmapinit                                              */
5611 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5612 /* Parameters:  fr(I) - pointer to rule to find hash table for              */
5613 /*                                                                          */
5614 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr.  */
5615 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap.                 */
5616 /* ------------------------------------------------------------------------ */
5617 static int
5618 ipf_grpmapinit(softc, fr)
5619         ipf_main_softc_t *softc;
5620         frentry_t *fr;
5621 {
5622         char name[FR_GROUPLEN];
5623         iphtable_t *iph;
5624
5625 #if defined(SNPRINTF) && defined(_KERNEL)
5626         SNPRINTF(name, sizeof(name), "%d", fr->fr_arg);
5627 #else
5628         (void) sprintf(name, "%d", fr->fr_arg);
5629 #endif
5630         iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5631         if (iph == NULL) {
5632                 IPFERROR(38);
5633                 return ESRCH;
5634         }
5635         if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5636                 IPFERROR(39);
5637                 return ESRCH;
5638         }
5639         iph->iph_ref++;
5640         fr->fr_ptr = iph;
5641         return 0;
5642 }
5643
5644
5645 /* ------------------------------------------------------------------------ */
5646 /* Function:    ipf_grpmapfini                                              */
5647 /* Returns:     int - 0 == success, else ESRCH because table entry not found*/
5648 /* Parameters:  softc(I) - pointer to soft context main structure           */
5649 /*              fr(I)    - pointer to rule to release hash table for        */
5650 /*                                                                          */
5651 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5652 /* be called to undo what ipf_grpmapinit caused to be done.                 */
5653 /* ------------------------------------------------------------------------ */
5654 static int
5655 ipf_grpmapfini(softc, fr)
5656         ipf_main_softc_t *softc;
5657         frentry_t *fr;
5658 {
5659         iphtable_t *iph;
5660         iph = fr->fr_ptr;
5661         if (iph != NULL)
5662                 ipf_lookup_deref(softc, IPLT_HASH, iph);
5663         return 0;
5664 }
5665
5666
5667 /* ------------------------------------------------------------------------ */
5668 /* Function:    ipf_srcgrpmap                                               */
5669 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5670 /* Parameters:  fin(I)    - pointer to packet information                   */
5671 /*              passp(IO) - pointer to current/new filter decision (unused) */
5672 /*                                                                          */
5673 /* Look for a rule group head in a hash table, using the source address as  */
5674 /* the key, and descend into that group and continue matching rules against */
5675 /* the packet.                                                              */
5676 /* ------------------------------------------------------------------------ */
5677 frentry_t *
5678 ipf_srcgrpmap(fin, passp)
5679         fr_info_t *fin;
5680         u_32_t *passp;
5681 {
5682         frgroup_t *fg;
5683         void *rval;
5684
5685         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5686                                  &fin->fin_src);
5687         if (rval == NULL)
5688                 return NULL;
5689
5690         fg = rval;
5691         fin->fin_fr = fg->fg_start;
5692         (void) ipf_scanlist(fin, *passp);
5693         return fin->fin_fr;
5694 }
5695
5696
5697 /* ------------------------------------------------------------------------ */
5698 /* Function:    ipf_dstgrpmap                                               */
5699 /* Returns:     frentry_t * - pointer to "new last matching" rule or NULL   */
5700 /* Parameters:  fin(I)    - pointer to packet information                   */
5701 /*              passp(IO) - pointer to current/new filter decision (unused) */
5702 /*                                                                          */
5703 /* Look for a rule group head in a hash table, using the destination        */
5704 /* address as the key, and descend into that group and continue matching    */
5705 /* rules against  the packet.                                               */
5706 /* ------------------------------------------------------------------------ */
5707 frentry_t *
5708 ipf_dstgrpmap(fin, passp)
5709         fr_info_t *fin;
5710         u_32_t *passp;
5711 {
5712         frgroup_t *fg;
5713         void *rval;
5714
5715         rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5716                                  &fin->fin_dst);
5717         if (rval == NULL)
5718                 return NULL;
5719
5720         fg = rval;
5721         fin->fin_fr = fg->fg_start;
5722         (void) ipf_scanlist(fin, *passp);
5723         return fin->fin_fr;
5724 }
5725
5726 /*
5727  * Queue functions
5728  * ===============
5729  * These functions manage objects on queues for efficient timeouts.  There
5730  * are a number of system defined queues as well as user defined timeouts.
5731  * It is expected that a lock is held in the domain in which the queue
5732  * belongs (i.e. either state or NAT) when calling any of these functions
5733  * that prevents ipf_freetimeoutqueue() from being called at the same time
5734  * as any other.
5735  */
5736
5737
5738 /* ------------------------------------------------------------------------ */
5739 /* Function:    ipf_addtimeoutqueue                                         */
5740 /* Returns:     struct ifqtq * - NULL if malloc fails, else pointer to      */
5741 /*                               timeout queue with given interval.         */
5742 /* Parameters:  parent(I)  - pointer to pointer to parent node of this list */
5743 /*                           of interface queues.                           */
5744 /*              seconds(I) - timeout value in seconds for this queue.       */
5745 /*                                                                          */
5746 /* This routine first looks for a timeout queue that matches the interval   */
5747 /* being requested.  If it finds one, increments the reference counter and  */
5748 /* returns a pointer to it.  If none are found, it allocates a new one and  */
5749 /* inserts it at the top of the list.                                       */
5750 /*                                                                          */
5751 /* Locking.                                                                 */
5752 /* It is assumed that the caller of this function has an appropriate lock   */
5753 /* held (exclusively) in the domain that encompases 'parent'.               */
5754 /* ------------------------------------------------------------------------ */
5755 ipftq_t *
5756 ipf_addtimeoutqueue(softc, parent, seconds)
5757         ipf_main_softc_t *softc;
5758         ipftq_t **parent;
5759         u_int seconds;
5760 {
5761         ipftq_t *ifq;
5762         u_int period;
5763
5764         period = seconds * IPF_HZ_DIVIDE;
5765
5766         MUTEX_ENTER(&softc->ipf_timeoutlock);
5767         for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5768                 if (ifq->ifq_ttl == period) {
5769                         /*
5770                          * Reset the delete flag, if set, so the structure
5771                          * gets reused rather than freed and reallocated.
5772                          */
5773                         MUTEX_ENTER(&ifq->ifq_lock);
5774                         ifq->ifq_flags &= ~IFQF_DELETE;
5775                         ifq->ifq_ref++;
5776                         MUTEX_EXIT(&ifq->ifq_lock);
5777                         MUTEX_EXIT(&softc->ipf_timeoutlock);
5778
5779                         return ifq;
5780                 }
5781         }
5782
5783         KMALLOC(ifq, ipftq_t *);
5784         if (ifq != NULL) {
5785                 MUTEX_NUKE(&ifq->ifq_lock);
5786                 IPFTQ_INIT(ifq, period, "ipftq mutex");
5787                 ifq->ifq_next = *parent;
5788                 ifq->ifq_pnext = parent;
5789                 ifq->ifq_flags = IFQF_USER;
5790                 ifq->ifq_ref++;
5791                 *parent = ifq;
5792                 softc->ipf_userifqs++;
5793         }
5794         MUTEX_EXIT(&softc->ipf_timeoutlock);
5795         return ifq;
5796 }
5797
5798
5799 /* ------------------------------------------------------------------------ */
5800 /* Function:    ipf_deletetimeoutqueue                                      */
5801 /* Returns:     int    - new reference count value of the timeout queue     */
5802 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5803 /* Locks:       ifq->ifq_lock                                               */
5804 /*                                                                          */
5805 /* This routine must be called when we're discarding a pointer to a timeout */
5806 /* queue object, taking care of the reference counter.                      */
5807 /*                                                                          */
5808 /* Now that this just sets a DELETE flag, it requires the expire code to    */
5809 /* check the list of user defined timeout queues and call the free function */
5810 /* below (currently commented out) to stop memory leaking.  It is done this */
5811 /* way because the locking may not be sufficient to safely do a free when   */
5812 /* this function is called.                                                 */
5813 /* ------------------------------------------------------------------------ */
5814 int
5815 ipf_deletetimeoutqueue(ifq)
5816         ipftq_t *ifq;
5817 {
5818
5819         ifq->ifq_ref--;
5820         if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5821                 ifq->ifq_flags |= IFQF_DELETE;
5822         }
5823
5824         return ifq->ifq_ref;
5825 }
5826
5827
5828 /* ------------------------------------------------------------------------ */
5829 /* Function:    ipf_freetimeoutqueue                                        */
5830 /* Parameters:  ifq(I) - timeout queue which is losing a reference.         */
5831 /* Returns:     Nil                                                         */
5832 /*                                                                          */
5833 /* Locking:                                                                 */
5834 /* It is assumed that the caller of this function has an appropriate lock   */
5835 /* held (exclusively) in the domain that encompases the callers "domain".   */
5836 /* The ifq_lock for this structure should not be held.                      */
5837 /*                                                                          */
5838 /* Remove a user defined timeout queue from the list of queues it is in and */
5839 /* tidy up after this is done.                                              */
5840 /* ------------------------------------------------------------------------ */
5841 void
5842 ipf_freetimeoutqueue(softc, ifq)
5843         ipf_main_softc_t *softc;
5844         ipftq_t *ifq;
5845 {
5846
5847         if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5848             ((ifq->ifq_flags & IFQF_USER) == 0)) {
5849                 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5850                        (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5851                        ifq->ifq_ref);
5852                 return;
5853         }
5854
5855         /*
5856          * Remove from its position in the list.
5857          */
5858         *ifq->ifq_pnext = ifq->ifq_next;
5859         if (ifq->ifq_next != NULL)
5860                 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5861         ifq->ifq_next = NULL;
5862         ifq->ifq_pnext = NULL;
5863
5864         MUTEX_DESTROY(&ifq->ifq_lock);
5865         ATOMIC_DEC(softc->ipf_userifqs);
5866         KFREE(ifq);
5867 }
5868
5869
5870 /* ------------------------------------------------------------------------ */
5871 /* Function:    ipf_deletequeueentry                                        */
5872 /* Returns:     Nil                                                         */
5873 /* Parameters:  tqe(I) - timeout queue entry to delete                      */
5874 /*                                                                          */
5875 /* Remove a tail queue entry from its queue and make it an orphan.          */
5876 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5877 /* queue is correct.  We can't, however, call ipf_freetimeoutqueue because  */
5878 /* the correct lock(s) may not be held that would make it safe to do so.    */
5879 /* ------------------------------------------------------------------------ */
5880 void
5881 ipf_deletequeueentry(tqe)
5882         ipftqent_t *tqe;
5883 {
5884         ipftq_t *ifq;
5885
5886         ifq = tqe->tqe_ifq;
5887
5888         MUTEX_ENTER(&ifq->ifq_lock);
5889
5890         if (tqe->tqe_pnext != NULL) {
5891                 *tqe->tqe_pnext = tqe->tqe_next;
5892                 if (tqe->tqe_next != NULL)
5893                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5894                 else    /* we must be the tail anyway */
5895                         ifq->ifq_tail = tqe->tqe_pnext;
5896
5897                 tqe->tqe_pnext = NULL;
5898                 tqe->tqe_ifq = NULL;
5899         }
5900
5901         (void) ipf_deletetimeoutqueue(ifq);
5902         ASSERT(ifq->ifq_ref > 0);
5903
5904         MUTEX_EXIT(&ifq->ifq_lock);
5905 }
5906
5907
5908 /* ------------------------------------------------------------------------ */
5909 /* Function:    ipf_queuefront                                              */
5910 /* Returns:     Nil                                                         */
5911 /* Parameters:  tqe(I) - pointer to timeout queue entry                     */
5912 /*                                                                          */
5913 /* Move a queue entry to the front of the queue, if it isn't already there. */
5914 /* ------------------------------------------------------------------------ */
5915 void
5916 ipf_queuefront(tqe)
5917         ipftqent_t *tqe;
5918 {
5919         ipftq_t *ifq;
5920
5921         ifq = tqe->tqe_ifq;
5922         if (ifq == NULL)
5923                 return;
5924
5925         MUTEX_ENTER(&ifq->ifq_lock);
5926         if (ifq->ifq_head != tqe) {
5927                 *tqe->tqe_pnext = tqe->tqe_next;
5928                 if (tqe->tqe_next)
5929                         tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5930                 else
5931                         ifq->ifq_tail = tqe->tqe_pnext;
5932
5933                 tqe->tqe_next = ifq->ifq_head;
5934                 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5935                 ifq->ifq_head = tqe;
5936                 tqe->tqe_pnext = &ifq->ifq_head;
5937         }
5938         MUTEX_EXIT(&ifq->ifq_lock);
5939 }
5940
5941
5942 /* ------------------------------------------------------------------------ */
5943 /* Function:    ipf_queueback                                               */
5944 /* Returns:     Nil                                                         */
5945 /* Parameters:  ticks(I) - ipf tick time to use with this call              */
5946 /*              tqe(I)   - pointer to timeout queue entry                   */
5947 /*                                                                          */
5948 /* Move a queue entry to the back of the queue, if it isn't already there.  */
5949 /* We use use ticks to calculate the expiration and mark for when we last   */
5950 /* touched the structure.                                                   */
5951 /* ------------------------------------------------------------------------ */
5952 void
5953 ipf_queueback(ticks, tqe)
5954         u_long ticks;
5955         ipftqent_t *tqe;
5956 {
5957         ipftq_t *ifq;
5958
5959         ifq = tqe->tqe_ifq;
5960         if (ifq == NULL)
5961                 return;
5962         tqe->tqe_die = ticks + ifq->ifq_ttl;
5963         tqe->tqe_touched = ticks;
5964
5965         MUTEX_ENTER(&ifq->ifq_lock);
5966         if (tqe->tqe_next != NULL) {            /* at the end already ? */
5967                 /*
5968                  * Remove from list
5969                  */
5970                 *tqe->tqe_pnext = tqe->tqe_next;
5971                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5972
5973                 /*
5974                  * Make it the last entry.
5975                  */
5976                 tqe->tqe_next = NULL;
5977                 tqe->tqe_pnext = ifq->ifq_tail;
5978                 *ifq->ifq_tail = tqe;
5979                 ifq->ifq_tail = &tqe->tqe_next;
5980         }
5981         MUTEX_EXIT(&ifq->ifq_lock);
5982 }
5983
5984
5985 /* ------------------------------------------------------------------------ */
5986 /* Function:    ipf_queueappend                                             */
5987 /* Returns:     Nil                                                         */
5988 /* Parameters:  ticks(I)  - ipf tick time to use with this call             */
5989 /*              tqe(I)    - pointer to timeout queue entry                  */
5990 /*              ifq(I)    - pointer to timeout queue                        */
5991 /*              parent(I) - owing object pointer                            */
5992 /*                                                                          */
5993 /* Add a new item to this queue and put it on the very end.                 */
5994 /* We use use ticks to calculate the expiration and mark for when we last   */
5995 /* touched the structure.                                                   */
5996 /* ------------------------------------------------------------------------ */
5997 void
5998 ipf_queueappend(ticks, tqe, ifq, parent)
5999         u_long ticks;
6000         ipftqent_t *tqe;
6001         ipftq_t *ifq;
6002         void *parent;
6003 {
6004
6005         MUTEX_ENTER(&ifq->ifq_lock);
6006         tqe->tqe_parent = parent;
6007         tqe->tqe_pnext = ifq->ifq_tail;
6008         *ifq->ifq_tail = tqe;
6009         ifq->ifq_tail = &tqe->tqe_next;
6010         tqe->tqe_next = NULL;
6011         tqe->tqe_ifq = ifq;
6012         tqe->tqe_die = ticks + ifq->ifq_ttl;
6013         tqe->tqe_touched = ticks;
6014         ifq->ifq_ref++;
6015         MUTEX_EXIT(&ifq->ifq_lock);
6016 }
6017
6018
6019 /* ------------------------------------------------------------------------ */
6020 /* Function:    ipf_movequeue                                               */
6021 /* Returns:     Nil                                                         */
6022 /* Parameters:  tq(I)   - pointer to timeout queue information              */
6023 /*              oifp(I) - old timeout queue entry was on                    */
6024 /*              nifp(I) - new timeout queue to put entry on                 */
6025 /*                                                                          */
6026 /* Move a queue entry from one timeout queue to another timeout queue.      */
6027 /* If it notices that the current entry is already last and does not need   */
6028 /* to move queue, the return.                                               */
6029 /* ------------------------------------------------------------------------ */
6030 void
6031 ipf_movequeue(ticks, tqe, oifq, nifq)
6032         u_long ticks;
6033         ipftqent_t *tqe;
6034         ipftq_t *oifq, *nifq;
6035 {
6036
6037         /*
6038          * If the queue hasn't changed and we last touched this entry at the
6039          * same ipf time, then we're not going to achieve anything by either
6040          * changing the ttl or moving it on the queue.
6041          */
6042         if (oifq == nifq && tqe->tqe_touched == ticks)
6043                 return;
6044
6045         /*
6046          * For any of this to be outside the lock, there is a risk that two
6047          * packets entering simultaneously, with one changing to a different
6048          * queue and one not, could end up with things in a bizarre state.
6049          */
6050         MUTEX_ENTER(&oifq->ifq_lock);
6051
6052         tqe->tqe_touched = ticks;
6053         tqe->tqe_die = ticks + nifq->ifq_ttl;
6054         /*
6055          * Is the operation here going to be a no-op ?
6056          */
6057         if (oifq == nifq) {
6058                 if ((tqe->tqe_next == NULL) ||
6059                     (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
6060                         MUTEX_EXIT(&oifq->ifq_lock);
6061                         return;
6062                 }
6063         }
6064
6065         /*
6066          * Remove from the old queue
6067          */
6068         *tqe->tqe_pnext = tqe->tqe_next;
6069         if (tqe->tqe_next)
6070                 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
6071         else
6072                 oifq->ifq_tail = tqe->tqe_pnext;
6073         tqe->tqe_next = NULL;
6074
6075         /*
6076          * If we're moving from one queue to another, release the
6077          * lock on the old queue and get a lock on the new queue.
6078          * For user defined queues, if we're moving off it, call
6079          * delete in case it can now be freed.
6080          */
6081         if (oifq != nifq) {
6082                 tqe->tqe_ifq = NULL;
6083
6084                 (void) ipf_deletetimeoutqueue(oifq);
6085
6086                 MUTEX_EXIT(&oifq->ifq_lock);
6087
6088                 MUTEX_ENTER(&nifq->ifq_lock);
6089
6090                 tqe->tqe_ifq = nifq;
6091                 nifq->ifq_ref++;
6092         }
6093
6094         /*
6095          * Add to the bottom of the new queue
6096          */
6097         tqe->tqe_pnext = nifq->ifq_tail;
6098         *nifq->ifq_tail = tqe;
6099         nifq->ifq_tail = &tqe->tqe_next;
6100         MUTEX_EXIT(&nifq->ifq_lock);
6101 }
6102
6103
6104 /* ------------------------------------------------------------------------ */
6105 /* Function:    ipf_updateipid                                              */
6106 /* Returns:     int - 0 == success, -1 == error (packet should be droppped) */
6107 /* Parameters:  fin(I) - pointer to packet information                      */
6108 /*                                                                          */
6109 /* When we are doing NAT, change the IP of every packet to represent a      */
6110 /* single sequence of packets coming from the host, hiding any host         */
6111 /* specific sequencing that might otherwise be revealed.  If the packet is  */
6112 /* a fragment, then store the 'new' IPid in the fragment cache and look up  */
6113 /* the fragment cache for non-leading fragments.  If a non-leading fragment */
6114 /* has no match in the cache, return an error.                              */
6115 /* ------------------------------------------------------------------------ */
6116 static int
6117 ipf_updateipid(fin)
6118         fr_info_t *fin;
6119 {
6120         u_short id, ido, sums;
6121         u_32_t sumd, sum;
6122         ip_t *ip;
6123
6124         ip = fin->fin_ip;
6125         ido = ntohs(ip->ip_id);
6126         if (fin->fin_off != 0) {
6127                 sum = ipf_frag_ipidknown(fin);
6128                 if (sum == 0xffffffff)
6129                         return -1;
6130                 sum &= 0xffff;
6131                 id = (u_short)sum;
6132                 ip->ip_id = htons(id);
6133         } else {
6134                 ip_fillid(ip);
6135                 id = ntohs(ip->ip_id);
6136                 if ((fin->fin_flx & FI_FRAG) != 0)
6137                         (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6138         }
6139
6140         if (id == ido)
6141                 return 0;
6142         CALC_SUMD(ido, id, sumd);       /* DESTRUCTIVE MACRO! id,ido change */
6143         sum = (~ntohs(ip->ip_sum)) & 0xffff;
6144         sum += sumd;
6145         sum = (sum >> 16) + (sum & 0xffff);
6146         sum = (sum >> 16) + (sum & 0xffff);
6147         sums = ~(u_short)sum;
6148         ip->ip_sum = htons(sums);
6149         return 0;
6150 }
6151
6152
6153 #ifdef  NEED_FRGETIFNAME
6154 /* ------------------------------------------------------------------------ */
6155 /* Function:    ipf_getifname                                               */
6156 /* Returns:     char *    - pointer to interface name                       */
6157 /* Parameters:  ifp(I)    - pointer to network interface                    */
6158 /*              buffer(O) - pointer to where to store interface name        */
6159 /*                                                                          */
6160 /* Constructs an interface name in the buffer passed.  The buffer passed is */
6161 /* expected to be at least LIFNAMSIZ in bytes big.  If buffer is passed in  */
6162 /* as a NULL pointer then return a pointer to a static array.               */
6163 /* ------------------------------------------------------------------------ */
6164 char *
6165 ipf_getifname(ifp, buffer)
6166         struct ifnet *ifp;
6167         char *buffer;
6168 {
6169         static char namebuf[LIFNAMSIZ];
6170 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6171      defined(__sgi) || defined(linux) || defined(_AIX51) || \
6172      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6173         int unit, space;
6174         char temp[20];
6175         char *s;
6176 # endif
6177
6178         if (buffer == NULL)
6179                 buffer = namebuf;
6180         (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6181         buffer[LIFNAMSIZ - 1] = '\0';
6182 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
6183      defined(__sgi) || defined(_AIX51) || \
6184      (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
6185         for (s = buffer; *s; s++)
6186                 ;
6187         unit = ifp->if_unit;
6188         space = LIFNAMSIZ - (s - buffer);
6189         if ((space > 0) && (unit >= 0)) {
6190 #  if defined(SNPRINTF) && defined(_KERNEL)
6191                 SNPRINTF(temp, sizeof(temp), "%d", unit);
6192 #  else
6193                 (void) sprintf(temp, "%d", unit);
6194 #  endif
6195                 (void) strncpy(s, temp, space);
6196         }
6197 # endif
6198         return buffer;
6199 }
6200 #endif
6201
6202
6203 /* ------------------------------------------------------------------------ */
6204 /* Function:    ipf_ioctlswitch                                             */
6205 /* Returns:     int     - -1 continue processing, else ioctl return value   */
6206 /* Parameters:  unit(I) - device unit opened                                */
6207 /*              data(I) - pointer to ioctl data                             */
6208 /*              cmd(I)  - ioctl command                                     */
6209 /*              mode(I) - mode value                                        */
6210 /*              uid(I)  - uid making the ioctl call                         */
6211 /*              ctx(I)  - pointer to context data                           */
6212 /*                                                                          */
6213 /* Based on the value of unit, call the appropriate ioctl handler or return */
6214 /* EIO if ipfilter is not running.   Also checks if write perms are req'd   */
6215 /* for the device in order to execute the ioctl.  A special case is made    */
6216 /* SIOCIPFINTERROR so that the same code isn't required in every handler.   */
6217 /* The context data pointer is passed through as this is used as the key    */
6218 /* for locating a matching token for continued access for walking lists,    */
6219 /* etc.                                                                     */
6220 /* ------------------------------------------------------------------------ */
6221 int
6222 ipf_ioctlswitch(softc, unit, data, cmd, mode, uid, ctx)
6223         ipf_main_softc_t *softc;
6224         int unit, mode, uid;
6225         ioctlcmd_t cmd;
6226         void *data, *ctx;
6227 {
6228         int error = 0;
6229
6230         switch (cmd)
6231         {
6232         case SIOCIPFINTERROR :
6233                 error = BCOPYOUT(&softc->ipf_interror, data,
6234                                  sizeof(softc->ipf_interror));
6235                 if (error != 0) {
6236                         IPFERROR(40);
6237                         error = EFAULT;
6238                 }
6239                 return error;
6240         default :
6241                 break;
6242         }
6243
6244         switch (unit)
6245         {
6246         case IPL_LOGIPF :
6247                 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6248                 break;
6249         case IPL_LOGNAT :
6250                 if (softc->ipf_running > 0) {
6251                         error = ipf_nat_ioctl(softc, data, cmd, mode,
6252                                               uid, ctx);
6253                 } else {
6254                         IPFERROR(42);
6255                         error = EIO;
6256                 }
6257                 break;
6258         case IPL_LOGSTATE :
6259                 if (softc->ipf_running > 0) {
6260                         error = ipf_state_ioctl(softc, data, cmd, mode,
6261                                                 uid, ctx);
6262                 } else {
6263                         IPFERROR(43);
6264                         error = EIO;
6265                 }
6266                 break;
6267         case IPL_LOGAUTH :
6268                 if (softc->ipf_running > 0) {
6269                         error = ipf_auth_ioctl(softc, data, cmd, mode,
6270                                                uid, ctx);
6271                 } else {
6272                         IPFERROR(44);
6273                         error = EIO;
6274                 }
6275                 break;
6276         case IPL_LOGSYNC :
6277                 if (softc->ipf_running > 0) {
6278                         error = ipf_sync_ioctl(softc, data, cmd, mode,
6279                                                uid, ctx);
6280                 } else {
6281                         error = EIO;
6282                         IPFERROR(45);
6283                 }
6284                 break;
6285         case IPL_LOGSCAN :
6286 #ifdef IPFILTER_SCAN
6287                 if (softc->ipf_running > 0)
6288                         error = ipf_scan_ioctl(softc, data, cmd, mode,
6289                                                uid, ctx);
6290                 else
6291 #endif
6292                 {
6293                         error = EIO;
6294                         IPFERROR(46);
6295                 }
6296                 break;
6297         case IPL_LOGLOOKUP :
6298                 if (softc->ipf_running > 0) {
6299                         error = ipf_lookup_ioctl(softc, data, cmd, mode,
6300                                                  uid, ctx);
6301                 } else {
6302                         error = EIO;
6303                         IPFERROR(47);
6304                 }
6305                 break;
6306         default :
6307                 IPFERROR(48);
6308                 error = EIO;
6309                 break;
6310         }
6311
6312         return error;
6313 }
6314
6315
6316 /*
6317  * This array defines the expected size of objects coming into the kernel
6318  * for the various recognised object types. The first column is flags (see
6319  * below), 2nd column is current size, 3rd column is the version number of
6320  * when the current size became current.
6321  * Flags:
6322  * 1 = minimum size, not absolute size
6323  */
6324 static  int     ipf_objbytes[IPFOBJ_COUNT][3] = {
6325         { 1,    sizeof(struct frentry),         5010000 },      /* 0 */
6326         { 1,    sizeof(struct friostat),        5010000 },
6327         { 0,    sizeof(struct fr_info),         5010000 },
6328         { 0,    sizeof(struct ipf_authstat),    4010100 },
6329         { 0,    sizeof(struct ipfrstat),        5010000 },
6330         { 1,    sizeof(struct ipnat),           5010000 },      /* 5 */
6331         { 0,    sizeof(struct natstat),         5010000 },
6332         { 0,    sizeof(struct ipstate_save),    5010000 },
6333         { 1,    sizeof(struct nat_save),        5010000 },
6334         { 0,    sizeof(struct natlookup),       5010000 },
6335         { 1,    sizeof(struct ipstate),         5010000 },      /* 10 */
6336         { 0,    sizeof(struct ips_stat),        5010000 },
6337         { 0,    sizeof(struct frauth),          5010000 },
6338         { 0,    sizeof(struct ipftune),         4010100 },
6339         { 0,    sizeof(struct nat),             5010000 },
6340         { 0,    sizeof(struct ipfruleiter),     4011400 },      /* 15 */
6341         { 0,    sizeof(struct ipfgeniter),      4011400 },
6342         { 0,    sizeof(struct ipftable),        4011400 },
6343         { 0,    sizeof(struct ipflookupiter),   4011400 },
6344         { 0,    sizeof(struct ipftq) * IPF_TCP_NSTATES },
6345         { 1,    0,                              0       }, /* IPFEXPR */
6346         { 0,    0,                              0       }, /* PROXYCTL */
6347         { 0,    sizeof (struct fripf),          5010000 }
6348 };
6349
6350
6351 /* ------------------------------------------------------------------------ */
6352 /* Function:    ipf_inobj                                                   */
6353 /* Returns:     int     - 0 = success, else failure                         */
6354 /* Parameters:  softc(I) - soft context pointerto work with                 */
6355 /*              data(I)  - pointer to ioctl data                            */
6356 /*              objp(O)  - where to store ipfobj structure                  */
6357 /*              ptr(I)   - pointer to data to copy out                      */
6358 /*              type(I)  - type of structure being moved                    */
6359 /*                                                                          */
6360 /* Copy in the contents of what the ipfobj_t points to.  In future, we      */
6361 /* add things to check for version numbers, sizes, etc, to make it backward */
6362 /* compatible at the ABI for user land.                                     */
6363 /* If objp is not NULL then we assume that the caller wants to see what is  */
6364 /* in the ipfobj_t structure being copied in. As an example, this can tell  */
6365 /* the caller what version of ipfilter the ioctl program was written to.    */
6366 /* ------------------------------------------------------------------------ */
6367 int
6368 ipf_inobj(softc, data, objp, ptr, type)
6369         ipf_main_softc_t *softc;
6370         void *data;
6371         ipfobj_t *objp;
6372         void *ptr;
6373         int type;
6374 {
6375         ipfobj_t obj;
6376         int error;
6377         int size;
6378
6379         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6380                 IPFERROR(49);
6381                 return EINVAL;
6382         }
6383
6384         if (objp == NULL)
6385                 objp = &obj;
6386         error = BCOPYIN(data, objp, sizeof(*objp));
6387         if (error != 0) {
6388                 IPFERROR(124);
6389                 return EFAULT;
6390         }
6391
6392         if (objp->ipfo_type != type) {
6393                 IPFERROR(50);
6394                 return EINVAL;
6395         }
6396
6397         if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6398                 if ((ipf_objbytes[type][0] & 1) != 0) {
6399                         if (objp->ipfo_size < ipf_objbytes[type][1]) {
6400                                 IPFERROR(51);
6401                                 return EINVAL;
6402                         }
6403                         size =  ipf_objbytes[type][1];
6404                 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6405                         size =  objp->ipfo_size;
6406                 } else {
6407                         IPFERROR(52);
6408                         return EINVAL;
6409                 }
6410                 error = COPYIN(objp->ipfo_ptr, ptr, size);
6411                 if (error != 0) {
6412                         IPFERROR(55);
6413                         error = EFAULT;
6414                 }
6415         } else {
6416 #ifdef  IPFILTER_COMPAT
6417                 error = ipf_in_compat(softc, objp, ptr, 0);
6418 #else
6419                 IPFERROR(54);
6420                 error = EINVAL;
6421 #endif
6422         }
6423         return error;
6424 }
6425
6426
6427 /* ------------------------------------------------------------------------ */
6428 /* Function:    ipf_inobjsz                                                 */
6429 /* Returns:     int     - 0 = success, else failure                         */
6430 /* Parameters:  softc(I) - soft context pointerto work with                 */
6431 /*              data(I)  - pointer to ioctl data                            */
6432 /*              ptr(I)   - pointer to store real data in                    */
6433 /*              type(I)  - type of structure being moved                    */
6434 /*              sz(I)    - size of data to copy                             */
6435 /*                                                                          */
6436 /* As per ipf_inobj, except the size of the object to copy in is passed in  */
6437 /* but it must not be smaller than the size defined for the type and the    */
6438 /* type must allow for varied sized objects.  The extra requirement here is */
6439 /* that sz must match the size of the object being passed in - this is not  */
6440 /* not possible nor required in ipf_inobj().                                */
6441 /* ------------------------------------------------------------------------ */
6442 int
6443 ipf_inobjsz(softc, data, ptr, type, sz)
6444         ipf_main_softc_t *softc;
6445         void *data;
6446         void *ptr;
6447         int type, sz;
6448 {
6449         ipfobj_t obj;
6450         int error;
6451
6452         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6453                 IPFERROR(56);
6454                 return EINVAL;
6455         }
6456
6457         error = BCOPYIN(data, &obj, sizeof(obj));
6458         if (error != 0) {
6459                 IPFERROR(125);
6460                 return EFAULT;
6461         }
6462
6463         if (obj.ipfo_type != type) {
6464                 IPFERROR(58);
6465                 return EINVAL;
6466         }
6467
6468         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6469                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6470                     (sz < ipf_objbytes[type][1])) {
6471                         IPFERROR(57);
6472                         return EINVAL;
6473                 }
6474                 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6475                 if (error != 0) {
6476                         IPFERROR(61);
6477                         error = EFAULT;
6478                 }
6479         } else {
6480 #ifdef  IPFILTER_COMPAT
6481                 error = ipf_in_compat(softc, &obj, ptr, sz);
6482 #else
6483                 IPFERROR(60);
6484                 error = EINVAL;
6485 #endif
6486         }
6487         return error;
6488 }
6489
6490
6491 /* ------------------------------------------------------------------------ */
6492 /* Function:    ipf_outobjsz                                                */
6493 /* Returns:     int     - 0 = success, else failure                         */
6494 /* Parameters:  data(I) - pointer to ioctl data                             */
6495 /*              ptr(I)  - pointer to store real data in                     */
6496 /*              type(I) - type of structure being moved                     */
6497 /*              sz(I)   - size of data to copy                              */
6498 /*                                                                          */
6499 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6500 /* but it must not be smaller than the size defined for the type and the    */
6501 /* type must allow for varied sized objects.  The extra requirement here is */
6502 /* that sz must match the size of the object being passed in - this is not  */
6503 /* not possible nor required in ipf_outobj().                               */
6504 /* ------------------------------------------------------------------------ */
6505 int
6506 ipf_outobjsz(softc, data, ptr, type, sz)
6507         ipf_main_softc_t *softc;
6508         void *data;
6509         void *ptr;
6510         int type, sz;
6511 {
6512         ipfobj_t obj;
6513         int error;
6514
6515         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6516                 IPFERROR(62);
6517                 return EINVAL;
6518         }
6519
6520         error = BCOPYIN(data, &obj, sizeof(obj));
6521         if (error != 0) {
6522                 IPFERROR(127);
6523                 return EFAULT;
6524         }
6525
6526         if (obj.ipfo_type != type) {
6527                 IPFERROR(63);
6528                 return EINVAL;
6529         }
6530
6531         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6532                 if (((ipf_objbytes[type][0] & 1) == 0) ||
6533                     (sz < ipf_objbytes[type][1])) {
6534                         IPFERROR(146);
6535                         return EINVAL;
6536                 }
6537                 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6538                 if (error != 0) {
6539                         IPFERROR(66);
6540                         error = EFAULT;
6541                 }
6542         } else {
6543 #ifdef  IPFILTER_COMPAT
6544                 error = ipf_out_compat(softc, &obj, ptr);
6545 #else
6546                 IPFERROR(65);
6547                 error = EINVAL;
6548 #endif
6549         }
6550         return error;
6551 }
6552
6553
6554 /* ------------------------------------------------------------------------ */
6555 /* Function:    ipf_outobj                                                  */
6556 /* Returns:     int     - 0 = success, else failure                         */
6557 /* Parameters:  data(I) - pointer to ioctl data                             */
6558 /*              ptr(I)  - pointer to store real data in                     */
6559 /*              type(I) - type of structure being moved                     */
6560 /*                                                                          */
6561 /* Copy out the contents of what ptr is to where ipfobj points to.  In      */
6562 /* future, we add things to check for version numbers, sizes, etc, to make  */
6563 /* it backward  compatible at the ABI for user land.                        */
6564 /* ------------------------------------------------------------------------ */
6565 int
6566 ipf_outobj(softc, data, ptr, type)
6567         ipf_main_softc_t *softc;
6568         void *data;
6569         void *ptr;
6570         int type;
6571 {
6572         ipfobj_t obj;
6573         int error;
6574
6575         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6576                 IPFERROR(67);
6577                 return EINVAL;
6578         }
6579
6580         error = BCOPYIN(data, &obj, sizeof(obj));
6581         if (error != 0) {
6582                 IPFERROR(126);
6583                 return EFAULT;
6584         }
6585
6586         if (obj.ipfo_type != type) {
6587                 IPFERROR(68);
6588                 return EINVAL;
6589         }
6590
6591         if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6592                 if ((ipf_objbytes[type][0] & 1) != 0) {
6593                         if (obj.ipfo_size < ipf_objbytes[type][1]) {
6594                                 IPFERROR(69);
6595                                 return EINVAL;
6596                         }
6597                 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6598                         IPFERROR(70);
6599                         return EINVAL;
6600                 }
6601
6602                 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6603                 if (error != 0) {
6604                         IPFERROR(73);
6605                         error = EFAULT;
6606                 }
6607         } else {
6608 #ifdef  IPFILTER_COMPAT
6609                 error = ipf_out_compat(softc, &obj, ptr);
6610 #else
6611                 IPFERROR(72);
6612                 error = EINVAL;
6613 #endif
6614         }
6615         return error;
6616 }
6617
6618
6619 /* ------------------------------------------------------------------------ */
6620 /* Function:    ipf_outobjk                                                 */
6621 /* Returns:     int     - 0 = success, else failure                         */
6622 /* Parameters:  obj(I)  - pointer to data description structure             */
6623 /*              ptr(I)  - pointer to kernel data to copy out                */
6624 /*                                                                          */
6625 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6626 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6627 /* already populated with information and now we just need to use it.       */
6628 /* There is no need for this function to have a "type" parameter as there   */
6629 /* is no point in validating information that comes from the kernel with    */
6630 /* itself.                                                                  */
6631 /* ------------------------------------------------------------------------ */
6632 int
6633 ipf_outobjk(softc, obj, ptr)
6634         ipf_main_softc_t *softc;
6635         ipfobj_t *obj;
6636         void *ptr;
6637 {
6638         int type = obj->ipfo_type;
6639         int error;
6640
6641         if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6642                 IPFERROR(147);
6643                 return EINVAL;
6644         }
6645
6646         if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6647                 if ((ipf_objbytes[type][0] & 1) != 0) {
6648                         if (obj->ipfo_size < ipf_objbytes[type][1]) {
6649                                 IPFERROR(148);
6650                                 return EINVAL;
6651                         }
6652
6653                 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6654                         IPFERROR(149);
6655                         return EINVAL;
6656                 }
6657
6658                 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6659                 if (error != 0) {
6660                         IPFERROR(150);
6661                         error = EFAULT;
6662                 }
6663         } else {
6664 #ifdef  IPFILTER_COMPAT
6665                 error = ipf_out_compat(softc, obj, ptr);
6666 #else
6667                 IPFERROR(151);
6668                 error = EINVAL;
6669 #endif
6670         }
6671         return error;
6672 }
6673
6674
6675 /* ------------------------------------------------------------------------ */
6676 /* Function:    ipf_checkl4sum                                              */
6677 /* Returns:     int     - 0 = good, -1 = bad, 1 = cannot check              */
6678 /* Parameters:  fin(I) - pointer to packet information                      */
6679 /*                                                                          */
6680 /* If possible, calculate the layer 4 checksum for the packet.  If this is  */
6681 /* not possible, return without indicating a failure or success but in a    */
6682 /* way that is ditinguishable. This function should only be called by the   */
6683 /* ipf_checkv6sum() for each platform.                                      */
6684 /* ------------------------------------------------------------------------ */
6685 INLINE int
6686 ipf_checkl4sum(fin)
6687         fr_info_t *fin;
6688 {
6689         u_short sum, hdrsum, *csump;
6690         udphdr_t *udp;
6691         int dosum;
6692
6693         /*
6694          * If the TCP packet isn't a fragment, isn't too short and otherwise
6695          * isn't already considered "bad", then validate the checksum.  If
6696          * this check fails then considered the packet to be "bad".
6697          */
6698         if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6699                 return 1;
6700
6701         csump = NULL;
6702         hdrsum = 0;
6703         dosum = 0;
6704         sum = 0;
6705
6706         switch (fin->fin_p)
6707         {
6708         case IPPROTO_TCP :
6709                 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6710                 dosum = 1;
6711                 break;
6712
6713         case IPPROTO_UDP :
6714                 udp = fin->fin_dp;
6715                 if (udp->uh_sum != 0) {
6716                         csump = &udp->uh_sum;
6717                         dosum = 1;
6718                 }
6719                 break;
6720
6721 #ifdef USE_INET6
6722         case IPPROTO_ICMPV6 :
6723                 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6724                 dosum = 1;
6725                 break;
6726 #endif
6727
6728         case IPPROTO_ICMP :
6729                 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6730                 dosum = 1;
6731                 break;
6732
6733         default :
6734                 return 1;
6735                 /*NOTREACHED*/
6736         }
6737
6738         if (csump != NULL)
6739                 hdrsum = *csump;
6740
6741         if (dosum) {
6742                 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6743         }
6744 #if !defined(_KERNEL)
6745         if (sum == hdrsum) {
6746                 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6747         } else {
6748                 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6749         }
6750 #endif
6751         DT2(l4sums, u_short, hdrsum, u_short, sum);
6752         if (hdrsum == sum) {
6753                 fin->fin_cksum = FI_CK_SUMOK;
6754                 return 0;
6755         }
6756         fin->fin_cksum = FI_CK_BAD;
6757         return -1;
6758 }
6759
6760
6761 /* ------------------------------------------------------------------------ */
6762 /* Function:    ipf_ifpfillv4addr                                           */
6763 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6764 /* Parameters:  atype(I)   - type of network address update to perform      */
6765 /*              sin(I)     - pointer to source of address information       */
6766 /*              mask(I)    - pointer to source of netmask information       */
6767 /*              inp(I)     - pointer to destination address store           */
6768 /*              inpmask(I) - pointer to destination netmask store           */
6769 /*                                                                          */
6770 /* Given a type of network address update (atype) to perform, copy          */
6771 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6772 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6773 /* which case the operation fails.  For all values of atype other than      */
6774 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6775 /* value.                                                                   */
6776 /* ------------------------------------------------------------------------ */
6777 int
6778 ipf_ifpfillv4addr(atype, sin, mask, inp, inpmask)
6779         int atype;
6780         struct sockaddr_in *sin, *mask;
6781         struct in_addr *inp, *inpmask;
6782 {
6783         if (inpmask != NULL && atype != FRI_NETMASKED)
6784                 inpmask->s_addr = 0xffffffff;
6785
6786         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6787                 if (atype == FRI_NETMASKED) {
6788                         if (inpmask == NULL)
6789                                 return -1;
6790                         inpmask->s_addr = mask->sin_addr.s_addr;
6791                 }
6792                 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6793         } else {
6794                 inp->s_addr = sin->sin_addr.s_addr;
6795         }
6796         return 0;
6797 }
6798
6799
6800 #ifdef  USE_INET6
6801 /* ------------------------------------------------------------------------ */
6802 /* Function:    ipf_ifpfillv6addr                                           */
6803 /* Returns:     int     - 0 = address update, -1 = address not updated      */
6804 /* Parameters:  atype(I)   - type of network address update to perform      */
6805 /*              sin(I)     - pointer to source of address information       */
6806 /*              mask(I)    - pointer to source of netmask information       */
6807 /*              inp(I)     - pointer to destination address store           */
6808 /*              inpmask(I) - pointer to destination netmask store           */
6809 /*                                                                          */
6810 /* Given a type of network address update (atype) to perform, copy          */
6811 /* information from sin/mask into inp/inpmask.  If ipnmask is NULL then no  */
6812 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in  */
6813 /* which case the operation fails.  For all values of atype other than      */
6814 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s  */
6815 /* value.                                                                   */
6816 /* ------------------------------------------------------------------------ */
6817 int
6818 ipf_ifpfillv6addr(atype, sin, mask, inp, inpmask)
6819         int atype;
6820         struct sockaddr_in6 *sin, *mask;
6821         i6addr_t *inp, *inpmask;
6822 {
6823         i6addr_t *src, *and;
6824
6825         src = (i6addr_t *)&sin->sin6_addr;
6826         and = (i6addr_t *)&mask->sin6_addr;
6827
6828         if (inpmask != NULL && atype != FRI_NETMASKED) {
6829                 inpmask->i6[0] = 0xffffffff;
6830                 inpmask->i6[1] = 0xffffffff;
6831                 inpmask->i6[2] = 0xffffffff;
6832                 inpmask->i6[3] = 0xffffffff;
6833         }
6834
6835         if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6836                 if (atype == FRI_NETMASKED) {
6837                         if (inpmask == NULL)
6838                                 return -1;
6839                         inpmask->i6[0] = and->i6[0];
6840                         inpmask->i6[1] = and->i6[1];
6841                         inpmask->i6[2] = and->i6[2];
6842                         inpmask->i6[3] = and->i6[3];
6843                 }
6844
6845                 inp->i6[0] = src->i6[0] & and->i6[0];
6846                 inp->i6[1] = src->i6[1] & and->i6[1];
6847                 inp->i6[2] = src->i6[2] & and->i6[2];
6848                 inp->i6[3] = src->i6[3] & and->i6[3];
6849         } else {
6850                 inp->i6[0] = src->i6[0];
6851                 inp->i6[1] = src->i6[1];
6852                 inp->i6[2] = src->i6[2];
6853                 inp->i6[3] = src->i6[3];
6854         }
6855         return 0;
6856 }
6857 #endif
6858
6859
6860 /* ------------------------------------------------------------------------ */
6861 /* Function:    ipf_matchtag                                                */
6862 /* Returns:     0 == mismatch, 1 == match.                                  */
6863 /* Parameters:  tag1(I) - pointer to first tag to compare                   */
6864 /*              tag2(I) - pointer to second tag to compare                  */
6865 /*                                                                          */
6866 /* Returns true (non-zero) or false(0) if the two tag structures can be     */
6867 /* considered to be a match or not match, respectively.  The tag is 16      */
6868 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so    */
6869 /* compare the ints instead, for speed. tag1 is the master of the           */
6870 /* comparison.  This function should only be called with both tag1 and tag2 */
6871 /* as non-NULL pointers.                                                    */
6872 /* ------------------------------------------------------------------------ */
6873 int
6874 ipf_matchtag(tag1, tag2)
6875         ipftag_t *tag1, *tag2;
6876 {
6877         if (tag1 == tag2)
6878                 return 1;
6879
6880         if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6881                 return 1;
6882
6883         if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6884             (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6885             (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6886             (tag1->ipt_num[3] == tag2->ipt_num[3]))
6887                 return 1;
6888         return 0;
6889 }
6890
6891
6892 /* ------------------------------------------------------------------------ */
6893 /* Function:    ipf_coalesce                                                */
6894 /* Returns:     1 == success, -1 == failure, 0 == no change                 */
6895 /* Parameters:  fin(I) - pointer to packet information                      */
6896 /*                                                                          */
6897 /* Attempt to get all of the packet data into a single, contiguous buffer.  */
6898 /* If this call returns a failure then the buffers have also been freed.    */
6899 /* ------------------------------------------------------------------------ */
6900 int
6901 ipf_coalesce(fin)
6902         fr_info_t *fin;
6903 {
6904
6905         if ((fin->fin_flx & FI_COALESCE) != 0)
6906                 return 1;
6907
6908         /*
6909          * If the mbuf pointers indicate that there is no mbuf to work with,
6910          * return but do not indicate success or failure.
6911          */
6912         if (fin->fin_m == NULL || fin->fin_mp == NULL)
6913                 return 0;
6914
6915 #if defined(_KERNEL)
6916         if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6917                 ipf_main_softc_t *softc = fin->fin_main_soft;
6918
6919                 DT1(frb_coalesce, fr_info_t *, fin);
6920                 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6921 # ifdef MENTAT
6922                 FREE_MB_T(*fin->fin_mp);
6923 # endif
6924                 fin->fin_reason = FRB_COALESCE;
6925                 *fin->fin_mp = NULL;
6926                 fin->fin_m = NULL;
6927                 return -1;
6928         }
6929 #else
6930         fin = fin;      /* LINT */
6931 #endif
6932         return 1;
6933 }
6934
6935
6936 /*
6937  * The following table lists all of the tunable variables that can be
6938  * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt.  The format of each row
6939  * in the table below is as follows:
6940  *
6941  * pointer to value, name of value, minimum, maximum, size of the value's
6942  *     container, value attribute flags
6943  *
6944  * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6945  * means the value can only be written to when IPFilter is loaded but disabled.
6946  * The obvious implication is if neither of these are set then the value can be
6947  * changed at any time without harm.
6948  */
6949
6950
6951 /* ------------------------------------------------------------------------ */
6952 /* Function:    ipf_tune_findbycookie                                       */
6953 /* Returns:     NULL = search failed, else pointer to tune struct           */
6954 /* Parameters:  cookie(I) - cookie value to search for amongst tuneables    */
6955 /*              next(O)   - pointer to place to store the cookie for the    */
6956 /*                          "next" tuneable, if it is desired.              */
6957 /*                                                                          */
6958 /* This function is used to walk through all of the existing tunables with  */
6959 /* successive calls.  It searches the known tunables for the one which has  */
6960 /* a matching value for "cookie" - ie its address.  When returning a match, */
6961 /* the next one to be found may be returned inside next.                    */
6962 /* ------------------------------------------------------------------------ */
6963 static ipftuneable_t *
6964 ipf_tune_findbycookie(ptop, cookie, next)
6965         ipftuneable_t **ptop;
6966         void *cookie, **next;
6967 {
6968         ipftuneable_t *ta, **tap;
6969
6970         for (ta = *ptop; ta->ipft_name != NULL; ta++)
6971                 if (ta == cookie) {
6972                         if (next != NULL) {
6973                                 /*
6974                                  * If the next entry in the array has a name
6975                                  * present, then return a pointer to it for
6976                                  * where to go next, else return a pointer to
6977                                  * the dynaminc list as a key to search there
6978                                  * next.  This facilitates a weak linking of
6979                                  * the two "lists" together.
6980                                  */
6981                                 if ((ta + 1)->ipft_name != NULL)
6982                                         *next = ta + 1;
6983                                 else
6984                                         *next = ptop;
6985                         }
6986                         return ta;
6987                 }
6988
6989         for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6990                 if (tap == cookie) {
6991                         if (next != NULL)
6992                                 *next = &ta->ipft_next;
6993                         return ta;
6994                 }
6995
6996         if (next != NULL)
6997                 *next = NULL;
6998         return NULL;
6999 }
7000
7001
7002 /* ------------------------------------------------------------------------ */
7003 /* Function:    ipf_tune_findbyname                                         */
7004 /* Returns:     NULL = search failed, else pointer to tune struct           */
7005 /* Parameters:  name(I) - name of the tuneable entry to find.               */
7006 /*                                                                          */
7007 /* Search the static array of tuneables and the list of dynamic tuneables   */
7008 /* for an entry with a matching name.  If we can find one, return a pointer */
7009 /* to the matching structure.                                               */
7010 /* ------------------------------------------------------------------------ */
7011 static ipftuneable_t *
7012 ipf_tune_findbyname(top, name)
7013         ipftuneable_t *top;
7014         const char *name;
7015 {
7016         ipftuneable_t *ta;
7017
7018         for (ta = top; ta != NULL; ta = ta->ipft_next)
7019                 if (!strcmp(ta->ipft_name, name)) {
7020                         return ta;
7021                 }
7022
7023         return NULL;
7024 }
7025
7026
7027 /* ------------------------------------------------------------------------ */
7028 /* Function:    ipf_tune_add_array                                          */
7029 /* Returns:     int - 0 == success, else failure                            */
7030 /* Parameters:  newtune - pointer to new tune array to add to tuneables     */
7031 /*                                                                          */
7032 /* Appends tune structures from the array passed in (newtune) to the end of */
7033 /* the current list of "dynamic" tuneable parameters.                       */
7034 /* If any entry to be added is already present (by name) then the operation */
7035 /* is aborted - entries that have been added are removed before returning.  */
7036 /* An entry with no name (NULL) is used as the indication that the end of   */
7037 /* the array has been reached.                                              */
7038 /* ------------------------------------------------------------------------ */
7039 int
7040 ipf_tune_add_array(softc, newtune)
7041         ipf_main_softc_t *softc;
7042         ipftuneable_t *newtune;
7043 {
7044         ipftuneable_t *nt, *dt;
7045         int error = 0;
7046
7047         for (nt = newtune; nt->ipft_name != NULL; nt++) {
7048                 error = ipf_tune_add(softc, nt);
7049                 if (error != 0) {
7050                         for (dt = newtune; dt != nt; dt++) {
7051                                 (void) ipf_tune_del(softc, dt);
7052                         }
7053                 }
7054         }
7055
7056         return error;
7057 }
7058
7059
7060 /* ------------------------------------------------------------------------ */
7061 /* Function:    ipf_tune_array_link                                         */
7062 /* Returns:     0 == success, -1 == failure                                 */
7063 /* Parameters:  softc(I) - soft context pointerto work with                 */
7064 /*              array(I) - pointer to an array of tuneables                 */
7065 /*                                                                          */
7066 /* Given an array of tunables (array), append them to the current list of   */
7067 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the  */
7068 /* the array for being appended to the list, initialise all of the next     */
7069 /* pointers so we don't need to walk parts of it with ++ and others with    */
7070 /* next. The array is expected to have an entry with a NULL name as the     */
7071 /* terminator. Trying to add an array with no non-NULL names will return as */
7072 /* a failure.                                                               */
7073 /* ------------------------------------------------------------------------ */
7074 int
7075 ipf_tune_array_link(softc, array)
7076         ipf_main_softc_t *softc;
7077         ipftuneable_t *array;
7078 {
7079         ipftuneable_t *t, **p;
7080
7081         t = array;
7082         if (t->ipft_name == NULL)
7083                 return -1;
7084
7085         for (; t[1].ipft_name != NULL; t++)
7086                 t[0].ipft_next = &t[1];
7087         t->ipft_next = NULL;
7088
7089         /*
7090          * Since a pointer to the last entry isn't kept, we need to find it
7091          * each time we want to add new variables to the list.
7092          */
7093         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7094                 if (t->ipft_name == NULL)
7095                         break;
7096         *p = array;
7097
7098         return 0;
7099 }
7100
7101
7102 /* ------------------------------------------------------------------------ */
7103 /* Function:    ipf_tune_array_unlink                                       */
7104 /* Returns:     0 == success, -1 == failure                                 */
7105 /* Parameters:  softc(I) - soft context pointerto work with                 */
7106 /*              array(I) - pointer to an array of tuneables                 */
7107 /*                                                                          */
7108 /* ------------------------------------------------------------------------ */
7109 int
7110 ipf_tune_array_unlink(softc, array)
7111         ipf_main_softc_t *softc;
7112         ipftuneable_t *array;
7113 {
7114         ipftuneable_t *t, **p;
7115
7116         for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
7117                 if (t == array)
7118                         break;
7119         if (t == NULL)
7120                 return -1;
7121
7122         for (; t[1].ipft_name != NULL; t++)
7123                 ;
7124
7125         *p = t->ipft_next;
7126
7127         return 0;
7128 }
7129
7130
7131 /* ------------------------------------------------------------------------ */
7132 /* Function:   ipf_tune_array_copy                                          */
7133 /* Returns:    NULL = failure, else pointer to new array                    */
7134 /* Parameters: base(I)     - pointer to structure base                      */
7135 /*             size(I)     - size of the array at template                  */
7136 /*             template(I) - original array to copy                         */
7137 /*                                                                          */
7138 /* Allocate memory for a new set of tuneable values and copy everything     */
7139 /* from template into the new region of memory.  The new region is full of  */
7140 /* uninitialised pointers (ipft_next) so set them up.  Now, ipftp_offset... */
7141 /*                                                                          */
7142 /* NOTE: the following assumes that sizeof(long) == sizeof(void *)          */
7143 /* In the array template, ipftp_offset is the offset (in bytes) of the      */
7144 /* location of the tuneable value inside the structure pointed to by base.  */
7145 /* As ipftp_offset is a union over the pointers to the tuneable values, if  */
7146 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in   */
7147 /* ipftp_void that points to the stored value.                              */
7148 /* ------------------------------------------------------------------------ */
7149 ipftuneable_t *
7150 ipf_tune_array_copy(base, size, template)
7151         void *base;
7152         size_t size;
7153         ipftuneable_t *template;
7154 {
7155         ipftuneable_t *copy;
7156         int i;
7157
7158
7159         KMALLOCS(copy, ipftuneable_t *, size);
7160         if (copy == NULL) {
7161                 return NULL;
7162         }
7163         bcopy(template, copy, size);
7164
7165         for (i = 0; copy[i].ipft_name; i++) {
7166                 copy[i].ipft_una.ipftp_offset += (u_long)base;
7167                 copy[i].ipft_next = copy + i + 1;
7168         }
7169
7170         return copy;
7171 }
7172
7173
7174 /* ------------------------------------------------------------------------ */
7175 /* Function:    ipf_tune_add                                                */
7176 /* Returns:     int - 0 == success, else failure                            */
7177 /* Parameters:  newtune - pointer to new tune entry to add to tuneables     */
7178 /*                                                                          */
7179 /* Appends tune structures from the array passed in (newtune) to the end of */
7180 /* the current list of "dynamic" tuneable parameters.  Once added, the      */
7181 /* owner of the object is not expected to ever change "ipft_next".          */
7182 /* ------------------------------------------------------------------------ */
7183 int
7184 ipf_tune_add(softc, newtune)
7185         ipf_main_softc_t *softc;
7186         ipftuneable_t *newtune;
7187 {
7188         ipftuneable_t *ta, **tap;
7189
7190         ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7191         if (ta != NULL) {
7192                 IPFERROR(74);
7193                 return EEXIST;
7194         }
7195
7196         for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7197                 ;
7198
7199         newtune->ipft_next = NULL;
7200         *tap = newtune;
7201         return 0;
7202 }
7203
7204
7205 /* ------------------------------------------------------------------------ */
7206 /* Function:    ipf_tune_del                                                */
7207 /* Returns:     int - 0 == success, else failure                            */
7208 /* Parameters:  oldtune - pointer to tune entry to remove from the list of  */
7209 /*                        current dynamic tuneables                         */
7210 /*                                                                          */
7211 /* Search for the tune structure, by pointer, in the list of those that are */
7212 /* dynamically added at run time.  If found, adjust the list so that this   */
7213 /* structure is no longer part of it.                                       */
7214 /* ------------------------------------------------------------------------ */
7215 int
7216 ipf_tune_del(softc, oldtune)
7217         ipf_main_softc_t *softc;
7218         ipftuneable_t *oldtune;
7219 {
7220         ipftuneable_t *ta, **tap;
7221         int error = 0;
7222
7223         for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7224              tap = &ta->ipft_next) {
7225                 if (ta == oldtune) {
7226                         *tap = oldtune->ipft_next;
7227                         oldtune->ipft_next = NULL;
7228                         break;
7229                 }
7230         }
7231
7232         if (ta == NULL) {
7233                 error = ESRCH;
7234                 IPFERROR(75);
7235         }
7236         return error;
7237 }
7238
7239
7240 /* ------------------------------------------------------------------------ */
7241 /* Function:    ipf_tune_del_array                                          */
7242 /* Returns:     int - 0 == success, else failure                            */
7243 /* Parameters:  oldtune - pointer to tuneables array                        */
7244 /*                                                                          */
7245 /* Remove each tuneable entry in the array from the list of "dynamic"       */
7246 /* tunables.  If one entry should fail to be found, an error will be        */
7247 /* returned and no further ones removed.                                    */
7248 /* An entry with a NULL name is used as the indicator of the last entry in  */
7249 /* the array.                                                               */
7250 /* ------------------------------------------------------------------------ */
7251 int
7252 ipf_tune_del_array(softc, oldtune)
7253         ipf_main_softc_t *softc;
7254         ipftuneable_t *oldtune;
7255 {
7256         ipftuneable_t *ot;
7257         int error = 0;
7258
7259         for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7260                 error = ipf_tune_del(softc, ot);
7261                 if (error != 0)
7262                         break;
7263         }
7264
7265         return error;
7266
7267 }
7268
7269
7270 /* ------------------------------------------------------------------------ */
7271 /* Function:    ipf_tune                                                    */
7272 /* Returns:     int - 0 == success, else failure                            */
7273 /* Parameters:  cmd(I)  - ioctl command number                              */
7274 /*              data(I) - pointer to ioctl data structure                   */
7275 /*                                                                          */
7276 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET.  These  */
7277 /* three ioctls provide the means to access and control global variables    */
7278 /* within IPFilter, allowing (for example) timeouts and table sizes to be   */
7279 /* changed without rebooting, reloading or recompiling.  The initialisation */
7280 /* and 'destruction' routines of the various components of ipfilter are all */
7281 /* each responsible for handling their own values being too big.            */
7282 /* ------------------------------------------------------------------------ */
7283 int
7284 ipf_ipftune(softc, cmd, data)
7285         ipf_main_softc_t *softc;
7286         ioctlcmd_t cmd;
7287         void *data;
7288 {
7289         ipftuneable_t *ta;
7290         ipftune_t tu;
7291         void *cookie;
7292         int error;
7293
7294         error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7295         if (error != 0)
7296                 return error;
7297
7298         tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7299         cookie = tu.ipft_cookie;
7300         ta = NULL;
7301
7302         switch (cmd)
7303         {
7304         case SIOCIPFGETNEXT :
7305                 /*
7306                  * If cookie is non-NULL, assume it to be a pointer to the last
7307                  * entry we looked at, so find it (if possible) and return a
7308                  * pointer to the next one after it.  The last entry in the
7309                  * the table is a NULL entry, so when we get to it, set cookie
7310                  * to NULL and return that, indicating end of list, erstwhile
7311                  * if we come in with cookie set to NULL, we are starting anew
7312                  * at the front of the list.
7313                  */
7314                 if (cookie != NULL) {
7315                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7316                                                    cookie, &tu.ipft_cookie);
7317                 } else {
7318                         ta = softc->ipf_tuners;
7319                         tu.ipft_cookie = ta + 1;
7320                 }
7321                 if (ta != NULL) {
7322                         /*
7323                          * Entry found, but does the data pointed to by that
7324                          * row fit in what we can return?
7325                          */
7326                         if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7327                                 IPFERROR(76);
7328                                 return EINVAL;
7329                         }
7330
7331                         tu.ipft_vlong = 0;
7332                         if (ta->ipft_sz == sizeof(u_long))
7333                                 tu.ipft_vlong = *ta->ipft_plong;
7334                         else if (ta->ipft_sz == sizeof(u_int))
7335                                 tu.ipft_vint = *ta->ipft_pint;
7336                         else if (ta->ipft_sz == sizeof(u_short))
7337                                 tu.ipft_vshort = *ta->ipft_pshort;
7338                         else if (ta->ipft_sz == sizeof(u_char))
7339                                 tu.ipft_vchar = *ta->ipft_pchar;
7340
7341                         tu.ipft_sz = ta->ipft_sz;
7342                         tu.ipft_min = ta->ipft_min;
7343                         tu.ipft_max = ta->ipft_max;
7344                         tu.ipft_flags = ta->ipft_flags;
7345                         bcopy(ta->ipft_name, tu.ipft_name,
7346                               MIN(sizeof(tu.ipft_name),
7347                                   strlen(ta->ipft_name) + 1));
7348                 }
7349                 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7350                 break;
7351
7352         case SIOCIPFGET :
7353         case SIOCIPFSET :
7354                 /*
7355                  * Search by name or by cookie value for a particular entry
7356                  * in the tuning paramter table.
7357                  */
7358                 IPFERROR(77);
7359                 error = ESRCH;
7360                 if (cookie != NULL) {
7361                         ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7362                                                    cookie, NULL);
7363                         if (ta != NULL)
7364                                 error = 0;
7365                 } else if (tu.ipft_name[0] != '\0') {
7366                         ta = ipf_tune_findbyname(softc->ipf_tuners,
7367                                                  tu.ipft_name);
7368                         if (ta != NULL)
7369                                 error = 0;
7370                 }
7371                 if (error != 0)
7372                         break;
7373
7374                 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7375                         /*
7376                          * Fetch the tuning parameters for a particular value
7377                          */
7378                         tu.ipft_vlong = 0;
7379                         if (ta->ipft_sz == sizeof(u_long))
7380                                 tu.ipft_vlong = *ta->ipft_plong;
7381                         else if (ta->ipft_sz == sizeof(u_int))
7382                                 tu.ipft_vint = *ta->ipft_pint;
7383                         else if (ta->ipft_sz == sizeof(u_short))
7384                                 tu.ipft_vshort = *ta->ipft_pshort;
7385                         else if (ta->ipft_sz == sizeof(u_char))
7386                                 tu.ipft_vchar = *ta->ipft_pchar;
7387                         tu.ipft_cookie = ta;
7388                         tu.ipft_sz = ta->ipft_sz;
7389                         tu.ipft_min = ta->ipft_min;
7390                         tu.ipft_max = ta->ipft_max;
7391                         tu.ipft_flags = ta->ipft_flags;
7392                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7393
7394                 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7395                         /*
7396                          * Set an internal parameter.  The hard part here is
7397                          * getting the new value safely and correctly out of
7398                          * the kernel (given we only know its size, not type.)
7399                          */
7400                         u_long in;
7401
7402                         if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7403                             (softc->ipf_running > 0)) {
7404                                 IPFERROR(78);
7405                                 error = EBUSY;
7406                                 break;
7407                         }
7408
7409                         in = tu.ipft_vlong;
7410                         if (in < ta->ipft_min || in > ta->ipft_max) {
7411                                 IPFERROR(79);
7412                                 error = EINVAL;
7413                                 break;
7414                         }
7415
7416                         if (ta->ipft_func != NULL) {
7417                                 SPL_INT(s);
7418
7419                                 SPL_NET(s);
7420                                 error = (*ta->ipft_func)(softc, ta,
7421                                                          &tu.ipft_un);
7422                                 SPL_X(s);
7423
7424                         } else if (ta->ipft_sz == sizeof(u_long)) {
7425                                 tu.ipft_vlong = *ta->ipft_plong;
7426                                 *ta->ipft_plong = in;
7427
7428                         } else if (ta->ipft_sz == sizeof(u_int)) {
7429                                 tu.ipft_vint = *ta->ipft_pint;
7430                                 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7431
7432                         } else if (ta->ipft_sz == sizeof(u_short)) {
7433                                 tu.ipft_vshort = *ta->ipft_pshort;
7434                                 *ta->ipft_pshort = (u_short)(in & 0xffff);
7435
7436                         } else if (ta->ipft_sz == sizeof(u_char)) {
7437                                 tu.ipft_vchar = *ta->ipft_pchar;
7438                                 *ta->ipft_pchar = (u_char)(in & 0xff);
7439                         }
7440                         error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7441                 }
7442                 break;
7443
7444         default :
7445                 IPFERROR(80);
7446                 error = EINVAL;
7447                 break;
7448         }
7449
7450         return error;
7451 }
7452
7453
7454 /* ------------------------------------------------------------------------ */
7455 /* Function:    ipf_zerostats                                               */
7456 /* Returns:     int - 0 = success, else failure                             */
7457 /* Parameters:  data(O) - pointer to pointer for copying data back to       */
7458 /*                                                                          */
7459 /* Copies the current statistics out to userspace and then zero's the       */
7460 /* current ones in the kernel. The lock is only held across the bzero() as  */
7461 /* the copyout may result in paging (ie network activity.)                  */
7462 /* ------------------------------------------------------------------------ */
7463 int
7464 ipf_zerostats(softc, data)
7465         ipf_main_softc_t *softc;
7466         caddr_t data;
7467 {
7468         friostat_t fio;
7469         ipfobj_t obj;
7470         int error;
7471
7472         error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7473         if (error != 0)
7474                 return error;
7475         ipf_getstat(softc, &fio, obj.ipfo_rev);
7476         error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7477         if (error != 0)
7478                 return error;
7479
7480         WRITE_ENTER(&softc->ipf_mutex);
7481         bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7482         RWLOCK_EXIT(&softc->ipf_mutex);
7483
7484         return 0;
7485 }
7486
7487
7488 /* ------------------------------------------------------------------------ */
7489 /* Function:    ipf_resolvedest                                             */
7490 /* Returns:     Nil                                                         */
7491 /* Parameters:  softc(I) - pointer to soft context main structure           */
7492 /*              base(I)  - where strings are stored                         */
7493 /*              fdp(IO)  - pointer to destination information to resolve    */
7494 /*              v(I)     - IP protocol version to match                     */
7495 /*                                                                          */
7496 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7497 /* if a matching name can be found for the particular IP protocol version   */
7498 /* then store the interface pointer in the frdest struct.  If no match is   */
7499 /* found, then set the interface pointer to be -1 as NULL is considered to  */
7500 /* indicate there is no information at all in the structure.                */
7501 /* ------------------------------------------------------------------------ */
7502 int
7503 ipf_resolvedest(softc, base, fdp, v)
7504         ipf_main_softc_t *softc;
7505         char *base;
7506         frdest_t *fdp;
7507         int v;
7508 {
7509         int errval = 0;
7510         void *ifp;
7511
7512         ifp = NULL;
7513
7514         if (fdp->fd_name != -1) {
7515                 if (fdp->fd_type == FRD_DSTLIST) {
7516                         ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7517                                                   IPLT_DSTLIST,
7518                                                   base + fdp->fd_name,
7519                                                   NULL);
7520                         if (ifp == NULL) {
7521                                 IPFERROR(144);
7522                                 errval = ESRCH;
7523                         }
7524                 } else {
7525                         ifp = GETIFP(base + fdp->fd_name, v);
7526                         if (ifp == NULL)
7527                                 ifp = (void *)-1;
7528                 }
7529         }
7530         fdp->fd_ptr = ifp;
7531
7532         if ((ifp != NULL) && (ifp != (void *)-1)) {
7533                 fdp->fd_local = ipf_deliverlocal(softc, v, ifp, &fdp->fd_ip6);
7534         }
7535
7536         return errval;
7537 }
7538
7539
7540 /* ------------------------------------------------------------------------ */
7541 /* Function:    ipf_resolvenic                                              */
7542 /* Returns:     void* - NULL = wildcard name, -1 = failed to find NIC, else */
7543 /*                      pointer to interface structure for NIC              */
7544 /* Parameters:  softc(I)- pointer to soft context main structure            */
7545 /*              name(I) - complete interface name                           */
7546 /*              v(I)    - IP protocol version                               */
7547 /*                                                                          */
7548 /* Look for a network interface structure that firstly has a matching name  */
7549 /* to that passed in and that is also being used for that IP protocol       */
7550 /* version (necessary on some platforms where there are separate listings   */
7551 /* for both IPv4 and IPv6 on the same physical NIC.                         */
7552 /* ------------------------------------------------------------------------ */
7553 void *
7554 ipf_resolvenic(softc, name, v)
7555         ipf_main_softc_t *softc;
7556         char *name;
7557         int v;
7558 {
7559         void *nic;
7560
7561         softc = softc;  /* gcc -Wextra */
7562         if (name[0] == '\0')
7563                 return NULL;
7564
7565         if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7566                 return NULL;
7567         }
7568
7569         nic = GETIFP(name, v);
7570         if (nic == NULL)
7571                 nic = (void *)-1;
7572         return nic;
7573 }
7574
7575
7576 /* ------------------------------------------------------------------------ */
7577 /* Function:    ipf_token_expire                                            */
7578 /* Returns:     None.                                                       */
7579 /* Parameters:  softc(I) - pointer to soft context main structure           */
7580 /*                                                                          */
7581 /* This function is run every ipf tick to see if there are any tokens that  */
7582 /* have been held for too long and need to be freed up.                     */
7583 /* ------------------------------------------------------------------------ */
7584 void
7585 ipf_token_expire(softc)
7586         ipf_main_softc_t *softc;
7587 {
7588         ipftoken_t *it;
7589
7590         WRITE_ENTER(&softc->ipf_tokens);
7591         while ((it = softc->ipf_token_head) != NULL) {
7592                 if (it->ipt_die > softc->ipf_ticks)
7593                         break;
7594
7595                 ipf_token_deref(softc, it);
7596         }
7597         RWLOCK_EXIT(&softc->ipf_tokens);
7598 }
7599
7600
7601 /* ------------------------------------------------------------------------ */
7602 /* Function:    ipf_token_flush                                             */
7603 /* Returns:     None.                                                       */
7604 /* Parameters:  softc(I) - pointer to soft context main structure           */
7605 /*                                                                          */
7606 /* Loop through all of the existing tokens and call deref to see if they    */
7607 /* can be freed. Normally a function like this might just loop on           */
7608 /* ipf_token_head but there is a chance that a token might have a ref count */
7609 /* of greater than one and in that case the the reference would drop twice  */
7610 /* by code that is only entitled to drop it once.                           */
7611 /* ------------------------------------------------------------------------ */
7612 static void
7613 ipf_token_flush(softc)
7614         ipf_main_softc_t *softc;
7615 {
7616         ipftoken_t *it, *next;
7617
7618         WRITE_ENTER(&softc->ipf_tokens);
7619         for (it = softc->ipf_token_head; it != NULL; it = next) {
7620                 next = it->ipt_next;
7621                 (void) ipf_token_deref(softc, it);
7622         }
7623         RWLOCK_EXIT(&softc->ipf_tokens);
7624 }
7625
7626
7627 /* ------------------------------------------------------------------------ */
7628 /* Function:    ipf_token_del                                               */
7629 /* Returns:     int     - 0 = success, else error                           */
7630 /* Parameters:  softc(I)- pointer to soft context main structure            */
7631 /*              type(I) - the token type to match                           */
7632 /*              uid(I)  - uid owning the token                              */
7633 /*              ptr(I)  - context pointer for the token                     */
7634 /*                                                                          */
7635 /* This function looks for a a token in the current list that matches up    */
7636 /* the fields (type, uid, ptr).  If none is found, ESRCH is returned, else  */
7637 /* call ipf_token_dewref() to remove it from the list. In the event that    */
7638 /* the token has a reference held elsewhere, setting ipt_complete to 2      */
7639 /* enables debugging to distinguish between the two paths that ultimately   */
7640 /* lead to a token to be deleted.                                           */
7641 /* ------------------------------------------------------------------------ */
7642 int
7643 ipf_token_del(softc, type, uid, ptr)
7644         ipf_main_softc_t *softc;
7645         int type, uid;
7646         void *ptr;
7647 {
7648         ipftoken_t *it;
7649         int error;
7650
7651         IPFERROR(82);
7652         error = ESRCH;
7653
7654         WRITE_ENTER(&softc->ipf_tokens);
7655         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7656                 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7657                     uid == it->ipt_uid) {
7658                         it->ipt_complete = 2;
7659                         ipf_token_deref(softc, it);
7660                         error = 0;
7661                         break;
7662                 }
7663         }
7664         RWLOCK_EXIT(&softc->ipf_tokens);
7665
7666         return error;
7667 }
7668
7669
7670 /* ------------------------------------------------------------------------ */
7671 /* Function:    ipf_token_mark_complete                                     */
7672 /* Returns:     None.                                                       */
7673 /* Parameters:  token(I) - pointer to token structure                       */
7674 /*                                                                          */
7675 /* Mark a token as being ineligable for being found with ipf_token_find.    */
7676 /* ------------------------------------------------------------------------ */
7677 void
7678 ipf_token_mark_complete(token)
7679         ipftoken_t *token;
7680 {
7681         if (token->ipt_complete == 0)
7682                 token->ipt_complete = 1;
7683 }
7684
7685
7686 /* ------------------------------------------------------------------------ */
7687 /* Function:    ipf_token_find                                               */
7688 /* Returns:     ipftoken_t * - NULL if no memory, else pointer to token     */
7689 /* Parameters:  softc(I)- pointer to soft context main structure            */
7690 /*              type(I) - the token type to match                           */
7691 /*              uid(I)  - uid owning the token                              */
7692 /*              ptr(I)  - context pointer for the token                     */
7693 /*                                                                          */
7694 /* This function looks for a live token in the list of current tokens that  */
7695 /* matches the tuple (type, uid, ptr).  If one cannot be found then one is  */
7696 /* allocated.  If one is found then it is moved to the top of the list of   */
7697 /* currently active tokens.                                                 */
7698 /* ------------------------------------------------------------------------ */
7699 ipftoken_t *
7700 ipf_token_find(softc, type, uid, ptr)
7701         ipf_main_softc_t *softc;
7702         int type, uid;
7703         void *ptr;
7704 {
7705         ipftoken_t *it, *new;
7706
7707         KMALLOC(new, ipftoken_t *);
7708         if (new != NULL)
7709                 bzero((char *)new, sizeof(*new));
7710
7711         WRITE_ENTER(&softc->ipf_tokens);
7712         for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7713                 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7714                     (uid == it->ipt_uid) && (it->ipt_complete < 2))
7715                         break;
7716         }
7717
7718         if (it == NULL) {
7719                 it = new;
7720                 new = NULL;
7721                 if (it == NULL) {
7722                         RWLOCK_EXIT(&softc->ipf_tokens);
7723                         return NULL;
7724                 }
7725                 it->ipt_ctx = ptr;
7726                 it->ipt_uid = uid;
7727                 it->ipt_type = type;
7728                 it->ipt_ref = 1;
7729         } else {
7730                 if (new != NULL) {
7731                         KFREE(new);
7732                         new = NULL;
7733                 }
7734
7735                 if (it->ipt_complete > 0)
7736                         it = NULL;
7737                 else
7738                         ipf_token_unlink(softc, it);
7739         }
7740
7741         if (it != NULL) {
7742                 it->ipt_pnext = softc->ipf_token_tail;
7743                 *softc->ipf_token_tail = it;
7744                 softc->ipf_token_tail = &it->ipt_next;
7745                 it->ipt_next = NULL;
7746                 it->ipt_ref++;
7747
7748                 it->ipt_die = softc->ipf_ticks + 20;
7749         }
7750
7751         RWLOCK_EXIT(&softc->ipf_tokens);
7752
7753         return it;
7754 }
7755
7756
7757 /* ------------------------------------------------------------------------ */
7758 /* Function:    ipf_token_unlink                                            */
7759 /* Returns:     None.                                                       */
7760 /* Parameters:  softc(I) - pointer to soft context main structure           */
7761 /*              token(I) - pointer to token structure                       */
7762 /* Write Locks: ipf_tokens                                                  */
7763 /*                                                                          */
7764 /* This function unlinks a token structure from the linked list of tokens   */
7765 /* that "own" it.  The head pointer never needs to be explicitly adjusted   */
7766 /* but the tail does due to the linked list implementation.                 */
7767 /* ------------------------------------------------------------------------ */
7768 static void
7769 ipf_token_unlink(softc, token)
7770         ipf_main_softc_t *softc;
7771         ipftoken_t *token;
7772 {
7773
7774         if (softc->ipf_token_tail == &token->ipt_next)
7775                 softc->ipf_token_tail = token->ipt_pnext;
7776
7777         *token->ipt_pnext = token->ipt_next;
7778         if (token->ipt_next != NULL)
7779                 token->ipt_next->ipt_pnext = token->ipt_pnext;
7780         token->ipt_next = NULL;
7781         token->ipt_pnext = NULL;
7782 }
7783
7784
7785 /* ------------------------------------------------------------------------ */
7786 /* Function:    ipf_token_deref                                             */
7787 /* Returns:     int      - 0 == token freed, else reference count           */
7788 /* Parameters:  softc(I) - pointer to soft context main structure           */
7789 /*              token(I) - pointer to token structure                       */
7790 /* Write Locks: ipf_tokens                                                  */
7791 /*                                                                          */
7792 /* Drop the reference count on the token structure and if it drops to zero, */
7793 /* call the dereference function for the token type because it is then      */
7794 /* possible to free the token data structure.                               */
7795 /* ------------------------------------------------------------------------ */
7796 int
7797 ipf_token_deref(softc, token)
7798         ipf_main_softc_t *softc;
7799         ipftoken_t *token;
7800 {
7801         void *data, **datap;
7802
7803         ASSERT(token->ipt_ref > 0);
7804         token->ipt_ref--;
7805         if (token->ipt_ref > 0)
7806                 return token->ipt_ref;
7807
7808         data = token->ipt_data;
7809         datap = &data;
7810
7811         if ((data != NULL) && (data != (void *)-1)) {
7812                 switch (token->ipt_type)
7813                 {
7814                 case IPFGENITER_IPF :
7815                         (void) ipf_derefrule(softc, (frentry_t **)datap);
7816                         break;
7817                 case IPFGENITER_IPNAT :
7818                         WRITE_ENTER(&softc->ipf_nat);
7819                         ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7820                         RWLOCK_EXIT(&softc->ipf_nat);
7821                         break;
7822                 case IPFGENITER_NAT :
7823                         ipf_nat_deref(softc, (nat_t **)datap);
7824                         break;
7825                 case IPFGENITER_STATE :
7826                         ipf_state_deref(softc, (ipstate_t **)datap);
7827                         break;
7828                 case IPFGENITER_FRAG :
7829                         ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7830                         break;
7831                 case IPFGENITER_NATFRAG :
7832                         ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7833                         break;
7834                 case IPFGENITER_HOSTMAP :
7835                         WRITE_ENTER(&softc->ipf_nat);
7836                         ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7837                         RWLOCK_EXIT(&softc->ipf_nat);
7838                         break;
7839                 default :
7840                         ipf_lookup_iterderef(softc, token->ipt_type, data);
7841                         break;
7842                 }
7843         }
7844
7845         ipf_token_unlink(softc, token);
7846         KFREE(token);
7847         return 0;
7848 }
7849
7850
7851 /* ------------------------------------------------------------------------ */
7852 /* Function:    ipf_nextrule                                                */
7853 /* Returns:     frentry_t * - NULL == no more rules, else pointer to next   */
7854 /* Parameters:  softc(I)    - pointer to soft context main structure        */
7855 /*              fr(I)       - pointer to filter rule                        */
7856 /*              out(I)      - 1 == out rules, 0 == input rules              */
7857 /*                                                                          */
7858 /* Starting with "fr", find the next rule to visit. This includes visiting  */
7859 /* the list of rule groups if either fr is NULL (empty list) or it is the   */
7860 /* last rule in the list. When walking rule lists, it is either input or    */
7861 /* output rules that are returned, never both.                              */
7862 /* ------------------------------------------------------------------------ */
7863 static frentry_t *
7864 ipf_nextrule(softc, active, unit, fr, out)
7865         ipf_main_softc_t *softc;
7866         int active, unit;
7867         frentry_t *fr;
7868         int out;
7869 {
7870         frentry_t *next;
7871         frgroup_t *fg;
7872
7873         if (fr != NULL && fr->fr_group != -1) {
7874                 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7875                                    unit, active, NULL);
7876                 if (fg != NULL)
7877                         fg = fg->fg_next;
7878         } else {
7879                 fg = softc->ipf_groups[unit][active];
7880         }
7881
7882         while (fg != NULL) {
7883                 next = fg->fg_start;
7884                 while (next != NULL) {
7885                         if (out) {
7886                                 if (next->fr_flags & FR_OUTQUE)
7887                                         return next;
7888                         } else if (next->fr_flags & FR_INQUE) {
7889                                 return next;
7890                         }
7891                         next = next->fr_next;
7892                 }
7893                 if (next == NULL)
7894                         fg = fg->fg_next;
7895         }
7896
7897         return NULL;
7898 }
7899
7900 /* ------------------------------------------------------------------------ */
7901 /* Function:    ipf_getnextrule                                             */
7902 /* Returns:     int - 0 = success, else error                               */
7903 /* Parameters:  softc(I)- pointer to soft context main structure            */
7904 /*              t(I)   - pointer to destination information to resolve      */
7905 /*              ptr(I) - pointer to ipfobj_t to copyin from user space      */
7906 /*                                                                          */
7907 /* This function's first job is to bring in the ipfruleiter_t structure via */
7908 /* the ipfobj_t structure to determine what should be the next rule to      */
7909 /* return. Once the ipfruleiter_t has been brought in, it then tries to     */
7910 /* find the 'next rule'.  This may include searching rule group lists or    */
7911 /* just be as simple as looking at the 'next' field in the rule structure.  */
7912 /* When we have found the rule to return, increase its reference count and  */
7913 /* if we used an existing rule to get here, decrease its reference count.   */
7914 /* ------------------------------------------------------------------------ */
7915 int
7916 ipf_getnextrule(softc, t, ptr)
7917         ipf_main_softc_t *softc;
7918         ipftoken_t *t;
7919         void *ptr;
7920 {
7921         frentry_t *fr, *next, zero;
7922         ipfruleiter_t it;
7923         int error, out;
7924         frgroup_t *fg;
7925         ipfobj_t obj;
7926         int predict;
7927         char *dst;
7928         int unit;
7929
7930         if (t == NULL || ptr == NULL) {
7931                 IPFERROR(84);
7932                 return EFAULT;
7933         }
7934
7935         error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7936         if (error != 0)
7937                 return error;
7938
7939         if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7940                 IPFERROR(85);
7941                 return EINVAL;
7942         }
7943         if ((it.iri_active != 0) && (it.iri_active != 1)) {
7944                 IPFERROR(86);
7945                 return EINVAL;
7946         }
7947         if (it.iri_nrules == 0) {
7948                 IPFERROR(87);
7949                 return ENOSPC;
7950         }
7951         if (it.iri_rule == NULL) {
7952                 IPFERROR(88);
7953                 return EFAULT;
7954         }
7955
7956         fg = NULL;
7957         fr = t->ipt_data;
7958         if ((it.iri_inout & F_OUT) != 0)
7959                 out = 1;
7960         else
7961                 out = 0;
7962         if ((it.iri_inout & F_ACIN) != 0)
7963                 unit = IPL_LOGCOUNT;
7964         else
7965                 unit = IPL_LOGIPF;
7966
7967         READ_ENTER(&softc->ipf_mutex);
7968         if (fr == NULL) {
7969                 if (*it.iri_group == '\0') {
7970                         if (unit == IPL_LOGCOUNT) {
7971                                 next = softc->ipf_acct[out][it.iri_active];
7972                         } else {
7973                                 next = softc->ipf_rules[out][it.iri_active];
7974                         }
7975                         if (next == NULL)
7976                                 next = ipf_nextrule(softc, it.iri_active,
7977                                                     unit, NULL, out);
7978                 } else {
7979                         fg = ipf_findgroup(softc, it.iri_group, unit,
7980                                            it.iri_active, NULL);
7981                         if (fg != NULL)
7982                                 next = fg->fg_start;
7983                         else
7984                                 next = NULL;
7985                 }
7986         } else {
7987                 next = fr->fr_next;
7988                 if (next == NULL)
7989                         next = ipf_nextrule(softc, it.iri_active, unit,
7990                                             fr, out);
7991         }
7992
7993         if (next != NULL && next->fr_next != NULL)
7994                 predict = 1;
7995         else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7996                 predict = 1;
7997         else
7998                 predict = 0;
7999
8000         if (fr != NULL)
8001                 (void) ipf_derefrule(softc, &fr);
8002
8003         obj.ipfo_type = IPFOBJ_FRENTRY;
8004         dst = (char *)it.iri_rule;
8005
8006         if (next != NULL) {
8007                 obj.ipfo_size = next->fr_size;
8008                 MUTEX_ENTER(&next->fr_lock);
8009                 next->fr_ref++;
8010                 MUTEX_EXIT(&next->fr_lock);
8011                 t->ipt_data = next;
8012         } else {
8013                 obj.ipfo_size = sizeof(frentry_t);
8014                 bzero(&zero, sizeof(zero));
8015                 next = &zero;
8016                 t->ipt_data = NULL;
8017         }
8018         it.iri_rule = predict ? next : NULL;
8019         if (predict == 0)
8020                 ipf_token_mark_complete(t);
8021
8022         RWLOCK_EXIT(&softc->ipf_mutex);
8023
8024         obj.ipfo_ptr = dst;
8025         error = ipf_outobjk(softc, &obj, next);
8026         if (error == 0 && t->ipt_data != NULL) {
8027                 dst += obj.ipfo_size;
8028                 if (next->fr_data != NULL) {
8029                         ipfobj_t dobj;
8030
8031                         if (next->fr_type == FR_T_IPFEXPR)
8032                                 dobj.ipfo_type = IPFOBJ_IPFEXPR;
8033                         else
8034                                 dobj.ipfo_type = IPFOBJ_FRIPF;
8035                         dobj.ipfo_size = next->fr_dsize;
8036                         dobj.ipfo_rev = obj.ipfo_rev;
8037                         dobj.ipfo_ptr = dst;
8038                         error = ipf_outobjk(softc, &dobj, next->fr_data);
8039                 }
8040         }
8041
8042         if ((fr != NULL) && (next == &zero))
8043                 (void) ipf_derefrule(softc, &fr);
8044
8045         return error;
8046 }
8047
8048
8049 /* ------------------------------------------------------------------------ */
8050 /* Function:    ipf_frruleiter                                              */
8051 /* Returns:     int - 0 = success, else error                               */
8052 /* Parameters:  softc(I)- pointer to soft context main structure            */
8053 /*              data(I) - the token type to match                           */
8054 /*              uid(I)  - uid owning the token                              */
8055 /*              ptr(I)  - context pointer for the token                     */
8056 /*                                                                          */
8057 /* This function serves as a stepping stone between ipf_ipf_ioctl and       */
8058 /* ipf_getnextrule.  It's role is to find the right token in the kernel for */
8059 /* the process doing the ioctl and use that to ask for the next rule.       */
8060 /* ------------------------------------------------------------------------ */
8061 static int
8062 ipf_frruleiter(softc, data, uid, ctx)
8063         ipf_main_softc_t *softc;
8064         void *data, *ctx;
8065         int uid;
8066 {
8067         ipftoken_t *token;
8068         ipfruleiter_t it;
8069         ipfobj_t obj;
8070         int error;
8071
8072         token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
8073         if (token != NULL) {
8074                 error = ipf_getnextrule(softc, token, data);
8075                 WRITE_ENTER(&softc->ipf_tokens);
8076                 ipf_token_deref(softc, token);
8077                 RWLOCK_EXIT(&softc->ipf_tokens);
8078         } else {
8079                 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
8080                 if (error != 0)
8081                         return error;
8082                 it.iri_rule = NULL;
8083                 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
8084         }
8085
8086         return error;
8087 }
8088
8089
8090 /* ------------------------------------------------------------------------ */
8091 /* Function:    ipf_geniter                                                 */
8092 /* Returns:     int - 0 = success, else error                               */
8093 /* Parameters:  softc(I) - pointer to soft context main structure           */
8094 /*              token(I) - pointer to ipftoken_t structure                  */
8095 /*              itp(I)   - pointer to iterator data                         */
8096 /*                                                                          */
8097 /* Decide which iterator function to call using information passed through  */
8098 /* the ipfgeniter_t structure at itp.                                       */
8099 /* ------------------------------------------------------------------------ */
8100 static int
8101 ipf_geniter(softc, token, itp)
8102         ipf_main_softc_t *softc;
8103         ipftoken_t *token;
8104         ipfgeniter_t *itp;
8105 {
8106         int error;
8107
8108         switch (itp->igi_type)
8109         {
8110         case IPFGENITER_FRAG :
8111                 error = ipf_frag_pkt_next(softc, token, itp);
8112                 break;
8113         default :
8114                 IPFERROR(92);
8115                 error = EINVAL;
8116                 break;
8117         }
8118
8119         return error;
8120 }
8121
8122
8123 /* ------------------------------------------------------------------------ */
8124 /* Function:    ipf_genericiter                                             */
8125 /* Returns:     int - 0 = success, else error                               */
8126 /* Parameters:  softc(I)- pointer to soft context main structure            */
8127 /*              data(I) - the token type to match                           */
8128 /*              uid(I)  - uid owning the token                              */
8129 /*              ptr(I)  - context pointer for the token                     */
8130 /*                                                                          */
8131 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role   */
8132 /* ------------------------------------------------------------------------ */
8133 int
8134 ipf_genericiter(softc, data, uid, ctx)
8135         ipf_main_softc_t *softc;
8136         void *data, *ctx;
8137         int uid;
8138 {
8139         ipftoken_t *token;
8140         ipfgeniter_t iter;
8141         int error;
8142
8143         error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
8144         if (error != 0)
8145                 return error;
8146
8147         token = ipf_token_find(softc, iter.igi_type, uid, ctx);
8148         if (token != NULL) {
8149                 token->ipt_subtype = iter.igi_type;
8150                 error = ipf_geniter(softc, token, &iter);
8151                 WRITE_ENTER(&softc->ipf_tokens);
8152                 ipf_token_deref(softc, token);
8153                 RWLOCK_EXIT(&softc->ipf_tokens);
8154         } else {
8155                 IPFERROR(93);
8156                 error = 0;
8157         }
8158
8159         return error;
8160 }
8161
8162
8163 /* ------------------------------------------------------------------------ */
8164 /* Function:    ipf_ipf_ioctl                                               */
8165 /* Returns:     int - 0 = success, else error                               */
8166 /* Parameters:  softc(I)- pointer to soft context main structure           */
8167 /*              data(I) - the token type to match                           */
8168 /*              cmd(I)  - the ioctl command number                          */
8169 /*              mode(I) - mode flags for the ioctl                          */
8170 /*              uid(I)  - uid owning the token                              */
8171 /*              ptr(I)  - context pointer for the token                     */
8172 /*                                                                          */
8173 /* This function handles all of the ioctl command that are actually isssued */
8174 /* to the /dev/ipl device.                                                  */
8175 /* ------------------------------------------------------------------------ */
8176 int
8177 ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx)
8178         ipf_main_softc_t *softc;
8179         caddr_t data;
8180         ioctlcmd_t cmd;
8181         int mode, uid;
8182         void *ctx;
8183 {
8184         friostat_t fio;
8185         int error, tmp;
8186         ipfobj_t obj;
8187         SPL_INT(s);
8188
8189         switch (cmd)
8190         {
8191         case SIOCFRENB :
8192                 if (!(mode & FWRITE)) {
8193                         IPFERROR(94);
8194                         error = EPERM;
8195                 } else {
8196                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8197                         if (error != 0) {
8198                                 IPFERROR(95);
8199                                 error = EFAULT;
8200                                 break;
8201                         }
8202
8203                         WRITE_ENTER(&softc->ipf_global);
8204                         if (tmp) {
8205                                 if (softc->ipf_running > 0)
8206                                         error = 0;
8207                                 else
8208                                         error = ipfattach(softc);
8209                                 if (error == 0)
8210                                         softc->ipf_running = 1;
8211                                 else
8212                                         (void) ipfdetach(softc);
8213                         } else {
8214                                 if (softc->ipf_running == 1)
8215                                         error = ipfdetach(softc);
8216                                 else
8217                                         error = 0;
8218                                 if (error == 0)
8219                                         softc->ipf_running = -1;
8220                         }
8221                         RWLOCK_EXIT(&softc->ipf_global);
8222                 }
8223                 break;
8224
8225         case SIOCIPFSET :
8226                 if (!(mode & FWRITE)) {
8227                         IPFERROR(96);
8228                         error = EPERM;
8229                         break;
8230                 }
8231                 /* FALLTHRU */
8232         case SIOCIPFGETNEXT :
8233         case SIOCIPFGET :
8234                 error = ipf_ipftune(softc, cmd, (void *)data);
8235                 break;
8236
8237         case SIOCSETFF :
8238                 if (!(mode & FWRITE)) {
8239                         IPFERROR(97);
8240                         error = EPERM;
8241                 } else {
8242                         error = BCOPYIN(data, &softc->ipf_flags,
8243                                         sizeof(softc->ipf_flags));
8244                         if (error != 0) {
8245                                 IPFERROR(98);
8246                                 error = EFAULT;
8247                         }
8248                 }
8249                 break;
8250
8251         case SIOCGETFF :
8252                 error = BCOPYOUT(&softc->ipf_flags, data,
8253                                  sizeof(softc->ipf_flags));
8254                 if (error != 0) {
8255                         IPFERROR(99);
8256                         error = EFAULT;
8257                 }
8258                 break;
8259
8260         case SIOCFUNCL :
8261                 error = ipf_resolvefunc(softc, (void *)data);
8262                 break;
8263
8264         case SIOCINAFR :
8265         case SIOCRMAFR :
8266         case SIOCADAFR :
8267         case SIOCZRLST :
8268                 if (!(mode & FWRITE)) {
8269                         IPFERROR(100);
8270                         error = EPERM;
8271                 } else {
8272                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8273                                           softc->ipf_active, 1);
8274                 }
8275                 break;
8276
8277         case SIOCINIFR :
8278         case SIOCRMIFR :
8279         case SIOCADIFR :
8280                 if (!(mode & FWRITE)) {
8281                         IPFERROR(101);
8282                         error = EPERM;
8283                 } else {
8284                         error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8285                                           1 - softc->ipf_active, 1);
8286                 }
8287                 break;
8288
8289         case SIOCSWAPA :
8290                 if (!(mode & FWRITE)) {
8291                         IPFERROR(102);
8292                         error = EPERM;
8293                 } else {
8294                         WRITE_ENTER(&softc->ipf_mutex);
8295                         error = BCOPYOUT(&softc->ipf_active, data,
8296                                          sizeof(softc->ipf_active));
8297                         if (error != 0) {
8298                                 IPFERROR(103);
8299                                 error = EFAULT;
8300                         } else {
8301                                 softc->ipf_active = 1 - softc->ipf_active;
8302                         }
8303                         RWLOCK_EXIT(&softc->ipf_mutex);
8304                 }
8305                 break;
8306
8307         case SIOCGETFS :
8308                 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8309                                   IPFOBJ_IPFSTAT);
8310                 if (error != 0)
8311                         break;
8312                 ipf_getstat(softc, &fio, obj.ipfo_rev);
8313                 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8314                 break;
8315
8316         case SIOCFRZST :
8317                 if (!(mode & FWRITE)) {
8318                         IPFERROR(104);
8319                         error = EPERM;
8320                 } else
8321                         error = ipf_zerostats(softc, (caddr_t)data);
8322                 break;
8323
8324         case SIOCIPFFL :
8325                 if (!(mode & FWRITE)) {
8326                         IPFERROR(105);
8327                         error = EPERM;
8328                 } else {
8329                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8330                         if (!error) {
8331                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8332                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8333                                 if (error != 0) {
8334                                         IPFERROR(106);
8335                                         error = EFAULT;
8336                                 }
8337                         } else {
8338                                 IPFERROR(107);
8339                                 error = EFAULT;
8340                         }
8341                 }
8342                 break;
8343
8344 #ifdef USE_INET6
8345         case SIOCIPFL6 :
8346                 if (!(mode & FWRITE)) {
8347                         IPFERROR(108);
8348                         error = EPERM;
8349                 } else {
8350                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8351                         if (!error) {
8352                                 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8353                                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8354                                 if (error != 0) {
8355                                         IPFERROR(109);
8356                                         error = EFAULT;
8357                                 }
8358                         } else {
8359                                 IPFERROR(110);
8360                                 error = EFAULT;
8361                         }
8362                 }
8363                 break;
8364 #endif
8365
8366         case SIOCSTLCK :
8367                 if (!(mode & FWRITE)) {
8368                         IPFERROR(122);
8369                         error = EPERM;
8370                 } else {
8371                         error = BCOPYIN(data, &tmp, sizeof(tmp));
8372                         if (error == 0) {
8373                                 ipf_state_setlock(softc->ipf_state_soft, tmp);
8374                                 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8375                                 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8376                                 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8377                         } else {
8378                                 IPFERROR(111);
8379                                 error = EFAULT;
8380                         }
8381                 }
8382                 break;
8383
8384 #ifdef  IPFILTER_LOG
8385         case SIOCIPFFB :
8386                 if (!(mode & FWRITE)) {
8387                         IPFERROR(112);
8388                         error = EPERM;
8389                 } else {
8390                         tmp = ipf_log_clear(softc, IPL_LOGIPF);
8391                         error = BCOPYOUT(&tmp, data, sizeof(tmp));
8392                         if (error) {
8393                                 IPFERROR(113);
8394                                 error = EFAULT;
8395                         }
8396                 }
8397                 break;
8398 #endif /* IPFILTER_LOG */
8399
8400         case SIOCFRSYN :
8401                 if (!(mode & FWRITE)) {
8402                         IPFERROR(114);
8403                         error = EPERM;
8404                 } else {
8405                         WRITE_ENTER(&softc->ipf_global);
8406 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8407                         error = ipfsync();
8408 #else
8409                         ipf_sync(softc, NULL);
8410                         error = 0;
8411 #endif
8412                         RWLOCK_EXIT(&softc->ipf_global);
8413
8414                 }
8415                 break;
8416
8417         case SIOCGFRST :
8418                 error = ipf_outobj(softc, (void *)data,
8419                                    ipf_frag_stats(softc->ipf_frag_soft),
8420                                    IPFOBJ_FRAGSTAT);
8421                 break;
8422
8423 #ifdef  IPFILTER_LOG
8424         case FIONREAD :
8425                 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8426                 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8427                 break;
8428 #endif
8429
8430         case SIOCIPFITER :
8431                 SPL_SCHED(s);
8432                 error = ipf_frruleiter(softc, data, uid, ctx);
8433                 SPL_X(s);
8434                 break;
8435
8436         case SIOCGENITER :
8437                 SPL_SCHED(s);
8438                 error = ipf_genericiter(softc, data, uid, ctx);
8439                 SPL_X(s);
8440                 break;
8441
8442         case SIOCIPFDELTOK :
8443                 error = BCOPYIN(data, &tmp, sizeof(tmp));
8444                 if (error == 0) {
8445                         SPL_SCHED(s);
8446                         error = ipf_token_del(softc, tmp, uid, ctx);
8447                         SPL_X(s);
8448                 }
8449                 break;
8450
8451         default :
8452                 IPFERROR(115);
8453                 error = EINVAL;
8454                 break;
8455         }
8456
8457         return error;
8458 }
8459
8460
8461 /* ------------------------------------------------------------------------ */
8462 /* Function:    ipf_decaps                                                  */
8463 /* Returns:     int        - -1 == decapsulation failed, else bit mask of   */
8464 /*                           flags indicating packet filtering decision.    */
8465 /* Parameters:  fin(I)     - pointer to packet information                  */
8466 /*              pass(I)    - IP protocol version to match                   */
8467 /*              l5proto(I) - layer 5 protocol to decode UDP data as.        */
8468 /*                                                                          */
8469 /* This function is called for packets that are wrapt up in other packets,  */
8470 /* for example, an IP packet that is the entire data segment for another IP */
8471 /* packet.  If the basic constraints for this are satisfied, change the     */
8472 /* buffer to point to the start of the inner packet and start processing    */
8473 /* rules belonging to the head group this rule specifies.                   */
8474 /* ------------------------------------------------------------------------ */
8475 u_32_t
8476 ipf_decaps(fin, pass, l5proto)
8477         fr_info_t *fin;
8478         u_32_t pass;
8479         int l5proto;
8480 {
8481         fr_info_t fin2, *fino = NULL;
8482         int elen, hlen, nh;
8483         grehdr_t gre;
8484         ip_t *ip;
8485         mb_t *m;
8486
8487         if ((fin->fin_flx & FI_COALESCE) == 0)
8488                 if (ipf_coalesce(fin) == -1)
8489                         goto cantdecaps;
8490
8491         m = fin->fin_m;
8492         hlen = fin->fin_hlen;
8493
8494         switch (fin->fin_p)
8495         {
8496         case IPPROTO_UDP :
8497                 /*
8498                  * In this case, the specific protocol being decapsulated
8499                  * inside UDP frames comes from the rule.
8500                  */
8501                 nh = fin->fin_fr->fr_icode;
8502                 break;
8503
8504         case IPPROTO_GRE :      /* 47 */
8505                 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8506                 hlen += sizeof(grehdr_t);
8507                 if (gre.gr_R|gre.gr_s)
8508                         goto cantdecaps;
8509                 if (gre.gr_C)
8510                         hlen += 4;
8511                 if (gre.gr_K)
8512                         hlen += 4;
8513                 if (gre.gr_S)
8514                         hlen += 4;
8515
8516                 nh = IPPROTO_IP;
8517
8518                 /*
8519                  * If the routing options flag is set, validate that it is
8520                  * there and bounce over it.
8521                  */
8522 #if 0
8523                 /* This is really heavy weight and lots of room for error, */
8524                 /* so for now, put it off and get the simple stuff right.  */
8525                 if (gre.gr_R) {
8526                         u_char off, len, *s;
8527                         u_short af;
8528                         int end;
8529
8530                         end = 0;
8531                         s = fin->fin_dp;
8532                         s += hlen;
8533                         aplen = fin->fin_plen - hlen;
8534                         while (aplen > 3) {
8535                                 af = (s[0] << 8) | s[1];
8536                                 off = s[2];
8537                                 len = s[3];
8538                                 aplen -= 4;
8539                                 s += 4;
8540                                 if (af == 0 && len == 0) {
8541                                         end = 1;
8542                                         break;
8543                                 }
8544                                 if (aplen < len)
8545                                         break;
8546                                 s += len;
8547                                 aplen -= len;
8548                         }
8549                         if (end != 1)
8550                                 goto cantdecaps;
8551                         hlen = s - (u_char *)fin->fin_dp;
8552                 }
8553 #endif
8554                 break;
8555
8556 #ifdef IPPROTO_IPIP
8557         case IPPROTO_IPIP :     /* 4 */
8558 #endif
8559                 nh = IPPROTO_IP;
8560                 break;
8561
8562         default :       /* Includes ESP, AH is special for IPv4 */
8563                 goto cantdecaps;
8564         }
8565
8566         switch (nh)
8567         {
8568         case IPPROTO_IP :
8569         case IPPROTO_IPV6 :
8570                 break;
8571         default :
8572                 goto cantdecaps;
8573         }
8574
8575         bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8576         fino = fin;
8577         fin = &fin2;
8578         elen = hlen;
8579 #if defined(MENTAT) && defined(_KERNEL)
8580         m->b_rptr += elen;
8581 #else
8582         m->m_data += elen;
8583         m->m_len -= elen;
8584 #endif
8585         fin->fin_plen -= elen;
8586
8587         ip = (ip_t *)((char *)fin->fin_ip + elen);
8588
8589         /*
8590          * Make sure we have at least enough data for the network layer
8591          * header.
8592          */
8593         if (IP_V(ip) == 4)
8594                 hlen = IP_HL(ip) << 2;
8595 #ifdef USE_INET6
8596         else if (IP_V(ip) == 6)
8597                 hlen = sizeof(ip6_t);
8598 #endif
8599         else
8600                 goto cantdecaps2;
8601
8602         if (fin->fin_plen < hlen)
8603                 goto cantdecaps2;
8604
8605         fin->fin_dp = (char *)ip + hlen;
8606
8607         if (IP_V(ip) == 4) {
8608                 /*
8609                  * Perform IPv4 header checksum validation.
8610                  */
8611                 if (ipf_cksum((u_short *)ip, hlen))
8612                         goto cantdecaps2;
8613         }
8614
8615         if (ipf_makefrip(hlen, ip, fin) == -1) {
8616 cantdecaps2:
8617                 if (m != NULL) {
8618 #if defined(MENTAT) && defined(_KERNEL)
8619                         m->b_rptr -= elen;
8620 #else
8621                         m->m_data -= elen;
8622                         m->m_len += elen;
8623 #endif
8624                 }
8625 cantdecaps:
8626                 DT1(frb_decapfrip, fr_info_t *, fin);
8627                 pass &= ~FR_CMDMASK;
8628                 pass |= FR_BLOCK|FR_QUICK;
8629                 fin->fin_reason = FRB_DECAPFRIP;
8630                 return -1;
8631         }
8632
8633         pass = ipf_scanlist(fin, pass);
8634
8635         /*
8636          * Copy the packet filter "result" fields out of the fr_info_t struct
8637          * that is local to the decapsulation processing and back into the
8638          * one we were called with.
8639          */
8640         fino->fin_flx = fin->fin_flx;
8641         fino->fin_rev = fin->fin_rev;
8642         fino->fin_icode = fin->fin_icode;
8643         fino->fin_rule = fin->fin_rule;
8644         (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8645         fino->fin_fr = fin->fin_fr;
8646         fino->fin_error = fin->fin_error;
8647         fino->fin_mp = fin->fin_mp;
8648         fino->fin_m = fin->fin_m;
8649         m = fin->fin_m;
8650         if (m != NULL) {
8651 #if defined(MENTAT) && defined(_KERNEL)
8652                 m->b_rptr -= elen;
8653 #else
8654                 m->m_data -= elen;
8655                 m->m_len += elen;
8656 #endif
8657         }
8658         return pass;
8659 }
8660
8661
8662 /* ------------------------------------------------------------------------ */
8663 /* Function:    ipf_matcharray_load                                         */
8664 /* Returns:     int         - 0 = success, else error                       */
8665 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8666 /*              data(I)     - pointer to ioctl data                         */
8667 /*              objp(I)     - ipfobj_t structure to load data into          */
8668 /*              arrayptr(I) - pointer to location to store array pointer    */
8669 /*                                                                          */
8670 /* This function loads in a mathing array through the ipfobj_t struct that  */
8671 /* describes it.  Sanity checking and array size limitations are enforced   */
8672 /* in this function to prevent userspace from trying to load in something   */
8673 /* that is insanely big.  Once the size of the array is known, the memory   */
8674 /* required is malloc'd and returned through changing *arrayptr.  The       */
8675 /* contents of the array are verified before returning.  Only in the event  */
8676 /* of a successful call is the caller required to free up the malloc area.  */
8677 /* ------------------------------------------------------------------------ */
8678 int
8679 ipf_matcharray_load(softc, data, objp, arrayptr)
8680         ipf_main_softc_t *softc;
8681         caddr_t data;
8682         ipfobj_t *objp;
8683         int **arrayptr;
8684 {
8685         int arraysize, *array, error;
8686
8687         *arrayptr = NULL;
8688
8689         error = BCOPYIN(data, objp, sizeof(*objp));
8690         if (error != 0) {
8691                 IPFERROR(116);
8692                 return EFAULT;
8693         }
8694
8695         if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8696                 IPFERROR(117);
8697                 return EINVAL;
8698         }
8699
8700         if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8701             (objp->ipfo_size > 1024)) {
8702                 IPFERROR(118);
8703                 return EINVAL;
8704         }
8705
8706         arraysize = objp->ipfo_size * sizeof(*array);
8707         KMALLOCS(array, int *, arraysize);
8708         if (array == NULL) {
8709                 IPFERROR(119);
8710                 return ENOMEM;
8711         }
8712
8713         error = COPYIN(objp->ipfo_ptr, array, arraysize);
8714         if (error != 0) {
8715                 KFREES(array, arraysize);
8716                 IPFERROR(120);
8717                 return EFAULT;
8718         }
8719
8720         if (ipf_matcharray_verify(array, arraysize) != 0) {
8721                 KFREES(array, arraysize);
8722                 IPFERROR(121);
8723                 return EINVAL;
8724         }
8725
8726         *arrayptr = array;
8727         return 0;
8728 }
8729
8730
8731 /* ------------------------------------------------------------------------ */
8732 /* Function:    ipf_matcharray_verify                                       */
8733 /* Returns:     Nil                                                         */
8734 /* Parameters:  array(I)     - pointer to matching array                    */
8735 /*              arraysize(I) - number of elements in the array              */
8736 /*                                                                          */
8737 /* Verify the contents of a matching array by stepping through each element */
8738 /* in it.  The actual commands in the array are not verified for            */
8739 /* correctness, only that all of the sizes are correctly within limits.     */
8740 /* ------------------------------------------------------------------------ */
8741 int
8742 ipf_matcharray_verify(array, arraysize)
8743         int *array, arraysize;
8744 {
8745         int i, nelem, maxidx;
8746         ipfexp_t *e;
8747
8748         nelem = arraysize / sizeof(*array);
8749
8750         /*
8751          * Currently, it makes no sense to have an array less than 6
8752          * elements long - the initial size at the from, a single operation
8753          * (minimum 4 in length) and a trailer, for a total of 6.
8754          */
8755         if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8756                 return -1;
8757         }
8758
8759         /*
8760          * Verify the size of data pointed to by array with how long
8761          * the array claims to be itself.
8762          */
8763         if (array[0] * sizeof(*array) != arraysize) {
8764                 return -1;
8765         }
8766
8767         maxidx = nelem - 1;
8768         /*
8769          * The last opcode in this array should be an IPF_EXP_END.
8770          */
8771         if (array[maxidx] != IPF_EXP_END) {
8772                 return -1;
8773         }
8774
8775         for (i = 1; i < maxidx; ) {
8776                 e = (ipfexp_t *)(array + i);
8777
8778                 /*
8779                  * The length of the bits to check must be at least 1
8780                  * (or else there is nothing to comapre with!) and it
8781                  * cannot exceed the length of the data present.
8782                  */
8783                 if ((e->ipfe_size < 1 ) ||
8784                     (e->ipfe_size + i > maxidx)) {
8785                         return -1;
8786                 }
8787                 i += e->ipfe_size;
8788         }
8789         return 0;
8790 }
8791
8792
8793 /* ------------------------------------------------------------------------ */
8794 /* Function:    ipf_fr_matcharray                                           */
8795 /* Returns:     int      - 0 = match failed, else positive match            */
8796 /* Parameters:  fin(I)   - pointer to packet information                    */
8797 /*              array(I) - pointer to matching array                        */
8798 /*                                                                          */
8799 /* This function is used to apply a matching array against a packet and     */
8800 /* return an indication of whether or not the packet successfully matches   */
8801 /* all of the commands in it.                                               */
8802 /* ------------------------------------------------------------------------ */
8803 static int
8804 ipf_fr_matcharray(fin, array)
8805         fr_info_t *fin;
8806         int *array;
8807 {
8808         int i, n, *x, rv, p;
8809         ipfexp_t *e;
8810
8811         rv = 0;
8812         n = array[0];
8813         x = array + 1;
8814
8815         for (; n > 0; x += 3 + x[3], rv = 0) {
8816                 e = (ipfexp_t *)x;
8817                 if (e->ipfe_cmd == IPF_EXP_END)
8818                         break;
8819                 n -= e->ipfe_size;
8820
8821                 /*
8822                  * The upper 16 bits currently store the protocol value.
8823                  * This is currently used with TCP and UDP port compares and
8824                  * allows "tcp.port = 80" without requiring an explicit
8825                  " "ip.pr = tcp" first.
8826                  */
8827                 p = e->ipfe_cmd >> 16;
8828                 if ((p != 0) && (p != fin->fin_p))
8829                         break;
8830
8831                 switch (e->ipfe_cmd)
8832                 {
8833                 case IPF_EXP_IP_PR :
8834                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8835                                 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8836                         }
8837                         break;
8838
8839                 case IPF_EXP_IP_SRCADDR :
8840                         if (fin->fin_v != 4)
8841                                 break;
8842                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8843                                 rv |= ((fin->fin_saddr &
8844                                         e->ipfe_arg0[i * 2 + 1]) ==
8845                                        e->ipfe_arg0[i * 2]);
8846                         }
8847                         break;
8848
8849                 case IPF_EXP_IP_DSTADDR :
8850                         if (fin->fin_v != 4)
8851                                 break;
8852                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8853                                 rv |= ((fin->fin_daddr &
8854                                         e->ipfe_arg0[i * 2 + 1]) ==
8855                                        e->ipfe_arg0[i * 2]);
8856                         }
8857                         break;
8858
8859                 case IPF_EXP_IP_ADDR :
8860                         if (fin->fin_v != 4)
8861                                 break;
8862                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8863                                 rv |= ((fin->fin_saddr &
8864                                         e->ipfe_arg0[i * 2 + 1]) ==
8865                                        e->ipfe_arg0[i * 2]) ||
8866                                       ((fin->fin_daddr &
8867                                         e->ipfe_arg0[i * 2 + 1]) ==
8868                                        e->ipfe_arg0[i * 2]);
8869                         }
8870                         break;
8871
8872 #ifdef USE_INET6
8873                 case IPF_EXP_IP6_SRCADDR :
8874                         if (fin->fin_v != 6)
8875                                 break;
8876                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8877                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8878                                                  &e->ipfe_arg0[i * 8 + 4],
8879                                                  &e->ipfe_arg0[i * 8]);
8880                         }
8881                         break;
8882
8883                 case IPF_EXP_IP6_DSTADDR :
8884                         if (fin->fin_v != 6)
8885                                 break;
8886                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8887                                 rv |= IP6_MASKEQ(&fin->fin_dst6,
8888                                                  &e->ipfe_arg0[i * 8 + 4],
8889                                                  &e->ipfe_arg0[i * 8]);
8890                         }
8891                         break;
8892
8893                 case IPF_EXP_IP6_ADDR :
8894                         if (fin->fin_v != 6)
8895                                 break;
8896                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8897                                 rv |= IP6_MASKEQ(&fin->fin_src6,
8898                                                  &e->ipfe_arg0[i * 8 + 4],
8899                                                  &e->ipfe_arg0[i * 8]) ||
8900                                       IP6_MASKEQ(&fin->fin_dst6,
8901                                                  &e->ipfe_arg0[i * 8 + 4],
8902                                                  &e->ipfe_arg0[i * 8]);
8903                         }
8904                         break;
8905 #endif
8906
8907                 case IPF_EXP_UDP_PORT :
8908                 case IPF_EXP_TCP_PORT :
8909                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8910                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8911                                       (fin->fin_dport == e->ipfe_arg0[i]);
8912                         }
8913                         break;
8914
8915                 case IPF_EXP_UDP_SPORT :
8916                 case IPF_EXP_TCP_SPORT :
8917                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8918                                 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8919                         }
8920                         break;
8921
8922                 case IPF_EXP_UDP_DPORT :
8923                 case IPF_EXP_TCP_DPORT :
8924                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8925                                 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8926                         }
8927                         break;
8928
8929                 case IPF_EXP_TCP_FLAGS :
8930                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
8931                                 rv |= ((fin->fin_tcpf &
8932                                         e->ipfe_arg0[i * 2 + 1]) ==
8933                                        e->ipfe_arg0[i * 2]);
8934                         }
8935                         break;
8936                 }
8937                 rv ^= e->ipfe_not;
8938
8939                 if (rv == 0)
8940                         break;
8941         }
8942
8943         return rv;
8944 }
8945
8946
8947 /* ------------------------------------------------------------------------ */
8948 /* Function:    ipf_queueflush                                              */
8949 /* Returns:     int - number of entries flushed (0 = none)                  */
8950 /* Parameters:  softc(I)    - pointer to soft context main structure        */
8951 /*              deletefn(I) - function to call to delete entry              */
8952 /*              ipfqs(I)    - top of the list of ipf internal queues        */
8953 /*              userqs(I)   - top of the list of user defined timeouts      */
8954 /*                                                                          */
8955 /* This fucntion gets called when the state/NAT hash tables fill up and we  */
8956 /* need to try a bit harder to free up some space.  The algorithm used here */
8957 /* split into two parts but both halves have the same goal: to reduce the   */
8958 /* number of connections considered to be "active" to the low watermark.    */
8959 /* There are two steps in doing this:                                       */
8960 /* 1) Remove any TCP connections that are already considered to be "closed" */
8961 /*    but have not yet been removed from the state table.  The two states   */
8962 /*    TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect       */
8963 /*    candidates for this style of removal.  If freeing up entries in       */
8964 /*    CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark,   */
8965 /*    we do not go on to step 2.                                            */
8966 /*                                                                          */
8967 /* 2) Look for the oldest entries on each timeout queue and free them if    */
8968 /*    they are within the given window we are considering.  Where the       */
8969 /*    window starts and the steps taken to increase its size depend upon    */
8970 /*    how long ipf has been running (ipf_ticks.)  Anything modified in the  */
8971 /*    last 30 seconds is not touched.                                       */
8972 /*                                              touched                     */
8973 /*         die     ipf_ticks  30*1.5    1800*1.5   |  43200*1.5             */
8974 /*           |          |        |           |     |     |                  */
8975 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8976 /*                     now        \_int=30s_/ \_int=1hr_/ \_int=12hr        */
8977 /*                                                                          */
8978 /* Points to note:                                                          */
8979 /* - tqe_die is the time, in the future, when entries die.                  */
8980 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8981 /*   ticks.                                                                 */
8982 /* - tqe_touched is when the entry was last used by NAT/state               */
8983 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be    */
8984 /*   ipf_ticks any given timeout queue and vice versa.                      */
8985 /* - both tqe_die and tqe_touched increase over time                        */
8986 /* - timeout queues are sorted with the highest value of tqe_die at the     */
8987 /*   bottom and therefore the smallest values of each are at the top        */
8988 /* - the pointer passed in as ipfqs should point to an array of timeout     */
8989 /*   queues representing each of the TCP states                             */
8990 /*                                                                          */
8991 /* We start by setting up a maximum range to scan for things to move of     */
8992 /* iend (newest) to istart (oldest) in chunks of "interval".  If nothing is */
8993 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8994 /* we start again with a new value for "iend" and "istart".  This is        */
8995 /* continued until we either finish the scan of 30 second intervals or the  */
8996 /* low water mark is reached.                                               */
8997 /* ------------------------------------------------------------------------ */
8998 int
8999 ipf_queueflush(softc, deletefn, ipfqs, userqs, activep, size, low)
9000         ipf_main_softc_t *softc;
9001         ipftq_delete_fn_t deletefn;
9002         ipftq_t *ipfqs, *userqs;
9003         u_int *activep;
9004         int size, low;
9005 {
9006         u_long interval, istart, iend;
9007         ipftq_t *ifq, *ifqnext;
9008         ipftqent_t *tqe, *tqn;
9009         int removed = 0;
9010
9011         for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
9012                 tqn = tqe->tqe_next;
9013                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9014                         removed++;
9015         }
9016         if ((*activep * 100 / size) > low) {
9017                 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
9018                      ((tqe = tqn) != NULL); ) {
9019                         tqn = tqe->tqe_next;
9020                         if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9021                                 removed++;
9022                 }
9023         }
9024
9025         if ((*activep * 100 / size) <= low) {
9026                 return removed;
9027         }
9028
9029         /*
9030          * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
9031          *       used then the operations are upgraded to floating point
9032          *       and kernels don't like floating point...
9033          */
9034         if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
9035                 istart = IPF_TTLVAL(86400 * 4);
9036                 interval = IPF_TTLVAL(43200);
9037         } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
9038                 istart = IPF_TTLVAL(43200);
9039                 interval = IPF_TTLVAL(1800);
9040         } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
9041                 istart = IPF_TTLVAL(1800);
9042                 interval = IPF_TTLVAL(30);
9043         } else {
9044                 return 0;
9045         }
9046         if (istart > softc->ipf_ticks) {
9047                 if (softc->ipf_ticks - interval < interval)
9048                         istart = interval;
9049                 else
9050                         istart = (softc->ipf_ticks / interval) * interval;
9051         }
9052
9053         iend = softc->ipf_ticks - interval;
9054
9055         while ((*activep * 100 / size) > low) {
9056                 u_long try;
9057
9058                 try = softc->ipf_ticks - istart;
9059
9060                 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
9061                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9062                                 if (try < tqe->tqe_touched)
9063                                         break;
9064                                 tqn = tqe->tqe_next;
9065                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9066                                         removed++;
9067                         }
9068                 }
9069
9070                 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
9071                         ifqnext = ifq->ifq_next;
9072
9073                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
9074                                 if (try < tqe->tqe_touched)
9075                                         break;
9076                                 tqn = tqe->tqe_next;
9077                                 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
9078                                         removed++;
9079                         }
9080                 }
9081
9082                 if (try >= iend) {
9083                         if (interval == IPF_TTLVAL(43200)) {
9084                                 interval = IPF_TTLVAL(1800);
9085                         } else if (interval == IPF_TTLVAL(1800)) {
9086                                 interval = IPF_TTLVAL(30);
9087                         } else {
9088                                 break;
9089                         }
9090                         if (interval >= softc->ipf_ticks)
9091                                 break;
9092
9093                         iend = softc->ipf_ticks - interval;
9094                 }
9095                 istart -= interval;
9096         }
9097
9098         return removed;
9099 }
9100
9101
9102 /* ------------------------------------------------------------------------ */
9103 /* Function:    ipf_deliverlocal                                            */
9104 /* Returns:     int - 1 = local address, 0 = non-local address              */
9105 /* Parameters:  softc(I)     - pointer to soft context main structure       */
9106 /*              ipversion(I) - IP protocol version (4 or 6)                 */
9107 /*              ifp(I)       - network interface pointer                    */
9108 /*              ipaddr(I)    - IPv4/6 destination address                   */
9109 /*                                                                          */
9110 /* This fucntion is used to determine in the address "ipaddr" belongs to    */
9111 /* the network interface represented by ifp.                                */
9112 /* ------------------------------------------------------------------------ */
9113 int
9114 ipf_deliverlocal(softc, ipversion, ifp, ipaddr)
9115         ipf_main_softc_t *softc;
9116         int ipversion;
9117         void *ifp;
9118         i6addr_t *ipaddr;
9119 {
9120         i6addr_t addr;
9121         int islocal = 0;
9122
9123         if (ipversion == 4) {
9124                 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9125                         if (addr.in4.s_addr == ipaddr->in4.s_addr)
9126                                 islocal = 1;
9127                 }
9128
9129 #ifdef USE_INET6
9130         } else if (ipversion == 6) {
9131                 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
9132                         if (IP6_EQ(&addr, ipaddr))
9133                                 islocal = 1;
9134                 }
9135 #endif
9136         }
9137
9138         return islocal;
9139 }
9140
9141
9142 /* ------------------------------------------------------------------------ */
9143 /* Function:    ipf_settimeout                                              */
9144 /* Returns:     int - 0 = success, -1 = failure                             */
9145 /* Parameters:  softc(I) - pointer to soft context main structure           */
9146 /*              t(I)     - pointer to tuneable array entry                  */
9147 /*              p(I)     - pointer to values passed in to apply             */
9148 /*                                                                          */
9149 /* This function is called to set the timeout values for each distinct      */
9150 /* queue timeout that is available.  When called, it calls into both the    */
9151 /* state and NAT code, telling them to update their timeout queues.         */
9152 /* ------------------------------------------------------------------------ */
9153 static int
9154 ipf_settimeout(softc, t, p)
9155         struct ipf_main_softc_s *softc;
9156         ipftuneable_t *t;
9157         ipftuneval_t *p;
9158 {
9159
9160         /*
9161          * ipf_interror should be set by the functions called here, not
9162          * by this function - it's just a middle man.
9163          */
9164         if (ipf_state_settimeout(softc, t, p) == -1)
9165                 return -1;
9166         if (ipf_nat_settimeout(softc, t, p) == -1)
9167                 return -1;
9168         return 0;
9169 }
9170
9171
9172 /* ------------------------------------------------------------------------ */
9173 /* Function:    ipf_apply_timeout                                           */
9174 /* Returns:     int - 0 = success, -1 = failure                             */
9175 /* Parameters:  head(I)    - pointer to tuneable array entry                */
9176 /*              seconds(I) - pointer to values passed in to apply           */
9177 /*                                                                          */
9178 /* This function applies a timeout of "seconds" to the timeout queue that   */
9179 /* is pointed to by "head".  All entries on this list have an expiration    */
9180 /* set to be the current tick value of ipf plus the ttl.  Given that this   */
9181 /* function should only be called when the delta is non-zero, the task is   */
9182 /* to walk the entire list and apply the change.  The sort order will not   */
9183 /* change.  The only catch is that this is O(n) across the list, so if the  */
9184 /* queue has lots of entries (10s of thousands or 100s of thousands), it    */
9185 /* could take a relatively long time to work through them all.              */
9186 /* ------------------------------------------------------------------------ */
9187 void
9188 ipf_apply_timeout(head, seconds)
9189         ipftq_t *head;
9190         u_int seconds;
9191 {
9192         u_int oldtimeout, newtimeout;
9193         ipftqent_t *tqe;
9194         int delta;
9195
9196         MUTEX_ENTER(&head->ifq_lock);
9197         oldtimeout = head->ifq_ttl;
9198         newtimeout = IPF_TTLVAL(seconds);
9199         delta = oldtimeout - newtimeout;
9200
9201         head->ifq_ttl = newtimeout;
9202
9203         for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
9204                 tqe->tqe_die += delta;
9205         }
9206         MUTEX_EXIT(&head->ifq_lock);
9207 }
9208
9209
9210 /* ------------------------------------------------------------------------ */
9211 /* Function:   ipf_settimeout_tcp                                           */
9212 /* Returns:    int - 0 = successfully applied, -1 = failed                  */
9213 /* Parameters: t(I)   - pointer to tuneable to change                       */
9214 /*             p(I)   - pointer to new timeout information                  */
9215 /*             tab(I) - pointer to table of TCP queues                      */
9216 /*                                                                          */
9217 /* This function applies the new timeout (p) to the TCP tunable (t) and     */
9218 /* updates all of the entries on the relevant timeout queue by calling      */
9219 /* ipf_apply_timeout().                                                     */
9220 /* ------------------------------------------------------------------------ */
9221 int
9222 ipf_settimeout_tcp(t, p, tab)
9223         ipftuneable_t *t;
9224         ipftuneval_t *p;
9225         ipftq_t *tab;
9226 {
9227         if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
9228             !strcmp(t->ipft_name, "tcp_established")) {
9229                 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
9230         } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
9231                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
9232         } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
9233                 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
9234         } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
9235                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9236                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9237                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9238         } else if (!strcmp(t->ipft_name, "tcp_listen")) {
9239                 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
9240         } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
9241                 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
9242         } else if (!strcmp(t->ipft_name, "tcp_closing")) {
9243                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
9244         } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
9245                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
9246         } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9247                 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9248         } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9249                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9250         } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9251                 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9252         } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9253                 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9254         } else {
9255                 /*
9256                  * ipf_interror isn't set here because it should be set
9257                  * by whatever called this function.
9258                  */
9259                 return -1;
9260         }
9261         return 0;
9262 }
9263
9264
9265 /* ------------------------------------------------------------------------ */
9266 /* Function:   ipf_main_soft_create                                         */
9267 /* Returns:    NULL = failure, else success                                 */
9268 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9269 /*                                                                          */
9270 /* Create the foundation soft context structure. In circumstances where it  */
9271 /* is not required to dynamically allocate the context, a pointer can be    */
9272 /* passed in (rather than NULL) to a structure to be initialised.           */
9273 /* The main thing of interest is that a number of locks are initialised     */
9274 /* here instead of in the where might be expected - in the relevant create  */
9275 /* function elsewhere.  This is done because the current locking design has */
9276 /* some areas where these locks are used outside of their module.           */
9277 /* Possibly the most important exercise that is done here is setting of all */
9278 /* the timeout values, allowing them to be changed before init().           */
9279 /* ------------------------------------------------------------------------ */
9280 void *
9281 ipf_main_soft_create(arg)
9282         void *arg;
9283 {
9284         ipf_main_softc_t *softc;
9285
9286         if (arg == NULL) {
9287                 KMALLOC(softc, ipf_main_softc_t *);
9288                 if (softc == NULL)
9289                         return NULL;
9290         } else {
9291                 softc = arg;
9292         }
9293
9294         bzero((char *)softc, sizeof(*softc));
9295
9296         /*
9297          * This serves as a flag as to whether or not the softc should be
9298          * free'd when _destroy is called.
9299          */
9300         softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9301
9302         softc->ipf_tuners = ipf_tune_array_copy(softc,
9303                                                 sizeof(ipf_main_tuneables),
9304                                                 ipf_main_tuneables);
9305         if (softc->ipf_tuners == NULL) {
9306                 ipf_main_soft_destroy(softc);
9307                 return NULL;
9308         }
9309
9310         MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9311         MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9312         RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9313         RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9314         RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9315         RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9316         RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9317         RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9318         RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9319
9320         softc->ipf_token_head = NULL;
9321         softc->ipf_token_tail = &softc->ipf_token_head;
9322
9323         softc->ipf_tcpidletimeout = FIVE_DAYS;
9324         softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9325         softc->ipf_tcplastack = IPF_TTLVAL(30);
9326         softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9327         softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9328         softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9329         softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9330         softc->ipf_tcpclosed = IPF_TTLVAL(30);
9331         softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9332         softc->ipf_udptimeout = IPF_TTLVAL(120);
9333         softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9334         softc->ipf_icmptimeout = IPF_TTLVAL(60);
9335         softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9336         softc->ipf_iptimeout = IPF_TTLVAL(60);
9337
9338 #if defined(IPFILTER_DEFAULT_BLOCK)
9339         softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9340 #else
9341         softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9342 #endif
9343         softc->ipf_minttl = 4;
9344         softc->ipf_icmpminfragmtu = 68;
9345         softc->ipf_flags = IPF_LOGGING;
9346
9347         return softc;
9348 }
9349
9350 /* ------------------------------------------------------------------------ */
9351 /* Function:   ipf_main_soft_init                                           */
9352 /* Returns:    0 = success, -1 = failure                                    */
9353 /* Parameters: softc(I) - pointer to soft context main structure            */
9354 /*                                                                          */
9355 /* A null-op function that exists as a placeholder so that the flow in      */
9356 /* other functions is obvious.                                              */
9357 /* ------------------------------------------------------------------------ */
9358 /*ARGSUSED*/
9359 int
9360 ipf_main_soft_init(softc)
9361         ipf_main_softc_t *softc;
9362 {
9363         return 0;
9364 }
9365
9366
9367 /* ------------------------------------------------------------------------ */
9368 /* Function:   ipf_main_soft_destroy                                        */
9369 /* Returns:    void                                                         */
9370 /* Parameters: softc(I) - pointer to soft context main structure            */
9371 /*                                                                          */
9372 /* Undo everything that we did in ipf_main_soft_create.                     */
9373 /*                                                                          */
9374 /* The most important check that needs to be made here is whether or not    */
9375 /* the structure was allocated by ipf_main_soft_create() by checking what   */
9376 /* value is stored in ipf_dynamic_main.                                     */
9377 /* ------------------------------------------------------------------------ */
9378 /*ARGSUSED*/
9379 void
9380 ipf_main_soft_destroy(softc)
9381         ipf_main_softc_t *softc;
9382 {
9383
9384         RW_DESTROY(&softc->ipf_frag);
9385         RW_DESTROY(&softc->ipf_poolrw);
9386         RW_DESTROY(&softc->ipf_nat);
9387         RW_DESTROY(&softc->ipf_state);
9388         RW_DESTROY(&softc->ipf_tokens);
9389         RW_DESTROY(&softc->ipf_mutex);
9390         RW_DESTROY(&softc->ipf_global);
9391         MUTEX_DESTROY(&softc->ipf_timeoutlock);
9392         MUTEX_DESTROY(&softc->ipf_rw);
9393
9394         if (softc->ipf_tuners != NULL) {
9395                 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9396         }
9397         if (softc->ipf_dynamic_softc == 1) {
9398                 KFREE(softc);
9399         }
9400 }
9401
9402
9403 /* ------------------------------------------------------------------------ */
9404 /* Function:   ipf_main_soft_fini                                           */
9405 /* Returns:    0 = success, -1 = failure                                    */
9406 /* Parameters: softc(I) - pointer to soft context main structure            */
9407 /*                                                                          */
9408 /* Clean out the rules which have been added since _init was last called,   */
9409 /* the only dynamic part of the mainline.                                   */
9410 /* ------------------------------------------------------------------------ */
9411 int
9412 ipf_main_soft_fini(softc)
9413         ipf_main_softc_t *softc;
9414 {
9415         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9416         (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9417         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9418         (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9419
9420         return 0;
9421 }
9422
9423
9424 /* ------------------------------------------------------------------------ */
9425 /* Function:   ipf_main_load                                                */
9426 /* Returns:    0 = success, -1 = failure                                    */
9427 /* Parameters: none                                                         */
9428 /*                                                                          */
9429 /* Handle global initialisation that needs to be done for the base part of  */
9430 /* IPFilter. At present this just amounts to initialising some ICMP lookup  */
9431 /* arrays that get used by the state/NAT code.                              */
9432 /* ------------------------------------------------------------------------ */
9433 int
9434 ipf_main_load()
9435 {
9436         int i;
9437
9438         /* fill icmp reply type table */
9439         for (i = 0; i <= ICMP_MAXTYPE; i++)
9440                 icmpreplytype4[i] = -1;
9441         icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9442         icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9443         icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9444         icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9445
9446 #ifdef  USE_INET6
9447         /* fill icmp reply type table */
9448         for (i = 0; i <= ICMP6_MAXTYPE; i++)
9449                 icmpreplytype6[i] = -1;
9450         icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9451         icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9452         icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9453         icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9454         icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9455 #endif
9456
9457         return 0;
9458 }
9459
9460
9461 /* ------------------------------------------------------------------------ */
9462 /* Function:   ipf_main_unload                                              */
9463 /* Returns:    0 = success, -1 = failure                                    */
9464 /* Parameters: none                                                         */
9465 /*                                                                          */
9466 /* A null-op function that exists as a placeholder so that the flow in      */
9467 /* other functions is obvious.                                              */
9468 /* ------------------------------------------------------------------------ */
9469 int
9470 ipf_main_unload()
9471 {
9472         return 0;
9473 }
9474
9475
9476 /* ------------------------------------------------------------------------ */
9477 /* Function:   ipf_load_all                                                 */
9478 /* Returns:    0 = success, -1 = failure                                    */
9479 /* Parameters: none                                                         */
9480 /*                                                                          */
9481 /* Work through all of the subsystems inside IPFilter and call the load     */
9482 /* function for each in an order that won't lead to a crash :)              */
9483 /* ------------------------------------------------------------------------ */
9484 int
9485 ipf_load_all()
9486 {
9487         if (ipf_main_load() == -1)
9488                 return -1;
9489
9490         if (ipf_state_main_load() == -1)
9491                 return -1;
9492
9493         if (ipf_nat_main_load() == -1)
9494                 return -1;
9495
9496         if (ipf_frag_main_load() == -1)
9497                 return -1;
9498
9499         if (ipf_auth_main_load() == -1)
9500                 return -1;
9501
9502         if (ipf_proxy_main_load() == -1)
9503                 return -1;
9504
9505         return 0;
9506 }
9507
9508
9509 /* ------------------------------------------------------------------------ */
9510 /* Function:   ipf_unload_all                                               */
9511 /* Returns:    0 = success, -1 = failure                                    */
9512 /* Parameters: none                                                         */
9513 /*                                                                          */
9514 /* Work through all of the subsystems inside IPFilter and call the unload   */
9515 /* function for each in an order that won't lead to a crash :)              */
9516 /* ------------------------------------------------------------------------ */
9517 int
9518 ipf_unload_all()
9519 {
9520         if (ipf_proxy_main_unload() == -1)
9521                 return -1;
9522
9523         if (ipf_auth_main_unload() == -1)
9524                 return -1;
9525
9526         if (ipf_frag_main_unload() == -1)
9527                 return -1;
9528
9529         if (ipf_nat_main_unload() == -1)
9530                 return -1;
9531
9532         if (ipf_state_main_unload() == -1)
9533                 return -1;
9534
9535         if (ipf_main_unload() == -1)
9536                 return -1;
9537
9538         return 0;
9539 }
9540
9541
9542 /* ------------------------------------------------------------------------ */
9543 /* Function:   ipf_create_all                                               */
9544 /* Returns:    NULL = failure, else success                                 */
9545 /* Parameters: arg(I) - pointer to soft context main structure              */
9546 /*                                                                          */
9547 /* Work through all of the subsystems inside IPFilter and call the create   */
9548 /* function for each in an order that won't lead to a crash :)              */
9549 /* ------------------------------------------------------------------------ */
9550 ipf_main_softc_t *
9551 ipf_create_all(arg)
9552         void *arg;
9553 {
9554         ipf_main_softc_t *softc;
9555
9556         softc = ipf_main_soft_create(arg);
9557         if (softc == NULL)
9558                 return NULL;
9559
9560 #ifdef IPFILTER_LOG
9561         softc->ipf_log_soft = ipf_log_soft_create(softc);
9562         if (softc->ipf_log_soft == NULL) {
9563                 ipf_destroy_all(softc);
9564                 return NULL;
9565         }
9566 #endif
9567
9568         softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9569         if (softc->ipf_lookup_soft == NULL) {
9570                 ipf_destroy_all(softc);
9571                 return NULL;
9572         }
9573
9574         softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9575         if (softc->ipf_sync_soft == NULL) {
9576                 ipf_destroy_all(softc);
9577                 return NULL;
9578         }
9579
9580         softc->ipf_state_soft = ipf_state_soft_create(softc);
9581         if (softc->ipf_state_soft == NULL) {
9582                 ipf_destroy_all(softc);
9583                 return NULL;
9584         }
9585
9586         softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9587         if (softc->ipf_nat_soft == NULL) {
9588                 ipf_destroy_all(softc);
9589                 return NULL;
9590         }
9591
9592         softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9593         if (softc->ipf_frag_soft == NULL) {
9594                 ipf_destroy_all(softc);
9595                 return NULL;
9596         }
9597
9598         softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9599         if (softc->ipf_auth_soft == NULL) {
9600                 ipf_destroy_all(softc);
9601                 return NULL;
9602         }
9603
9604         softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9605         if (softc->ipf_proxy_soft == NULL) {
9606                 ipf_destroy_all(softc);
9607                 return NULL;
9608         }
9609
9610         return softc;
9611 }
9612
9613
9614 /* ------------------------------------------------------------------------ */
9615 /* Function:   ipf_destroy_all                                              */
9616 /* Returns:    void                                                         */
9617 /* Parameters: softc(I) - pointer to soft context main structure            */
9618 /*                                                                          */
9619 /* Work through all of the subsystems inside IPFilter and call the destroy  */
9620 /* function for each in an order that won't lead to a crash :)              */
9621 /*                                                                          */
9622 /* Every one of these functions is expected to succeed, so there is no      */
9623 /* checking of return values.                                               */
9624 /* ------------------------------------------------------------------------ */
9625 void
9626 ipf_destroy_all(softc)
9627         ipf_main_softc_t *softc;
9628 {
9629
9630         if (softc->ipf_state_soft != NULL) {
9631                 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9632                 softc->ipf_state_soft = NULL;
9633         }
9634
9635         if (softc->ipf_nat_soft != NULL) {
9636                 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9637                 softc->ipf_nat_soft = NULL;
9638         }
9639
9640         if (softc->ipf_frag_soft != NULL) {
9641                 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9642                 softc->ipf_frag_soft = NULL;
9643         }
9644
9645         if (softc->ipf_auth_soft != NULL) {
9646                 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9647                 softc->ipf_auth_soft = NULL;
9648         }
9649
9650         if (softc->ipf_proxy_soft != NULL) {
9651                 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9652                 softc->ipf_proxy_soft = NULL;
9653         }
9654
9655         if (softc->ipf_sync_soft != NULL) {
9656                 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9657                 softc->ipf_sync_soft = NULL;
9658         }
9659
9660         if (softc->ipf_lookup_soft != NULL) {
9661                 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9662                 softc->ipf_lookup_soft = NULL;
9663         }
9664
9665 #ifdef IPFILTER_LOG
9666         if (softc->ipf_log_soft != NULL) {
9667                 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9668                 softc->ipf_log_soft = NULL;
9669         }
9670 #endif
9671
9672         ipf_main_soft_destroy(softc);
9673 }
9674
9675
9676 /* ------------------------------------------------------------------------ */
9677 /* Function:   ipf_init_all                                                 */
9678 /* Returns:    0 = success, -1 = failure                                    */
9679 /* Parameters: softc(I) - pointer to soft context main structure            */
9680 /*                                                                          */
9681 /* Work through all of the subsystems inside IPFilter and call the init     */
9682 /* function for each in an order that won't lead to a crash :)              */
9683 /* ------------------------------------------------------------------------ */
9684 int
9685 ipf_init_all(softc)
9686         ipf_main_softc_t *softc;
9687 {
9688
9689         if (ipf_main_soft_init(softc) == -1)
9690                 return -1;
9691
9692 #ifdef IPFILTER_LOG
9693         if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9694                 return -1;
9695 #endif
9696
9697         if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9698                 return -1;
9699
9700         if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9701                 return -1;
9702
9703         if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9704                 return -1;
9705
9706         if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9707                 return -1;
9708
9709         if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9710                 return -1;
9711
9712         if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9713                 return -1;
9714
9715         if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9716                 return -1;
9717
9718         return 0;
9719 }
9720
9721
9722 /* ------------------------------------------------------------------------ */
9723 /* Function:   ipf_fini_all                                                 */
9724 /* Returns:    0 = success, -1 = failure                                    */
9725 /* Parameters: softc(I) - pointer to soft context main structure            */
9726 /*                                                                          */
9727 /* Work through all of the subsystems inside IPFilter and call the fini     */
9728 /* function for each in an order that won't lead to a crash :)              */
9729 /* ------------------------------------------------------------------------ */
9730 int
9731 ipf_fini_all(softc)
9732         ipf_main_softc_t *softc;
9733 {
9734
9735         ipf_token_flush(softc);
9736
9737         if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9738                 return -1;
9739
9740         if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9741                 return -1;
9742
9743         if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9744                 return -1;
9745
9746         if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9747                 return -1;
9748
9749         if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9750                 return -1;
9751
9752         if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9753                 return -1;
9754
9755         if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9756                 return -1;
9757
9758 #ifdef IPFILTER_LOG
9759         if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9760                 return -1;
9761 #endif
9762
9763         if (ipf_main_soft_fini(softc) == -1)
9764                 return -1;
9765
9766         return 0;
9767 }
9768
9769
9770 /* ------------------------------------------------------------------------ */
9771 /* Function:    ipf_rule_expire                                             */
9772 /* Returns:     Nil                                                         */
9773 /* Parameters:  softc(I) - pointer to soft context main structure           */
9774 /*                                                                          */
9775 /* At present this function exists just to support temporary addition of    */
9776 /* firewall rules. Both inactive and active lists are scanned for items to  */
9777 /* purge, as by rights, the expiration is computed as soon as the rule is   */
9778 /* loaded in.                                                               */
9779 /* ------------------------------------------------------------------------ */
9780 void
9781 ipf_rule_expire(softc)
9782         ipf_main_softc_t *softc;
9783 {
9784         frentry_t *fr;
9785
9786         if ((softc->ipf_rule_explist[0] == NULL) &&
9787             (softc->ipf_rule_explist[1] == NULL))
9788                 return;
9789
9790         WRITE_ENTER(&softc->ipf_mutex);
9791
9792         while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9793                 /*
9794                  * Because the list is kept sorted on insertion, the fist
9795                  * one that dies in the future means no more work to do.
9796                  */
9797                 if (fr->fr_die > softc->ipf_ticks)
9798                         break;
9799                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9800         }
9801
9802         while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9803                 /*
9804                  * Because the list is kept sorted on insertion, the fist
9805                  * one that dies in the future means no more work to do.
9806                  */
9807                 if (fr->fr_die > softc->ipf_ticks)
9808                         break;
9809                 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9810         }
9811
9812         RWLOCK_EXIT(&softc->ipf_mutex);
9813 }
9814
9815
9816 static int ipf_ht_node_cmp __P((struct host_node_s *, struct host_node_s *));
9817 static void ipf_ht_node_make_key __P((host_track_t *, host_node_t *, int,
9818                                       i6addr_t *));
9819
9820 host_node_t RBI_ZERO(ipf_rb);
9821 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9822
9823
9824 /* ------------------------------------------------------------------------ */
9825 /* Function:    ipf_ht_node_cmp                                             */
9826 /* Returns:     int   - 0 == nodes are the same, ..                         */
9827 /* Parameters:  k1(I) - pointer to first key to compare                     */
9828 /*              k2(I) - pointer to second key to compare                    */
9829 /*                                                                          */
9830 /* The "key" for the node is a combination of two fields: the address       */
9831 /* family and the address itself.                                           */
9832 /*                                                                          */
9833 /* Because we're not actually interpreting the address data, it isn't       */
9834 /* necessary to convert them to/from network/host byte order. The mask is   */
9835 /* just used to remove bits that aren't significant - it doesn't matter     */
9836 /* where they are, as long as they're always in the same place.             */
9837 /*                                                                          */
9838 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because    */
9839 /* this is where individual ones will differ the most - but not true for    */
9840 /* for /48's, etc.                                                          */
9841 /* ------------------------------------------------------------------------ */
9842 static int
9843 ipf_ht_node_cmp(k1, k2)
9844         struct host_node_s *k1, *k2;
9845 {
9846         int i;
9847
9848         i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9849         if (i != 0)
9850                 return i;
9851
9852         if (k1->hn_addr.adf_family == AF_INET)
9853                 return (k2->hn_addr.adf_addr.in4.s_addr -
9854                         k1->hn_addr.adf_addr.in4.s_addr);
9855
9856         i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9857         if (i != 0)
9858                 return i;
9859         i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9860         if (i != 0)
9861                 return i;
9862         i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9863         if (i != 0)
9864                 return i;
9865         i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9866         return i;
9867 }
9868
9869
9870 /* ------------------------------------------------------------------------ */
9871 /* Function:    ipf_ht_node_make_key                                        */
9872 /* Returns:     Nil                                                         */
9873 /* parameters:  htp(I)    - pointer to address tracking structure           */
9874 /*              key(I)    - where to store masked address for lookup        */
9875 /*              family(I) - protocol family of address                      */
9876 /*              addr(I)   - pointer to network address                      */
9877 /*                                                                          */
9878 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9879 /* copy the address passed in into the key structure whilst masking out the */
9880 /* bits that we don't want.                                                 */
9881 /*                                                                          */
9882 /* Because the parser will set ht_netmask to 128 if there is no protocol    */
9883 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we  */
9884 /* have to be wary of that and not allow 32-128 to happen.                  */
9885 /* ------------------------------------------------------------------------ */
9886 static void
9887 ipf_ht_node_make_key(htp, key, family, addr)
9888         host_track_t *htp;
9889         host_node_t *key;
9890         int family;
9891         i6addr_t *addr;
9892 {
9893         key->hn_addr.adf_family = family;
9894         if (family == AF_INET) {
9895                 u_32_t mask;
9896                 int bits;
9897
9898                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9899                 bits = htp->ht_netmask;
9900                 if (bits >= 32) {
9901                         mask = 0xffffffff;
9902                 } else {
9903                         mask = htonl(0xffffffff << (32 - bits));
9904                 }
9905                 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9906 #ifdef USE_INET6
9907         } else {
9908                 int bits = htp->ht_netmask;
9909
9910                 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9911                 if (bits > 96) {
9912                         key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9913                                              htonl(0xffffffff << (128 - bits));
9914                         key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9915                         key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9916                         key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9917                 } else if (bits > 64) {
9918                         key->hn_addr.adf_addr.i6[3] = 0;
9919                         key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9920                                              htonl(0xffffffff << (96 - bits));
9921                         key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9922                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9923                 } else if (bits > 32) {
9924                         key->hn_addr.adf_addr.i6[3] = 0;
9925                         key->hn_addr.adf_addr.i6[2] = 0;
9926                         key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9927                                              htonl(0xffffffff << (64 - bits));
9928                         key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9929                 } else {
9930                         key->hn_addr.adf_addr.i6[3] = 0;
9931                         key->hn_addr.adf_addr.i6[2] = 0;
9932                         key->hn_addr.adf_addr.i6[1] = 0;
9933                         key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9934                                              htonl(0xffffffff << (32 - bits));
9935                 }
9936 #endif
9937         }
9938 }
9939
9940
9941 /* ------------------------------------------------------------------------ */
9942 /* Function:    ipf_ht_node_add                                             */
9943 /* Returns:     int       - 0 == success,  -1 == failure                    */
9944 /* Parameters:  softc(I)  - pointer to soft context main structure          */
9945 /*              htp(I)    - pointer to address tracking structure           */
9946 /*              family(I) - protocol family of address                      */
9947 /*              addr(I)   - pointer to network address                      */
9948 /*                                                                          */
9949 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
9950 /*       ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
9951 /*                                                                          */
9952 /* After preparing the key with the address information to find, look in    */
9953 /* the red-black tree to see if the address is known. A successful call to  */
9954 /* this function can mean one of two things: a new node was added to the    */
9955 /* tree or a matching node exists and we're able to bump up its activity.   */
9956 /* ------------------------------------------------------------------------ */
9957 int
9958 ipf_ht_node_add(softc, htp, family, addr)
9959         ipf_main_softc_t *softc;
9960         host_track_t *htp;
9961         int family;
9962         i6addr_t *addr;
9963 {
9964         host_node_t *h;
9965         host_node_t k;
9966
9967         ipf_ht_node_make_key(htp, &k, family, addr);
9968
9969         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9970         if (h == NULL) {
9971                 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9972                         return -1;
9973                 KMALLOC(h, host_node_t *);
9974                 if (h == NULL) {
9975                         DT(ipf_rb_no_mem);
9976                         LBUMP(ipf_rb_no_mem);
9977                         return -1;
9978                 }
9979
9980                 /*
9981                  * If there was a macro to initialise the RB node then that
9982                  * would get used here, but there isn't...
9983                  */
9984                 bzero((char *)h, sizeof(*h));
9985                 h->hn_addr = k.hn_addr;
9986                 h->hn_addr.adf_family = k.hn_addr.adf_family;
9987                 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9988                 htp->ht_cur_nodes++;
9989         } else {
9990                 if ((htp->ht_max_per_node != 0) &&
9991                     (h->hn_active >= htp->ht_max_per_node)) {
9992                         DT(ipf_rb_node_max);
9993                         LBUMP(ipf_rb_node_max);
9994                         return -1;
9995                 }
9996         }
9997
9998         h->hn_active++;
9999
10000         return 0;
10001 }
10002
10003
10004 /* ------------------------------------------------------------------------ */
10005 /* Function:    ipf_ht_node_del                                             */
10006 /* Returns:     int       - 0 == success,  -1 == failure                    */
10007 /* parameters:  htp(I)    - pointer to address tracking structure           */
10008 /*              family(I) - protocol family of address                      */
10009 /*              addr(I)   - pointer to network address                      */
10010 /*                                                                          */
10011 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS  */
10012 /*       ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp.         */
10013 /*                                                                          */
10014 /* Try and find the address passed in amongst the leavese on this tree to   */
10015 /* be friend. If found then drop the active account for that node drops by  */
10016 /* one. If that count reaches 0, it is time to free it all up.              */
10017 /* ------------------------------------------------------------------------ */
10018 int
10019 ipf_ht_node_del(htp, family, addr)
10020         host_track_t *htp;
10021         int family;
10022         i6addr_t *addr;
10023 {
10024         host_node_t *h;
10025         host_node_t k;
10026
10027         ipf_ht_node_make_key(htp, &k, family, addr);
10028
10029         h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
10030         if (h == NULL) {
10031                 return -1;
10032         } else {
10033                 h->hn_active--;
10034                 if (h->hn_active == 0) {
10035                         (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
10036                         htp->ht_cur_nodes--;
10037                         KFREE(h);
10038                 }
10039         }
10040
10041         return 0;
10042 }
10043
10044
10045 /* ------------------------------------------------------------------------ */
10046 /* Function:    ipf_rb_ht_init                                              */
10047 /* Returns:     Nil                                                         */
10048 /* Parameters:  head(I) - pointer to host tracking structure                */
10049 /*                                                                          */
10050 /* Initialise the host tracking structure to be ready for use above.        */
10051 /* ------------------------------------------------------------------------ */
10052 void
10053 ipf_rb_ht_init(head)
10054         host_track_t *head;
10055 {
10056         RBI_INIT(ipf_rb, &head->ht_root);
10057 }
10058
10059
10060 /* ------------------------------------------------------------------------ */
10061 /* Function:    ipf_rb_ht_freenode                                          */
10062 /* Returns:     Nil                                                         */
10063 /* Parameters:  head(I) - pointer to host tracking structure                */
10064 /*              arg(I)  - additional argument from walk caller              */
10065 /*                                                                          */
10066 /* Free an actual host_node_t structure.                                    */
10067 /* ------------------------------------------------------------------------ */
10068 void
10069 ipf_rb_ht_freenode(node, arg)
10070         host_node_t *node;
10071         void *arg;
10072 {
10073         KFREE(node);
10074 }
10075
10076
10077 /* ------------------------------------------------------------------------ */
10078 /* Function:    ipf_rb_ht_flush                                             */
10079 /* Returns:     Nil                                                         */
10080 /* Parameters:  head(I) - pointer to host tracking structure                */
10081 /*                                                                          */
10082 /* Remove all of the nodes in the tree tracking hosts by calling a walker   */
10083 /* and free'ing each one.                                                   */
10084 /* ------------------------------------------------------------------------ */
10085 void
10086 ipf_rb_ht_flush(head)
10087         host_track_t *head;
10088 {
10089         RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
10090 }
10091
10092
10093 /* ------------------------------------------------------------------------ */
10094 /* Function:    ipf_slowtimer                                               */
10095 /* Returns:     Nil                                                         */
10096 /* Parameters:  ptr(I) - pointer to main ipf soft context structure         */
10097 /*                                                                          */
10098 /* Slowly expire held state for fragments.  Timeouts are set * in           */
10099 /* expectation of this being called twice per second.                       */
10100 /* ------------------------------------------------------------------------ */
10101 void
10102 ipf_slowtimer(softc)
10103         ipf_main_softc_t *softc;
10104 {
10105
10106         ipf_token_expire(softc);
10107         ipf_frag_expire(softc);
10108         ipf_state_expire(softc);
10109         ipf_nat_expire(softc);
10110         ipf_auth_expire(softc);
10111         ipf_lookup_expire(softc);
10112         ipf_rule_expire(softc);
10113         ipf_sync_expire(softc);
10114         softc->ipf_ticks++;
10115 #   if defined(__OpenBSD__)
10116         timeout_add(&ipf_slowtimer_ch, hz/2);
10117 #   endif
10118 }
10119
10120
10121 /* ------------------------------------------------------------------------ */
10122 /* Function:    ipf_inet_mask_add                                           */
10123 /* Returns:     Nil                                                         */
10124 /* Parameters:  bits(I) - pointer to nat context information                */
10125 /*              mtab(I) - pointer to mask hash table structure              */
10126 /*                                                                          */
10127 /* When called, bits represents the mask of a new NAT rule that has just    */
10128 /* been added. This function inserts a bitmask into the array of masks to   */
10129 /* search when searching for a matching NAT rule for a packet.              */
10130 /* Prevention of duplicate masks is achieved by checking the use count for  */
10131 /* a given netmask.                                                         */
10132 /* ------------------------------------------------------------------------ */
10133 void
10134 ipf_inet_mask_add(bits, mtab)
10135         int bits;
10136         ipf_v4_masktab_t *mtab;
10137 {
10138         u_32_t mask;
10139         int i, j;
10140
10141         mtab->imt4_masks[bits]++;
10142         if (mtab->imt4_masks[bits] > 1)
10143                 return;
10144
10145         if (bits == 0)
10146                 mask = 0;
10147         else
10148                 mask = 0xffffffff << (32 - bits);
10149
10150         for (i = 0; i < 33; i++) {
10151                 if (ntohl(mtab->imt4_active[i]) < mask) {
10152                         for (j = 32; j > i; j--)
10153                                 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
10154                         mtab->imt4_active[i] = htonl(mask);
10155                         break;
10156                 }
10157         }
10158         mtab->imt4_max++;
10159 }
10160
10161
10162 /* ------------------------------------------------------------------------ */
10163 /* Function:    ipf_inet_mask_del                                           */
10164 /* Returns:     Nil                                                         */
10165 /* Parameters:  bits(I) - number of bits set in the netmask                 */
10166 /*              mtab(I) - pointer to mask hash table structure              */
10167 /*                                                                          */
10168 /* Remove the 32bit bitmask represented by "bits" from the collection of    */
10169 /* netmasks stored inside of mtab.                                          */
10170 /* ------------------------------------------------------------------------ */
10171 void
10172 ipf_inet_mask_del(bits, mtab)
10173         int bits;
10174         ipf_v4_masktab_t *mtab;
10175 {
10176         u_32_t mask;
10177         int i, j;
10178
10179         mtab->imt4_masks[bits]--;
10180         if (mtab->imt4_masks[bits] > 0)
10181                 return;
10182
10183         mask = htonl(0xffffffff << (32 - bits));
10184         for (i = 0; i < 33; i++) {
10185                 if (mtab->imt4_active[i] == mask) {
10186                         for (j = i + 1; j < 33; j++)
10187                                 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
10188                         break;
10189                 }
10190         }
10191         mtab->imt4_max--;
10192         ASSERT(mtab->imt4_max >= 0);
10193 }
10194
10195
10196 #ifdef USE_INET6
10197 /* ------------------------------------------------------------------------ */
10198 /* Function:    ipf_inet6_mask_add                                          */
10199 /* Returns:     Nil                                                         */
10200 /* Parameters:  bits(I) - number of bits set in mask                        */
10201 /*              mask(I) - pointer to mask to add                            */
10202 /*              mtab(I) - pointer to mask hash table structure              */
10203 /*                                                                          */
10204 /* When called, bitcount represents the mask of a IPv6 NAT map rule that    */
10205 /* has just been added. This function inserts a bitmask into the array of   */
10206 /* masks to search when searching for a matching NAT rule for a packet.     */
10207 /* Prevention of duplicate masks is achieved by checking the use count for  */
10208 /* a given netmask.                                                         */
10209 /* ------------------------------------------------------------------------ */
10210 void
10211 ipf_inet6_mask_add(bits, mask, mtab)
10212         int bits;
10213         i6addr_t *mask;
10214         ipf_v6_masktab_t *mtab;
10215 {
10216         i6addr_t zero;
10217         int i, j;
10218
10219         mtab->imt6_masks[bits]++;
10220         if (mtab->imt6_masks[bits] > 1)
10221                 return;
10222
10223         if (bits == 0) {
10224                 mask = &zero;
10225                 zero.i6[0] = 0;
10226                 zero.i6[1] = 0;
10227                 zero.i6[2] = 0;
10228                 zero.i6[3] = 0;
10229         }
10230
10231         for (i = 0; i < 129; i++) {
10232                 if (IP6_LT(&mtab->imt6_active[i], mask)) {
10233                         for (j = 128; j > i; j--)
10234                                 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
10235                         mtab->imt6_active[i] = *mask;
10236                         break;
10237                 }
10238         }
10239         mtab->imt6_max++;
10240 }
10241
10242
10243 /* ------------------------------------------------------------------------ */
10244 /* Function:    ipf_inet6_mask_del                                          */
10245 /* Returns:     Nil                                                         */
10246 /* Parameters:  bits(I) - number of bits set in mask                        */
10247 /*              mask(I) - pointer to mask to remove                         */
10248 /*              mtab(I) - pointer to mask hash table structure              */
10249 /*                                                                          */
10250 /* Remove the 128bit bitmask represented by "bits" from the collection of   */
10251 /* netmasks stored inside of mtab.                                          */
10252 /* ------------------------------------------------------------------------ */
10253 void
10254 ipf_inet6_mask_del(bits, mask, mtab)
10255         int bits;
10256         i6addr_t *mask;
10257         ipf_v6_masktab_t *mtab;
10258 {
10259         i6addr_t zero;
10260         int i, j;
10261
10262         mtab->imt6_masks[bits]--;
10263         if (mtab->imt6_masks[bits] > 0)
10264                 return;
10265
10266         if (bits == 0)
10267                 mask = &zero;
10268         zero.i6[0] = 0;
10269         zero.i6[1] = 0;
10270         zero.i6[2] = 0;
10271         zero.i6[3] = 0;
10272
10273         for (i = 0; i < 129; i++) {
10274                 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
10275                         for (j = i + 1; j < 129; j++) {
10276                                 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
10277                                 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10278                                         break;
10279                         }
10280                         break;
10281                 }
10282         }
10283         mtab->imt6_max--;
10284         ASSERT(mtab->imt6_max >= 0);
10285 }
10286 #endif