fil.c revision 1.17 1 /* $NetBSD: fil.c,v 1.17 2016/04/03 15:52:37 christos Exp $ */
2
3 /*
4 * Copyright (C) 2012 by Darren Reed.
5 *
6 * See the IPFILTER.LICENCE file for details on licencing.
7 *
8 * Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $
9 *
10 */
11 #if defined(KERNEL) || defined(_KERNEL)
12 # undef KERNEL
13 # undef _KERNEL
14 # define KERNEL 1
15 # define _KERNEL 1
16 #endif
17 #include <sys/errno.h>
18 #include <sys/types.h>
19 #include <sys/param.h>
20 #include <sys/time.h>
21 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
22 (__FreeBSD_version >= 220000)
23 # if (__FreeBSD_version >= 400000)
24 # if !defined(IPFILTER_LKM)
25 # include "opt_inet6.h"
26 # endif
27 # if (__FreeBSD_version == 400019)
28 # define CSUM_DELAY_DATA
29 # endif
30 # endif
31 # include <sys/filio.h>
32 #else
33 # include <sys/ioctl.h>
34 #endif
35 #if (defined(__SVR4) || defined(__svr4__)) && defined(sun)
36 # include <sys/filio.h>
37 #endif
38 #if !defined(_AIX51)
39 # include <sys/fcntl.h>
40 #endif
41 #if defined(_KERNEL)
42 # include <sys/systm.h>
43 # include <sys/file.h>
44 #else
45 # include <stdio.h>
46 # include <string.h>
47 # include <stdlib.h>
48 # include <stddef.h>
49 # include <sys/file.h>
50 # define _KERNEL
51 # ifdef __OpenBSD__
52 struct file;
53 # endif
54 # include <sys/uio.h>
55 # undef _KERNEL
56 #endif
57 #if !defined(__SVR4) && !defined(__svr4__) && !defined(__hpux) && \
58 !defined(linux)
59 # include <sys/mbuf.h>
60 #else
61 # if !defined(linux)
62 # include <sys/byteorder.h>
63 # endif
64 # if (SOLARIS2 < 5) && defined(sun)
65 # include <sys/dditypes.h>
66 # endif
67 #endif
68 #ifdef __hpux
69 # define _NET_ROUTE_INCLUDED
70 #endif
71 #if !defined(linux)
72 # include <sys/protosw.h>
73 #endif
74 #include <sys/socket.h>
75 #include <net/if.h>
76 #ifdef sun
77 # include <net/af.h>
78 #endif
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #if defined(__sgi) && defined(IFF_DRVRLOCK) /* IRIX 6 */
83 # include <sys/hashing.h>
84 # include <netinet/in_var.h>
85 #endif
86 #include <netinet/tcp.h>
87 #if (!defined(__sgi) && !defined(AIX)) || defined(_KERNEL)
88 # include <netinet/udp.h>
89 # include <netinet/ip_icmp.h>
90 #endif
91 #ifdef __hpux
92 # undef _NET_ROUTE_INCLUDED
93 #endif
94 #ifdef __osf__
95 # undef _RADIX_H_
96 #endif
97 #include "netinet/ip_compat.h"
98 #ifdef USE_INET6
99 # include <netinet/icmp6.h>
100 # if !SOLARIS && defined(_KERNEL) && !defined(__osf__) && !defined(__hpux)
101 # include <netinet6/in6_var.h>
102 # endif
103 #endif
104 #include "netinet/ip_fil.h"
105 #include "netinet/ip_nat.h"
106 #include "netinet/ip_frag.h"
107 #include "netinet/ip_state.h"
108 #include "netinet/ip_proxy.h"
109 #include "netinet/ip_auth.h"
110 #ifdef IPFILTER_SCAN
111 # include "netinet/ip_scan.h"
112 #endif
113 #include "netinet/ip_sync.h"
114 #include "netinet/ip_lookup.h"
115 #include "netinet/ip_pool.h"
116 #include "netinet/ip_htable.h"
117 #ifdef IPFILTER_COMPILED
118 # include "netinet/ip_rules.h"
119 #endif
120 #if defined(IPFILTER_BPF) && defined(_KERNEL)
121 # include <net/bpf.h>
122 #endif
123 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 300000)
124 # include <sys/malloc.h>
125 #endif
126 #include "netinet/ipl.h"
127
128 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
129 # include <sys/callout.h>
130 extern struct callout ipf_slowtimer_ch;
131 #endif
132 #if defined(__OpenBSD__)
133 # include <sys/timeout.h>
134 extern struct timeout ipf_slowtimer_ch;
135 #endif
136 /* END OF INCLUDES */
137
138 #if !defined(lint)
139 #if defined(__NetBSD__)
140 #include <sys/cdefs.h>
141 __KERNEL_RCSID(0, "$NetBSD: fil.c,v 1.17 2016/04/03 15:52:37 christos Exp $");
142 #else
143 static const char sccsid[] = "@(#)fil.c 1.36 6/5/96 (C) 1993-2000 Darren Reed";
144 static const char rcsid[] = "@(#)Id: fil.c,v 1.1.1.2 2012/07/22 13:45:07 darrenr Exp $";
145 #endif
146 #endif
147
148 #ifndef _KERNEL
149 # include "ipf.h"
150 # include "ipt.h"
151 extern int opts;
152 extern int blockreason;
153 #endif /* _KERNEL */
154
155 #define LBUMP(x) softc->x++
156 #define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
157
158 static INLINE int ipf_check_ipf(fr_info_t *, frentry_t *, int);
159 static u_32_t ipf_checkcipso(fr_info_t *, u_char *, int);
160 static u_32_t ipf_checkripso(u_char *);
161 static u_32_t ipf_decaps(fr_info_t *, u_32_t, int);
162 #ifdef IPFILTER_LOG
163 static frentry_t *ipf_dolog(fr_info_t *, u_32_t *);
164 #endif
165 static int ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
166 static int ipf_flush_groups(ipf_main_softc_t *, frgroup_t **, int);
167 static ipfunc_t ipf_findfunc(ipfunc_t);
168 static void *ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
169 i6addr_t *, i6addr_t *);
170 static frentry_t *ipf_firewall(fr_info_t *, u_32_t *);
171 static int ipf_fr_matcharray(fr_info_t *, int *);
172 static int ipf_frruleiter(ipf_main_softc_t *, void *, int, void *);
173 static void ipf_funcfini(ipf_main_softc_t *, frentry_t *);;
174 static int ipf_funcinit(ipf_main_softc_t *, frentry_t *);
175 static int ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
176 ipfgeniter_t *);
177 static void ipf_getstat(ipf_main_softc_t *,
178 struct friostat *, int);
179 static int ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
180 static void ipf_group_free(frgroup_t *);
181 static int ipf_grpmapfini(struct ipf_main_softc_s *, frentry_t *);
182 static int ipf_grpmapinit(struct ipf_main_softc_s *, frentry_t *);
183 static frentry_t *ipf_nextrule(ipf_main_softc_t *, int, int,
184 frentry_t *, int);
185 static int ipf_portcheck(frpcmp_t *, u_32_t);
186 static INLINE int ipf_pr_ah(fr_info_t *);
187 static INLINE void ipf_pr_esp(fr_info_t *);
188 static INLINE void ipf_pr_gre(fr_info_t *);
189 static INLINE void ipf_pr_udp(fr_info_t *);
190 static INLINE void ipf_pr_tcp(fr_info_t *);
191 static INLINE void ipf_pr_icmp(fr_info_t *);
192 static INLINE void ipf_pr_ipv4hdr(fr_info_t *);
193 static INLINE void ipf_pr_short(fr_info_t *, int);
194 static INLINE int ipf_pr_tcpcommon(fr_info_t *);
195 static INLINE int ipf_pr_udpcommon(fr_info_t *);
196 static void ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
197 int, int);
198 static void ipf_rule_expire_insert(ipf_main_softc_t *,
199 frentry_t *, int);
200 static int ipf_synclist(ipf_main_softc_t *, frentry_t *, void *);
201 static void ipf_token_flush(ipf_main_softc_t *);
202 static void ipf_token_unlink(ipf_main_softc_t *, ipftoken_t *);
203 static ipftuneable_t *ipf_tune_findbyname(ipftuneable_t *, const char *);
204 static ipftuneable_t *ipf_tune_findbycookie(ipftuneable_t **, void *,
205 void **);
206 static int ipf_updateipid(fr_info_t *);
207 static int ipf_settimeout(struct ipf_main_softc_s *,
208 struct ipftuneable *, ipftuneval_t *);
209
210
211 /*
212 * bit values for identifying presence of individual IP options
213 * All of these tables should be ordered by increasing key value on the left
214 * hand side to allow for binary searching of the array and include a trailer
215 * with a 0 for the bitmask for linear searches to easily find the end with.
216 */
217 static const struct optlist ipopts[20] = {
218 { IPOPT_NOP, 0x000001 },
219 { IPOPT_RR, 0x000002 },
220 { IPOPT_ZSU, 0x000004 },
221 { IPOPT_MTUP, 0x000008 },
222 { IPOPT_MTUR, 0x000010 },
223 { IPOPT_ENCODE, 0x000020 },
224 { IPOPT_TS, 0x000040 },
225 { IPOPT_TR, 0x000080 },
226 { IPOPT_SECURITY, 0x000100 },
227 { IPOPT_LSRR, 0x000200 },
228 { IPOPT_E_SEC, 0x000400 },
229 { IPOPT_CIPSO, 0x000800 },
230 { IPOPT_SATID, 0x001000 },
231 { IPOPT_SSRR, 0x002000 },
232 { IPOPT_ADDEXT, 0x004000 },
233 { IPOPT_VISA, 0x008000 },
234 { IPOPT_IMITD, 0x010000 },
235 { IPOPT_EIP, 0x020000 },
236 { IPOPT_FINN, 0x040000 },
237 { 0, 0x000000 }
238 };
239
240 #ifdef USE_INET6
241 static struct optlist ip6exthdr[] = {
242 { IPPROTO_HOPOPTS, 0x000001 },
243 { IPPROTO_IPV6, 0x000002 },
244 { IPPROTO_ROUTING, 0x000004 },
245 { IPPROTO_FRAGMENT, 0x000008 },
246 { IPPROTO_ESP, 0x000010 },
247 { IPPROTO_AH, 0x000020 },
248 { IPPROTO_NONE, 0x000040 },
249 { IPPROTO_DSTOPTS, 0x000080 },
250 { IPPROTO_MOBILITY, 0x000100 },
251 { 0, 0 }
252 };
253 #endif
254
255 /*
256 * bit values for identifying presence of individual IP security options
257 */
258 static const struct optlist secopt[8] = {
259 { IPSO_CLASS_RES4, 0x01 },
260 { IPSO_CLASS_TOPS, 0x02 },
261 { IPSO_CLASS_SECR, 0x04 },
262 { IPSO_CLASS_RES3, 0x08 },
263 { IPSO_CLASS_CONF, 0x10 },
264 { IPSO_CLASS_UNCL, 0x20 },
265 { IPSO_CLASS_RES2, 0x40 },
266 { IPSO_CLASS_RES1, 0x80 }
267 };
268
269 char ipfilter_version[] = IPL_VERSION;
270
271 int ipf_features = 0
272 #ifdef IPFILTER_LKM
273 | IPF_FEAT_LKM
274 #endif
275 #ifdef IPFILTER_LOG
276 | IPF_FEAT_LOG
277 #endif
278 | IPF_FEAT_LOOKUP
279 #ifdef IPFILTER_BPF
280 | IPF_FEAT_BPF
281 #endif
282 #ifdef IPFILTER_COMPILED
283 | IPF_FEAT_COMPILED
284 #endif
285 #ifdef IPFILTER_CKSUM
286 | IPF_FEAT_CKSUM
287 #endif
288 | IPF_FEAT_SYNC
289 #ifdef IPFILTER_SCAN
290 | IPF_FEAT_SCAN
291 #endif
292 #ifdef USE_INET6
293 | IPF_FEAT_IPV6
294 #endif
295 ;
296
297
298 /*
299 * Table of functions available for use with call rules.
300 */
301 static ipfunc_resolve_t ipf_availfuncs[] = {
302 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
303 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
304 { "", NULL, NULL, NULL }
305 };
306
307 static ipftuneable_t ipf_main_tuneables[] = {
308 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
309 "ipf_flags", 0, 0xffffffff,
310 stsizeof(ipf_main_softc_t, ipf_flags),
311 0, NULL, NULL },
312 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
313 "active", 0, 0,
314 stsizeof(ipf_main_softc_t, ipf_active),
315 IPFT_RDONLY, NULL, NULL },
316 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
317 "control_forwarding", 0, 1,
318 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
319 0, NULL, NULL },
320 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
321 "update_ipid", 0, 1,
322 stsizeof(ipf_main_softc_t, ipf_update_ipid),
323 0, NULL, NULL },
324 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
325 "chksrc", 0, 1,
326 stsizeof(ipf_main_softc_t, ipf_chksrc),
327 0, NULL, NULL },
328 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
329 "min_ttl", 0, 1,
330 stsizeof(ipf_main_softc_t, ipf_minttl),
331 0, NULL, NULL },
332 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
333 "icmp_minfragmtu", 0, 1,
334 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
335 0, NULL, NULL },
336 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
337 "default_pass", 0, 0xffffffff,
338 stsizeof(ipf_main_softc_t, ipf_pass),
339 0, NULL, NULL },
340 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
341 "tcp_idle_timeout", 1, 0x7fffffff,
342 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
343 0, NULL, ipf_settimeout },
344 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
345 "tcp_close_wait", 1, 0x7fffffff,
346 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
347 0, NULL, ipf_settimeout },
348 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
349 "tcp_last_ack", 1, 0x7fffffff,
350 stsizeof(ipf_main_softc_t, ipf_tcplastack),
351 0, NULL, ipf_settimeout },
352 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
353 "tcp_timeout", 1, 0x7fffffff,
354 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
355 0, NULL, ipf_settimeout },
356 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
357 "tcp_syn_sent", 1, 0x7fffffff,
358 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
359 0, NULL, ipf_settimeout },
360 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
361 "tcp_syn_received", 1, 0x7fffffff,
362 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
363 0, NULL, ipf_settimeout },
364 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
365 "tcp_closed", 1, 0x7fffffff,
366 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
367 0, NULL, ipf_settimeout },
368 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
369 "tcp_half_closed", 1, 0x7fffffff,
370 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
371 0, NULL, ipf_settimeout },
372 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
373 "tcp_time_wait", 1, 0x7fffffff,
374 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
375 0, NULL, ipf_settimeout },
376 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
377 "udp_timeout", 1, 0x7fffffff,
378 stsizeof(ipf_main_softc_t, ipf_udptimeout),
379 0, NULL, ipf_settimeout },
380 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
381 "udp_ack_timeout", 1, 0x7fffffff,
382 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
383 0, NULL, ipf_settimeout },
384 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
385 "icmp_timeout", 1, 0x7fffffff,
386 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
387 0, NULL, ipf_settimeout },
388 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
389 "icmp_ack_timeout", 1, 0x7fffffff,
390 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
391 0, NULL, ipf_settimeout },
392 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
393 "ip_timeout", 1, 0x7fffffff,
394 stsizeof(ipf_main_softc_t, ipf_iptimeout),
395 0, NULL, ipf_settimeout },
396 #if defined(INSTANCES) && defined(_KERNEL)
397 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
398 "intercept_loopback", 0, 1,
399 stsizeof(ipf_main_softc_t, ipf_get_loopback),
400 0, NULL, ipf_set_loopback },
401 #endif
402 { { 0 },
403 NULL, 0, 0,
404 0,
405 0, NULL, NULL }
406 };
407
408
409 /*
410 * The next section of code is a a collection of small routines that set
411 * fields in the fr_info_t structure passed based on properties of the
412 * current packet. There are different routines for the same protocol
413 * for each of IPv4 and IPv6. Adding a new protocol, for which there
414 * will "special" inspection for setup, is now more easily done by adding
415 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
416 * adding more code to a growing switch statement.
417 */
418 #ifdef USE_INET6
419 static INLINE int ipf_pr_ah6(fr_info_t *);
420 static INLINE void ipf_pr_esp6(fr_info_t *);
421 static INLINE void ipf_pr_gre6(fr_info_t *);
422 static INLINE void ipf_pr_udp6(fr_info_t *);
423 static INLINE void ipf_pr_tcp6(fr_info_t *);
424 static INLINE void ipf_pr_icmp6(fr_info_t *);
425 static INLINE void ipf_pr_ipv6hdr(fr_info_t *);
426 static INLINE void ipf_pr_short6(fr_info_t *, int);
427 static INLINE int ipf_pr_hopopts6(fr_info_t *);
428 static INLINE int ipf_pr_mobility6(fr_info_t *);
429 static INLINE int ipf_pr_routing6(fr_info_t *);
430 static INLINE int ipf_pr_dstopts6(fr_info_t *);
431 static INLINE int ipf_pr_fragment6(fr_info_t *);
432 static INLINE struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
433
434
435 /* ------------------------------------------------------------------------ */
436 /* Function: ipf_pr_short6 */
437 /* Returns: void */
438 /* Parameters: fin(I) - pointer to packet information */
439 /* xmin(I) - minimum header size */
440 /* */
441 /* IPv6 Only */
442 /* This is function enforces the 'is a packet too short to be legit' rule */
443 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
444 /* for ipf_pr_short() for more details. */
445 /* ------------------------------------------------------------------------ */
446 static INLINE void
447 ipf_pr_short6(fr_info_t *fin, int xmin)
448 {
449
450 if (fin->fin_dlen < xmin)
451 fin->fin_flx |= FI_SHORT;
452 }
453
454
455 /* ------------------------------------------------------------------------ */
456 /* Function: ipf_pr_ipv6hdr */
457 /* Returns: void */
458 /* Parameters: fin(I) - pointer to packet information */
459 /* */
460 /* IPv6 Only */
461 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
462 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
463 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
464 /* of that possibility arising. */
465 /* ------------------------------------------------------------------------ */
466 static INLINE void
467 ipf_pr_ipv6hdr(fr_info_t *fin)
468 {
469 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
470 int p, go = 1, i, hdrcount;
471 fr_ip_t *fi = &fin->fin_fi;
472
473 fin->fin_off = 0;
474
475 fi->fi_tos = 0;
476 fi->fi_optmsk = 0;
477 fi->fi_secmsk = 0;
478 fi->fi_auth = 0;
479
480 p = ip6->ip6_nxt;
481 fin->fin_crc = p;
482 fi->fi_ttl = ip6->ip6_hlim;
483 fi->fi_src.in6 = ip6->ip6_src;
484 fin->fin_crc += fi->fi_src.i6[0];
485 fin->fin_crc += fi->fi_src.i6[1];
486 fin->fin_crc += fi->fi_src.i6[2];
487 fin->fin_crc += fi->fi_src.i6[3];
488 fi->fi_dst.in6 = ip6->ip6_dst;
489 fin->fin_crc += fi->fi_dst.i6[0];
490 fin->fin_crc += fi->fi_dst.i6[1];
491 fin->fin_crc += fi->fi_dst.i6[2];
492 fin->fin_crc += fi->fi_dst.i6[3];
493 fin->fin_id = 0;
494 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
495 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
496
497 hdrcount = 0;
498 while (go && !(fin->fin_flx & FI_SHORT)) {
499 switch (p)
500 {
501 case IPPROTO_UDP :
502 ipf_pr_udp6(fin);
503 go = 0;
504 break;
505
506 case IPPROTO_TCP :
507 ipf_pr_tcp6(fin);
508 go = 0;
509 break;
510
511 case IPPROTO_ICMPV6 :
512 ipf_pr_icmp6(fin);
513 go = 0;
514 break;
515
516 case IPPROTO_GRE :
517 ipf_pr_gre6(fin);
518 go = 0;
519 break;
520
521 case IPPROTO_HOPOPTS :
522 p = ipf_pr_hopopts6(fin);
523 break;
524
525 case IPPROTO_MOBILITY :
526 p = ipf_pr_mobility6(fin);
527 break;
528
529 case IPPROTO_DSTOPTS :
530 p = ipf_pr_dstopts6(fin);
531 break;
532
533 case IPPROTO_ROUTING :
534 p = ipf_pr_routing6(fin);
535 break;
536
537 case IPPROTO_AH :
538 p = ipf_pr_ah6(fin);
539 break;
540
541 case IPPROTO_ESP :
542 ipf_pr_esp6(fin);
543 go = 0;
544 break;
545
546 case IPPROTO_IPV6 :
547 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
548 if (ip6exthdr[i].ol_val == p) {
549 fin->fin_flx |= ip6exthdr[i].ol_bit;
550 break;
551 }
552 go = 0;
553 break;
554
555 case IPPROTO_NONE :
556 go = 0;
557 break;
558
559 case IPPROTO_FRAGMENT :
560 p = ipf_pr_fragment6(fin);
561 /*
562 * Given that the only fragments we want to let through
563 * (where fin_off != 0) are those where the non-first
564 * fragments only have data, we can safely stop looking
565 * at headers if this is a non-leading fragment.
566 */
567 if (fin->fin_off != 0)
568 go = 0;
569 break;
570
571 default :
572 go = 0;
573 break;
574 }
575 hdrcount++;
576
577 /*
578 * It is important to note that at this point, for the
579 * extension headers (go != 0), the entire header may not have
580 * been pulled up when the code gets to this point. This is
581 * only done for "go != 0" because the other header handlers
582 * will all pullup their complete header. The other indicator
583 * of an incomplete packet is that this was just an extension
584 * header.
585 */
586 if ((go != 0) && (p != IPPROTO_NONE) &&
587 (ipf_pr_pullup(fin, 0) == -1)) {
588 p = IPPROTO_NONE;
589 break;
590 }
591 }
592
593 /*
594 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
595 * and destroy whatever packet was here. The caller of this function
596 * expects us to return if there is a problem with ipf_pullup.
597 */
598 if (fin->fin_m == NULL) {
599 ipf_main_softc_t *softc = fin->fin_main_soft;
600
601 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
602 return;
603 }
604
605 fi->fi_p = p;
606
607 /*
608 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
609 * "go != 0" imples the above loop hasn't arrived at a layer 4 header.
610 */
611 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
612 ipf_main_softc_t *softc = fin->fin_main_soft;
613
614 fin->fin_flx |= FI_BAD;
615 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
616 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
617 }
618 }
619
620
621 /* ------------------------------------------------------------------------ */
622 /* Function: ipf_pr_ipv6exthdr */
623 /* Returns: struct ip6_ext * - pointer to the start of the next header */
624 /* or NULL if there is a prolblem. */
625 /* Parameters: fin(I) - pointer to packet information */
626 /* multiple(I) - flag indicating yes/no if multiple occurances */
627 /* of this extension header are allowed. */
628 /* proto(I) - protocol number for this extension header */
629 /* */
630 /* IPv6 Only */
631 /* This function embodies a number of common checks that all IPv6 extension */
632 /* headers must be subjected to. For example, making sure the packet is */
633 /* big enough for it to be in, checking if it is repeated and setting a */
634 /* flag to indicate its presence. */
635 /* ------------------------------------------------------------------------ */
636 static INLINE struct ip6_ext *
637 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
638 {
639 ipf_main_softc_t *softc = fin->fin_main_soft;
640 struct ip6_ext *hdr;
641 u_short shift;
642 int i;
643
644 fin->fin_flx |= FI_V6EXTHDR;
645
646 /* 8 is default length of extension hdr */
647 if ((fin->fin_dlen - 8) < 0) {
648 fin->fin_flx |= FI_SHORT;
649 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
650 return NULL;
651 }
652
653 if (ipf_pr_pullup(fin, 8) == -1) {
654 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
655 return NULL;
656 }
657
658 hdr = fin->fin_dp;
659 switch (proto)
660 {
661 case IPPROTO_FRAGMENT :
662 shift = 8;
663 break;
664 default :
665 shift = 8 + (hdr->ip6e_len << 3);
666 break;
667 }
668
669 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
670 fin->fin_flx |= FI_BAD;
671 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
672 return NULL;
673 }
674
675 fin->fin_dp = (char *)fin->fin_dp + shift;
676 fin->fin_dlen -= shift;
677
678 /*
679 * If we have seen a fragment header, do not set any flags to indicate
680 * the presence of this extension header as it has no impact on the
681 * end result until after it has been defragmented.
682 */
683 if (fin->fin_flx & FI_FRAG)
684 return hdr;
685
686 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
687 if (ip6exthdr[i].ol_val == proto) {
688 /*
689 * Most IPv6 extension headers are only allowed once.
690 */
691 if ((multiple == 0) &&
692 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0))
693 fin->fin_flx |= FI_BAD;
694 else
695 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
696 break;
697 }
698
699 return hdr;
700 }
701
702
703 /* ------------------------------------------------------------------------ */
704 /* Function: ipf_pr_hopopts6 */
705 /* Returns: int - value of the next header or IPPROTO_NONE if error */
706 /* Parameters: fin(I) - pointer to packet information */
707 /* */
708 /* IPv6 Only */
709 /* This is function checks pending hop by hop options extension header */
710 /* ------------------------------------------------------------------------ */
711 static INLINE int
712 ipf_pr_hopopts6(fr_info_t *fin)
713 {
714 struct ip6_ext *hdr;
715
716 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
717 if (hdr == NULL)
718 return IPPROTO_NONE;
719 return hdr->ip6e_nxt;
720 }
721
722
723 /* ------------------------------------------------------------------------ */
724 /* Function: ipf_pr_mobility6 */
725 /* Returns: int - value of the next header or IPPROTO_NONE if error */
726 /* Parameters: fin(I) - pointer to packet information */
727 /* */
728 /* IPv6 Only */
729 /* This is function checks the IPv6 mobility extension header */
730 /* ------------------------------------------------------------------------ */
731 static INLINE int
732 ipf_pr_mobility6(fr_info_t *fin)
733 {
734 struct ip6_ext *hdr;
735
736 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
737 if (hdr == NULL)
738 return IPPROTO_NONE;
739 return hdr->ip6e_nxt;
740 }
741
742
743 /* ------------------------------------------------------------------------ */
744 /* Function: ipf_pr_routing6 */
745 /* Returns: int - value of the next header or IPPROTO_NONE if error */
746 /* Parameters: fin(I) - pointer to packet information */
747 /* */
748 /* IPv6 Only */
749 /* This is function checks pending routing extension header */
750 /* ------------------------------------------------------------------------ */
751 static INLINE int
752 ipf_pr_routing6(fr_info_t *fin)
753 {
754 struct ip6_routing *hdr;
755
756 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
757 if (hdr == NULL)
758 return IPPROTO_NONE;
759
760 switch (hdr->ip6r_type)
761 {
762 case 0 :
763 /*
764 * Nasty extension header length?
765 */
766 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
767 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
768 ipf_main_softc_t *softc = fin->fin_main_soft;
769
770 fin->fin_flx |= FI_BAD;
771 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
772 return IPPROTO_NONE;
773 }
774 break;
775
776 default :
777 break;
778 }
779
780 return hdr->ip6r_nxt;
781 }
782
783
784 /* ------------------------------------------------------------------------ */
785 /* Function: ipf_pr_fragment6 */
786 /* Returns: int - value of the next header or IPPROTO_NONE if error */
787 /* Parameters: fin(I) - pointer to packet information */
788 /* */
789 /* IPv6 Only */
790 /* Examine the IPv6 fragment header and extract fragment offset information.*/
791 /* */
792 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
793 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
794 /* packets with a fragment header can fit into. They are as follows: */
795 /* */
796 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
797 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
798 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
799 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
800 /* 5. [IPV6][0-n EH][FH][data] */
801 /* */
802 /* IPV6 = IPv6 header, FH = Fragment Header, */
803 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
804 /* */
805 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
806 /* scenario in which they happen is in extreme circumstances that are most */
807 /* likely to be an indication of an attack rather than normal traffic. */
808 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
809 /* are two rules that can be used to guard against type 3 packets: L4 */
810 /* headers must always be in a packet that has the offset field set to 0 */
811 /* and no packet is allowed to overlay that where offset = 0. */
812 /* ------------------------------------------------------------------------ */
813 static INLINE int
814 ipf_pr_fragment6(fr_info_t *fin)
815 {
816 ipf_main_softc_t *softc = fin->fin_main_soft;
817 struct ip6_frag *frag;
818
819 fin->fin_flx |= FI_FRAG;
820
821 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
822 if (frag == NULL) {
823 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
824 return IPPROTO_NONE;
825 }
826
827 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
828 /*
829 * Any fragment that isn't the last fragment must have its
830 * length as a multiple of 8.
831 */
832 if ((fin->fin_plen & 7) != 0)
833 fin->fin_flx |= FI_BAD;
834 }
835
836 fin->fin_fraghdr = frag;
837 fin->fin_id = frag->ip6f_ident;
838 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
839 if (fin->fin_off != 0)
840 fin->fin_flx |= FI_FRAGBODY;
841
842 /*
843 * Jumbograms aren't handled, so the max. length is 64k
844 */
845 if ((fin->fin_off << 3) + fin->fin_dlen > 65535)
846 fin->fin_flx |= FI_BAD;
847
848 /*
849 * We don't know where the transport layer header (or whatever is next
850 * is), as it could be behind destination options (amongst others) so
851 * return the fragment header as the type of packet this is. Note that
852 * this effectively disables the fragment cache for > 1 protocol at a
853 * time.
854 */
855 return frag->ip6f_nxt;
856 }
857
858
859 /* ------------------------------------------------------------------------ */
860 /* Function: ipf_pr_dstopts6 */
861 /* Returns: int - value of the next header or IPPROTO_NONE if error */
862 /* Parameters: fin(I) - pointer to packet information */
863 /* */
864 /* IPv6 Only */
865 /* This is function checks pending destination options extension header */
866 /* ------------------------------------------------------------------------ */
867 static INLINE int
868 ipf_pr_dstopts6(fr_info_t *fin)
869 {
870 ipf_main_softc_t *softc = fin->fin_main_soft;
871 struct ip6_ext *hdr;
872
873 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
874 if (hdr == NULL) {
875 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
876 return IPPROTO_NONE;
877 }
878 return hdr->ip6e_nxt;
879 }
880
881
882 /* ------------------------------------------------------------------------ */
883 /* Function: ipf_pr_icmp6 */
884 /* Returns: void */
885 /* Parameters: fin(I) - pointer to packet information */
886 /* */
887 /* IPv6 Only */
888 /* This routine is mainly concerned with determining the minimum valid size */
889 /* for an ICMPv6 packet. */
890 /* ------------------------------------------------------------------------ */
891 static INLINE void
892 ipf_pr_icmp6(fr_info_t *fin)
893 {
894 int minicmpsz = sizeof(struct icmp6_hdr);
895 struct icmp6_hdr *icmp6;
896
897 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
898 ipf_main_softc_t *softc = fin->fin_main_soft;
899
900 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
901 return;
902 }
903
904 if (fin->fin_dlen > 1) {
905 ip6_t *ip6;
906
907 icmp6 = fin->fin_dp;
908
909 fin->fin_data[0] = *(u_short *)icmp6;
910
911 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
912 fin->fin_flx |= FI_ICMPQUERY;
913
914 switch (icmp6->icmp6_type)
915 {
916 case ICMP6_ECHO_REPLY :
917 case ICMP6_ECHO_REQUEST :
918 if (fin->fin_dlen >= 6)
919 fin->fin_data[1] = icmp6->icmp6_id;
920 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
921 break;
922
923 case ICMP6_DST_UNREACH :
924 case ICMP6_PACKET_TOO_BIG :
925 case ICMP6_TIME_EXCEEDED :
926 case ICMP6_PARAM_PROB :
927 fin->fin_flx |= FI_ICMPERR;
928 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
929 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
930 break;
931
932 if (M_LEN(fin->fin_m) < fin->fin_plen) {
933 if (ipf_coalesce(fin) != 1)
934 return;
935 }
936
937 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
938 return;
939
940 /*
941 * If the destination of this packet doesn't match the
942 * source of the original packet then this packet is
943 * not correct.
944 */
945 icmp6 = fin->fin_dp;
946 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
947 if (IP6_NEQ(&fin->fin_fi.fi_dst,
948 &ip6->ip6_src))
949 fin->fin_flx |= FI_BAD;
950 break;
951 default :
952 break;
953 }
954 }
955
956 ipf_pr_short6(fin, minicmpsz);
957 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
958 u_char p = fin->fin_p;
959
960 fin->fin_p = IPPROTO_ICMPV6;
961 ipf_checkv6sum(fin);
962 fin->fin_p = p;
963 }
964 }
965
966
967 /* ------------------------------------------------------------------------ */
968 /* Function: ipf_pr_udp6 */
969 /* Returns: void */
970 /* Parameters: fin(I) - pointer to packet information */
971 /* */
972 /* IPv6 Only */
973 /* Analyse the packet for IPv6/UDP properties. */
974 /* Is not expected to be called for fragmented packets. */
975 /* ------------------------------------------------------------------------ */
976 static INLINE void
977 ipf_pr_udp6(fr_info_t *fin)
978 {
979
980 if (ipf_pr_udpcommon(fin) == 0) {
981 u_char p = fin->fin_p;
982
983 fin->fin_p = IPPROTO_UDP;
984 ipf_checkv6sum(fin);
985 fin->fin_p = p;
986 }
987 }
988
989
990 /* ------------------------------------------------------------------------ */
991 /* Function: ipf_pr_tcp6 */
992 /* Returns: void */
993 /* Parameters: fin(I) - pointer to packet information */
994 /* */
995 /* IPv6 Only */
996 /* Analyse the packet for IPv6/TCP properties. */
997 /* Is not expected to be called for fragmented packets. */
998 /* ------------------------------------------------------------------------ */
999 static INLINE void
1000 ipf_pr_tcp6(fr_info_t *fin)
1001 {
1002
1003 if (ipf_pr_tcpcommon(fin) == 0) {
1004 u_char p = fin->fin_p;
1005
1006 fin->fin_p = IPPROTO_TCP;
1007 ipf_checkv6sum(fin);
1008 fin->fin_p = p;
1009 }
1010 }
1011
1012
1013 /* ------------------------------------------------------------------------ */
1014 /* Function: ipf_pr_esp6 */
1015 /* Returns: void */
1016 /* Parameters: fin(I) - pointer to packet information */
1017 /* */
1018 /* IPv6 Only */
1019 /* Analyse the packet for ESP properties. */
1020 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1021 /* even though the newer ESP packets must also have a sequence number that */
1022 /* is 32bits as well, it is not possible(?) to determine the version from a */
1023 /* simple packet header. */
1024 /* ------------------------------------------------------------------------ */
1025 static INLINE void
1026 ipf_pr_esp6(fr_info_t *fin)
1027 {
1028
1029 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1030 ipf_main_softc_t *softc = fin->fin_main_soft;
1031
1032 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1033 return;
1034 }
1035 }
1036
1037
1038 /* ------------------------------------------------------------------------ */
1039 /* Function: ipf_pr_ah6 */
1040 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1041 /* Parameters: fin(I) - pointer to packet information */
1042 /* */
1043 /* IPv6 Only */
1044 /* Analyse the packet for AH properties. */
1045 /* The minimum length is taken to be the combination of all fields in the */
1046 /* header being present and no authentication data (null algorithm used.) */
1047 /* ------------------------------------------------------------------------ */
1048 static INLINE int
1049 ipf_pr_ah6(fr_info_t *fin)
1050 {
1051 authhdr_t *ah;
1052
1053 fin->fin_flx |= FI_AH;
1054
1055 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1056 if (ah == NULL) {
1057 ipf_main_softc_t *softc = fin->fin_main_soft;
1058
1059 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1060 return IPPROTO_NONE;
1061 }
1062
1063 ipf_pr_short6(fin, sizeof(*ah));
1064
1065 /*
1066 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1067 * enough data to satisfy ah_next (the very first one.)
1068 */
1069 return ah->ah_next;
1070 }
1071
1072
1073 /* ------------------------------------------------------------------------ */
1074 /* Function: ipf_pr_gre6 */
1075 /* Returns: void */
1076 /* Parameters: fin(I) - pointer to packet information */
1077 /* */
1078 /* Analyse the packet for GRE properties. */
1079 /* ------------------------------------------------------------------------ */
1080 static INLINE void
1081 ipf_pr_gre6(fr_info_t *fin)
1082 {
1083 grehdr_t *gre;
1084
1085 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1086 ipf_main_softc_t *softc = fin->fin_main_soft;
1087
1088 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1089 return;
1090 }
1091
1092 gre = fin->fin_dp;
1093 if (GRE_REV(gre->gr_flags) == 1)
1094 fin->fin_data[0] = gre->gr_call;
1095 }
1096 #endif /* USE_INET6 */
1097
1098
1099 /* ------------------------------------------------------------------------ */
1100 /* Function: ipf_pr_pullup */
1101 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1102 /* Parameters: fin(I) - pointer to packet information */
1103 /* plen(I) - length (excluding L3 header) to pullup */
1104 /* */
1105 /* Short inline function to cut down on code duplication to perform a call */
1106 /* to ipf_pullup to ensure there is the required amount of data, */
1107 /* consecutively in the packet buffer. */
1108 /* */
1109 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1110 /* points to the first byte after the complete layer 3 header, which will */
1111 /* include all of the known extension headers for IPv6 or options for IPv4. */
1112 /* */
1113 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1114 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1115 /* - fin_ip) to what is passed through. */
1116 /* ------------------------------------------------------------------------ */
1117 int
1118 ipf_pr_pullup(fr_info_t *fin, int plen)
1119 {
1120 ipf_main_softc_t *softc = fin->fin_main_soft;
1121
1122 if (fin->fin_m != NULL) {
1123 if (fin->fin_dp != NULL)
1124 plen += (char *)fin->fin_dp -
1125 ((char *)fin->fin_ip + fin->fin_hlen);
1126 plen += fin->fin_hlen;
1127 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1128 #if defined(_KERNEL)
1129 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1130 DT(ipf_pullup_fail);
1131 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1132 return -1;
1133 }
1134 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1135 #else
1136 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1137 /*
1138 * Fake ipf_pullup failing
1139 */
1140 fin->fin_reason = FRB_PULLUP;
1141 *fin->fin_mp = NULL;
1142 fin->fin_m = NULL;
1143 fin->fin_ip = NULL;
1144 return -1;
1145 #endif
1146 }
1147 }
1148 return 0;
1149 }
1150
1151
1152 /* ------------------------------------------------------------------------ */
1153 /* Function: ipf_pr_short */
1154 /* Returns: void */
1155 /* Parameters: fin(I) - pointer to packet information */
1156 /* xmin(I) - minimum header size */
1157 /* */
1158 /* Check if a packet is "short" as defined by xmin. The rule we are */
1159 /* applying here is that the packet must not be fragmented within the layer */
1160 /* 4 header. That is, it must not be a fragment that has its offset set to */
1161 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1162 /* entire layer 4 header must be present (min). */
1163 /* ------------------------------------------------------------------------ */
1164 static INLINE void
1165 ipf_pr_short(fr_info_t *fin, int xmin)
1166 {
1167
1168 if (fin->fin_off == 0) {
1169 if (fin->fin_dlen < xmin)
1170 fin->fin_flx |= FI_SHORT;
1171 } else if (fin->fin_off < xmin) {
1172 fin->fin_flx |= FI_SHORT;
1173 }
1174 }
1175
1176
1177 /* ------------------------------------------------------------------------ */
1178 /* Function: ipf_pr_icmp */
1179 /* Returns: void */
1180 /* Parameters: fin(I) - pointer to packet information */
1181 /* */
1182 /* IPv4 Only */
1183 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1184 /* except extrememly bad packets, both type and code will be present. */
1185 /* The expected minimum size of an ICMP packet is very much dependent on */
1186 /* the type of it. */
1187 /* */
1188 /* XXX - other ICMP sanity checks? */
1189 /* ------------------------------------------------------------------------ */
1190 static INLINE void
1191 ipf_pr_icmp(fr_info_t *fin)
1192 {
1193 ipf_main_softc_t *softc = fin->fin_main_soft;
1194 int minicmpsz = sizeof(struct icmp);
1195 icmphdr_t *icmp;
1196 ip_t *oip;
1197
1198 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1199
1200 if (fin->fin_off != 0) {
1201 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1202 return;
1203 }
1204
1205 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1206 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1207 return;
1208 }
1209
1210 icmp = fin->fin_dp;
1211
1212 fin->fin_data[0] = *(u_short *)icmp;
1213 fin->fin_data[1] = icmp->icmp_id;
1214
1215 switch (icmp->icmp_type)
1216 {
1217 case ICMP_ECHOREPLY :
1218 case ICMP_ECHO :
1219 /* Router discovery messaes - RFC 1256 */
1220 case ICMP_ROUTERADVERT :
1221 case ICMP_ROUTERSOLICIT :
1222 fin->fin_flx |= FI_ICMPQUERY;
1223 minicmpsz = ICMP_MINLEN;
1224 break;
1225 /*
1226 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1227 * 3 * timestamp(3 * 4)
1228 */
1229 case ICMP_TSTAMP :
1230 case ICMP_TSTAMPREPLY :
1231 fin->fin_flx |= FI_ICMPQUERY;
1232 minicmpsz = 20;
1233 break;
1234 /*
1235 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1236 * mask(4)
1237 */
1238 case ICMP_IREQ :
1239 case ICMP_IREQREPLY :
1240 case ICMP_MASKREQ :
1241 case ICMP_MASKREPLY :
1242 fin->fin_flx |= FI_ICMPQUERY;
1243 minicmpsz = 12;
1244 break;
1245 /*
1246 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1247 */
1248 case ICMP_UNREACH :
1249 #ifdef icmp_nextmtu
1250 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1251 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu)
1252 fin->fin_flx |= FI_BAD;
1253 }
1254 #endif
1255 case ICMP_SOURCEQUENCH :
1256 case ICMP_REDIRECT :
1257 case ICMP_TIMXCEED :
1258 case ICMP_PARAMPROB :
1259 fin->fin_flx |= FI_ICMPERR;
1260 if (ipf_coalesce(fin) != 1) {
1261 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1262 return;
1263 }
1264
1265 /*
1266 * ICMP error packets should not be generated for IP
1267 * packets that are a fragment that isn't the first
1268 * fragment.
1269 */
1270 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1271 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0)
1272 fin->fin_flx |= FI_BAD;
1273
1274 /*
1275 * If the destination of this packet doesn't match the
1276 * source of the original packet then this packet is
1277 * not correct.
1278 */
1279 if (oip->ip_src.s_addr != fin->fin_daddr)
1280 fin->fin_flx |= FI_BAD;
1281 break;
1282 default :
1283 break;
1284 }
1285
1286 ipf_pr_short(fin, minicmpsz);
1287
1288 ipf_checkv4sum(fin);
1289 }
1290
1291
1292 /* ------------------------------------------------------------------------ */
1293 /* Function: ipf_pr_tcpcommon */
1294 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1295 /* Parameters: fin(I) - pointer to packet information */
1296 /* */
1297 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1298 /* and make some checks with how they interact with other fields. */
1299 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1300 /* valid and mark the packet as bad if not. */
1301 /* ------------------------------------------------------------------------ */
1302 static INLINE int
1303 ipf_pr_tcpcommon(fr_info_t *fin)
1304 {
1305 ipf_main_softc_t *softc = fin->fin_main_soft;
1306 int flags, tlen;
1307 tcphdr_t *tcp;
1308
1309 fin->fin_flx |= FI_TCPUDP;
1310 if (fin->fin_off != 0) {
1311 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1312 return 0;
1313 }
1314
1315 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1316 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1317 return -1;
1318 }
1319
1320 tcp = fin->fin_dp;
1321 if (fin->fin_dlen > 3) {
1322 fin->fin_sport = ntohs(tcp->th_sport);
1323 fin->fin_dport = ntohs(tcp->th_dport);
1324 }
1325
1326 if ((fin->fin_flx & FI_SHORT) != 0) {
1327 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1328 return 1;
1329 }
1330
1331 /*
1332 * Use of the TCP data offset *must* result in a value that is at
1333 * least the same size as the TCP header.
1334 */
1335 tlen = TCP_OFF(tcp) << 2;
1336 if (tlen < sizeof(tcphdr_t)) {
1337 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1338 fin->fin_flx |= FI_BAD;
1339 return 1;
1340 }
1341
1342 flags = tcp->th_flags;
1343 fin->fin_tcpf = tcp->th_flags;
1344
1345 /*
1346 * If the urgent flag is set, then the urgent pointer must
1347 * also be set and vice versa. Good TCP packets do not have
1348 * just one of these set.
1349 */
1350 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1351 fin->fin_flx |= FI_BAD;
1352 #if 0
1353 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1354 /*
1355 * Ignore this case (#if 0) as it shows up in "real"
1356 * traffic with bogus values in the urgent pointer field.
1357 */
1358 fin->fin_flx |= FI_BAD;
1359 #endif
1360 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1361 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1362 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1363 fin->fin_flx |= FI_BAD;
1364 #if 1
1365 } else if (((flags & TH_SYN) != 0) &&
1366 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1367 /*
1368 * SYN with URG and PUSH set is not for normal TCP but it is
1369 * possible(?) with T/TCP...but who uses T/TCP?
1370 */
1371 fin->fin_flx |= FI_BAD;
1372 #endif
1373 } else if (!(flags & TH_ACK)) {
1374 /*
1375 * If the ack bit isn't set, then either the SYN or
1376 * RST bit must be set. If the SYN bit is set, then
1377 * we expect the ACK field to be 0. If the ACK is
1378 * not set and if URG, PSH or FIN are set, consdier
1379 * that to indicate a bad TCP packet.
1380 */
1381 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1382 /*
1383 * Cisco PIX sets the ACK field to a random value.
1384 * In light of this, do not set FI_BAD until a patch
1385 * is available from Cisco to ensure that
1386 * interoperability between existing systems is
1387 * achieved.
1388 */
1389 /*fin->fin_flx |= FI_BAD*/;
1390 } else if (!(flags & (TH_RST|TH_SYN))) {
1391 fin->fin_flx |= FI_BAD;
1392 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1393 fin->fin_flx |= FI_BAD;
1394 }
1395 }
1396 if (fin->fin_flx & FI_BAD) {
1397 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_bad_flags);
1398 return 1;
1399 }
1400
1401 /*
1402 * At this point, it's not exactly clear what is to be gained by
1403 * marking up which TCP options are and are not present. The one we
1404 * are most interested in is the TCP window scale. This is only in
1405 * a SYN packet [RFC1323] so we don't need this here...?
1406 * Now if we were to analyse the header for passive fingerprinting,
1407 * then that might add some weight to adding this...
1408 */
1409 if (tlen == sizeof(tcphdr_t)) {
1410 return 0;
1411 }
1412
1413 if (ipf_pr_pullup(fin, tlen) == -1) {
1414 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1415 return -1;
1416 }
1417
1418 #if 0
1419 tcp = fin->fin_dp;
1420 ip = fin->fin_ip;
1421 s = (u_char *)(tcp + 1);
1422 off = IP_HL(ip) << 2;
1423 # ifdef _KERNEL
1424 if (fin->fin_mp != NULL) {
1425 mb_t *m = *fin->fin_mp;
1426
1427 if (off + tlen > M_LEN(m))
1428 return;
1429 }
1430 # endif
1431 for (tlen -= (int)sizeof(*tcp); tlen > 0; ) {
1432 opt = *s;
1433 if (opt == '\0')
1434 break;
1435 else if (opt == TCPOPT_NOP)
1436 ol = 1;
1437 else {
1438 if (tlen < 2)
1439 break;
1440 ol = (int)*(s + 1);
1441 if (ol < 2 || ol > tlen)
1442 break;
1443 }
1444
1445 for (i = 9, mv = 4; mv >= 0; ) {
1446 op = ipopts + i;
1447 if (opt == (u_char)op->ol_val) {
1448 optmsk |= op->ol_bit;
1449 break;
1450 }
1451 }
1452 tlen -= ol;
1453 s += ol;
1454 }
1455 #endif /* 0 */
1456
1457 return 0;
1458 }
1459
1460
1461
1462 /* ------------------------------------------------------------------------ */
1463 /* Function: ipf_pr_udpcommon */
1464 /* Returns: int - 0 = header ok, 1 = bad packet */
1465 /* Parameters: fin(I) - pointer to packet information */
1466 /* */
1467 /* Extract the UDP source and destination ports, if present. If compiled */
1468 /* with IPFILTER_CKSUM, check to see if the UDP checksum is valid. */
1469 /* ------------------------------------------------------------------------ */
1470 static INLINE int
1471 ipf_pr_udpcommon(fr_info_t *fin)
1472 {
1473 udphdr_t *udp;
1474
1475 fin->fin_flx |= FI_TCPUDP;
1476
1477 if (!fin->fin_off && (fin->fin_dlen > 3)) {
1478 if (ipf_pr_pullup(fin, sizeof(*udp)) == -1) {
1479 ipf_main_softc_t *softc = fin->fin_main_soft;
1480
1481 fin->fin_flx |= FI_SHORT;
1482 LBUMPD(ipf_stats[fin->fin_out], fr_udp_pullup);
1483 return 1;
1484 }
1485
1486 udp = fin->fin_dp;
1487
1488 fin->fin_sport = ntohs(udp->uh_sport);
1489 fin->fin_dport = ntohs(udp->uh_dport);
1490 }
1491
1492 return 0;
1493 }
1494
1495
1496 /* ------------------------------------------------------------------------ */
1497 /* Function: ipf_pr_tcp */
1498 /* Returns: void */
1499 /* Parameters: fin(I) - pointer to packet information */
1500 /* */
1501 /* IPv4 Only */
1502 /* Analyse the packet for IPv4/TCP properties. */
1503 /* ------------------------------------------------------------------------ */
1504 static INLINE void
1505 ipf_pr_tcp(fr_info_t *fin)
1506 {
1507
1508 ipf_pr_short(fin, sizeof(tcphdr_t));
1509
1510 if (ipf_pr_tcpcommon(fin) == 0)
1511 ipf_checkv4sum(fin);
1512 }
1513
1514
1515 /* ------------------------------------------------------------------------ */
1516 /* Function: ipf_pr_udp */
1517 /* Returns: void */
1518 /* Parameters: fin(I) - pointer to packet information */
1519 /* */
1520 /* IPv4 Only */
1521 /* Analyse the packet for IPv4/UDP properties. */
1522 /* ------------------------------------------------------------------------ */
1523 static INLINE void
1524 ipf_pr_udp(fr_info_t *fin)
1525 {
1526
1527 ipf_pr_short(fin, sizeof(udphdr_t));
1528
1529 if (ipf_pr_udpcommon(fin) == 0)
1530 ipf_checkv4sum(fin);
1531 }
1532
1533
1534 /* ------------------------------------------------------------------------ */
1535 /* Function: ipf_pr_esp */
1536 /* Returns: void */
1537 /* Parameters: fin(I) - pointer to packet information */
1538 /* */
1539 /* Analyse the packet for ESP properties. */
1540 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1541 /* even though the newer ESP packets must also have a sequence number that */
1542 /* is 32bits as well, it is not possible(?) to determine the version from a */
1543 /* simple packet header. */
1544 /* ------------------------------------------------------------------------ */
1545 static INLINE void
1546 ipf_pr_esp(fr_info_t *fin)
1547 {
1548
1549 if (fin->fin_off == 0) {
1550 ipf_pr_short(fin, 8);
1551 if (ipf_pr_pullup(fin, 8) == -1) {
1552 ipf_main_softc_t *softc = fin->fin_main_soft;
1553
1554 LBUMPD(ipf_stats[fin->fin_out], fr_v4_esp_pullup);
1555 }
1556 }
1557 }
1558
1559
1560 /* ------------------------------------------------------------------------ */
1561 /* Function: ipf_pr_ah */
1562 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1563 /* Parameters: fin(I) - pointer to packet information */
1564 /* */
1565 /* Analyse the packet for AH properties. */
1566 /* The minimum length is taken to be the combination of all fields in the */
1567 /* header being present and no authentication data (null algorithm used.) */
1568 /* ------------------------------------------------------------------------ */
1569 static INLINE int
1570 ipf_pr_ah(fr_info_t *fin)
1571 {
1572 ipf_main_softc_t *softc = fin->fin_main_soft;
1573 authhdr_t *ah;
1574 int len;
1575
1576 fin->fin_flx |= FI_AH;
1577 ipf_pr_short(fin, sizeof(*ah));
1578
1579 if (((fin->fin_flx & FI_SHORT) != 0) || (fin->fin_off != 0)) {
1580 LBUMPD(ipf_stats[fin->fin_out], fr_v4_ah_bad);
1581 return IPPROTO_NONE;
1582 }
1583
1584 if (ipf_pr_pullup(fin, sizeof(*ah)) == -1) {
1585 DT(fr_v4_ah_pullup_1);
1586 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1587 return IPPROTO_NONE;
1588 }
1589
1590 ah = (authhdr_t *)fin->fin_dp;
1591
1592 len = (ah->ah_plen + 2) << 2;
1593 ipf_pr_short(fin, len);
1594 if (ipf_pr_pullup(fin, len) == -1) {
1595 DT(fr_v4_ah_pullup_2);
1596 LBUMP(ipf_stats[fin->fin_out].fr_v4_ah_pullup);
1597 return IPPROTO_NONE;
1598 }
1599
1600 /*
1601 * Adjust fin_dp and fin_dlen for skipping over the authentication
1602 * header.
1603 */
1604 fin->fin_dp = (char *)fin->fin_dp + len;
1605 fin->fin_dlen -= len;
1606 return ah->ah_next;
1607 }
1608
1609
1610 /* ------------------------------------------------------------------------ */
1611 /* Function: ipf_pr_gre */
1612 /* Returns: void */
1613 /* Parameters: fin(I) - pointer to packet information */
1614 /* */
1615 /* Analyse the packet for GRE properties. */
1616 /* ------------------------------------------------------------------------ */
1617 static INLINE void
1618 ipf_pr_gre(fr_info_t *fin)
1619 {
1620 ipf_main_softc_t *softc = fin->fin_main_soft;
1621 grehdr_t *gre;
1622
1623 ipf_pr_short(fin, sizeof(grehdr_t));
1624
1625 if (fin->fin_off != 0) {
1626 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_frag);
1627 return;
1628 }
1629
1630 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1631 LBUMPD(ipf_stats[fin->fin_out], fr_v4_gre_pullup);
1632 return;
1633 }
1634
1635 gre = fin->fin_dp;
1636 if (GRE_REV(gre->gr_flags) == 1)
1637 fin->fin_data[0] = gre->gr_call;
1638 }
1639
1640
1641 /* ------------------------------------------------------------------------ */
1642 /* Function: ipf_pr_ipv4hdr */
1643 /* Returns: void */
1644 /* Parameters: fin(I) - pointer to packet information */
1645 /* */
1646 /* IPv4 Only */
1647 /* Analyze the IPv4 header and set fields in the fr_info_t structure. */
1648 /* Check all options present and flag their presence if any exist. */
1649 /* ------------------------------------------------------------------------ */
1650 static INLINE void
1651 ipf_pr_ipv4hdr(fr_info_t *fin)
1652 {
1653 u_short optmsk = 0, secmsk = 0, auth = 0;
1654 int hlen, ol, mv, p, i;
1655 const struct optlist *op;
1656 u_char *s, opt;
1657 u_short off;
1658 fr_ip_t *fi;
1659 ip_t *ip;
1660
1661 fi = &fin->fin_fi;
1662 hlen = fin->fin_hlen;
1663
1664 ip = fin->fin_ip;
1665 p = ip->ip_p;
1666 fi->fi_p = p;
1667 fin->fin_crc = p;
1668 fi->fi_tos = ip->ip_tos;
1669 fin->fin_id = ip->ip_id;
1670 off = ntohs(ip->ip_off);
1671
1672 /* Get both TTL and protocol */
1673 fi->fi_p = ip->ip_p;
1674 fi->fi_ttl = ip->ip_ttl;
1675
1676 /* Zero out bits not used in IPv6 address */
1677 fi->fi_src.i6[1] = 0;
1678 fi->fi_src.i6[2] = 0;
1679 fi->fi_src.i6[3] = 0;
1680 fi->fi_dst.i6[1] = 0;
1681 fi->fi_dst.i6[2] = 0;
1682 fi->fi_dst.i6[3] = 0;
1683
1684 fi->fi_saddr = ip->ip_src.s_addr;
1685 fin->fin_crc += fi->fi_saddr;
1686 fi->fi_daddr = ip->ip_dst.s_addr;
1687 fin->fin_crc += fi->fi_daddr;
1688 if (IN_CLASSD(fi->fi_daddr))
1689 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
1690
1691 /*
1692 * set packet attribute flags based on the offset and
1693 * calculate the byte offset that it represents.
1694 */
1695 off &= IP_MF|IP_OFFMASK;
1696 if (off != 0) {
1697 int morefrag = off & IP_MF;
1698
1699 fi->fi_flx |= FI_FRAG;
1700 off &= IP_OFFMASK;
1701 if (off != 0) {
1702 fin->fin_flx |= FI_FRAGBODY;
1703 off <<= 3;
1704 if ((off + fin->fin_dlen > 65535) ||
1705 (fin->fin_dlen == 0) ||
1706 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1707 /*
1708 * The length of the packet, starting at its
1709 * offset cannot exceed 65535 (0xffff) as the
1710 * length of an IP packet is only 16 bits.
1711 *
1712 * Any fragment that isn't the last fragment
1713 * must have a length greater than 0 and it
1714 * must be an even multiple of 8.
1715 */
1716 fi->fi_flx |= FI_BAD;
1717 }
1718 }
1719 }
1720 fin->fin_off = off;
1721
1722 /*
1723 * Call per-protocol setup and checking
1724 */
1725 if (p == IPPROTO_AH) {
1726 /*
1727 * Treat AH differently because we expect there to be another
1728 * layer 4 header after it.
1729 */
1730 p = ipf_pr_ah(fin);
1731 }
1732
1733 switch (p)
1734 {
1735 case IPPROTO_UDP :
1736 ipf_pr_udp(fin);
1737 break;
1738 case IPPROTO_TCP :
1739 ipf_pr_tcp(fin);
1740 break;
1741 case IPPROTO_ICMP :
1742 ipf_pr_icmp(fin);
1743 break;
1744 case IPPROTO_ESP :
1745 ipf_pr_esp(fin);
1746 break;
1747 case IPPROTO_GRE :
1748 ipf_pr_gre(fin);
1749 break;
1750 }
1751
1752 ip = fin->fin_ip;
1753 if (ip == NULL)
1754 return;
1755
1756 /*
1757 * If it is a standard IP header (no options), set the flag fields
1758 * which relate to options to 0.
1759 */
1760 if (hlen == sizeof(*ip)) {
1761 fi->fi_optmsk = 0;
1762 fi->fi_secmsk = 0;
1763 fi->fi_auth = 0;
1764 return;
1765 }
1766
1767 /*
1768 * So the IP header has some IP options attached. Walk the entire
1769 * list of options present with this packet and set flags to indicate
1770 * which ones are here and which ones are not. For the somewhat out
1771 * of date and obscure security classification options, set a flag to
1772 * represent which classification is present.
1773 */
1774 fi->fi_flx |= FI_OPTIONS;
1775
1776 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1777 opt = *s;
1778 if (opt == '\0')
1779 break;
1780 else if (opt == IPOPT_NOP)
1781 ol = 1;
1782 else {
1783 if (hlen < 2)
1784 break;
1785 ol = (int)*(s + 1);
1786 if (ol < 2 || ol > hlen)
1787 break;
1788 }
1789 for (i = 9, mv = 4; mv >= 0; ) {
1790 op = ipopts + i;
1791
1792 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1793 u_32_t doi;
1794
1795 switch (opt)
1796 {
1797 case IPOPT_SECURITY :
1798 if (optmsk & op->ol_bit) {
1799 fin->fin_flx |= FI_BAD;
1800 } else {
1801 doi = ipf_checkripso(s);
1802 secmsk = doi >> 16;
1803 auth = doi & 0xffff;
1804 }
1805 break;
1806
1807 case IPOPT_CIPSO :
1808
1809 if (optmsk & op->ol_bit) {
1810 fin->fin_flx |= FI_BAD;
1811 } else {
1812 doi = ipf_checkcipso(fin,
1813 s, ol);
1814 secmsk = doi >> 16;
1815 auth = doi & 0xffff;
1816 }
1817 break;
1818 }
1819 optmsk |= op->ol_bit;
1820 }
1821
1822 if (opt < op->ol_val)
1823 i -= mv;
1824 else
1825 i += mv;
1826 mv--;
1827 }
1828 hlen -= ol;
1829 s += ol;
1830 }
1831
1832 /*
1833 *
1834 */
1835 if (auth && !(auth & 0x0100))
1836 auth &= 0xff00;
1837 fi->fi_optmsk = optmsk;
1838 fi->fi_secmsk = secmsk;
1839 fi->fi_auth = auth;
1840 }
1841
1842
1843 /* ------------------------------------------------------------------------ */
1844 /* Function: ipf_checkripso */
1845 /* Returns: void */
1846 /* Parameters: s(I) - pointer to start of RIPSO option */
1847 /* */
1848 /* ------------------------------------------------------------------------ */
1849 static u_32_t
1850 ipf_checkripso(u_char *s)
1851 {
1852 const struct optlist *sp;
1853 u_short secmsk = 0, auth = 0;
1854 u_char sec;
1855 int j, m;
1856
1857 sec = *(s + 2); /* classification */
1858 for (j = 3, m = 2; m >= 0; ) {
1859 sp = secopt + j;
1860 if (sec == sp->ol_val) {
1861 secmsk |= sp->ol_bit;
1862 auth = *(s + 3);
1863 auth *= 256;
1864 auth += *(s + 4);
1865 break;
1866 }
1867 if (sec < sp->ol_val)
1868 j -= m;
1869 else
1870 j += m;
1871 m--;
1872 }
1873
1874 return (secmsk << 16) | auth;
1875 }
1876
1877
1878 /* ------------------------------------------------------------------------ */
1879 /* Function: ipf_checkcipso */
1880 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1881 /* Parameters: fin(IO) - pointer to packet information */
1882 /* s(I) - pointer to start of CIPSO option */
1883 /* ol(I) - length of CIPSO option field */
1884 /* */
1885 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1886 /* header and returns that whilst also storing the highest sensitivity */
1887 /* value found in the fr_info_t structure. */
1888 /* */
1889 /* No attempt is made to extract the category bitmaps as these are defined */
1890 /* by the user (rather than the protocol) and can be rather numerous on the */
1891 /* end nodes. */
1892 /* ------------------------------------------------------------------------ */
1893 static u_32_t
1894 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1895 {
1896 ipf_main_softc_t *softc = fin->fin_main_soft;
1897 fr_ip_t *fi;
1898 u_32_t doi;
1899 u_char *t, tag, tlen, sensitivity;
1900 int len;
1901
1902 if (ol < 6 || ol > 40) {
1903 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1904 fin->fin_flx |= FI_BAD;
1905 return 0;
1906 }
1907
1908 fi = &fin->fin_fi;
1909 fi->fi_sensitivity = 0;
1910 /*
1911 * The DOI field MUST be there.
1912 */
1913 bcopy(s + 2, &doi, sizeof(doi));
1914
1915 t = (u_char *)s + 6;
1916 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1917 tag = *t;
1918 tlen = *(t + 1);
1919 if (tlen > len || tlen < 4 || tlen > 34) {
1920 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1921 fin->fin_flx |= FI_BAD;
1922 return 0;
1923 }
1924
1925 sensitivity = 0;
1926 /*
1927 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1928 * draft (16 July 1992) that has expired.
1929 */
1930 if (tag == 0) {
1931 fin->fin_flx |= FI_BAD;
1932 continue;
1933 } else if (tag == 1) {
1934 if (*(t + 2) != 0) {
1935 fin->fin_flx |= FI_BAD;
1936 continue;
1937 }
1938 sensitivity = *(t + 3);
1939 /* Category bitmap for categories 0-239 */
1940
1941 } else if (tag == 4) {
1942 if (*(t + 2) != 0) {
1943 fin->fin_flx |= FI_BAD;
1944 continue;
1945 }
1946 sensitivity = *(t + 3);
1947 /* Enumerated categories, 16bits each, upto 15 */
1948
1949 } else if (tag == 5) {
1950 if (*(t + 2) != 0) {
1951 fin->fin_flx |= FI_BAD;
1952 continue;
1953 }
1954 sensitivity = *(t + 3);
1955 /* Range of categories (2*16bits), up to 7 pairs */
1956
1957 } else if (tag > 127) {
1958 /* Custom defined DOI */
1959 ;
1960 } else {
1961 fin->fin_flx |= FI_BAD;
1962 continue;
1963 }
1964
1965 if (sensitivity > fi->fi_sensitivity)
1966 fi->fi_sensitivity = sensitivity;
1967 }
1968
1969 return doi;
1970 }
1971
1972
1973 /* ------------------------------------------------------------------------ */
1974 /* Function: ipf_makefrip */
1975 /* Returns: int - 0 == packet ok, -1 == packet freed */
1976 /* Parameters: hlen(I) - length of IP packet header */
1977 /* ip(I) - pointer to the IP header */
1978 /* fin(IO) - pointer to packet information */
1979 /* */
1980 /* Compact the IP header into a structure which contains just the info. */
1981 /* which is useful for comparing IP headers with and store this information */
1982 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
1983 /* this function will be called with either an IPv4 or IPv6 packet. */
1984 /* ------------------------------------------------------------------------ */
1985 int
1986 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
1987 {
1988 ipf_main_softc_t *softc = fin->fin_main_soft;
1989 int v;
1990
1991 fin->fin_depth = 0;
1992 fin->fin_hlen = (u_short)hlen;
1993 fin->fin_ip = ip;
1994 fin->fin_rule = 0xffffffff;
1995 fin->fin_group[0] = -1;
1996 fin->fin_group[1] = '\0';
1997 fin->fin_dp = (char *)ip + hlen;
1998
1999 v = fin->fin_v;
2000 if (v == 4) {
2001 fin->fin_plen = ntohs(ip->ip_len);
2002 fin->fin_dlen = fin->fin_plen - hlen;
2003 ipf_pr_ipv4hdr(fin);
2004 #ifdef USE_INET6
2005 } else if (v == 6) {
2006 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2007 fin->fin_dlen = fin->fin_plen;
2008 fin->fin_plen += hlen;
2009
2010 ipf_pr_ipv6hdr(fin);
2011 #endif
2012 }
2013 if (fin->fin_ip == NULL) {
2014 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2015 return -1;
2016 }
2017 return 0;
2018 }
2019
2020
2021 /* ------------------------------------------------------------------------ */
2022 /* Function: ipf_portcheck */
2023 /* Returns: int - 1 == port matched, 0 == port match failed */
2024 /* Parameters: frp(I) - pointer to port check `expression' */
2025 /* pop(I) - port number to evaluate */
2026 /* */
2027 /* Perform a comparison of a port number against some other(s), using a */
2028 /* structure with compare information stored in it. */
2029 /* ------------------------------------------------------------------------ */
2030 static INLINE int
2031 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2032 {
2033 int err = 1;
2034 u_32_t po;
2035
2036 po = frp->frp_port;
2037
2038 /*
2039 * Do opposite test to that required and continue if that succeeds.
2040 */
2041 switch (frp->frp_cmp)
2042 {
2043 case FR_EQUAL :
2044 if (pop != po) /* EQUAL */
2045 err = 0;
2046 break;
2047 case FR_NEQUAL :
2048 if (pop == po) /* NOTEQUAL */
2049 err = 0;
2050 break;
2051 case FR_LESST :
2052 if (pop >= po) /* LESSTHAN */
2053 err = 0;
2054 break;
2055 case FR_GREATERT :
2056 if (pop <= po) /* GREATERTHAN */
2057 err = 0;
2058 break;
2059 case FR_LESSTE :
2060 if (pop > po) /* LT or EQ */
2061 err = 0;
2062 break;
2063 case FR_GREATERTE :
2064 if (pop < po) /* GT or EQ */
2065 err = 0;
2066 break;
2067 case FR_OUTRANGE :
2068 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2069 err = 0;
2070 break;
2071 case FR_INRANGE :
2072 if (pop <= po || pop >= frp->frp_top) /* In range */
2073 err = 0;
2074 break;
2075 case FR_INCRANGE :
2076 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2077 err = 0;
2078 break;
2079 default :
2080 break;
2081 }
2082 return err;
2083 }
2084
2085
2086 /* ------------------------------------------------------------------------ */
2087 /* Function: ipf_tcpudpchk */
2088 /* Returns: int - 1 == protocol matched, 0 == check failed */
2089 /* Parameters: fda(I) - pointer to packet information */
2090 /* ft(I) - pointer to structure with comparison data */
2091 /* */
2092 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2093 /* structure containing information that we want to match against. */
2094 /* ------------------------------------------------------------------------ */
2095 int
2096 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2097 {
2098 int err = 1;
2099
2100 /*
2101 * Both ports should *always* be in the first fragment.
2102 * So far, I cannot find any cases where they can not be.
2103 *
2104 * compare destination ports
2105 */
2106 if (ft->ftu_dcmp)
2107 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2108
2109 /*
2110 * compare source ports
2111 */
2112 if (err && ft->ftu_scmp)
2113 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2114
2115 /*
2116 * If we don't have all the TCP/UDP header, then how can we
2117 * expect to do any sort of match on it ? If we were looking for
2118 * TCP flags, then NO match. If not, then match (which should
2119 * satisfy the "short" class too).
2120 */
2121 if (err && (fi->fi_p == IPPROTO_TCP)) {
2122 if (fi->fi_flx & FI_SHORT)
2123 return !(ft->ftu_tcpf | ft->ftu_tcpfm);
2124 /*
2125 * Match the flags ? If not, abort this match.
2126 */
2127 if (ft->ftu_tcpfm &&
2128 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2129 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2130 ft->ftu_tcpfm, ft->ftu_tcpf));
2131 err = 0;
2132 }
2133 }
2134 return err;
2135 }
2136
2137
2138 /* ------------------------------------------------------------------------ */
2139 /* Function: ipf_check_ipf */
2140 /* Returns: int - 0 == match, else no match */
2141 /* Parameters: fin(I) - pointer to packet information */
2142 /* fr(I) - pointer to filter rule */
2143 /* portcmp(I) - flag indicating whether to attempt matching on */
2144 /* TCP/UDP port data. */
2145 /* */
2146 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2147 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2148 /* this function. */
2149 /* ------------------------------------------------------------------------ */
2150 static INLINE int
2151 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2152 {
2153 u_32_t *ld, *lm, *lip;
2154 fripf_t *fri;
2155 fr_ip_t *fi;
2156 int i;
2157
2158 fi = &fin->fin_fi;
2159 fri = fr->fr_ipf;
2160 lip = (u_32_t *)fi;
2161 lm = (u_32_t *)&fri->fri_mip;
2162 ld = (u_32_t *)&fri->fri_ip;
2163
2164 /*
2165 * first 32 bits to check coversion:
2166 * IP version, TOS, TTL, protocol
2167 */
2168 i = ((*lip & *lm) != *ld);
2169 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2170 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2171 if (i)
2172 return 1;
2173
2174 /*
2175 * Next 32 bits is a constructed bitmask indicating which IP options
2176 * are present (if any) in this packet.
2177 */
2178 lip++, lm++, ld++;
2179 i = ((*lip & *lm) != *ld);
2180 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2181 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2182 if (i != 0)
2183 return 1;
2184
2185 lip++, lm++, ld++;
2186 /*
2187 * Unrolled loops (4 each, for 32 bits) for address checks.
2188 */
2189 /*
2190 * Check the source address.
2191 */
2192 if (fr->fr_satype == FRI_LOOKUP) {
2193 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2194 fi->fi_v, lip, fin->fin_plen);
2195 if (i == -1)
2196 return 1;
2197 lip += 3;
2198 lm += 3;
2199 ld += 3;
2200 } else {
2201 i = ((*lip & *lm) != *ld);
2202 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2203 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2204 if (fi->fi_v == 6) {
2205 lip++, lm++, ld++;
2206 i |= ((*lip & *lm) != *ld);
2207 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2208 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2209 lip++, lm++, ld++;
2210 i |= ((*lip & *lm) != *ld);
2211 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2212 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2213 lip++, lm++, ld++;
2214 i |= ((*lip & *lm) != *ld);
2215 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2216 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2217 } else {
2218 lip += 3;
2219 lm += 3;
2220 ld += 3;
2221 }
2222 }
2223 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2224 if (i != 0)
2225 return 1;
2226
2227 /*
2228 * Check the destination address.
2229 */
2230 lip++, lm++, ld++;
2231 if (fr->fr_datype == FRI_LOOKUP) {
2232 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2233 fi->fi_v, lip, fin->fin_plen);
2234 if (i == -1)
2235 return 1;
2236 lip += 3;
2237 lm += 3;
2238 ld += 3;
2239 } else {
2240 i = ((*lip & *lm) != *ld);
2241 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2242 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2243 if (fi->fi_v == 6) {
2244 lip++, lm++, ld++;
2245 i |= ((*lip & *lm) != *ld);
2246 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2247 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2248 lip++, lm++, ld++;
2249 i |= ((*lip & *lm) != *ld);
2250 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2251 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2252 lip++, lm++, ld++;
2253 i |= ((*lip & *lm) != *ld);
2254 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2255 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2256 } else {
2257 lip += 3;
2258 lm += 3;
2259 ld += 3;
2260 }
2261 }
2262 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2263 if (i != 0)
2264 return 1;
2265 /*
2266 * IP addresses matched. The next 32bits contains:
2267 * mast of old IP header security & authentication bits.
2268 */
2269 lip++, lm++, ld++;
2270 i = (*ld - (*lip & *lm));
2271 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2272
2273 /*
2274 * Next we have 32 bits of packet flags.
2275 */
2276 lip++, lm++, ld++;
2277 i |= (*ld - (*lip & *lm));
2278 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2279
2280 if (i == 0) {
2281 /*
2282 * If a fragment, then only the first has what we're
2283 * looking for here...
2284 */
2285 if (portcmp) {
2286 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2287 i = 1;
2288 } else {
2289 if (fr->fr_dcmp || fr->fr_scmp ||
2290 fr->fr_tcpf || fr->fr_tcpfm)
2291 i = 1;
2292 if (fr->fr_icmpm || fr->fr_icmp) {
2293 if (((fi->fi_p != IPPROTO_ICMP) &&
2294 (fi->fi_p != IPPROTO_ICMPV6)) ||
2295 fin->fin_off || (fin->fin_dlen < 2))
2296 i = 1;
2297 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2298 fr->fr_icmp) {
2299 FR_DEBUG(("i. %#x & %#x != %#x\n",
2300 fin->fin_data[0],
2301 fr->fr_icmpm, fr->fr_icmp));
2302 i = 1;
2303 }
2304 }
2305 }
2306 }
2307 return i;
2308 }
2309
2310
2311 /* ------------------------------------------------------------------------ */
2312 /* Function: ipf_scanlist */
2313 /* Returns: int - result flags of scanning filter list */
2314 /* Parameters: fin(I) - pointer to packet information */
2315 /* pass(I) - default result to return for filtering */
2316 /* */
2317 /* Check the input/output list of rules for a match to the current packet. */
2318 /* If a match is found, the value of fr_flags from the rule becomes the */
2319 /* return value and fin->fin_fr points to the matched rule. */
2320 /* */
2321 /* This function may be called recusively upto 16 times (limit inbuilt.) */
2322 /* When unwinding, it should finish up with fin_depth as 0. */
2323 /* */
2324 /* Could be per interface, but this gets real nasty when you don't have, */
2325 /* or can't easily change, the kernel source code to . */
2326 /* ------------------------------------------------------------------------ */
2327 int
2328 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2329 {
2330 ipf_main_softc_t *softc = fin->fin_main_soft;
2331 int rulen, portcmp, off, skip;
2332 struct frentry *fr, *fnext;
2333 u_32_t passt, passo;
2334
2335 /*
2336 * Do not allow nesting deeper than 16 levels.
2337 */
2338 if (fin->fin_depth >= 16)
2339 return pass;
2340
2341 fr = fin->fin_fr;
2342
2343 /*
2344 * If there are no rules in this list, return now.
2345 */
2346 if (fr == NULL)
2347 return pass;
2348
2349 skip = 0;
2350 portcmp = 0;
2351 fin->fin_depth++;
2352 fin->fin_fr = NULL;
2353 off = fin->fin_off;
2354
2355 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2356 portcmp = 1;
2357
2358 for (rulen = 0; fr; fr = fnext, rulen++) {
2359 fnext = fr->fr_next;
2360 if (skip != 0) {
2361 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2362 skip--;
2363 continue;
2364 }
2365
2366 /*
2367 * In all checks below, a null (zero) value in the
2368 * filter struture is taken to mean a wildcard.
2369 *
2370 * check that we are working for the right interface
2371 */
2372 #ifdef _KERNEL
2373 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2374 continue;
2375 #else
2376 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2377 printf("\n");
2378 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2379 FR_ISPASS(pass) ? 'p' :
2380 FR_ISACCOUNT(pass) ? 'A' :
2381 FR_ISAUTH(pass) ? 'a' :
2382 (pass & FR_NOMATCH) ? 'n' :'b'));
2383 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2384 continue;
2385 FR_VERBOSE((":i"));
2386 #endif
2387
2388 switch (fr->fr_type)
2389 {
2390 case FR_T_IPF :
2391 case FR_T_IPF_BUILTIN :
2392 if (ipf_check_ipf(fin, fr, portcmp))
2393 continue;
2394 break;
2395 #if defined(IPFILTER_BPF)
2396 case FR_T_BPFOPC :
2397 case FR_T_BPFOPC_BUILTIN :
2398 {
2399 u_char *mc;
2400 int wlen;
2401
2402 if (*fin->fin_mp == NULL)
2403 continue;
2404 if (fin->fin_family != fr->fr_family)
2405 continue;
2406 mc = (u_char *)fin->fin_m;
2407 wlen = fin->fin_dlen + fin->fin_hlen;
2408 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2409 continue;
2410 break;
2411 }
2412 #endif
2413 case FR_T_CALLFUNC_BUILTIN :
2414 {
2415 frentry_t *f;
2416
2417 f = (*fr->fr_func)(fin, &pass);
2418 if (f != NULL)
2419 fr = f;
2420 else
2421 continue;
2422 break;
2423 }
2424
2425 case FR_T_IPFEXPR :
2426 case FR_T_IPFEXPR_BUILTIN :
2427 if (fin->fin_family != fr->fr_family)
2428 continue;
2429 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2430 continue;
2431 break;
2432
2433 default :
2434 break;
2435 }
2436
2437 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2438 if (fin->fin_nattag == NULL)
2439 continue;
2440 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2441 continue;
2442 }
2443 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2444
2445 passt = fr->fr_flags;
2446
2447 /*
2448 * If the rule is a "call now" rule, then call the function
2449 * in the rule, if it exists and use the results from that.
2450 * If the function pointer is bad, just make like we ignore
2451 * it, except for increasing the hit counter.
2452 */
2453 if ((passt & FR_CALLNOW) != 0) {
2454 frentry_t *frs;
2455
2456 ATOMIC_INC64(fr->fr_hits);
2457 if ((fr->fr_func == NULL) ||
2458 (fr->fr_func == (ipfunc_t)-1))
2459 continue;
2460
2461 frs = fin->fin_fr;
2462 fin->fin_fr = fr;
2463 fr = (*fr->fr_func)(fin, &passt);
2464 if (fr == NULL) {
2465 fin->fin_fr = frs;
2466 continue;
2467 }
2468 passt = fr->fr_flags;
2469 }
2470 fin->fin_fr = fr;
2471
2472 #ifdef IPFILTER_LOG
2473 /*
2474 * Just log this packet...
2475 */
2476 if ((passt & FR_LOGMASK) == FR_LOG) {
2477 if (ipf_log_pkt(fin, passt) == -1) {
2478 if (passt & FR_LOGORBLOCK) {
2479 DT(frb_logfail);
2480 passt &= ~FR_CMDMASK;
2481 passt |= FR_BLOCK|FR_QUICK;
2482 fin->fin_reason = FRB_LOGFAIL;
2483 }
2484 }
2485 }
2486 #endif /* IPFILTER_LOG */
2487
2488 MUTEX_ENTER(&fr->fr_lock);
2489 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2490 fr->fr_hits++;
2491 MUTEX_EXIT(&fr->fr_lock);
2492 fin->fin_rule = rulen;
2493
2494 passo = pass;
2495 if (FR_ISSKIP(passt)) {
2496 skip = fr->fr_arg;
2497 continue;
2498 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2499 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2500 pass = passt;
2501 }
2502
2503 if (passt & (FR_RETICMP|FR_FAKEICMP))
2504 fin->fin_icode = fr->fr_icode;
2505
2506 if (fr->fr_group != -1) {
2507 (void) strncpy(fin->fin_group,
2508 FR_NAME(fr, fr_group),
2509 strlen(FR_NAME(fr, fr_group)));
2510 } else {
2511 fin->fin_group[0] = '\0';
2512 }
2513
2514 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2515
2516 if (fr->fr_grphead != NULL) {
2517 fin->fin_fr = fr->fr_grphead->fg_start;
2518 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2519
2520 if (FR_ISDECAPS(passt))
2521 passt = ipf_decaps(fin, pass, fr->fr_icode);
2522 else
2523 passt = ipf_scanlist(fin, pass);
2524
2525 if (fin->fin_fr == NULL) {
2526 fin->fin_rule = rulen;
2527 if (fr->fr_group != -1)
2528 (void) strncpy(fin->fin_group,
2529 fr->fr_names +
2530 fr->fr_group,
2531 strlen(fr->fr_names +
2532 fr->fr_group));
2533 fin->fin_fr = fr;
2534 passt = pass;
2535 }
2536 pass = passt;
2537 }
2538
2539 if (pass & FR_QUICK) {
2540 /*
2541 * Finally, if we've asked to track state for this
2542 * packet, set it up. Add state for "quick" rules
2543 * here so that if the action fails we can consider
2544 * the rule to "not match" and keep on processing
2545 * filter rules.
2546 */
2547 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2548 !(fin->fin_flx & FI_STATE)) {
2549 int out = fin->fin_out;
2550
2551 fin->fin_fr = fr;
2552 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2553 LBUMPD(ipf_stats[out], fr_ads);
2554 } else {
2555 LBUMPD(ipf_stats[out], fr_bads);
2556 pass = passo;
2557 continue;
2558 }
2559 }
2560 break;
2561 }
2562 }
2563 fin->fin_depth--;
2564 return pass;
2565 }
2566
2567
2568 /* ------------------------------------------------------------------------ */
2569 /* Function: ipf_acctpkt */
2570 /* Returns: frentry_t* - always returns NULL */
2571 /* Parameters: fin(I) - pointer to packet information */
2572 /* passp(IO) - pointer to current/new filter decision (unused) */
2573 /* */
2574 /* Checks a packet against accounting rules, if there are any for the given */
2575 /* IP protocol version. */
2576 /* */
2577 /* N.B.: this function returns NULL to match the prototype used by other */
2578 /* functions called from the IPFilter "mainline" in ipf_check(). */
2579 /* ------------------------------------------------------------------------ */
2580 frentry_t *
2581 ipf_acctpkt(fr_info_t *fin, u_32_t *passp)
2582 {
2583 ipf_main_softc_t *softc = fin->fin_main_soft;
2584 char group[FR_GROUPLEN];
2585 frentry_t *fr, *frsave;
2586 u_32_t pass, rulen;
2587
2588 passp = passp;
2589 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2590
2591 if (fr != NULL) {
2592 frsave = fin->fin_fr;
2593 bcopy(fin->fin_group, group, FR_GROUPLEN);
2594 rulen = fin->fin_rule;
2595 fin->fin_fr = fr;
2596 pass = ipf_scanlist(fin, FR_NOMATCH);
2597 if (FR_ISACCOUNT(pass)) {
2598 LBUMPD(ipf_stats[0], fr_acct);
2599 }
2600 fin->fin_fr = frsave;
2601 bcopy(group, fin->fin_group, FR_GROUPLEN);
2602 fin->fin_rule = rulen;
2603 }
2604 return NULL;
2605 }
2606
2607
2608 /* ------------------------------------------------------------------------ */
2609 /* Function: ipf_firewall */
2610 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2611 /* were found, returns NULL. */
2612 /* Parameters: fin(I) - pointer to packet information */
2613 /* passp(IO) - pointer to current/new filter decision (unused) */
2614 /* */
2615 /* Applies an appropriate set of firewall rules to the packet, to see if */
2616 /* there are any matches. The first check is to see if a match can be seen */
2617 /* in the cache. If not, then search an appropriate list of rules. Once a */
2618 /* matching rule is found, take any appropriate actions as defined by the */
2619 /* rule - except logging. */
2620 /* ------------------------------------------------------------------------ */
2621 static frentry_t *
2622 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2623 {
2624 ipf_main_softc_t *softc = fin->fin_main_soft;
2625 frentry_t *fr;
2626 u_32_t pass;
2627 int out;
2628
2629 out = fin->fin_out;
2630 pass = *passp;
2631
2632 /*
2633 * This rule cache will only affect packets that are not being
2634 * statefully filtered.
2635 */
2636 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2637 if (fin->fin_fr != NULL)
2638 pass = ipf_scanlist(fin, softc->ipf_pass);
2639
2640 if ((pass & FR_NOMATCH)) {
2641 LBUMPD(ipf_stats[out], fr_nom);
2642 }
2643 fr = fin->fin_fr;
2644
2645 /*
2646 * Apply packets per second rate-limiting to a rule as required.
2647 */
2648 if ((fr != NULL) && (fr->fr_pps != 0) &&
2649 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2650 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2651 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2652 pass |= FR_BLOCK;
2653 LBUMPD(ipf_stats[out], fr_ppshit);
2654 fin->fin_reason = FRB_PPSRATE;
2655 }
2656
2657 /*
2658 * If we fail to add a packet to the authorization queue, then we
2659 * drop the packet later. However, if it was added then pretend
2660 * we've dropped it already.
2661 */
2662 if (FR_ISAUTH(pass)) {
2663 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2664 DT1(frb_authnew, fr_info_t *, fin);
2665 fin->fin_m = *fin->fin_mp = NULL;
2666 fin->fin_reason = FRB_AUTHNEW;
2667 fin->fin_error = 0;
2668 } else {
2669 IPFERROR(1);
2670 fin->fin_error = ENOSPC;
2671 }
2672 }
2673
2674 if ((fr != NULL) && (fr->fr_func != NULL) &&
2675 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2676 (void) (*fr->fr_func)(fin, &pass);
2677
2678 /*
2679 * If a rule is a pre-auth rule, check again in the list of rules
2680 * loaded for authenticated use. It does not particulary matter
2681 * if this search fails because a "preauth" result, from a rule,
2682 * is treated as "not a pass", hence the packet is blocked.
2683 */
2684 if (FR_ISPREAUTH(pass)) {
2685 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2686 }
2687
2688 /*
2689 * If the rule has "keep frag" and the packet is actually a fragment,
2690 * then create a fragment state entry.
2691 */
2692 if ((pass & (FR_KEEPFRAG|FR_KEEPSTATE)) == FR_KEEPFRAG) {
2693 if (fin->fin_flx & FI_FRAG) {
2694 if (ipf_frag_new(softc, fin, pass) == -1) {
2695 LBUMP(ipf_stats[out].fr_bnfr);
2696 } else {
2697 LBUMP(ipf_stats[out].fr_nfr);
2698 }
2699 } else {
2700 LBUMP(ipf_stats[out].fr_cfr);
2701 }
2702 }
2703
2704 fr = fin->fin_fr;
2705 *passp = pass;
2706
2707 return fr;
2708 }
2709
2710
2711 /* ------------------------------------------------------------------------ */
2712 /* Function: ipf_check */
2713 /* Returns: int - 0 == packet allowed through, */
2714 /* User space: */
2715 /* -1 == packet blocked */
2716 /* 1 == packet not matched */
2717 /* -2 == requires authentication */
2718 /* Kernel: */
2719 /* > 0 == filter error # for packet */
2720 /* Parameters: ip(I) - pointer to start of IPv4/6 packet */
2721 /* hlen(I) - length of header */
2722 /* ifp(I) - pointer to interface this packet is on */
2723 /* out(I) - 0 == packet going in, 1 == packet going out */
2724 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2725 /* IP packet. */
2726 /* Solaris & HP-UX ONLY : */
2727 /* qpi(I) - pointer to STREAMS queue information for this */
2728 /* interface & direction. */
2729 /* */
2730 /* ipf_check() is the master function for all IPFilter packet processing. */
2731 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2732 /* authorisation (or pre-authorisation), presence of related state info., */
2733 /* generating log entries, IP packet accounting, routing of packets as */
2734 /* directed by firewall rules and of course whether or not to allow the */
2735 /* packet to be further processed by the kernel. */
2736 /* */
2737 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2738 /* freed. Packets passed may be returned with the pointer pointed to by */
2739 /* by "mp" changed to a new buffer. */
2740 /* ------------------------------------------------------------------------ */
2741 int
2742 ipf_check(void *ctx, ip_t *ip, int hlen, void *ifp, int out,
2743 #if defined(_KERNEL) && defined(MENTAT)
2744 void *qif,
2745 #endif
2746 mb_t **mp)
2747 {
2748 /*
2749 * The above really sucks, but short of writing a diff
2750 */
2751 ipf_main_softc_t *softc = ctx;
2752 fr_info_t frinfo;
2753 fr_info_t *fin = &frinfo;
2754 u_32_t pass = softc->ipf_pass;
2755 frentry_t *fr = NULL;
2756 int v = IP_V(ip);
2757 mb_t *mc = NULL;
2758 mb_t *m;
2759 /*
2760 * The first part of ipf_check() deals with making sure that what goes
2761 * into the filtering engine makes some sense. Information about the
2762 * the packet is distilled, collected into a fr_info_t structure and
2763 * the an attempt to ensure the buffer the packet is in is big enough
2764 * to hold all the required packet headers.
2765 */
2766 #ifdef _KERNEL
2767 # ifdef MENTAT
2768 qpktinfo_t *qpi = qif;
2769
2770 # ifdef __sparc
2771 if ((u_int)ip & 0x3)
2772 return 2;
2773 # endif
2774 # else
2775 SPL_INT(s);
2776 # endif
2777
2778 if (softc->ipf_running <= 0) {
2779 return 0;
2780 }
2781
2782 bzero((char *)fin, sizeof(*fin));
2783
2784 # ifdef MENTAT
2785 if (qpi->qpi_flags & QF_BROADCAST)
2786 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2787 if (qpi->qpi_flags & QF_MULTICAST)
2788 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2789 m = qpi->qpi_m;
2790 fin->fin_qfm = m;
2791 fin->fin_qpi = qpi;
2792 # else /* MENTAT */
2793
2794 m = *mp;
2795
2796 # if defined(M_MCAST)
2797 if ((m->m_flags & M_MCAST) != 0)
2798 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2799 # endif
2800 # if defined(M_MLOOP)
2801 if ((m->m_flags & M_MLOOP) != 0)
2802 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2803 # endif
2804 # if defined(M_BCAST)
2805 if ((m->m_flags & M_BCAST) != 0)
2806 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2807 # endif
2808 # ifdef M_CANFASTFWD
2809 /*
2810 * XXX For now, IP Filter and fast-forwarding of cached flows
2811 * XXX are mutually exclusive. Eventually, IP Filter should
2812 * XXX get a "can-fast-forward" filter rule.
2813 */
2814 m->m_flags &= ~M_CANFASTFWD;
2815 # endif /* M_CANFASTFWD */
2816 # if defined(CSUM_DELAY_DATA) && (!defined(__FreeBSD_version) || \
2817 (__FreeBSD_version < 501108))
2818 /*
2819 * disable delayed checksums.
2820 */
2821 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2822 in_delayed_cksum(m);
2823 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2824 }
2825 # endif /* CSUM_DELAY_DATA */
2826 # endif /* MENTAT */
2827 #else
2828 bzero((char *)fin, sizeof(*fin));
2829 m = *mp;
2830 # if defined(M_MCAST)
2831 if ((m->m_flags & M_MCAST) != 0)
2832 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2833 # endif
2834 # if defined(M_MLOOP)
2835 if ((m->m_flags & M_MLOOP) != 0)
2836 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2837 # endif
2838 # if defined(M_BCAST)
2839 if ((m->m_flags & M_BCAST) != 0)
2840 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2841 # endif
2842 #endif /* _KERNEL */
2843
2844 fin->fin_v = v;
2845 fin->fin_m = m;
2846 fin->fin_ip = ip;
2847 fin->fin_mp = mp;
2848 fin->fin_out = out;
2849 fin->fin_ifp = ifp;
2850 fin->fin_error = ENETUNREACH;
2851 fin->fin_hlen = (u_short)hlen;
2852 fin->fin_dp = (char *)ip + hlen;
2853 fin->fin_main_soft = softc;
2854
2855 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2856
2857 SPL_NET(s);
2858
2859 #ifdef USE_INET6
2860 if (v == 6) {
2861 LBUMP(ipf_stats[out].fr_ipv6);
2862 /*
2863 * Jumbo grams are quite likely too big for internal buffer
2864 * structures to handle comfortably, for now, so just drop
2865 * them.
2866 */
2867 if (((ip6_t *)ip)->ip6_plen == 0) {
2868 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2869 pass = FR_BLOCK|FR_NOMATCH;
2870 fin->fin_reason = FRB_JUMBO;
2871 goto finished;
2872 }
2873 fin->fin_family = AF_INET6;
2874 } else
2875 #endif
2876 {
2877 fin->fin_family = AF_INET;
2878 }
2879
2880 if (ipf_makefrip(hlen, ip, fin) == -1) {
2881 DT1(frb_makefrip, fr_info_t *, fin);
2882 pass = FR_BLOCK|FR_NOMATCH;
2883 fin->fin_reason = FRB_MAKEFRIP;
2884 goto finished;
2885 }
2886
2887 /*
2888 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2889 * becomes NULL and so we have no packet to free.
2890 */
2891 if (*fin->fin_mp == NULL)
2892 goto finished;
2893
2894 if (!out) {
2895 if (v == 4) {
2896 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2897 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2898 fin->fin_flx |= FI_BADSRC;
2899 }
2900 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2901 LBUMPD(ipf_stats[0], fr_v4_badttl);
2902 fin->fin_flx |= FI_LOWTTL;
2903 }
2904 }
2905 #ifdef USE_INET6
2906 else if (v == 6) {
2907 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2908 LBUMPD(ipf_stats[0], fr_v6_badttl);
2909 fin->fin_flx |= FI_LOWTTL;
2910 }
2911 }
2912 #endif
2913 }
2914
2915 if (fin->fin_flx & FI_SHORT) {
2916 LBUMPD(ipf_stats[out], fr_short);
2917 }
2918
2919 #if 0
2920 READ_ENTER(&softc->ipf_mutex);
2921 #endif
2922
2923 if (!out) {
2924 switch (fin->fin_v)
2925 {
2926 case 4 :
2927 if (ipf_nat_checkin(fin, &pass) == -1) {
2928 goto filterdone;
2929 }
2930 break;
2931 #ifdef USE_INET6
2932 case 6 :
2933 if (ipf_nat6_checkin(fin, &pass) == -1) {
2934 goto filterdone;
2935 }
2936 break;
2937 #endif
2938 default :
2939 break;
2940 }
2941 }
2942 /*
2943 * Check auth now.
2944 * If a packet is found in the auth table, then skip checking
2945 * the access lists for permission but we do need to consider
2946 * the result as if it were from the ACL's. In addition, being
2947 * found in the auth table means it has been seen before, so do
2948 * not pass it through accounting (again), lest it be counted twice.
2949 */
2950 fr = ipf_auth_check(fin, &pass);
2951 if (!out && (fr == NULL))
2952 (void) ipf_acctpkt(fin, NULL);
2953
2954 if (fr == NULL) {
2955 if ((fin->fin_flx & FI_FRAG) != 0)
2956 fr = ipf_frag_known(fin, &pass);
2957
2958 if (fr == NULL)
2959 fr = ipf_state_check(fin, &pass);
2960 }
2961
2962 if ((pass & FR_NOMATCH) || (fr == NULL))
2963 fr = ipf_firewall(fin, &pass);
2964
2965 /*
2966 * If we've asked to track state for this packet, set it up.
2967 * Here rather than ipf_firewall because ipf_checkauth may decide
2968 * to return a packet for "keep state"
2969 */
2970 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
2971 !(fin->fin_flx & FI_STATE)) {
2972 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2973 LBUMP(ipf_stats[out].fr_ads);
2974 } else {
2975 LBUMP(ipf_stats[out].fr_bads);
2976 if (FR_ISPASS(pass)) {
2977 DT(frb_stateadd);
2978 pass &= ~FR_CMDMASK;
2979 pass |= FR_BLOCK;
2980 fin->fin_reason = FRB_STATEADD;
2981 }
2982 }
2983 }
2984
2985 fin->fin_fr = fr;
2986 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
2987 fin->fin_dif = &fr->fr_dif;
2988 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
2989 }
2990
2991 /*
2992 * Only count/translate packets which will be passed on, out the
2993 * interface.
2994 */
2995 if (out && FR_ISPASS(pass)) {
2996 (void) ipf_acctpkt(fin, NULL);
2997
2998 switch (fin->fin_v)
2999 {
3000 case 4 :
3001 if (ipf_nat_checkout(fin, &pass) == -1) {
3002 ;
3003 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3004 if (ipf_updateipid(fin) == -1) {
3005 DT(frb_updateipid);
3006 LBUMP(ipf_stats[1].fr_ipud);
3007 pass &= ~FR_CMDMASK;
3008 pass |= FR_BLOCK;
3009 fin->fin_reason = FRB_UPDATEIPID;
3010 } else {
3011 LBUMP(ipf_stats[0].fr_ipud);
3012 }
3013 }
3014 break;
3015 #ifdef USE_INET6
3016 case 6 :
3017 (void) ipf_nat6_checkout(fin, &pass);
3018 break;
3019 #endif
3020 default :
3021 break;
3022 }
3023 }
3024
3025 filterdone:
3026 #ifdef IPFILTER_LOG
3027 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3028 (void) ipf_dolog(fin, &pass);
3029 }
3030 #endif
3031
3032 /*
3033 * The FI_STATE flag is cleared here so that calling ipf_state_check
3034 * will work when called from inside of fr_fastroute. Although
3035 * there is a similar flag, FI_NATED, for NAT, it does have the same
3036 * impact on code execution.
3037 */
3038 fin->fin_flx &= ~FI_STATE;
3039
3040 #if defined(FASTROUTE_RECURSION)
3041 /*
3042 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3043 * a packet below can sometimes cause a recursive call into IPFilter.
3044 * On those platforms where that does happen, we need to hang onto
3045 * the filter rule just in case someone decides to remove or flush it
3046 * in the meantime.
3047 */
3048 if (fr != NULL) {
3049 MUTEX_ENTER(&fr->fr_lock);
3050 fr->fr_ref++;
3051 MUTEX_EXIT(&fr->fr_lock);
3052 }
3053 #if 0
3054 RWLOCK_EXIT(&softc->ipf_mutex);
3055 #endif
3056 #endif
3057
3058 if ((pass & FR_RETMASK) != 0) {
3059 /*
3060 * Should we return an ICMP packet to indicate error
3061 * status passing through the packet filter ?
3062 * WARNING: ICMP error packets AND TCP RST packets should
3063 * ONLY be sent in repsonse to incoming packets. Sending
3064 * them in response to outbound packets can result in a
3065 * panic on some operating systems.
3066 */
3067 if (!out) {
3068 if (pass & FR_RETICMP) {
3069 int dst;
3070
3071 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3072 dst = 1;
3073 else
3074 dst = 0;
3075 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3076 dst);
3077 LBUMP(ipf_stats[0].fr_ret);
3078 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3079 !(fin->fin_flx & FI_SHORT)) {
3080 if (((fin->fin_flx & FI_OOW) != 0) ||
3081 (ipf_send_reset(fin) == 0)) {
3082 LBUMP(ipf_stats[1].fr_ret);
3083 }
3084 }
3085
3086 /*
3087 * When using return-* with auth rules, the auth code
3088 * takes over disposing of this packet.
3089 */
3090 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3091 DT1(frb_authcapture, fr_info_t *, fin);
3092 fin->fin_m = *fin->fin_mp = NULL;
3093 fin->fin_reason = FRB_AUTHCAPTURE;
3094 m = NULL;
3095 }
3096 } else {
3097 if (pass & FR_RETRST) {
3098 fin->fin_error = ECONNRESET;
3099 }
3100 }
3101 }
3102
3103 /*
3104 * After the above so that ICMP unreachables and TCP RSTs get
3105 * created properly.
3106 */
3107 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3108 ipf_nat_uncreate(fin);
3109
3110 /*
3111 * If we didn't drop off the bottom of the list of rules (and thus
3112 * the 'current' rule fr is not NULL), then we may have some extra
3113 * instructions about what to do with a packet.
3114 * Once we're finished return to our caller, freeing the packet if
3115 * we are dropping it.
3116 */
3117 if (fr != NULL) {
3118 frdest_t *fdp;
3119
3120 /*
3121 * Generate a duplicated packet first because ipf_fastroute
3122 * can lead to fin_m being free'd... not good.
3123 */
3124 fdp = fin->fin_dif;
3125 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3126 (fdp->fd_ptr != (void *)-1) && (fin->fin_m != NULL)) {
3127 mc = M_COPY(fin->fin_m);
3128 if (mc != NULL)
3129 ipf_fastroute(mc, &mc, fin, fdp);
3130 }
3131
3132 fdp = fin->fin_tif;
3133 if (!out && (pass & FR_FASTROUTE)) {
3134 /*
3135 * For fastroute rule, no destination interface defined
3136 * so pass NULL as the frdest_t parameter
3137 */
3138 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3139 m = *mp = NULL;
3140 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3141 (fdp->fd_ptr != (struct ifnet *)-1)) {
3142 /* this is for to rules: */
3143 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3144 m = *mp = NULL;
3145 }
3146
3147 #if defined(FASTROUTE_RECURSION)
3148 (void) ipf_derefrule(softc, &fr);
3149 #endif
3150 }
3151 #if !defined(FASTROUTE_RECURSION)
3152 #if 0
3153 RWLOCK_EXIT(&softc->ipf_mutex);
3154 #endif
3155 #endif
3156
3157 finished:
3158 if (!FR_ISPASS(pass)) {
3159 LBUMP(ipf_stats[out].fr_block);
3160 if (*mp != NULL) {
3161 #ifdef _KERNEL
3162 FREE_MB_T(*mp);
3163 #endif
3164 m = *mp = NULL;
3165 }
3166 } else {
3167 LBUMP(ipf_stats[out].fr_pass);
3168 #if defined(_KERNEL) && defined(__sgi)
3169 if ((fin->fin_hbuf != NULL) &&
3170 (mtod(fin->fin_m, struct ip *) != fin->fin_ip)) {
3171 COPYBACK(fin->fin_m, 0, fin->fin_plen, fin->fin_hbuf);
3172 }
3173 #endif
3174 }
3175
3176 SPL_X(s);
3177
3178 #ifdef _KERNEL
3179 if (FR_ISPASS(pass))
3180 return 0;
3181 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3182 return fin->fin_error;
3183 #else /* _KERNEL */
3184 if (*mp != NULL)
3185 (*mp)->mb_ifp = fin->fin_ifp;
3186 blockreason = fin->fin_reason;
3187 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3188 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3189 if ((pass & FR_NOMATCH) != 0)
3190 return 1;
3191
3192 if ((pass & FR_RETMASK) != 0)
3193 switch (pass & FR_RETMASK)
3194 {
3195 case FR_RETRST :
3196 return 3;
3197 case FR_RETICMP :
3198 return 4;
3199 case FR_FAKEICMP :
3200 return 5;
3201 }
3202
3203 switch (pass & FR_CMDMASK)
3204 {
3205 case FR_PASS :
3206 return 0;
3207 case FR_BLOCK :
3208 return -1;
3209 case FR_AUTH :
3210 return -2;
3211 case FR_ACCOUNT :
3212 return -3;
3213 case FR_PREAUTH :
3214 return -4;
3215 }
3216 return 2;
3217 #endif /* _KERNEL */
3218 }
3219
3220
3221 #ifdef IPFILTER_LOG
3222 /* ------------------------------------------------------------------------ */
3223 /* Function: ipf_dolog */
3224 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3225 /* Parameters: fin(I) - pointer to packet information */
3226 /* passp(IO) - pointer to current/new filter decision (unused) */
3227 /* */
3228 /* Checks flags set to see how a packet should be logged, if it is to be */
3229 /* logged. Adjust statistics based on its success or not. */
3230 /* ------------------------------------------------------------------------ */
3231 frentry_t *
3232 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3233 {
3234 ipf_main_softc_t *softc = fin->fin_main_soft;
3235 u_32_t pass;
3236 int out;
3237
3238 out = fin->fin_out;
3239 pass = *passp;
3240
3241 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3242 pass |= FF_LOGNOMATCH;
3243 LBUMPD(ipf_stats[out], fr_npkl);
3244 goto logit;
3245
3246 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3247 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3248 if ((pass & FR_LOGMASK) != FR_LOGP)
3249 pass |= FF_LOGPASS;
3250 LBUMPD(ipf_stats[out], fr_ppkl);
3251 goto logit;
3252
3253 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3254 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3255 if ((pass & FR_LOGMASK) != FR_LOGB)
3256 pass |= FF_LOGBLOCK;
3257 LBUMPD(ipf_stats[out], fr_bpkl);
3258
3259 logit:
3260 if (ipf_log_pkt(fin, pass) == -1) {
3261 /*
3262 * If the "or-block" option has been used then
3263 * block the packet if we failed to log it.
3264 */
3265 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3266 DT1(frb_logfail2, u_int, pass);
3267 pass &= ~FR_CMDMASK;
3268 pass |= FR_BLOCK;
3269 fin->fin_reason = FRB_LOGFAIL2;
3270 }
3271 }
3272 *passp = pass;
3273 }
3274
3275 return fin->fin_fr;
3276 }
3277 #endif /* IPFILTER_LOG */
3278
3279
3280 /* ------------------------------------------------------------------------ */
3281 /* Function: ipf_cksum */
3282 /* Returns: u_short - IP header checksum */
3283 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3284 /* len(I) - length of buffer in bytes */
3285 /* */
3286 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3287 /* */
3288 /* N.B.: addr should be 16bit aligned. */
3289 /* ------------------------------------------------------------------------ */
3290 u_short
3291 ipf_cksum(u_short *addr, int len)
3292 {
3293 u_32_t sum = 0;
3294
3295 for (sum = 0; len > 1; len -= 2)
3296 sum += *addr++;
3297
3298 /* mop up an odd byte, if necessary */
3299 if (len == 1)
3300 sum += *(u_char *)addr;
3301
3302 /*
3303 * add back carry outs from top 16 bits to low 16 bits
3304 */
3305 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3306 sum += (sum >> 16); /* add carry */
3307 return (u_short)(~sum);
3308 }
3309
3310
3311 /* ------------------------------------------------------------------------ */
3312 /* Function: fr_cksum */
3313 /* Returns: u_short - layer 4 checksum */
3314 /* Parameters: fin(I) - pointer to packet information */
3315 /* ip(I) - pointer to IP header */
3316 /* l4proto(I) - protocol to caclulate checksum for */
3317 /* l4hdr(I) - pointer to layer 4 header */
3318 /* */
3319 /* Calculates the TCP checksum for the packet held in "m", using the data */
3320 /* in the IP header "ip" to seed it. */
3321 /* */
3322 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3323 /* and the TCP header. We also assume that data blocks aren't allocated in */
3324 /* odd sizes. */
3325 /* */
3326 /* Expects ip_len and ip_off to be in network byte order when called. */
3327 /* ------------------------------------------------------------------------ */
3328 u_short
3329 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3330 {
3331 u_short *sp, slen, sumsave, *csump;
3332 u_int sum, sum2;
3333 int hlen;
3334 int off;
3335 #ifdef USE_INET6
3336 ip6_t *ip6;
3337 #endif
3338
3339 csump = NULL;
3340 sumsave = 0;
3341 sp = NULL;
3342 slen = 0;
3343 hlen = 0;
3344 sum = 0;
3345
3346 sum = htons((u_short)l4proto);
3347 /*
3348 * Add up IP Header portion
3349 */
3350 #ifdef USE_INET6
3351 if (IP_V(ip) == 4) {
3352 #endif
3353 hlen = IP_HL(ip) << 2;
3354 off = hlen;
3355 sp = (u_short *)&ip->ip_src;
3356 sum += *sp++; /* ip_src */
3357 sum += *sp++;
3358 sum += *sp++; /* ip_dst */
3359 sum += *sp++;
3360 #ifdef USE_INET6
3361 } else if (IP_V(ip) == 6) {
3362 ip6 = (ip6_t *)ip;
3363 hlen = sizeof(*ip6);
3364 off = ((char *)fin->fin_dp - (char *)fin->fin_ip);
3365 sp = (u_short *)&ip6->ip6_src;
3366 sum += *sp++; /* ip6_src */
3367 sum += *sp++;
3368 sum += *sp++;
3369 sum += *sp++;
3370 sum += *sp++;
3371 sum += *sp++;
3372 sum += *sp++;
3373 sum += *sp++;
3374 /* This needs to be routing header aware. */
3375 sum += *sp++; /* ip6_dst */
3376 sum += *sp++;
3377 sum += *sp++;
3378 sum += *sp++;
3379 sum += *sp++;
3380 sum += *sp++;
3381 sum += *sp++;
3382 sum += *sp++;
3383 } else {
3384 return 0xffff;
3385 }
3386 #endif
3387 slen = fin->fin_plen - off;
3388 sum += htons(slen);
3389
3390 switch (l4proto)
3391 {
3392 case IPPROTO_UDP :
3393 csump = &((udphdr_t *)l4hdr)->uh_sum;
3394 break;
3395
3396 case IPPROTO_TCP :
3397 csump = &((tcphdr_t *)l4hdr)->th_sum;
3398 break;
3399 case IPPROTO_ICMP :
3400 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3401 sum = 0; /* Pseudo-checksum is not included */
3402 break;
3403 #ifdef USE_INET6
3404 case IPPROTO_ICMPV6 :
3405 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3406 break;
3407 #endif
3408 default :
3409 break;
3410 }
3411
3412 if (csump != NULL) {
3413 sumsave = *csump;
3414 *csump = 0;
3415 }
3416
3417 sum2 = ipf_pcksum(fin, off, sum);
3418 if (csump != NULL)
3419 *csump = sumsave;
3420 return sum2;
3421 }
3422
3423
3424 /* ------------------------------------------------------------------------ */
3425 /* Function: ipf_findgroup */
3426 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3427 /* Parameters: softc(I) - pointer to soft context main structure */
3428 /* group(I) - group name to search for */
3429 /* unit(I) - device to which this group belongs */
3430 /* set(I) - which set of rules (inactive/inactive) this is */
3431 /* fgpp(O) - pointer to place to store pointer to the pointer */
3432 /* to where to add the next (last) group or where */
3433 /* to delete group from. */
3434 /* */
3435 /* Search amongst the defined groups for a particular group number. */
3436 /* ------------------------------------------------------------------------ */
3437 frgroup_t *
3438 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3439 frgroup_t ***fgpp)
3440 {
3441 frgroup_t *fg, **fgp;
3442
3443 /*
3444 * Which list of groups to search in is dependent on which list of
3445 * rules are being operated on.
3446 */
3447 fgp = &softc->ipf_groups[unit][set];
3448
3449 while ((fg = *fgp) != NULL) {
3450 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3451 break;
3452 else
3453 fgp = &fg->fg_next;
3454 }
3455 if (fgpp != NULL)
3456 *fgpp = fgp;
3457 return fg;
3458 }
3459
3460
3461 /* ------------------------------------------------------------------------ */
3462 /* Function: ipf_group_add */
3463 /* Returns: frgroup_t * - NULL == did not create group, */
3464 /* != NULL == pointer to the group */
3465 /* Parameters: softc(I) - pointer to soft context main structure */
3466 /* num(I) - group number to add */
3467 /* head(I) - rule pointer that is using this as the head */
3468 /* flags(I) - rule flags which describe the type of rule it is */
3469 /* unit(I) - device to which this group will belong to */
3470 /* set(I) - which set of rules (inactive/inactive) this is */
3471 /* Write Locks: ipf_mutex */
3472 /* */
3473 /* Add a new group head, or if it already exists, increase the reference */
3474 /* count to it. */
3475 /* ------------------------------------------------------------------------ */
3476 frgroup_t *
3477 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3478 minor_t unit, int set)
3479 {
3480 frgroup_t *fg, **fgp;
3481 u_32_t gflags;
3482
3483 if (group == NULL)
3484 return NULL;
3485
3486 if (unit == IPL_LOGIPF && *group == '\0')
3487 return NULL;
3488
3489 fgp = NULL;
3490 gflags = flags & FR_INOUT;
3491
3492 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3493 if (fg != NULL) {
3494 if (fg->fg_head == NULL && head != NULL)
3495 fg->fg_head = head;
3496 if (fg->fg_flags == 0)
3497 fg->fg_flags = gflags;
3498 else if (gflags != fg->fg_flags)
3499 return NULL;
3500 fg->fg_ref++;
3501 return fg;
3502 }
3503
3504 KMALLOC(fg, frgroup_t *);
3505 if (fg != NULL) {
3506 fg->fg_head = head;
3507 fg->fg_start = NULL;
3508 fg->fg_next = *fgp;
3509 bcopy(group, fg->fg_name, strlen(group) + 1);
3510 fg->fg_flags = gflags;
3511 fg->fg_ref = 1;
3512 fg->fg_set = &softc->ipf_groups[unit][set];
3513 *fgp = fg;
3514 }
3515 return fg;
3516 }
3517
3518
3519 /* ------------------------------------------------------------------------ */
3520 /* Function: ipf_group_del */
3521 /* Returns: int - number of rules deleted */
3522 /* Parameters: softc(I) - pointer to soft context main structure */
3523 /* group(I) - group name to delete */
3524 /* fr(I) - filter rule from which group is referenced */
3525 /* Write Locks: ipf_mutex */
3526 /* */
3527 /* This function is called whenever a reference to a group is to be dropped */
3528 /* and thus its reference count needs to be lowered and the group free'd if */
3529 /* the reference count reaches zero. Passing in fr is really for the sole */
3530 /* purpose of knowing when the head rule is being deleted. */
3531 /* ------------------------------------------------------------------------ */
3532 void
3533 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3534 {
3535
3536 if (group->fg_head == fr)
3537 group->fg_head = NULL;
3538
3539 group->fg_ref--;
3540 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3541 ipf_group_free(group);
3542 }
3543
3544
3545 /* ------------------------------------------------------------------------ */
3546 /* Function: ipf_group_free */
3547 /* Returns: Nil */
3548 /* Parameters: group(I) - pointer to filter rule group */
3549 /* */
3550 /* Remove the group from the list of groups and free it. */
3551 /* ------------------------------------------------------------------------ */
3552 static void
3553 ipf_group_free(frgroup_t *group)
3554 {
3555 frgroup_t **gp;
3556
3557 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3558 if (*gp == group) {
3559 *gp = group->fg_next;
3560 break;
3561 }
3562 }
3563 KFREE(group);
3564 }
3565
3566
3567 /* ------------------------------------------------------------------------ */
3568 /* Function: ipf_group_flush */
3569 /* Returns: int - number of rules flush from group */
3570 /* Parameters: softc(I) - pointer to soft context main structure */
3571 /* Parameters: group(I) - pointer to filter rule group */
3572 /* */
3573 /* Remove all of the rules that currently are listed under the given group. */
3574 /* ------------------------------------------------------------------------ */
3575 static int
3576 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3577 {
3578 int gone = 0;
3579
3580 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3581
3582 return gone;
3583 }
3584
3585
3586 /* ------------------------------------------------------------------------ */
3587 /* Function: ipf_getrulen */
3588 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3589 /* Parameters: softc(I) - pointer to soft context main structure */
3590 /* Parameters: unit(I) - device for which to count the rule's number */
3591 /* flags(I) - which set of rules to find the rule in */
3592 /* group(I) - group name */
3593 /* n(I) - rule number to find */
3594 /* */
3595 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3596 /* group # g doesn't exist or there are less than n rules in the group. */
3597 /* ------------------------------------------------------------------------ */
3598 frentry_t *
3599 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3600 {
3601 frentry_t *fr;
3602 frgroup_t *fg;
3603
3604 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3605 if (fg == NULL)
3606 return NULL;
3607 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3608 ;
3609 if (n != 0)
3610 return NULL;
3611 return fr;
3612 }
3613
3614
3615 /* ------------------------------------------------------------------------ */
3616 /* Function: ipf_flushlist */
3617 /* Returns: int - >= 0 - number of flushed rules */
3618 /* Parameters: softc(I) - pointer to soft context main structure */
3619 /* nfreedp(O) - pointer to int where flush count is stored */
3620 /* listp(I) - pointer to list to flush pointer */
3621 /* Write Locks: ipf_mutex */
3622 /* */
3623 /* Recursively flush rules from the list, descending groups as they are */
3624 /* encountered. if a rule is the head of a group and it has lost all its */
3625 /* group members, then also delete the group reference. nfreedp is needed */
3626 /* to store the accumulating count of rules removed, whereas the returned */
3627 /* value is just the number removed from the current list. The latter is */
3628 /* needed to correctly adjust reference counts on rules that define groups. */
3629 /* */
3630 /* NOTE: Rules not loaded from user space cannot be flushed. */
3631 /* ------------------------------------------------------------------------ */
3632 static int
3633 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3634 {
3635 int freed = 0;
3636 frentry_t *fp;
3637
3638 while ((fp = *listp) != NULL) {
3639 if ((fp->fr_type & FR_T_BUILTIN) ||
3640 !(fp->fr_flags & FR_COPIED)) {
3641 listp = &fp->fr_next;
3642 continue;
3643 }
3644 *listp = fp->fr_next;
3645 if (fp->fr_next != NULL)
3646 fp->fr_next->fr_pnext = fp->fr_pnext;
3647 fp->fr_pnext = NULL;
3648
3649 if (fp->fr_grphead != NULL) {
3650 freed += ipf_group_flush(softc, fp->fr_grphead);
3651 fp->fr_names[fp->fr_grhead] = '\0';
3652 }
3653
3654 if (fp->fr_icmpgrp != NULL) {
3655 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3656 fp->fr_names[fp->fr_icmphead] = '\0';
3657 }
3658
3659 if (fp->fr_srctrack.ht_max_nodes)
3660 ipf_rb_ht_flush(&fp->fr_srctrack);
3661
3662 fp->fr_next = NULL;
3663
3664 ASSERT(fp->fr_ref > 0);
3665 if (ipf_derefrule(softc, &fp) == 0)
3666 freed++;
3667 }
3668 *nfreedp += freed;
3669 return freed;
3670 }
3671
3672
3673 /* ------------------------------------------------------------------------ */
3674 /* Function: ipf_flush */
3675 /* Returns: int - >= 0 - number of flushed rules */
3676 /* Parameters: softc(I) - pointer to soft context main structure */
3677 /* unit(I) - device for which to flush rules */
3678 /* flags(I) - which set of rules to flush */
3679 /* */
3680 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3681 /* and IPv6) as defined by the value of flags. */
3682 /* ------------------------------------------------------------------------ */
3683 int
3684 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3685 {
3686 int flushed = 0, set;
3687
3688 WRITE_ENTER(&softc->ipf_mutex);
3689
3690 set = softc->ipf_active;
3691 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3692 set = 1 - set;
3693
3694 if (flags & FR_OUTQUE) {
3695 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3696 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3697 }
3698 if (flags & FR_INQUE) {
3699 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3700 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3701 }
3702
3703 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3704 flags & (FR_INQUE|FR_OUTQUE));
3705
3706 RWLOCK_EXIT(&softc->ipf_mutex);
3707
3708 if (unit == IPL_LOGIPF) {
3709 int tmp;
3710
3711 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3712 if (tmp >= 0)
3713 flushed += tmp;
3714 }
3715 return flushed;
3716 }
3717
3718
3719 /* ------------------------------------------------------------------------ */
3720 /* Function: ipf_flush_groups */
3721 /* Returns: int - >= 0 - number of flushed rules */
3722 /* Parameters: softc(I) - soft context pointerto work with */
3723 /* grhead(I) - pointer to the start of the group list to flush */
3724 /* flags(I) - which set of rules to flush */
3725 /* */
3726 /* Walk through all of the groups under the given group head and remove all */
3727 /* of those that match the flags passed in. The for loop here is bit more */
3728 /* complicated than usual because the removal of a rule with ipf_derefrule */
3729 /* may end up removing not only the structure pointed to by "fg" but also */
3730 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3731 /* removed from the group then it is necessary to start again. */
3732 /* ------------------------------------------------------------------------ */
3733 static int
3734 ipf_flush_groups( ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3735 {
3736 frentry_t *fr, **frp;
3737 frgroup_t *fg, **fgp;
3738 int flushed = 0;
3739 int removed = 0;
3740
3741 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3742 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3743 fg = fg->fg_next;
3744 if (fg == NULL)
3745 break;
3746 removed = 0;
3747 frp = &fg->fg_start;
3748 while ((removed == 0) && ((fr = *frp) != NULL)) {
3749 if ((fr->fr_flags & flags) == 0) {
3750 frp = &fr->fr_next;
3751 } else {
3752 if (fr->fr_next != NULL)
3753 fr->fr_next->fr_pnext = fr->fr_pnext;
3754 *frp = fr->fr_next;
3755 fr->fr_pnext = NULL;
3756 fr->fr_next = NULL;
3757 (void) ipf_derefrule(softc, &fr);
3758 flushed++;
3759 removed++;
3760 }
3761 }
3762 if (removed == 0)
3763 fgp = &fg->fg_next;
3764 }
3765 return flushed;
3766 }
3767
3768
3769 /* ------------------------------------------------------------------------ */
3770 /* Function: memstr */
3771 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3772 /* Parameters: src(I) - pointer to byte sequence to match */
3773 /* dst(I) - pointer to byte sequence to search */
3774 /* slen(I) - match length */
3775 /* dlen(I) - length available to search in */
3776 /* */
3777 /* Search dst for a sequence of bytes matching those at src and extend for */
3778 /* slen bytes. */
3779 /* ------------------------------------------------------------------------ */
3780 char *
3781 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3782 {
3783 char *s = NULL;
3784
3785 while (dlen >= slen) {
3786 if (memcmp(src, dst, slen) == 0) {
3787 s = dst;
3788 break;
3789 }
3790 dst++;
3791 dlen--;
3792 }
3793 return s;
3794 }
3795
3796
3797 /* ------------------------------------------------------------------------ */
3798 /* Function: ipf_fixskip */
3799 /* Returns: Nil */
3800 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3801 /* rp(I) - rule added/removed with skip in it. */
3802 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3803 /* depending on whether a rule was just added */
3804 /* or removed. */
3805 /* */
3806 /* Adjust all the rules in a list which would have skip'd past the position */
3807 /* where we are inserting to skip to the right place given the change. */
3808 /* ------------------------------------------------------------------------ */
3809 void
3810 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3811 {
3812 int rules, rn;
3813 frentry_t *fp;
3814
3815 rules = 0;
3816 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3817 rules++;
3818
3819 if (!fp)
3820 return;
3821
3822 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3823 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3824 fp->fr_arg += addremove;
3825 }
3826
3827
3828 #ifdef _KERNEL
3829 /* ------------------------------------------------------------------------ */
3830 /* Function: count4bits */
3831 /* Returns: int - >= 0 - number of consecutive bits in input */
3832 /* Parameters: ip(I) - 32bit IP address */
3833 /* */
3834 /* IPv4 ONLY */
3835 /* count consecutive 1's in bit mask. If the mask generated by counting */
3836 /* consecutive 1's is different to that passed, return -1, else return # */
3837 /* of bits. */
3838 /* ------------------------------------------------------------------------ */
3839 int
3840 count4bits(u_32_t ip)
3841 {
3842 u_32_t ipn;
3843 int cnt = 0, i, j;
3844
3845 ip = ipn = ntohl(ip);
3846 for (i = 32; i; i--, ipn *= 2)
3847 if (ipn & 0x80000000)
3848 cnt++;
3849 else
3850 break;
3851 ipn = 0;
3852 for (i = 32, j = cnt; i; i--, j--) {
3853 ipn *= 2;
3854 if (j > 0)
3855 ipn++;
3856 }
3857 if (ipn == ip)
3858 return cnt;
3859 return -1;
3860 }
3861
3862
3863 /* ------------------------------------------------------------------------ */
3864 /* Function: count6bits */
3865 /* Returns: int - >= 0 - number of consecutive bits in input */
3866 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3867 /* */
3868 /* IPv6 ONLY */
3869 /* count consecutive 1's in bit mask. */
3870 /* ------------------------------------------------------------------------ */
3871 # ifdef USE_INET6
3872 int
3873 count6bits(u_32_t *msk)
3874 {
3875 int i = 0, k;
3876 u_32_t j;
3877
3878 for (k = 3; k >= 0; k--)
3879 if (msk[k] == 0xffffffff)
3880 i += 32;
3881 else {
3882 for (j = msk[k]; j; j <<= 1)
3883 if (j & 0x80000000)
3884 i++;
3885 }
3886 return i;
3887 }
3888 # endif
3889 #endif /* _KERNEL */
3890
3891
3892 /* ------------------------------------------------------------------------ */
3893 /* Function: ipf_synclist */
3894 /* Returns: int - 0 = no failures, else indication of first failure */
3895 /* Parameters: fr(I) - start of filter list to sync interface names for */
3896 /* ifp(I) - interface pointer for limiting sync lookups */
3897 /* Write Locks: ipf_mutex */
3898 /* */
3899 /* Walk through a list of filter rules and resolve any interface names into */
3900 /* pointers. Where dynamic addresses are used, also update the IP address */
3901 /* used in the rule. The interface pointer is used to limit the lookups to */
3902 /* a specific set of matching names if it is non-NULL. */
3903 /* Errors can occur when resolving the destination name of to/dup-to fields */
3904 /* when the name points to a pool and that pool doest not exist. If this */
3905 /* does happen then it is necessary to check if there are any lookup refs */
3906 /* that need to be dropped before returning with an error. */
3907 /* ------------------------------------------------------------------------ */
3908 static int
3909 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3910 {
3911 frentry_t *frt, *start = fr;
3912 frdest_t *fdp;
3913 char *name;
3914 int error;
3915 void *ifa;
3916 int v, i;
3917
3918 error = 0;
3919
3920 for (; fr; fr = fr->fr_next) {
3921 if (fr->fr_family == AF_INET)
3922 v = 4;
3923 else if (fr->fr_family == AF_INET6)
3924 v = 6;
3925 else
3926 v = 0;
3927
3928 /*
3929 * Lookup all the interface names that are part of the rule.
3930 */
3931 for (i = 0; i < 4; i++) {
3932 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3933 continue;
3934 if (fr->fr_ifnames[i] == -1)
3935 continue;
3936 name = FR_NAME(fr, fr_ifnames[i]);
3937 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3938 }
3939
3940 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3941 if (fr->fr_satype != FRI_NORMAL &&
3942 fr->fr_satype != FRI_LOOKUP) {
3943 ifa = ipf_resolvenic(softc, fr->fr_names +
3944 fr->fr_sifpidx, v);
3945 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3946 &fr->fr_src6, &fr->fr_smsk6);
3947 }
3948 if (fr->fr_datype != FRI_NORMAL &&
3949 fr->fr_datype != FRI_LOOKUP) {
3950 ifa = ipf_resolvenic(softc, fr->fr_names +
3951 fr->fr_sifpidx, v);
3952 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
3953 &fr->fr_dst6, &fr->fr_dmsk6);
3954 }
3955 }
3956
3957 fdp = &fr->fr_tifs[0];
3958 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3959 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3960 if (error != 0)
3961 goto unwind;
3962 }
3963
3964 fdp = &fr->fr_tifs[1];
3965 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3966 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3967 if (error != 0)
3968 goto unwind;
3969 }
3970
3971 fdp = &fr->fr_dif;
3972 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3973 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3974 if (error != 0)
3975 goto unwind;
3976 }
3977
3978 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3979 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
3980 fr->fr_srcptr = ipf_lookup_res_num(softc,
3981 fr->fr_srctype,
3982 IPL_LOGIPF,
3983 fr->fr_srcnum,
3984 &fr->fr_srcfunc);
3985 }
3986 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3987 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
3988 fr->fr_dstptr = ipf_lookup_res_num(softc,
3989 fr->fr_dsttype,
3990 IPL_LOGIPF,
3991 fr->fr_dstnum,
3992 &fr->fr_dstfunc);
3993 }
3994 }
3995 return 0;
3996
3997 unwind:
3998 for (frt = start; frt != fr; fr = fr->fr_next) {
3999 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4000 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
4001 ipf_lookup_deref(softc, frt->fr_srctype,
4002 frt->fr_srcptr);
4003 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
4004 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4005 ipf_lookup_deref(softc, frt->fr_dsttype,
4006 frt->fr_dstptr);
4007 }
4008 return error;
4009 }
4010
4011
4012 /* ------------------------------------------------------------------------ */
4013 /* Function: ipf_sync */
4014 /* Returns: void */
4015 /* Parameters: Nil */
4016 /* */
4017 /* ipf_sync() is called when we suspect that the interface list or */
4018 /* information about interfaces (like IP#) has changed. Go through all */
4019 /* filter rules, NAT entries and the state table and check if anything */
4020 /* needs to be changed/updated. */
4021 /* ------------------------------------------------------------------------ */
4022 int
4023 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4024 {
4025 int i;
4026
4027 # if !SOLARIS
4028 ipf_nat_sync(softc, ifp);
4029 ipf_state_sync(softc, ifp);
4030 ipf_lookup_sync(softc, ifp);
4031 # endif
4032
4033 WRITE_ENTER(&softc->ipf_mutex);
4034 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4035 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4036 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4037 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4038
4039 for (i = 0; i < IPL_LOGSIZE; i++) {
4040 frgroup_t *g;
4041
4042 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4043 (void) ipf_synclist(softc, g->fg_start, ifp);
4044 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4045 (void) ipf_synclist(softc, g->fg_start, ifp);
4046 }
4047 RWLOCK_EXIT(&softc->ipf_mutex);
4048
4049 return 0;
4050 }
4051
4052
4053 /*
4054 * In the functions below, bcopy() is called because the pointer being
4055 * copied _from_ in this instance is a pointer to a char buf (which could
4056 * end up being unaligned) and on the kernel's local stack.
4057 */
4058 /* ------------------------------------------------------------------------ */
4059 /* Function: copyinptr */
4060 /* Returns: int - 0 = success, else failure */
4061 /* Parameters: src(I) - pointer to the source address */
4062 /* dst(I) - destination address */
4063 /* size(I) - number of bytes to copy */
4064 /* */
4065 /* Copy a block of data in from user space, given a pointer to the pointer */
4066 /* to start copying from (src) and a pointer to where to store it (dst). */
4067 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4068 /* ------------------------------------------------------------------------ */
4069 int
4070 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4071 {
4072 void *ca;
4073 int error;
4074
4075 # if SOLARIS
4076 error = COPYIN(src, &ca, sizeof(ca));
4077 if (error != 0)
4078 return error;
4079 # else
4080 bcopy(src, (void *)&ca, sizeof(ca));
4081 # endif
4082 error = COPYIN(ca, dst, size);
4083 if (error != 0) {
4084 IPFERROR(3);
4085 error = EFAULT;
4086 }
4087 return error;
4088 }
4089
4090
4091 /* ------------------------------------------------------------------------ */
4092 /* Function: copyoutptr */
4093 /* Returns: int - 0 = success, else failure */
4094 /* Parameters: src(I) - pointer to the source address */
4095 /* dst(I) - destination address */
4096 /* size(I) - number of bytes to copy */
4097 /* */
4098 /* Copy a block of data out to user space, given a pointer to the pointer */
4099 /* to start copying from (src) and a pointer to where to store it (dst). */
4100 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4101 /* ------------------------------------------------------------------------ */
4102 int
4103 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4104 {
4105 void *ca;
4106 int error;
4107
4108 bcopy(dst, &ca, sizeof(ca));
4109 error = COPYOUT(src, ca, size);
4110 if (error != 0) {
4111 IPFERROR(4);
4112 error = EFAULT;
4113 }
4114 return error;
4115 }
4116 #ifdef _KERNEL
4117 #endif
4118
4119
4120 /* ------------------------------------------------------------------------ */
4121 /* Function: ipf_lock */
4122 /* Returns: int - 0 = success, else error */
4123 /* Parameters: data(I) - pointer to lock value to set */
4124 /* lockp(O) - pointer to location to store old lock value */
4125 /* */
4126 /* Get the new value for the lock integer, set it and return the old value */
4127 /* in *lockp. */
4128 /* ------------------------------------------------------------------------ */
4129 int
4130 ipf_lock(void *data, int *lockp)
4131 {
4132 int arg, err;
4133
4134 err = BCOPYIN(data, &arg, sizeof(arg));
4135 if (err != 0)
4136 return EFAULT;
4137 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4138 if (err != 0)
4139 return EFAULT;
4140 *lockp = arg;
4141 return 0;
4142 }
4143
4144
4145 /* ------------------------------------------------------------------------ */
4146 /* Function: ipf_getstat */
4147 /* Returns: Nil */
4148 /* Parameters: softc(I) - pointer to soft context main structure */
4149 /* fiop(I) - pointer to ipfilter stats structure */
4150 /* rev(I) - version claim by program doing ioctl */
4151 /* */
4152 /* Stores a copy of current pointers, counters, etc, in the friostat */
4153 /* structure. */
4154 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4155 /* program is looking for. This ensure that validation of the version it */
4156 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4157 /* allow older binaries to work but kernels without it will not. */
4158 /* ------------------------------------------------------------------------ */
4159 /*ARGSUSED*/
4160 static void
4161 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4162 {
4163 int i;
4164
4165 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4166 sizeof(ipf_statistics_t) * 2);
4167 fiop->f_locks[IPL_LOGSTATE] = -1;
4168 fiop->f_locks[IPL_LOGNAT] = -1;
4169 fiop->f_locks[IPL_LOGIPF] = -1;
4170 fiop->f_locks[IPL_LOGAUTH] = -1;
4171
4172 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4173 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4174 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4175 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4176 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4177 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4178 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4179 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4180
4181 fiop->f_ticks = softc->ipf_ticks;
4182 fiop->f_active = softc->ipf_active;
4183 fiop->f_froute[0] = softc->ipf_frouteok[0];
4184 fiop->f_froute[1] = softc->ipf_frouteok[1];
4185 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4186 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4187
4188 fiop->f_running = softc->ipf_running;
4189 for (i = 0; i < IPL_LOGSIZE; i++) {
4190 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4191 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4192 }
4193 #ifdef IPFILTER_LOG
4194 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4195 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4196 fiop->f_logging = 1;
4197 #else
4198 fiop->f_log_ok = 0;
4199 fiop->f_log_fail = 0;
4200 fiop->f_logging = 0;
4201 #endif
4202 fiop->f_defpass = softc->ipf_pass;
4203 fiop->f_features = ipf_features;
4204
4205 #ifdef IPFILTER_COMPAT
4206 snprintf(fiop->f_version, sizeof(fiop->f_version),
4207 "IP Filter: v%d.%d.%d", (rev / 1000000) % 100,
4208 (rev / 10000) % 100, (rev / 100) % 100);
4209 #else
4210 rev = rev;
4211 (void) strncpy(fiop->f_version, ipfilter_version,
4212 sizeof(fiop->f_version));
4213 fiop->f_version[sizeof(fiop->f_version) - 1] = '\0';
4214 #endif
4215 }
4216
4217
4218 #ifdef USE_INET6
4219 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4220 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4221 -1, /* 1: UNUSED */
4222 -1, /* 2: UNUSED */
4223 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4224 -1, /* 4: ICMP_SOURCEQUENCH */
4225 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4226 -1, /* 6: UNUSED */
4227 -1, /* 7: UNUSED */
4228 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4229 -1, /* 9: UNUSED */
4230 -1, /* 10: UNUSED */
4231 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4232 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4233 -1, /* 13: ICMP_TSTAMP */
4234 -1, /* 14: ICMP_TSTAMPREPLY */
4235 -1, /* 15: ICMP_IREQ */
4236 -1, /* 16: ICMP_IREQREPLY */
4237 -1, /* 17: ICMP_MASKREQ */
4238 -1, /* 18: ICMP_MASKREPLY */
4239 };
4240
4241
4242 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4243 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4244 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4245 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4246 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4247 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4248 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4249 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4250 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4251 -1, /* 8: ICMP_UNREACH_ISOLATED */
4252 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4253 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4254 -1, /* 11: ICMP_UNREACH_TOSNET */
4255 -1, /* 12: ICMP_UNREACH_TOSHOST */
4256 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4257 };
4258 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4259 #endif
4260
4261 int icmpreplytype4[ICMP_MAXTYPE + 1];
4262
4263
4264 /* ------------------------------------------------------------------------ */
4265 /* Function: ipf_matchicmpqueryreply */
4266 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4267 /* Parameters: v(I) - IP protocol version (4 or 6) */
4268 /* ic(I) - ICMP information */
4269 /* icmp(I) - ICMP packet header */
4270 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4271 /* */
4272 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4273 /* reply to one as described by what's in ic. If it is a match, return 1, */
4274 /* else return 0 for no match. */
4275 /* ------------------------------------------------------------------------ */
4276 int
4277 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4278 {
4279 int ictype;
4280
4281 ictype = ic->ici_type;
4282
4283 if (v == 4) {
4284 /*
4285 * If we matched its type on the way in, then when going out
4286 * it will still be the same type.
4287 */
4288 if ((!rev && (icmp->icmp_type == ictype)) ||
4289 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4290 if (icmp->icmp_type != ICMP_ECHOREPLY)
4291 return 1;
4292 if (icmp->icmp_id == ic->ici_id)
4293 return 1;
4294 }
4295 }
4296 #ifdef USE_INET6
4297 else if (v == 6) {
4298 if ((!rev && (icmp->icmp_type == ictype)) ||
4299 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4300 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4301 return 1;
4302 if (icmp->icmp_id == ic->ici_id)
4303 return 1;
4304 }
4305 }
4306 #endif
4307 return 0;
4308 }
4309
4310
4311 /* ------------------------------------------------------------------------ */
4312 /* Function: frrequest */
4313 /* Returns: int - 0 == success, > 0 == errno value */
4314 /* Parameters: unit(I) - device for which this is for */
4315 /* req(I) - ioctl command (SIOC*) */
4316 /* data(I) - pointr to ioctl data */
4317 /* set(I) - 1 or 0 (filter set) */
4318 /* makecopy(I) - flag indicating whether data points to a rule */
4319 /* in kernel space & hence doesn't need copying. */
4320 /* */
4321 /* This function handles all the requests which operate on the list of */
4322 /* filter rules. This includes adding, deleting, insertion. It is also */
4323 /* responsible for creating groups when a "head" rule is loaded. Interface */
4324 /* names are resolved here and other sanity checks are made on the content */
4325 /* of the rule structure being loaded. If a rule has user defined timeouts */
4326 /* then make sure they are created and initialised before exiting. */
4327 /* ------------------------------------------------------------------------ */
4328 int
4329 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, void *data,
4330 int set, int makecopy)
4331 {
4332 int error = 0, in, family, addrem, need_free = 0;
4333 frentry_t frd, *fp, *f, **fprev, **ftail;
4334 void *ptr, *uptr;
4335 u_int *p, *pp;
4336 frgroup_t *fg;
4337 char *group;
4338
4339 ptr = NULL;
4340 fg = NULL;
4341 fp = &frd;
4342 if (makecopy != 0) {
4343 bzero(fp, sizeof(frd));
4344 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4345 if (error) {
4346 return error;
4347 }
4348 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4349 IPFERROR(6);
4350 return EINVAL;
4351 }
4352 KMALLOCS(f, frentry_t *, fp->fr_size);
4353 if (f == NULL) {
4354 IPFERROR(131);
4355 return ENOMEM;
4356 }
4357 bzero(f, fp->fr_size);
4358 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4359 fp->fr_size);
4360 if (error) {
4361 KFREES(f, fp->fr_size);
4362 return error;
4363 }
4364
4365 fp = f;
4366 f = NULL;
4367 fp->fr_next = NULL;
4368 fp->fr_dnext = NULL;
4369 fp->fr_pnext = NULL;
4370 fp->fr_pdnext = NULL;
4371 fp->fr_grp = NULL;
4372 fp->fr_grphead = NULL;
4373 fp->fr_icmpgrp = NULL;
4374 fp->fr_isc = (void *)-1;
4375 fp->fr_ptr = NULL;
4376 fp->fr_ref = 0;
4377 fp->fr_flags |= FR_COPIED;
4378 } else {
4379 fp = (frentry_t *)data;
4380 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4381 IPFERROR(7);
4382 return EINVAL;
4383 }
4384 fp->fr_flags &= ~FR_COPIED;
4385 }
4386
4387 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4388 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4389 IPFERROR(8);
4390 error = EINVAL;
4391 goto donenolock;
4392 }
4393
4394 family = fp->fr_family;
4395 uptr = fp->fr_data;
4396
4397 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4398 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4399 addrem = 0;
4400 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4401 addrem = 1;
4402 else if (req == (ioctlcmd_t)SIOCZRLST)
4403 addrem = 2;
4404 else {
4405 IPFERROR(9);
4406 error = EINVAL;
4407 goto donenolock;
4408 }
4409
4410 /*
4411 * Only filter rules for IPv4 or IPv6 are accepted.
4412 */
4413 if (family == AF_INET) {
4414 /*EMPTY*/;
4415 #ifdef USE_INET6
4416 } else if (family == AF_INET6) {
4417 /*EMPTY*/;
4418 #endif
4419 } else if (family != 0) {
4420 IPFERROR(10);
4421 error = EINVAL;
4422 goto donenolock;
4423 }
4424
4425 /*
4426 * If the rule is being loaded from user space, i.e. we had to copy it
4427 * into kernel space, then do not trust the function pointer in the
4428 * rule.
4429 */
4430 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4431 if (ipf_findfunc(fp->fr_func) == NULL) {
4432 IPFERROR(11);
4433 error = ESRCH;
4434 goto donenolock;
4435 }
4436
4437 if (addrem == 0) {
4438 error = ipf_funcinit(softc, fp);
4439 if (error != 0)
4440 goto donenolock;
4441 }
4442 }
4443 if ((fp->fr_flags & FR_CALLNOW) &&
4444 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4445 IPFERROR(142);
4446 error = ESRCH;
4447 goto donenolock;
4448 }
4449 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4450 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4451 IPFERROR(143);
4452 error = ESRCH;
4453 goto donenolock;
4454 }
4455
4456 ptr = NULL;
4457
4458 if (FR_ISACCOUNT(fp->fr_flags))
4459 unit = IPL_LOGCOUNT;
4460
4461 /*
4462 * Check that each group name in the rule has a start index that
4463 * is valid.
4464 */
4465 if (fp->fr_icmphead != -1) {
4466 if ((fp->fr_icmphead < 0) ||
4467 (fp->fr_icmphead >= fp->fr_namelen)) {
4468 IPFERROR(136);
4469 error = EINVAL;
4470 goto donenolock;
4471 }
4472 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4473 fp->fr_names[fp->fr_icmphead] = '\0';
4474 }
4475
4476 if (fp->fr_grhead != -1) {
4477 if ((fp->fr_grhead < 0) ||
4478 (fp->fr_grhead >= fp->fr_namelen)) {
4479 IPFERROR(137);
4480 error = EINVAL;
4481 goto donenolock;
4482 }
4483 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4484 fp->fr_names[fp->fr_grhead] = '\0';
4485 }
4486
4487 if (fp->fr_group != -1) {
4488 if ((fp->fr_group < 0) ||
4489 (fp->fr_group >= fp->fr_namelen)) {
4490 IPFERROR(138);
4491 error = EINVAL;
4492 goto donenolock;
4493 }
4494 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4495 /*
4496 * Allow loading rules that are in groups to cause
4497 * them to be created if they don't already exit.
4498 */
4499 group = FR_NAME(fp, fr_group);
4500 if (addrem == 0) {
4501 fg = ipf_group_add(softc, group, NULL,
4502 fp->fr_flags, unit, set);
4503 if (fg == NULL) {
4504 IPFERROR(152);
4505 error = ESRCH;
4506 goto donenolock;
4507 }
4508 fp->fr_grp = fg;
4509 } else {
4510 fg = ipf_findgroup(softc, group, unit,
4511 set, NULL);
4512 if (fg == NULL) {
4513 IPFERROR(12);
4514 error = ESRCH;
4515 goto donenolock;
4516 }
4517 }
4518
4519 if (fg->fg_flags == 0) {
4520 fg->fg_flags = fp->fr_flags & FR_INOUT;
4521 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4522 IPFERROR(13);
4523 error = ESRCH;
4524 goto donenolock;
4525 }
4526 }
4527 } else {
4528 /*
4529 * If a rule is going to be part of a group then it does
4530 * not matter whether it is an in or out rule, but if it
4531 * isn't in a group, then it does...
4532 */
4533 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4534 IPFERROR(14);
4535 error = EINVAL;
4536 goto donenolock;
4537 }
4538 }
4539 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4540
4541 /*
4542 * Work out which rule list this change is being applied to.
4543 */
4544 ftail = NULL;
4545 fprev = NULL;
4546 if (unit == IPL_LOGAUTH) {
4547 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4548 (fp->fr_tifs[1].fd_ptr != NULL) ||
4549 (fp->fr_dif.fd_ptr != NULL) ||
4550 (fp->fr_flags & FR_FASTROUTE)) {
4551 IPFERROR(145);
4552 error = EINVAL;
4553 goto donenolock;
4554 }
4555 fprev = ipf_auth_rulehead(softc);
4556 } else {
4557 if (FR_ISACCOUNT(fp->fr_flags))
4558 fprev = &softc->ipf_acct[in][set];
4559 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4560 fprev = &softc->ipf_rules[in][set];
4561 }
4562 if (fprev == NULL) {
4563 IPFERROR(15);
4564 error = ESRCH;
4565 goto donenolock;
4566 }
4567
4568 if (fg != NULL)
4569 fprev = &fg->fg_start;
4570
4571 /*
4572 * Copy in extra data for the rule.
4573 */
4574 if (fp->fr_dsize != 0) {
4575 if (makecopy != 0) {
4576 KMALLOCS(ptr, void *, fp->fr_dsize);
4577 if (ptr == NULL) {
4578 IPFERROR(16);
4579 error = ENOMEM;
4580 goto donenolock;
4581 }
4582
4583 /*
4584 * The bcopy case is for when the data is appended
4585 * to the rule by ipf_in_compat().
4586 */
4587 if (uptr >= (void *)fp &&
4588 uptr < (void *)((char *)fp + fp->fr_size)) {
4589 bcopy(uptr, ptr, fp->fr_dsize);
4590 error = 0;
4591 } else {
4592 error = COPYIN(uptr, ptr, fp->fr_dsize);
4593 if (error != 0) {
4594 IPFERROR(17);
4595 error = EFAULT;
4596 goto donenolock;
4597 }
4598 }
4599 } else {
4600 ptr = uptr;
4601 }
4602 fp->fr_data = ptr;
4603 } else {
4604 fp->fr_data = NULL;
4605 }
4606
4607 /*
4608 * Perform per-rule type sanity checks of their members.
4609 * All code after this needs to be aware that allocated memory
4610 * may need to be free'd before exiting.
4611 */
4612 switch (fp->fr_type & ~FR_T_BUILTIN)
4613 {
4614 #if defined(IPFILTER_BPF)
4615 case FR_T_BPFOPC :
4616 if (fp->fr_dsize == 0) {
4617 IPFERROR(19);
4618 error = EINVAL;
4619 break;
4620 }
4621 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4622 IPFERROR(20);
4623 error = EINVAL;
4624 break;
4625 }
4626 break;
4627 #endif
4628 case FR_T_IPF :
4629 /*
4630 * Preparation for error case at the bottom of this function.
4631 */
4632 if (fp->fr_datype == FRI_LOOKUP)
4633 fp->fr_dstptr = NULL;
4634 if (fp->fr_satype == FRI_LOOKUP)
4635 fp->fr_srcptr = NULL;
4636
4637 if (fp->fr_dsize != sizeof(fripf_t)) {
4638 IPFERROR(21);
4639 error = EINVAL;
4640 break;
4641 }
4642
4643 /*
4644 * Allowing a rule with both "keep state" and "with oow" is
4645 * pointless because adding a state entry to the table will
4646 * fail with the out of window (oow) flag set.
4647 */
4648 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4649 IPFERROR(22);
4650 error = EINVAL;
4651 break;
4652 }
4653
4654 switch (fp->fr_satype)
4655 {
4656 case FRI_BROADCAST :
4657 case FRI_DYNAMIC :
4658 case FRI_NETWORK :
4659 case FRI_NETMASKED :
4660 case FRI_PEERADDR :
4661 if (fp->fr_sifpidx < 0) {
4662 IPFERROR(23);
4663 error = EINVAL;
4664 }
4665 break;
4666 case FRI_LOOKUP :
4667 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4668 &fp->fr_src6,
4669 &fp->fr_smsk6);
4670 if (fp->fr_srcfunc == NULL) {
4671 IPFERROR(132);
4672 error = ESRCH;
4673 break;
4674 }
4675 break;
4676 case FRI_NORMAL :
4677 break;
4678 default :
4679 IPFERROR(133);
4680 error = EINVAL;
4681 break;
4682 }
4683 if (error != 0)
4684 break;
4685
4686 switch (fp->fr_datype)
4687 {
4688 case FRI_BROADCAST :
4689 case FRI_DYNAMIC :
4690 case FRI_NETWORK :
4691 case FRI_NETMASKED :
4692 case FRI_PEERADDR :
4693 if (fp->fr_difpidx < 0) {
4694 IPFERROR(24);
4695 error = EINVAL;
4696 }
4697 break;
4698 case FRI_LOOKUP :
4699 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4700 &fp->fr_dst6,
4701 &fp->fr_dmsk6);
4702 if (fp->fr_dstfunc == NULL) {
4703 IPFERROR(134);
4704 error = ESRCH;
4705 }
4706 break;
4707 case FRI_NORMAL :
4708 break;
4709 default :
4710 IPFERROR(135);
4711 error = EINVAL;
4712 }
4713 break;
4714
4715 case FR_T_NONE :
4716 case FR_T_CALLFUNC :
4717 case FR_T_COMPIPF :
4718 break;
4719
4720 case FR_T_IPFEXPR :
4721 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4722 IPFERROR(25);
4723 error = EINVAL;
4724 }
4725 break;
4726
4727 default :
4728 IPFERROR(26);
4729 error = EINVAL;
4730 break;
4731 }
4732 if (error != 0)
4733 goto donenolock;
4734
4735 if (fp->fr_tif.fd_name != -1) {
4736 if ((fp->fr_tif.fd_name < 0) ||
4737 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4738 IPFERROR(139);
4739 error = EINVAL;
4740 goto donenolock;
4741 }
4742 }
4743
4744 if (fp->fr_dif.fd_name != -1) {
4745 if ((fp->fr_dif.fd_name < 0) ||
4746 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4747 IPFERROR(140);
4748 error = EINVAL;
4749 goto donenolock;
4750 }
4751 }
4752
4753 if (fp->fr_rif.fd_name != -1) {
4754 if ((fp->fr_rif.fd_name < 0) ||
4755 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4756 IPFERROR(141);
4757 error = EINVAL;
4758 goto donenolock;
4759 }
4760 }
4761
4762 /*
4763 * Lookup all the interface names that are part of the rule.
4764 */
4765 error = ipf_synclist(softc, fp, NULL);
4766 if (error != 0)
4767 goto donenolock;
4768 fp->fr_statecnt = 0;
4769 if (fp->fr_srctrack.ht_max_nodes != 0)
4770 ipf_rb_ht_init(&fp->fr_srctrack);
4771
4772 /*
4773 * Look for an existing matching filter rule, but don't include the
4774 * next or interface pointer in the comparison (fr_next, fr_ifa).
4775 * This elminates rules which are indentical being loaded. Checksum
4776 * the constant part of the filter rule to make comparisons quicker
4777 * (this meaning no pointers are included).
4778 */
4779 for (fp->fr_cksum = 0, p = (u_int *)&fp->fr_func, pp = &fp->fr_cksum;
4780 p < pp; p++)
4781 fp->fr_cksum += *p;
4782 pp = (u_int *)((char *)fp->fr_caddr + fp->fr_dsize);
4783 for (p = (u_int *)fp->fr_data; p < pp; p++)
4784 fp->fr_cksum += *p;
4785
4786 WRITE_ENTER(&softc->ipf_mutex);
4787
4788 /*
4789 * Now that the filter rule lists are locked, we can walk the
4790 * chain of them without fear.
4791 */
4792 ftail = fprev;
4793 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4794 if (fp->fr_collect <= f->fr_collect) {
4795 ftail = fprev;
4796 f = NULL;
4797 break;
4798 }
4799 fprev = ftail;
4800 }
4801
4802 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4803 DT2(rule_cmp, frentry_t *, fp, frentry_t *, f);
4804 if ((fp->fr_cksum != f->fr_cksum) ||
4805 (fp->fr_size != f->fr_size) ||
4806 (f->fr_dsize != fp->fr_dsize))
4807 continue;
4808 if (bcmp((char *)&f->fr_func, (char *)&fp->fr_func,
4809 fp->fr_size - offsetof(struct frentry, fr_func)) != 0)
4810 continue;
4811 if ((!ptr && !f->fr_data) ||
4812 (ptr && f->fr_data &&
4813 !bcmp((char *)ptr, (char *)f->fr_data, f->fr_dsize)))
4814 break;
4815 }
4816
4817 /*
4818 * If zero'ing statistics, copy current to caller and zero.
4819 */
4820 if (addrem == 2) {
4821 if (f == NULL) {
4822 IPFERROR(27);
4823 error = ESRCH;
4824 } else {
4825 /*
4826 * Copy and reduce lock because of impending copyout.
4827 * Well we should, but if we do then the atomicity of
4828 * this call and the correctness of fr_hits and
4829 * fr_bytes cannot be guaranteed. As it is, this code
4830 * only resets them to 0 if they are successfully
4831 * copied out into user space.
4832 */
4833 bcopy((char *)f, (char *)fp, f->fr_size);
4834 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4835
4836 /*
4837 * When we copy this rule back out, set the data
4838 * pointer to be what it was in user space.
4839 */
4840 fp->fr_data = uptr;
4841 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4842
4843 if (error == 0) {
4844 if ((f->fr_dsize != 0) && (uptr != NULL))
4845 error = COPYOUT(f->fr_data, uptr,
4846 f->fr_dsize);
4847 if (error != 0) {
4848 IPFERROR(28);
4849 error = EFAULT;
4850 }
4851 if (error == 0) {
4852 f->fr_hits = 0;
4853 f->fr_bytes = 0;
4854 }
4855 }
4856 }
4857
4858 if (makecopy != 0) {
4859 if (ptr != NULL) {
4860 KFREES(ptr, fp->fr_dsize);
4861 }
4862 KFREES(fp, fp->fr_size);
4863 }
4864 RWLOCK_EXIT(&softc->ipf_mutex);
4865 return error;
4866 }
4867
4868 if (!f) {
4869 /*
4870 * At the end of this, ftail must point to the place where the
4871 * new rule is to be saved/inserted/added.
4872 * For SIOCAD*FR, this should be the last rule in the group of
4873 * rules that have equal fr_collect fields.
4874 * For SIOCIN*FR, ...
4875 */
4876 if (req == (ioctlcmd_t)SIOCADAFR ||
4877 req == (ioctlcmd_t)SIOCADIFR) {
4878
4879 for (ftail = fprev; (f = *ftail) != NULL; ) {
4880 if (f->fr_collect > fp->fr_collect)
4881 break;
4882 ftail = &f->fr_next;
4883 fprev = ftail;
4884 }
4885 ftail = fprev;
4886 f = NULL;
4887 ptr = NULL;
4888 } else if (req == (ioctlcmd_t)SIOCINAFR ||
4889 req == (ioctlcmd_t)SIOCINIFR) {
4890 while ((f = *fprev) != NULL) {
4891 if (f->fr_collect >= fp->fr_collect)
4892 break;
4893 fprev = &f->fr_next;
4894 }
4895 ftail = fprev;
4896 if (fp->fr_hits != 0) {
4897 while (fp->fr_hits && (f = *ftail)) {
4898 if (f->fr_collect != fp->fr_collect)
4899 break;
4900 fprev = ftail;
4901 ftail = &f->fr_next;
4902 fp->fr_hits--;
4903 }
4904 }
4905 f = NULL;
4906 ptr = NULL;
4907 }
4908 }
4909
4910 /*
4911 * Request to remove a rule.
4912 */
4913 if (addrem == 1) {
4914 if (!f) {
4915 IPFERROR(29);
4916 error = ESRCH;
4917 } else {
4918 /*
4919 * Do not allow activity from user space to interfere
4920 * with rules not loaded that way.
4921 */
4922 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
4923 IPFERROR(30);
4924 error = EPERM;
4925 goto done;
4926 }
4927
4928 /*
4929 * Return EBUSY if the rule is being reference by
4930 * something else (eg state information.)
4931 */
4932 if (f->fr_ref > 1) {
4933 IPFERROR(31);
4934 error = EBUSY;
4935 goto done;
4936 }
4937 #ifdef IPFILTER_SCAN
4938 if (f->fr_isctag != -1 &&
4939 (f->fr_isc != (struct ipscan *)-1))
4940 ipf_scan_detachfr(f);
4941 #endif
4942
4943 if (unit == IPL_LOGAUTH) {
4944 error = ipf_auth_precmd(softc, req, f, ftail);
4945 goto done;
4946 }
4947
4948 ipf_rule_delete(softc, f, unit, set);
4949
4950 need_free = makecopy;
4951 }
4952 } else {
4953 /*
4954 * Not removing, so we must be adding/inserting a rule.
4955 */
4956 if (f != NULL) {
4957 IPFERROR(32);
4958 error = EEXIST;
4959 goto done;
4960 }
4961 if (unit == IPL_LOGAUTH) {
4962 error = ipf_auth_precmd(softc, req, fp, ftail);
4963 goto done;
4964 }
4965
4966 MUTEX_NUKE(&fp->fr_lock);
4967 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
4968 if (fp->fr_die != 0)
4969 ipf_rule_expire_insert(softc, fp, set);
4970
4971 fp->fr_hits = 0;
4972 if (makecopy != 0)
4973 fp->fr_ref = 1;
4974 fp->fr_pnext = ftail;
4975 fp->fr_next = *ftail;
4976 if (fp->fr_next != NULL)
4977 fp->fr_next->fr_pnext = &fp->fr_next;
4978 *ftail = fp;
4979 if (addrem == 0)
4980 ipf_fixskip(ftail, fp, 1);
4981
4982 fp->fr_icmpgrp = NULL;
4983 if (fp->fr_icmphead != -1) {
4984 group = FR_NAME(fp, fr_icmphead);
4985 fg = ipf_group_add(softc, group, fp, 0, unit, set);
4986 fp->fr_icmpgrp = fg;
4987 }
4988
4989 fp->fr_grphead = NULL;
4990 if (fp->fr_grhead != -1) {
4991 group = FR_NAME(fp, fr_grhead);
4992 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
4993 unit, set);
4994 fp->fr_grphead = fg;
4995 }
4996 }
4997 done:
4998 RWLOCK_EXIT(&softc->ipf_mutex);
4999 donenolock:
5000 if (need_free || (error != 0)) {
5001 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5002 if ((fp->fr_satype == FRI_LOOKUP) &&
5003 (fp->fr_srcptr != NULL))
5004 ipf_lookup_deref(softc, fp->fr_srctype,
5005 fp->fr_srcptr);
5006 if ((fp->fr_datype == FRI_LOOKUP) &&
5007 (fp->fr_dstptr != NULL))
5008 ipf_lookup_deref(softc, fp->fr_dsttype,
5009 fp->fr_dstptr);
5010 }
5011 if (fp->fr_grp != NULL) {
5012 WRITE_ENTER(&softc->ipf_mutex);
5013 ipf_group_del(softc, fp->fr_grp, fp);
5014 RWLOCK_EXIT(&softc->ipf_mutex);
5015 }
5016 if ((ptr != NULL) && (makecopy != 0)) {
5017 KFREES(ptr, fp->fr_dsize);
5018 }
5019 KFREES(fp, fp->fr_size);
5020 }
5021 return (error);
5022 }
5023
5024
5025 /* ------------------------------------------------------------------------ */
5026 /* Function: ipf_rule_delete */
5027 /* Returns: Nil */
5028 /* Parameters: softc(I) - pointer to soft context main structure */
5029 /* f(I) - pointer to the rule being deleted */
5030 /* ftail(I) - pointer to the pointer to f */
5031 /* unit(I) - device for which this is for */
5032 /* set(I) - 1 or 0 (filter set) */
5033 /* */
5034 /* This function attempts to do what it can to delete a filter rule: remove */
5035 /* it from any linked lists and remove any groups it is responsible for. */
5036 /* But in the end, removing a rule can only drop the reference count - we */
5037 /* must use that as the guide for whether or not it can be freed. */
5038 /* ------------------------------------------------------------------------ */
5039 static void
5040 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5041 {
5042
5043 /*
5044 * If fr_pdnext is set, then the rule is on the expire list, so
5045 * remove it from there.
5046 */
5047 if (f->fr_pdnext != NULL) {
5048 *f->fr_pdnext = f->fr_dnext;
5049 if (f->fr_dnext != NULL)
5050 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5051 f->fr_pdnext = NULL;
5052 f->fr_dnext = NULL;
5053 }
5054
5055 ipf_fixskip(f->fr_pnext, f, -1);
5056 if (f->fr_pnext != NULL)
5057 *f->fr_pnext = f->fr_next;
5058 if (f->fr_next != NULL)
5059 f->fr_next->fr_pnext = f->fr_pnext;
5060 f->fr_pnext = NULL;
5061 f->fr_next = NULL;
5062
5063 (void) ipf_derefrule(softc, &f);
5064 }
5065
5066 /* ------------------------------------------------------------------------ */
5067 /* Function: ipf_rule_expire_insert */
5068 /* Returns: Nil */
5069 /* Parameters: softc(I) - pointer to soft context main structure */
5070 /* f(I) - pointer to rule to be added to expire list */
5071 /* set(I) - 1 or 0 (filter set) */
5072 /* */
5073 /* If the new rule has a given expiration time, insert it into the list of */
5074 /* expiring rules with the ones to be removed first added to the front of */
5075 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5076 /* expiration interval checks. */
5077 /* ------------------------------------------------------------------------ */
5078 static void
5079 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5080 {
5081 frentry_t *fr;
5082
5083 /*
5084 */
5085
5086 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5087 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5088 fr = fr->fr_dnext) {
5089 if (f->fr_die < fr->fr_die)
5090 break;
5091 if (fr->fr_dnext == NULL) {
5092 /*
5093 * We've got to the last rule and everything
5094 * wanted to be expired before this new node,
5095 * so we have to tack it on the end...
5096 */
5097 fr->fr_dnext = f;
5098 f->fr_pdnext = &fr->fr_dnext;
5099 fr = NULL;
5100 break;
5101 }
5102 }
5103
5104 if (softc->ipf_rule_explist[set] == NULL) {
5105 softc->ipf_rule_explist[set] = f;
5106 f->fr_pdnext = &softc->ipf_rule_explist[set];
5107 } else if (fr != NULL) {
5108 f->fr_dnext = fr;
5109 f->fr_pdnext = fr->fr_pdnext;
5110 fr->fr_pdnext = &f->fr_dnext;
5111 }
5112 }
5113
5114
5115 /* ------------------------------------------------------------------------ */
5116 /* Function: ipf_findlookup */
5117 /* Returns: NULL = failure, else success */
5118 /* Parameters: softc(I) - pointer to soft context main structure */
5119 /* unit(I) - ipf device we want to find match for */
5120 /* fp(I) - rule for which lookup is for */
5121 /* addrp(I) - pointer to lookup information in address struct */
5122 /* maskp(O) - pointer to lookup information for storage */
5123 /* */
5124 /* When using pools and hash tables to store addresses for matching in */
5125 /* rules, it is necessary to resolve both the object referred to by the */
5126 /* name or address (and return that pointer) and also provide the means by */
5127 /* which to determine if an address belongs to that object to make the */
5128 /* packet matching quicker. */
5129 /* ------------------------------------------------------------------------ */
5130 static void *
5131 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5132 i6addr_t *addrp, i6addr_t *maskp)
5133 {
5134 void *ptr = NULL;
5135
5136 switch (addrp->iplookupsubtype)
5137 {
5138 case 0 :
5139 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5140 addrp->iplookupnum,
5141 &maskp->iplookupfunc);
5142 break;
5143 case 1 :
5144 if (addrp->iplookupname < 0)
5145 break;
5146 if (addrp->iplookupname >= fr->fr_namelen)
5147 break;
5148 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5149 fr->fr_names + addrp->iplookupname,
5150 &maskp->iplookupfunc);
5151 break;
5152 default :
5153 break;
5154 }
5155
5156 return ptr;
5157 }
5158
5159
5160 /* ------------------------------------------------------------------------ */
5161 /* Function: ipf_funcinit */
5162 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5163 /* Parameters: softc(I) - pointer to soft context main structure */
5164 /* fr(I) - pointer to filter rule */
5165 /* */
5166 /* If a rule is a call rule, then check if the function it points to needs */
5167 /* an init function to be called now the rule has been loaded. */
5168 /* ------------------------------------------------------------------------ */
5169 static int
5170 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5171 {
5172 ipfunc_resolve_t *ft;
5173 int err;
5174
5175 IPFERROR(34);
5176 err = ESRCH;
5177
5178 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5179 if (ft->ipfu_addr == fr->fr_func) {
5180 err = 0;
5181 if (ft->ipfu_init != NULL)
5182 err = (*ft->ipfu_init)(softc, fr);
5183 break;
5184 }
5185 return err;
5186 }
5187
5188
5189 /* ------------------------------------------------------------------------ */
5190 /* Function: ipf_funcfini */
5191 /* Returns: Nil */
5192 /* Parameters: softc(I) - pointer to soft context main structure */
5193 /* fr(I) - pointer to filter rule */
5194 /* */
5195 /* For a given filter rule, call the matching "fini" function if the rule */
5196 /* is using a known function that would have resulted in the "init" being */
5197 /* called for ealier. */
5198 /* ------------------------------------------------------------------------ */
5199 static void
5200 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5201 {
5202 ipfunc_resolve_t *ft;
5203
5204 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5205 if (ft->ipfu_addr == fr->fr_func) {
5206 if (ft->ipfu_fini != NULL)
5207 (void) (*ft->ipfu_fini)(softc, fr);
5208 break;
5209 }
5210 }
5211
5212
5213 /* ------------------------------------------------------------------------ */
5214 /* Function: ipf_findfunc */
5215 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5216 /* Parameters: funcptr(I) - function pointer to lookup */
5217 /* */
5218 /* Look for a function in the table of known functions. */
5219 /* ------------------------------------------------------------------------ */
5220 static ipfunc_t
5221 ipf_findfunc(ipfunc_t funcptr)
5222 {
5223 ipfunc_resolve_t *ft;
5224
5225 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5226 if (ft->ipfu_addr == funcptr)
5227 return funcptr;
5228 return NULL;
5229 }
5230
5231
5232 /* ------------------------------------------------------------------------ */
5233 /* Function: ipf_resolvefunc */
5234 /* Returns: int - 0 == success, else error */
5235 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5236 /* */
5237 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5238 /* This will either be the function name (if the pointer is set) or the */
5239 /* function pointer if the name is set. When found, fill in the other one */
5240 /* so that the entire, complete, structure can be copied back to user space.*/
5241 /* ------------------------------------------------------------------------ */
5242 int
5243 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5244 {
5245 ipfunc_resolve_t res, *ft;
5246 int error;
5247
5248 error = BCOPYIN(data, &res, sizeof(res));
5249 if (error != 0) {
5250 IPFERROR(123);
5251 return EFAULT;
5252 }
5253
5254 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5255 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5256 if (strncmp(res.ipfu_name, ft->ipfu_name,
5257 sizeof(res.ipfu_name)) == 0) {
5258 res.ipfu_addr = ft->ipfu_addr;
5259 res.ipfu_init = ft->ipfu_init;
5260 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5261 IPFERROR(35);
5262 return EFAULT;
5263 }
5264 return 0;
5265 }
5266 }
5267 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5268 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5269 if (ft->ipfu_addr == res.ipfu_addr) {
5270 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5271 sizeof(res.ipfu_name));
5272 res.ipfu_init = ft->ipfu_init;
5273 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5274 IPFERROR(36);
5275 return EFAULT;
5276 }
5277 return 0;
5278 }
5279 }
5280 IPFERROR(37);
5281 return ESRCH;
5282 }
5283
5284
5285 #if !defined(_KERNEL) || (!defined(__NetBSD__) && !defined(__OpenBSD__) && \
5286 !defined(__FreeBSD__)) || \
5287 FREEBSD_LT_REV(501000) || NETBSD_LT_REV(105000000) || \
5288 OPENBSD_LT_REV(200006)
5289 /*
5290 * From: NetBSD
5291 * ppsratecheck(): packets (or events) per second limitation.
5292 */
5293 int
5294 ppsratecheck(lasttime, curpps, maxpps)
5295 struct timeval *lasttime;
5296 int *curpps;
5297 int maxpps; /* maximum pps allowed */
5298 {
5299 struct timeval tv, delta;
5300 int rv;
5301
5302 GETKTIME(&tv);
5303
5304 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5305 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5306 if (delta.tv_usec < 0) {
5307 delta.tv_sec--;
5308 delta.tv_usec += 1000000;
5309 }
5310
5311 /*
5312 * check for 0,0 is so that the message will be seen at least once.
5313 * if more than one second have passed since the last update of
5314 * lasttime, reset the counter.
5315 *
5316 * we do increment *curpps even in *curpps < maxpps case, as some may
5317 * try to use *curpps for stat purposes as well.
5318 */
5319 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5320 delta.tv_sec >= 1) {
5321 *lasttime = tv;
5322 *curpps = 0;
5323 rv = 1;
5324 } else if (maxpps < 0)
5325 rv = 1;
5326 else if (*curpps < maxpps)
5327 rv = 1;
5328 else
5329 rv = 0;
5330 *curpps = *curpps + 1;
5331
5332 return (rv);
5333 }
5334 #endif
5335
5336
5337 /* ------------------------------------------------------------------------ */
5338 /* Function: ipf_derefrule */
5339 /* Returns: int - 0 == rule freed up, else rule not freed */
5340 /* Parameters: fr(I) - pointer to filter rule */
5341 /* */
5342 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5343 /* free it and any associated storage space being used by it. */
5344 /* ------------------------------------------------------------------------ */
5345 int
5346 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5347 {
5348 frentry_t *fr;
5349 frdest_t *fdp;
5350
5351 fr = *frp;
5352 *frp = NULL;
5353
5354 MUTEX_ENTER(&fr->fr_lock);
5355 fr->fr_ref--;
5356 if (fr->fr_ref == 0) {
5357 MUTEX_EXIT(&fr->fr_lock);
5358 MUTEX_DESTROY(&fr->fr_lock);
5359
5360 ipf_funcfini(softc, fr);
5361
5362 fdp = &fr->fr_tif;
5363 if (fdp->fd_type == FRD_DSTLIST)
5364 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5365
5366 fdp = &fr->fr_rif;
5367 if (fdp->fd_type == FRD_DSTLIST)
5368 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5369
5370 fdp = &fr->fr_dif;
5371 if (fdp->fd_type == FRD_DSTLIST)
5372 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5373
5374 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5375 fr->fr_satype == FRI_LOOKUP)
5376 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5377 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5378 fr->fr_datype == FRI_LOOKUP)
5379 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5380
5381 if (fr->fr_grp != NULL)
5382 ipf_group_del(softc, fr->fr_grp, fr);
5383
5384 if (fr->fr_grphead != NULL)
5385 ipf_group_del(softc, fr->fr_grphead, fr);
5386
5387 if (fr->fr_icmpgrp != NULL)
5388 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5389
5390 if ((fr->fr_flags & FR_COPIED) != 0) {
5391 if (fr->fr_dsize) {
5392 KFREES(fr->fr_data, fr->fr_dsize);
5393 }
5394 KFREES(fr, fr->fr_size);
5395 return 0;
5396 }
5397 return 1;
5398 } else {
5399 MUTEX_EXIT(&fr->fr_lock);
5400 }
5401 return -1;
5402 }
5403
5404
5405 /* ------------------------------------------------------------------------ */
5406 /* Function: ipf_grpmapinit */
5407 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5408 /* Parameters: fr(I) - pointer to rule to find hash table for */
5409 /* */
5410 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5411 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5412 /* ------------------------------------------------------------------------ */
5413 static int
5414 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5415 {
5416 char name[FR_GROUPLEN];
5417 iphtable_t *iph;
5418
5419 (void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5420 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5421 if (iph == NULL) {
5422 IPFERROR(38);
5423 return ESRCH;
5424 }
5425 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5426 IPFERROR(39);
5427 return ESRCH;
5428 }
5429 iph->iph_ref++;
5430 fr->fr_ptr = iph;
5431 return 0;
5432 }
5433
5434
5435 /* ------------------------------------------------------------------------ */
5436 /* Function: ipf_grpmapfini */
5437 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5438 /* Parameters: softc(I) - pointer to soft context main structure */
5439 /* fr(I) - pointer to rule to release hash table for */
5440 /* */
5441 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5442 /* be called to undo what ipf_grpmapinit caused to be done. */
5443 /* ------------------------------------------------------------------------ */
5444 static int
5445 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5446 {
5447 iphtable_t *iph;
5448 iph = fr->fr_ptr;
5449 if (iph != NULL)
5450 ipf_lookup_deref(softc, IPLT_HASH, iph);
5451 return 0;
5452 }
5453
5454
5455 /* ------------------------------------------------------------------------ */
5456 /* Function: ipf_srcgrpmap */
5457 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5458 /* Parameters: fin(I) - pointer to packet information */
5459 /* passp(IO) - pointer to current/new filter decision (unused) */
5460 /* */
5461 /* Look for a rule group head in a hash table, using the source address as */
5462 /* the key, and descend into that group and continue matching rules against */
5463 /* the packet. */
5464 /* ------------------------------------------------------------------------ */
5465 frentry_t *
5466 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5467 {
5468 frgroup_t *fg;
5469 void *rval;
5470
5471 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5472 &fin->fin_src);
5473 if (rval == NULL)
5474 return NULL;
5475
5476 fg = rval;
5477 fin->fin_fr = fg->fg_start;
5478 (void) ipf_scanlist(fin, *passp);
5479 return fin->fin_fr;
5480 }
5481
5482
5483 /* ------------------------------------------------------------------------ */
5484 /* Function: ipf_dstgrpmap */
5485 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5486 /* Parameters: fin(I) - pointer to packet information */
5487 /* passp(IO) - pointer to current/new filter decision (unused) */
5488 /* */
5489 /* Look for a rule group head in a hash table, using the destination */
5490 /* address as the key, and descend into that group and continue matching */
5491 /* rules against the packet. */
5492 /* ------------------------------------------------------------------------ */
5493 frentry_t *
5494 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5495 {
5496 frgroup_t *fg;
5497 void *rval;
5498
5499 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5500 &fin->fin_dst);
5501 if (rval == NULL)
5502 return NULL;
5503
5504 fg = rval;
5505 fin->fin_fr = fg->fg_start;
5506 (void) ipf_scanlist(fin, *passp);
5507 return fin->fin_fr;
5508 }
5509
5510 /*
5511 * Queue functions
5512 * ===============
5513 * These functions manage objects on queues for efficient timeouts. There
5514 * are a number of system defined queues as well as user defined timeouts.
5515 * It is expected that a lock is held in the domain in which the queue
5516 * belongs (i.e. either state or NAT) when calling any of these functions
5517 * that prevents ipf_freetimeoutqueue() from being called at the same time
5518 * as any other.
5519 */
5520
5521
5522 /* ------------------------------------------------------------------------ */
5523 /* Function: ipf_addtimeoutqueue */
5524 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5525 /* timeout queue with given interval. */
5526 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5527 /* of interface queues. */
5528 /* seconds(I) - timeout value in seconds for this queue. */
5529 /* */
5530 /* This routine first looks for a timeout queue that matches the interval */
5531 /* being requested. If it finds one, increments the reference counter and */
5532 /* returns a pointer to it. If none are found, it allocates a new one and */
5533 /* inserts it at the top of the list. */
5534 /* */
5535 /* Locking. */
5536 /* It is assumed that the caller of this function has an appropriate lock */
5537 /* held (exclusively) in the domain that encompases 'parent'. */
5538 /* ------------------------------------------------------------------------ */
5539 ipftq_t *
5540 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5541 {
5542 ipftq_t *ifq;
5543 u_int period;
5544
5545 period = seconds * IPF_HZ_DIVIDE;
5546
5547 MUTEX_ENTER(&softc->ipf_timeoutlock);
5548 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5549 if (ifq->ifq_ttl == period) {
5550 /*
5551 * Reset the delete flag, if set, so the structure
5552 * gets reused rather than freed and reallocated.
5553 */
5554 MUTEX_ENTER(&ifq->ifq_lock);
5555 ifq->ifq_flags &= ~IFQF_DELETE;
5556 ifq->ifq_ref++;
5557 MUTEX_EXIT(&ifq->ifq_lock);
5558 MUTEX_EXIT(&softc->ipf_timeoutlock);
5559
5560 return ifq;
5561 }
5562 }
5563
5564 KMALLOC(ifq, ipftq_t *);
5565 if (ifq != NULL) {
5566 MUTEX_NUKE(&ifq->ifq_lock);
5567 IPFTQ_INIT(ifq, period, "ipftq mutex");
5568 ifq->ifq_next = *parent;
5569 ifq->ifq_pnext = parent;
5570 ifq->ifq_flags = IFQF_USER;
5571 ifq->ifq_ref++;
5572 *parent = ifq;
5573 softc->ipf_userifqs++;
5574 }
5575 MUTEX_EXIT(&softc->ipf_timeoutlock);
5576 return ifq;
5577 }
5578
5579
5580 /* ------------------------------------------------------------------------ */
5581 /* Function: ipf_deletetimeoutqueue */
5582 /* Returns: int - new reference count value of the timeout queue */
5583 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5584 /* Locks: ifq->ifq_lock */
5585 /* */
5586 /* This routine must be called when we're discarding a pointer to a timeout */
5587 /* queue object, taking care of the reference counter. */
5588 /* */
5589 /* Now that this just sets a DELETE flag, it requires the expire code to */
5590 /* check the list of user defined timeout queues and call the free function */
5591 /* below (currently commented out) to stop memory leaking. It is done this */
5592 /* way because the locking may not be sufficient to safely do a free when */
5593 /* this function is called. */
5594 /* ------------------------------------------------------------------------ */
5595 int
5596 ipf_deletetimeoutqueue(ipftq_t *ifq)
5597 {
5598
5599 ifq->ifq_ref--;
5600 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5601 ifq->ifq_flags |= IFQF_DELETE;
5602 }
5603
5604 return ifq->ifq_ref;
5605 }
5606
5607
5608 /* ------------------------------------------------------------------------ */
5609 /* Function: ipf_freetimeoutqueue */
5610 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5611 /* Returns: Nil */
5612 /* */
5613 /* Locking: */
5614 /* It is assumed that the caller of this function has an appropriate lock */
5615 /* held (exclusively) in the domain that encompases the callers "domain". */
5616 /* The ifq_lock for this structure should not be held. */
5617 /* */
5618 /* Remove a user defined timeout queue from the list of queues it is in and */
5619 /* tidy up after this is done. */
5620 /* ------------------------------------------------------------------------ */
5621 void
5622 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5623 {
5624
5625 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5626 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5627 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5628 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5629 ifq->ifq_ref);
5630 return;
5631 }
5632
5633 /*
5634 * Remove from its position in the list.
5635 */
5636 *ifq->ifq_pnext = ifq->ifq_next;
5637 if (ifq->ifq_next != NULL)
5638 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5639 ifq->ifq_next = NULL;
5640 ifq->ifq_pnext = NULL;
5641
5642 MUTEX_DESTROY(&ifq->ifq_lock);
5643 ATOMIC_DEC(softc->ipf_userifqs);
5644 KFREE(ifq);
5645 }
5646
5647
5648 /* ------------------------------------------------------------------------ */
5649 /* Function: ipf_deletequeueentry */
5650 /* Returns: Nil */
5651 /* Parameters: tqe(I) - timeout queue entry to delete */
5652 /* */
5653 /* Remove a tail queue entry from its queue and make it an orphan. */
5654 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5655 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5656 /* the correct lock(s) may not be held that would make it safe to do so. */
5657 /* ------------------------------------------------------------------------ */
5658 void
5659 ipf_deletequeueentry(ipftqent_t *tqe)
5660 {
5661 ipftq_t *ifq;
5662
5663 ifq = tqe->tqe_ifq;
5664
5665 MUTEX_ENTER(&ifq->ifq_lock);
5666
5667 if (tqe->tqe_pnext != NULL) {
5668 *tqe->tqe_pnext = tqe->tqe_next;
5669 if (tqe->tqe_next != NULL)
5670 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5671 else /* we must be the tail anyway */
5672 ifq->ifq_tail = tqe->tqe_pnext;
5673
5674 tqe->tqe_pnext = NULL;
5675 tqe->tqe_ifq = NULL;
5676 }
5677
5678 (void) ipf_deletetimeoutqueue(ifq);
5679 ASSERT(ifq->ifq_ref > 0);
5680
5681 MUTEX_EXIT(&ifq->ifq_lock);
5682 }
5683
5684
5685 /* ------------------------------------------------------------------------ */
5686 /* Function: ipf_queuefront */
5687 /* Returns: Nil */
5688 /* Parameters: tqe(I) - pointer to timeout queue entry */
5689 /* */
5690 /* Move a queue entry to the front of the queue, if it isn't already there. */
5691 /* ------------------------------------------------------------------------ */
5692 void
5693 ipf_queuefront(ipftqent_t *tqe)
5694 {
5695 ipftq_t *ifq;
5696
5697 ifq = tqe->tqe_ifq;
5698 if (ifq == NULL)
5699 return;
5700
5701 MUTEX_ENTER(&ifq->ifq_lock);
5702 if (ifq->ifq_head != tqe) {
5703 *tqe->tqe_pnext = tqe->tqe_next;
5704 if (tqe->tqe_next)
5705 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5706 else
5707 ifq->ifq_tail = tqe->tqe_pnext;
5708
5709 tqe->tqe_next = ifq->ifq_head;
5710 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5711 ifq->ifq_head = tqe;
5712 tqe->tqe_pnext = &ifq->ifq_head;
5713 }
5714 MUTEX_EXIT(&ifq->ifq_lock);
5715 }
5716
5717
5718 /* ------------------------------------------------------------------------ */
5719 /* Function: ipf_queueback */
5720 /* Returns: Nil */
5721 /* Parameters: ticks(I) - ipf tick time to use with this call */
5722 /* tqe(I) - pointer to timeout queue entry */
5723 /* */
5724 /* Move a queue entry to the back of the queue, if it isn't already there. */
5725 /* We use use ticks to calculate the expiration and mark for when we last */
5726 /* touched the structure. */
5727 /* ------------------------------------------------------------------------ */
5728 void
5729 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5730 {
5731 ipftq_t *ifq;
5732
5733 ifq = tqe->tqe_ifq;
5734 if (ifq == NULL)
5735 return;
5736 tqe->tqe_die = ticks + ifq->ifq_ttl;
5737 tqe->tqe_touched = ticks;
5738
5739 MUTEX_ENTER(&ifq->ifq_lock);
5740 if (tqe->tqe_next != NULL) { /* at the end already ? */
5741 /*
5742 * Remove from list
5743 */
5744 *tqe->tqe_pnext = tqe->tqe_next;
5745 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5746
5747 /*
5748 * Make it the last entry.
5749 */
5750 tqe->tqe_next = NULL;
5751 tqe->tqe_pnext = ifq->ifq_tail;
5752 *ifq->ifq_tail = tqe;
5753 ifq->ifq_tail = &tqe->tqe_next;
5754 }
5755 MUTEX_EXIT(&ifq->ifq_lock);
5756 }
5757
5758
5759 /* ------------------------------------------------------------------------ */
5760 /* Function: ipf_queueappend */
5761 /* Returns: Nil */
5762 /* Parameters: ticks(I) - ipf tick time to use with this call */
5763 /* tqe(I) - pointer to timeout queue entry */
5764 /* ifq(I) - pointer to timeout queue */
5765 /* parent(I) - owing object pointer */
5766 /* */
5767 /* Add a new item to this queue and put it on the very end. */
5768 /* We use use ticks to calculate the expiration and mark for when we last */
5769 /* touched the structure. */
5770 /* ------------------------------------------------------------------------ */
5771 void
5772 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5773 {
5774
5775 MUTEX_ENTER(&ifq->ifq_lock);
5776 tqe->tqe_parent = parent;
5777 tqe->tqe_pnext = ifq->ifq_tail;
5778 *ifq->ifq_tail = tqe;
5779 ifq->ifq_tail = &tqe->tqe_next;
5780 tqe->tqe_next = NULL;
5781 tqe->tqe_ifq = ifq;
5782 tqe->tqe_die = ticks + ifq->ifq_ttl;
5783 tqe->tqe_touched = ticks;
5784 ifq->ifq_ref++;
5785 MUTEX_EXIT(&ifq->ifq_lock);
5786 }
5787
5788
5789 /* ------------------------------------------------------------------------ */
5790 /* Function: ipf_movequeue */
5791 /* Returns: Nil */
5792 /* Parameters: tq(I) - pointer to timeout queue information */
5793 /* oifp(I) - old timeout queue entry was on */
5794 /* nifp(I) - new timeout queue to put entry on */
5795 /* */
5796 /* Move a queue entry from one timeout queue to another timeout queue. */
5797 /* If it notices that the current entry is already last and does not need */
5798 /* to move queue, the return. */
5799 /* ------------------------------------------------------------------------ */
5800 void
5801 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5802 {
5803
5804 /*
5805 * If the queue hasn't changed and we last touched this entry at the
5806 * same ipf time, then we're not going to achieve anything by either
5807 * changing the ttl or moving it on the queue.
5808 */
5809 if (oifq == nifq && tqe->tqe_touched == ticks)
5810 return;
5811
5812 /*
5813 * For any of this to be outside the lock, there is a risk that two
5814 * packets entering simultaneously, with one changing to a different
5815 * queue and one not, could end up with things in a bizarre state.
5816 */
5817 MUTEX_ENTER(&oifq->ifq_lock);
5818
5819 tqe->tqe_touched = ticks;
5820 tqe->tqe_die = ticks + nifq->ifq_ttl;
5821 /*
5822 * Is the operation here going to be a no-op ?
5823 */
5824 if (oifq == nifq) {
5825 if ((tqe->tqe_next == NULL) ||
5826 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5827 MUTEX_EXIT(&oifq->ifq_lock);
5828 return;
5829 }
5830 }
5831
5832 /*
5833 * Remove from the old queue
5834 */
5835 *tqe->tqe_pnext = tqe->tqe_next;
5836 if (tqe->tqe_next)
5837 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5838 else
5839 oifq->ifq_tail = tqe->tqe_pnext;
5840 tqe->tqe_next = NULL;
5841
5842 /*
5843 * If we're moving from one queue to another, release the
5844 * lock on the old queue and get a lock on the new queue.
5845 * For user defined queues, if we're moving off it, call
5846 * delete in case it can now be freed.
5847 */
5848 if (oifq != nifq) {
5849 tqe->tqe_ifq = NULL;
5850
5851 (void) ipf_deletetimeoutqueue(oifq);
5852
5853 MUTEX_EXIT(&oifq->ifq_lock);
5854
5855 MUTEX_ENTER(&nifq->ifq_lock);
5856
5857 tqe->tqe_ifq = nifq;
5858 nifq->ifq_ref++;
5859 }
5860
5861 /*
5862 * Add to the bottom of the new queue
5863 */
5864 tqe->tqe_pnext = nifq->ifq_tail;
5865 *nifq->ifq_tail = tqe;
5866 nifq->ifq_tail = &tqe->tqe_next;
5867 MUTEX_EXIT(&nifq->ifq_lock);
5868 }
5869
5870
5871 /* ------------------------------------------------------------------------ */
5872 /* Function: ipf_updateipid */
5873 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
5874 /* Parameters: fin(I) - pointer to packet information */
5875 /* */
5876 /* When we are doing NAT, change the IP of every packet to represent a */
5877 /* single sequence of packets coming from the host, hiding any host */
5878 /* specific sequencing that might otherwise be revealed. If the packet is */
5879 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
5880 /* the fragment cache for non-leading fragments. If a non-leading fragment */
5881 /* has no match in the cache, return an error. */
5882 /* ------------------------------------------------------------------------ */
5883 static int
5884 ipf_updateipid(fr_info_t *fin)
5885 {
5886 u_short id, ido, sums;
5887 u_32_t sumd, sum;
5888 ip_t *ip;
5889
5890 if (fin->fin_off != 0) {
5891 sum = ipf_frag_ipidknown(fin);
5892 if (sum == 0xffffffff)
5893 return -1;
5894 sum &= 0xffff;
5895 id = (u_short)sum;
5896 } else {
5897 id = ipf_nextipid(fin);
5898 if (fin->fin_off == 0 && (fin->fin_flx & FI_FRAG) != 0)
5899 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
5900 }
5901
5902 ip = fin->fin_ip;
5903 ido = ntohs(ip->ip_id);
5904 if (id == ido)
5905 return 0;
5906 ip->ip_id = htons(id);
5907 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
5908 sum = (~ntohs(ip->ip_sum)) & 0xffff;
5909 sum += sumd;
5910 sum = (sum >> 16) + (sum & 0xffff);
5911 sum = (sum >> 16) + (sum & 0xffff);
5912 sums = ~(u_short)sum;
5913 ip->ip_sum = htons(sums);
5914 return 0;
5915 }
5916
5917
5918 #ifdef NEED_FRGETIFNAME
5919 /* ------------------------------------------------------------------------ */
5920 /* Function: ipf_getifname */
5921 /* Returns: char * - pointer to interface name */
5922 /* Parameters: ifp(I) - pointer to network interface */
5923 /* buffer(O) - pointer to where to store interface name */
5924 /* */
5925 /* Constructs an interface name in the buffer passed. The buffer passed is */
5926 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
5927 /* as a NULL pointer then return a pointer to a static array. */
5928 /* ------------------------------------------------------------------------ */
5929 char *
5930 ipf_getifname(ifp, buffer)
5931 struct ifnet *ifp;
5932 char *buffer;
5933 {
5934 static char namebuf[LIFNAMSIZ];
5935 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5936 defined(__sgi) || defined(linux) || defined(_AIX51) || \
5937 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5938 int unit, space;
5939 char temp[20];
5940 char *s;
5941 # endif
5942
5943 if (buffer == NULL)
5944 buffer = namebuf;
5945 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
5946 buffer[LIFNAMSIZ - 1] = '\0';
5947 # if defined(MENTAT) || defined(__FreeBSD__) || defined(__osf__) || \
5948 defined(__sgi) || defined(_AIX51) || \
5949 (defined(sun) && !defined(__SVR4) && !defined(__svr4__))
5950 for (s = buffer; *s; s++)
5951 ;
5952 unit = ifp->if_unit;
5953 space = LIFNAMSIZ - (s - buffer);
5954 if ((space > 0) && (unit >= 0)) {
5955 snprintf(temp, sizeof(temp), "%d", unit);
5956 (void) strncpy(s, temp, space);
5957 s[space - 1] = '\0';
5958 }
5959 # endif
5960 return buffer;
5961 }
5962 #endif
5963
5964
5965 /* ------------------------------------------------------------------------ */
5966 /* Function: ipf_ioctlswitch */
5967 /* Returns: int - -1 continue processing, else ioctl return value */
5968 /* Parameters: unit(I) - device unit opened */
5969 /* data(I) - pointer to ioctl data */
5970 /* cmd(I) - ioctl command */
5971 /* mode(I) - mode value */
5972 /* uid(I) - uid making the ioctl call */
5973 /* ctx(I) - pointer to context data */
5974 /* */
5975 /* Based on the value of unit, call the appropriate ioctl handler or return */
5976 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
5977 /* for the device in order to execute the ioctl. A special case is made */
5978 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
5979 /* The context data pointer is passed through as this is used as the key */
5980 /* for locating a matching token for continued access for walking lists, */
5981 /* etc. */
5982 /* ------------------------------------------------------------------------ */
5983 int
5984 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
5985 int mode, int uid, void *ctx)
5986 {
5987 int error = 0;
5988
5989 switch (cmd)
5990 {
5991 case SIOCIPFINTERROR :
5992 error = BCOPYOUT(&softc->ipf_interror, data,
5993 sizeof(softc->ipf_interror));
5994 if (error != 0) {
5995 IPFERROR(40);
5996 error = EFAULT;
5997 }
5998 return error;
5999 default :
6000 break;
6001 }
6002
6003 switch (unit)
6004 {
6005 case IPL_LOGIPF :
6006 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6007 break;
6008 case IPL_LOGNAT :
6009 if (softc->ipf_running > 0) {
6010 error = ipf_nat_ioctl(softc, data, cmd, mode,
6011 uid, ctx);
6012 } else {
6013 IPFERROR(42);
6014 error = EIO;
6015 }
6016 break;
6017 case IPL_LOGSTATE :
6018 if (softc->ipf_running > 0) {
6019 error = ipf_state_ioctl(softc, data, cmd, mode,
6020 uid, ctx);
6021 } else {
6022 IPFERROR(43);
6023 error = EIO;
6024 }
6025 break;
6026 case IPL_LOGAUTH :
6027 if (softc->ipf_running > 0) {
6028 error = ipf_auth_ioctl(softc, data, cmd, mode,
6029 uid, ctx);
6030 } else {
6031 IPFERROR(44);
6032 error = EIO;
6033 }
6034 break;
6035 case IPL_LOGSYNC :
6036 if (softc->ipf_running > 0) {
6037 error = ipf_sync_ioctl(softc, data, cmd, mode,
6038 uid, ctx);
6039 } else {
6040 error = EIO;
6041 IPFERROR(45);
6042 }
6043 break;
6044 case IPL_LOGSCAN :
6045 #ifdef IPFILTER_SCAN
6046 if (softc->ipf_running > 0)
6047 error = ipf_scan_ioctl(softc, data, cmd, mode,
6048 uid, ctx);
6049 else
6050 #endif
6051 {
6052 error = EIO;
6053 IPFERROR(46);
6054 }
6055 break;
6056 case IPL_LOGLOOKUP :
6057 if (softc->ipf_running > 0) {
6058 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6059 uid, ctx);
6060 } else {
6061 error = EIO;
6062 IPFERROR(47);
6063 }
6064 break;
6065 default :
6066 IPFERROR(48);
6067 error = EIO;
6068 break;
6069 }
6070
6071 return error;
6072 }
6073
6074
6075 /*
6076 * This array defines the expected size of objects coming into the kernel
6077 * for the various recognised object types. The first column is flags (see
6078 * below), 2nd column is current size, 3rd column is the version number of
6079 * when the current size became current.
6080 * Flags:
6081 * 1 = minimum size, not absolute size
6082 */
6083 static int ipf_objbytes[IPFOBJ_COUNT][3] = {
6084 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6085 { 1, sizeof(struct friostat), 5010000 },
6086 { 0, sizeof(struct fr_info), 5010000 },
6087 { 0, sizeof(struct ipf_authstat), 4010100 },
6088 { 0, sizeof(struct ipfrstat), 5010000 },
6089 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6090 { 0, sizeof(struct natstat), 5010000 },
6091 { 0, sizeof(struct ipstate_save), 5010000 },
6092 { 1, sizeof(struct nat_save), 5010000 },
6093 { 0, sizeof(struct natlookup), 5010000 },
6094 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6095 { 0, sizeof(struct ips_stat), 5010000 },
6096 { 0, sizeof(struct frauth), 5010000 },
6097 { 0, sizeof(struct ipftune), 4010100 },
6098 { 0, sizeof(struct nat), 5010000 },
6099 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6100 { 0, sizeof(struct ipfgeniter), 4011400 },
6101 { 0, sizeof(struct ipftable), 4011400 },
6102 { 0, sizeof(struct ipflookupiter), 4011400 },
6103 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6104 { 1, 0, 0 }, /* IPFEXPR */
6105 { 0, 0, 0 }, /* PROXYCTL */
6106 { 0, sizeof (struct fripf), 5010000 }
6107 };
6108
6109
6110 /* ------------------------------------------------------------------------ */
6111 /* Function: ipf_inobj */
6112 /* Returns: int - 0 = success, else failure */
6113 /* Parameters: softc(I) - soft context pointerto work with */
6114 /* data(I) - pointer to ioctl data */
6115 /* objp(O) - where to store ipfobj structure */
6116 /* ptr(I) - pointer to data to copy out */
6117 /* type(I) - type of structure being moved */
6118 /* */
6119 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6120 /* add things to check for version numbers, sizes, etc, to make it backward */
6121 /* compatible at the ABI for user land. */
6122 /* If objp is not NULL then we assume that the caller wants to see what is */
6123 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6124 /* the caller what version of ipfilter the ioctl program was written to. */
6125 /* ------------------------------------------------------------------------ */
6126 int
6127 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6128 int type)
6129 {
6130 ipfobj_t obj;
6131 int error;
6132 int size;
6133
6134 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6135 IPFERROR(49);
6136 return EINVAL;
6137 }
6138
6139 if (objp == NULL)
6140 objp = &obj;
6141 error = BCOPYIN(data, objp, sizeof(*objp));
6142 if (error != 0) {
6143 IPFERROR(124);
6144 return EFAULT;
6145 }
6146
6147 if (objp->ipfo_type != type) {
6148 IPFERROR(50);
6149 return EINVAL;
6150 }
6151
6152 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6153 if ((ipf_objbytes[type][0] & 1) != 0) {
6154 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6155 IPFERROR(51);
6156 return EINVAL;
6157 }
6158 size = ipf_objbytes[type][1];
6159 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6160 size = objp->ipfo_size;
6161 } else {
6162 IPFERROR(52);
6163 return EINVAL;
6164 }
6165 error = COPYIN(objp->ipfo_ptr, ptr, size);
6166 if (error != 0) {
6167 IPFERROR(55);
6168 error = EFAULT;
6169 }
6170 } else {
6171 #ifdef IPFILTER_COMPAT
6172 error = ipf_in_compat(softc, objp, ptr, 0);
6173 #else
6174 IPFERROR(54);
6175 error = EINVAL;
6176 #endif
6177 }
6178 return error;
6179 }
6180
6181
6182 /* ------------------------------------------------------------------------ */
6183 /* Function: ipf_inobjsz */
6184 /* Returns: int - 0 = success, else failure */
6185 /* Parameters: softc(I) - soft context pointerto work with */
6186 /* data(I) - pointer to ioctl data */
6187 /* ptr(I) - pointer to store real data in */
6188 /* type(I) - type of structure being moved */
6189 /* sz(I) - size of data to copy */
6190 /* */
6191 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6192 /* but it must not be smaller than the size defined for the type and the */
6193 /* type must allow for varied sized objects. The extra requirement here is */
6194 /* that sz must match the size of the object being passed in - this is not */
6195 /* not possible nor required in ipf_inobj(). */
6196 /* ------------------------------------------------------------------------ */
6197 int
6198 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6199 {
6200 ipfobj_t obj;
6201 int error;
6202
6203 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6204 IPFERROR(56);
6205 return EINVAL;
6206 }
6207
6208 error = BCOPYIN(data, &obj, sizeof(obj));
6209 if (error != 0) {
6210 IPFERROR(125);
6211 return EFAULT;
6212 }
6213
6214 if (obj.ipfo_type != type) {
6215 IPFERROR(58);
6216 return EINVAL;
6217 }
6218
6219 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6220 if (((ipf_objbytes[type][0] & 1) == 0) ||
6221 (sz < ipf_objbytes[type][1])) {
6222 IPFERROR(57);
6223 return EINVAL;
6224 }
6225 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6226 if (error != 0) {
6227 IPFERROR(61);
6228 error = EFAULT;
6229 }
6230 } else {
6231 #ifdef IPFILTER_COMPAT
6232 error = ipf_in_compat(softc, &obj, ptr, sz);
6233 #else
6234 IPFERROR(60);
6235 error = EINVAL;
6236 #endif
6237 }
6238 return error;
6239 }
6240
6241
6242 /* ------------------------------------------------------------------------ */
6243 /* Function: ipf_outobjsz */
6244 /* Returns: int - 0 = success, else failure */
6245 /* Parameters: data(I) - pointer to ioctl data */
6246 /* ptr(I) - pointer to store real data in */
6247 /* type(I) - type of structure being moved */
6248 /* sz(I) - size of data to copy */
6249 /* */
6250 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6251 /* but it must not be smaller than the size defined for the type and the */
6252 /* type must allow for varied sized objects. The extra requirement here is */
6253 /* that sz must match the size of the object being passed in - this is not */
6254 /* not possible nor required in ipf_outobj(). */
6255 /* ------------------------------------------------------------------------ */
6256 int
6257 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6258 {
6259 ipfobj_t obj;
6260 int error;
6261
6262 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6263 IPFERROR(62);
6264 return EINVAL;
6265 }
6266
6267 error = BCOPYIN(data, &obj, sizeof(obj));
6268 if (error != 0) {
6269 IPFERROR(127);
6270 return EFAULT;
6271 }
6272
6273 if (obj.ipfo_type != type) {
6274 IPFERROR(63);
6275 return EINVAL;
6276 }
6277
6278 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6279 if (((ipf_objbytes[type][0] & 1) == 0) ||
6280 (sz < ipf_objbytes[type][1])) {
6281 IPFERROR(146);
6282 return EINVAL;
6283 }
6284 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6285 if (error != 0) {
6286 IPFERROR(66);
6287 error = EFAULT;
6288 }
6289 } else {
6290 #ifdef IPFILTER_COMPAT
6291 error = ipf_out_compat(softc, &obj, ptr);
6292 #else
6293 IPFERROR(65);
6294 error = EINVAL;
6295 #endif
6296 }
6297 return error;
6298 }
6299
6300
6301 /* ------------------------------------------------------------------------ */
6302 /* Function: ipf_outobj */
6303 /* Returns: int - 0 = success, else failure */
6304 /* Parameters: data(I) - pointer to ioctl data */
6305 /* ptr(I) - pointer to store real data in */
6306 /* type(I) - type of structure being moved */
6307 /* */
6308 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6309 /* future, we add things to check for version numbers, sizes, etc, to make */
6310 /* it backward compatible at the ABI for user land. */
6311 /* ------------------------------------------------------------------------ */
6312 int
6313 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6314 {
6315 ipfobj_t obj;
6316 int error;
6317
6318 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6319 IPFERROR(67);
6320 return EINVAL;
6321 }
6322
6323 error = BCOPYIN(data, &obj, sizeof(obj));
6324 if (error != 0) {
6325 IPFERROR(126);
6326 return EFAULT;
6327 }
6328
6329 if (obj.ipfo_type != type) {
6330 IPFERROR(68);
6331 return EINVAL;
6332 }
6333
6334 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6335 if ((ipf_objbytes[type][0] & 1) != 0) {
6336 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6337 IPFERROR(69);
6338 return EINVAL;
6339 }
6340 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6341 IPFERROR(70);
6342 return EINVAL;
6343 }
6344
6345 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6346 if (error != 0) {
6347 IPFERROR(73);
6348 error = EFAULT;
6349 }
6350 } else {
6351 #ifdef IPFILTER_COMPAT
6352 error = ipf_out_compat(softc, &obj, ptr);
6353 #else
6354 IPFERROR(72);
6355 error = EINVAL;
6356 #endif
6357 }
6358 return error;
6359 }
6360
6361
6362 /* ------------------------------------------------------------------------ */
6363 /* Function: ipf_outobjk */
6364 /* Returns: int - 0 = success, else failure */
6365 /* Parameters: obj(I) - pointer to data description structure */
6366 /* ptr(I) - pointer to kernel data to copy out */
6367 /* */
6368 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6369 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6370 /* already populated with information and now we just need to use it. */
6371 /* There is no need for this function to have a "type" parameter as there */
6372 /* is no point in validating information that comes from the kernel with */
6373 /* itself. */
6374 /* ------------------------------------------------------------------------ */
6375 int
6376 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6377 {
6378 int type = obj->ipfo_type;
6379 int error;
6380
6381 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6382 IPFERROR(147);
6383 return EINVAL;
6384 }
6385
6386 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6387 if ((ipf_objbytes[type][0] & 1) != 0) {
6388 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6389 IPFERROR(148);
6390 return EINVAL;
6391 }
6392
6393 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6394 IPFERROR(149);
6395 return EINVAL;
6396 }
6397
6398 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6399 if (error != 0) {
6400 IPFERROR(150);
6401 error = EFAULT;
6402 }
6403 } else {
6404 #ifdef IPFILTER_COMPAT
6405 error = ipf_out_compat(softc, obj, ptr);
6406 #else
6407 IPFERROR(151);
6408 error = EINVAL;
6409 #endif
6410 }
6411 return error;
6412 }
6413
6414
6415 /* ------------------------------------------------------------------------ */
6416 /* Function: ipf_checkl4sum */
6417 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6418 /* Parameters: fin(I) - pointer to packet information */
6419 /* */
6420 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6421 /* not possible, return without indicating a failure or success but in a */
6422 /* way that is ditinguishable. This function should only be called by the */
6423 /* ipf_checkv6sum() for each platform. */
6424 /* ------------------------------------------------------------------------ */
6425 int
6426 ipf_checkl4sum(fr_info_t *fin)
6427 {
6428 u_short sum, hdrsum, *csump;
6429 udphdr_t *udp;
6430 int dosum;
6431
6432 /*
6433 * If the TCP packet isn't a fragment, isn't too short and otherwise
6434 * isn't already considered "bad", then validate the checksum. If
6435 * this check fails then considered the packet to be "bad".
6436 */
6437 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6438 return 1;
6439
6440 csump = NULL;
6441 hdrsum = 0;
6442 dosum = 0;
6443 sum = 0;
6444
6445 switch (fin->fin_p)
6446 {
6447 case IPPROTO_TCP :
6448 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6449 dosum = 1;
6450 break;
6451
6452 case IPPROTO_UDP :
6453 udp = fin->fin_dp;
6454 if (udp->uh_sum != 0) {
6455 csump = &udp->uh_sum;
6456 dosum = 1;
6457 }
6458 break;
6459
6460 #ifdef USE_INET6
6461 case IPPROTO_ICMPV6 :
6462 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6463 dosum = 1;
6464 break;
6465 #endif
6466
6467 case IPPROTO_ICMP :
6468 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6469 dosum = 1;
6470 break;
6471
6472 default :
6473 return 1;
6474 /*NOTREACHED*/
6475 }
6476
6477 if (csump != NULL)
6478 hdrsum = *csump;
6479
6480 if (dosum) {
6481 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6482 }
6483 #if !defined(_KERNEL)
6484 if (sum == hdrsum) {
6485 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6486 } else {
6487 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6488 }
6489 #endif
6490 DT2(l4sums, u_short, hdrsum, u_short, sum);
6491 if (hdrsum == sum) {
6492 fin->fin_cksum = FI_CK_SUMOK;
6493 return 0;
6494 }
6495 fin->fin_cksum = FI_CK_BAD;
6496 return -1;
6497 }
6498
6499
6500 /* ------------------------------------------------------------------------ */
6501 /* Function: ipf_ifpfillv4addr */
6502 /* Returns: int - 0 = address update, -1 = address not updated */
6503 /* Parameters: atype(I) - type of network address update to perform */
6504 /* sin(I) - pointer to source of address information */
6505 /* mask(I) - pointer to source of netmask information */
6506 /* inp(I) - pointer to destination address store */
6507 /* inpmask(I) - pointer to destination netmask store */
6508 /* */
6509 /* Given a type of network address update (atype) to perform, copy */
6510 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6511 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6512 /* which case the operation fails. For all values of atype other than */
6513 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6514 /* value. */
6515 /* ------------------------------------------------------------------------ */
6516 int
6517 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6518 struct in_addr *inp, struct in_addr *inpmask)
6519 {
6520 if (inpmask != NULL && atype != FRI_NETMASKED)
6521 inpmask->s_addr = 0xffffffff;
6522
6523 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6524 if (atype == FRI_NETMASKED) {
6525 if (inpmask == NULL)
6526 return -1;
6527 inpmask->s_addr = mask->sin_addr.s_addr;
6528 }
6529 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6530 } else {
6531 inp->s_addr = sin->sin_addr.s_addr;
6532 }
6533 return 0;
6534 }
6535
6536
6537 #ifdef USE_INET6
6538 /* ------------------------------------------------------------------------ */
6539 /* Function: ipf_ifpfillv6addr */
6540 /* Returns: int - 0 = address update, -1 = address not updated */
6541 /* Parameters: atype(I) - type of network address update to perform */
6542 /* sin(I) - pointer to source of address information */
6543 /* mask(I) - pointer to source of netmask information */
6544 /* inp(I) - pointer to destination address store */
6545 /* inpmask(I) - pointer to destination netmask store */
6546 /* */
6547 /* Given a type of network address update (atype) to perform, copy */
6548 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6549 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6550 /* which case the operation fails. For all values of atype other than */
6551 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6552 /* value. */
6553 /* ------------------------------------------------------------------------ */
6554 int
6555 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6556 struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6557 {
6558 i6addr_t *src, *and;
6559
6560 src = (i6addr_t *)&sin->sin6_addr;
6561 and = (i6addr_t *)&mask->sin6_addr;
6562
6563 if (inpmask != NULL && atype != FRI_NETMASKED) {
6564 inpmask->i6[0] = 0xffffffff;
6565 inpmask->i6[1] = 0xffffffff;
6566 inpmask->i6[2] = 0xffffffff;
6567 inpmask->i6[3] = 0xffffffff;
6568 }
6569
6570 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6571 if (atype == FRI_NETMASKED) {
6572 if (inpmask == NULL)
6573 return -1;
6574 inpmask->i6[0] = and->i6[0];
6575 inpmask->i6[1] = and->i6[1];
6576 inpmask->i6[2] = and->i6[2];
6577 inpmask->i6[3] = and->i6[3];
6578 }
6579
6580 inp->i6[0] = src->i6[0] & and->i6[0];
6581 inp->i6[1] = src->i6[1] & and->i6[1];
6582 inp->i6[2] = src->i6[2] & and->i6[2];
6583 inp->i6[3] = src->i6[3] & and->i6[3];
6584 } else {
6585 inp->i6[0] = src->i6[0];
6586 inp->i6[1] = src->i6[1];
6587 inp->i6[2] = src->i6[2];
6588 inp->i6[3] = src->i6[3];
6589 }
6590 return 0;
6591 }
6592 #endif
6593
6594
6595 /* ------------------------------------------------------------------------ */
6596 /* Function: ipf_matchtag */
6597 /* Returns: 0 == mismatch, 1 == match. */
6598 /* Parameters: tag1(I) - pointer to first tag to compare */
6599 /* tag2(I) - pointer to second tag to compare */
6600 /* */
6601 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6602 /* considered to be a match or not match, respectively. The tag is 16 */
6603 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6604 /* compare the ints instead, for speed. tag1 is the master of the */
6605 /* comparison. This function should only be called with both tag1 and tag2 */
6606 /* as non-NULL pointers. */
6607 /* ------------------------------------------------------------------------ */
6608 int
6609 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6610 {
6611 if (tag1 == tag2)
6612 return 1;
6613
6614 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6615 return 1;
6616
6617 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6618 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6619 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6620 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6621 return 1;
6622 return 0;
6623 }
6624
6625
6626 /* ------------------------------------------------------------------------ */
6627 /* Function: ipf_coalesce */
6628 /* Returns: 1 == success, -1 == failure, 0 == no change */
6629 /* Parameters: fin(I) - pointer to packet information */
6630 /* */
6631 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6632 /* If this call returns a failure then the buffers have also been freed. */
6633 /* ------------------------------------------------------------------------ */
6634 int
6635 ipf_coalesce(fr_info_t *fin)
6636 {
6637
6638 if ((fin->fin_flx & FI_COALESCE) != 0)
6639 return 1;
6640
6641 /*
6642 * If the mbuf pointers indicate that there is no mbuf to work with,
6643 * return but do not indicate success or failure.
6644 */
6645 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6646 return 0;
6647
6648 #if defined(_KERNEL)
6649 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6650 ipf_main_softc_t *softc = fin->fin_main_soft;
6651
6652 DT1(frb_coalesce, fr_info_t *, fin);
6653 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6654 # ifdef MENTAT
6655 FREE_MB_T(*fin->fin_mp);
6656 # endif
6657 fin->fin_reason = FRB_COALESCE;
6658 *fin->fin_mp = NULL;
6659 fin->fin_m = NULL;
6660 return -1;
6661 }
6662 #else
6663 fin = fin; /* LINT */
6664 #endif
6665 return 1;
6666 }
6667
6668
6669 /*
6670 * The following table lists all of the tunable variables that can be
6671 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6672 * in the table below is as follows:
6673 *
6674 * pointer to value, name of value, minimum, maximum, size of the value's
6675 * container, value attribute flags
6676 *
6677 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6678 * means the value can only be written to when IPFilter is loaded but disabled.
6679 * The obvious implication is if neither of these are set then the value can be
6680 * changed at any time without harm.
6681 */
6682
6683
6684 /* ------------------------------------------------------------------------ */
6685 /* Function: ipf_tune_findbycookie */
6686 /* Returns: NULL = search failed, else pointer to tune struct */
6687 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6688 /* next(O) - pointer to place to store the cookie for the */
6689 /* "next" tuneable, if it is desired. */
6690 /* */
6691 /* This function is used to walk through all of the existing tunables with */
6692 /* successive calls. It searches the known tunables for the one which has */
6693 /* a matching value for "cookie" - ie its address. When returning a match, */
6694 /* the next one to be found may be returned inside next. */
6695 /* ------------------------------------------------------------------------ */
6696 static ipftuneable_t *
6697 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6698 {
6699 ipftuneable_t *ta, **tap;
6700
6701 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6702 if (ta == cookie) {
6703 if (next != NULL) {
6704 /*
6705 * If the next entry in the array has a name
6706 * present, then return a pointer to it for
6707 * where to go next, else return a pointer to
6708 * the dynaminc list as a key to search there
6709 * next. This facilitates a weak linking of
6710 * the two "lists" together.
6711 */
6712 if ((ta + 1)->ipft_name != NULL)
6713 *next = ta + 1;
6714 else
6715 *next = ptop;
6716 }
6717 return ta;
6718 }
6719
6720 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6721 if (tap == cookie) {
6722 if (next != NULL)
6723 *next = &ta->ipft_next;
6724 return ta;
6725 }
6726
6727 if (next != NULL)
6728 *next = NULL;
6729 return NULL;
6730 }
6731
6732
6733 /* ------------------------------------------------------------------------ */
6734 /* Function: ipf_tune_findbyname */
6735 /* Returns: NULL = search failed, else pointer to tune struct */
6736 /* Parameters: name(I) - name of the tuneable entry to find. */
6737 /* */
6738 /* Search the static array of tuneables and the list of dynamic tuneables */
6739 /* for an entry with a matching name. If we can find one, return a pointer */
6740 /* to the matching structure. */
6741 /* ------------------------------------------------------------------------ */
6742 static ipftuneable_t *
6743 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6744 {
6745 ipftuneable_t *ta;
6746
6747 for (ta = top; ta != NULL; ta = ta->ipft_next)
6748 if (!strcmp(ta->ipft_name, name)) {
6749 return ta;
6750 }
6751
6752 return NULL;
6753 }
6754
6755
6756 /* ------------------------------------------------------------------------ */
6757 /* Function: ipf_tune_add_array */
6758 /* Returns: int - 0 == success, else failure */
6759 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6760 /* */
6761 /* Appends tune structures from the array passed in (newtune) to the end of */
6762 /* the current list of "dynamic" tuneable parameters. */
6763 /* If any entry to be added is already present (by name) then the operation */
6764 /* is aborted - entries that have been added are removed before returning. */
6765 /* An entry with no name (NULL) is used as the indication that the end of */
6766 /* the array has been reached. */
6767 /* ------------------------------------------------------------------------ */
6768 int
6769 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6770 {
6771 ipftuneable_t *nt, *dt;
6772 int error = 0;
6773
6774 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6775 error = ipf_tune_add(softc, nt);
6776 if (error != 0) {
6777 for (dt = newtune; dt != nt; dt++) {
6778 (void) ipf_tune_del(softc, dt);
6779 }
6780 }
6781 }
6782
6783 return error;
6784 }
6785
6786
6787 /* ------------------------------------------------------------------------ */
6788 /* Function: ipf_tune_array_link */
6789 /* Returns: 0 == success, -1 == failure */
6790 /* Parameters: softc(I) - soft context pointerto work with */
6791 /* array(I) - pointer to an array of tuneables */
6792 /* */
6793 /* Given an array of tunables (array), append them to the current list of */
6794 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
6795 /* the array for being appended to the list, initialise all of the next */
6796 /* pointers so we don't need to walk parts of it with ++ and others with */
6797 /* next. The array is expected to have an entry with a NULL name as the */
6798 /* terminator. Trying to add an array with no non-NULL names will return as */
6799 /* a failure. */
6800 /* ------------------------------------------------------------------------ */
6801 int
6802 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6803 {
6804 ipftuneable_t *t, **p;
6805
6806 t = array;
6807 if (t->ipft_name == NULL)
6808 return -1;
6809
6810 for (; t[1].ipft_name != NULL; t++)
6811 t[0].ipft_next = &t[1];
6812 t->ipft_next = NULL;
6813
6814 /*
6815 * Since a pointer to the last entry isn't kept, we need to find it
6816 * each time we want to add new variables to the list.
6817 */
6818 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6819 if (t->ipft_name == NULL)
6820 break;
6821 *p = array;
6822
6823 return 0;
6824 }
6825
6826
6827 /* ------------------------------------------------------------------------ */
6828 /* Function: ipf_tune_array_unlink */
6829 /* Returns: 0 == success, -1 == failure */
6830 /* Parameters: softc(I) - soft context pointerto work with */
6831 /* array(I) - pointer to an array of tuneables */
6832 /* */
6833 /* ------------------------------------------------------------------------ */
6834 int
6835 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6836 {
6837 ipftuneable_t *t, **p;
6838
6839 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6840 if (t == array)
6841 break;
6842 if (t == NULL)
6843 return -1;
6844
6845 for (; t[1].ipft_name != NULL; t++)
6846 ;
6847
6848 *p = t->ipft_next;
6849
6850 return 0;
6851 }
6852
6853
6854 /* ------------------------------------------------------------------------ */
6855 /* Function: ipf_tune_array_copy */
6856 /* Returns: NULL = failure, else pointer to new array */
6857 /* Parameters: base(I) - pointer to structure base */
6858 /* size(I) - size of the array at template */
6859 /* template(I) - original array to copy */
6860 /* */
6861 /* Allocate memory for a new set of tuneable values and copy everything */
6862 /* from template into the new region of memory. The new region is full of */
6863 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
6864 /* */
6865 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
6866 /* In the array template, ipftp_offset is the offset (in bytes) of the */
6867 /* location of the tuneable value inside the structure pointed to by base. */
6868 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
6869 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
6870 /* ipftp_void that points to the stored value. */
6871 /* ------------------------------------------------------------------------ */
6872 ipftuneable_t *
6873 ipf_tune_array_copy(void *base, size_t size, ipftuneable_t *template)
6874 {
6875 ipftuneable_t *copy;
6876 int i;
6877
6878
6879 KMALLOCS(copy, ipftuneable_t *, size);
6880 if (copy == NULL) {
6881 return NULL;
6882 }
6883 bcopy(template, copy, size);
6884
6885 for (i = 0; copy[i].ipft_name; i++) {
6886 copy[i].ipft_una.ipftp_offset += (u_long)base;
6887 copy[i].ipft_next = copy + i + 1;
6888 }
6889
6890 return copy;
6891 }
6892
6893
6894 /* ------------------------------------------------------------------------ */
6895 /* Function: ipf_tune_add */
6896 /* Returns: int - 0 == success, else failure */
6897 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
6898 /* */
6899 /* Appends tune structures from the array passed in (newtune) to the end of */
6900 /* the current list of "dynamic" tuneable parameters. Once added, the */
6901 /* owner of the object is not expected to ever change "ipft_next". */
6902 /* ------------------------------------------------------------------------ */
6903 int
6904 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6905 {
6906 ipftuneable_t *ta, **tap;
6907
6908 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
6909 if (ta != NULL) {
6910 IPFERROR(74);
6911 return EEXIST;
6912 }
6913
6914 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
6915 ;
6916
6917 newtune->ipft_next = NULL;
6918 *tap = newtune;
6919 return 0;
6920 }
6921
6922
6923 /* ------------------------------------------------------------------------ */
6924 /* Function: ipf_tune_del */
6925 /* Returns: int - 0 == success, else failure */
6926 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
6927 /* current dynamic tuneables */
6928 /* */
6929 /* Search for the tune structure, by pointer, in the list of those that are */
6930 /* dynamically added at run time. If found, adjust the list so that this */
6931 /* structure is no longer part of it. */
6932 /* ------------------------------------------------------------------------ */
6933 int
6934 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6935 {
6936 ipftuneable_t *ta, **tap;
6937 int error = 0;
6938
6939 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
6940 tap = &ta->ipft_next) {
6941 if (ta == oldtune) {
6942 *tap = oldtune->ipft_next;
6943 oldtune->ipft_next = NULL;
6944 break;
6945 }
6946 }
6947
6948 if (ta == NULL) {
6949 error = ESRCH;
6950 IPFERROR(75);
6951 }
6952 return error;
6953 }
6954
6955
6956 /* ------------------------------------------------------------------------ */
6957 /* Function: ipf_tune_del_array */
6958 /* Returns: int - 0 == success, else failure */
6959 /* Parameters: oldtune - pointer to tuneables array */
6960 /* */
6961 /* Remove each tuneable entry in the array from the list of "dynamic" */
6962 /* tunables. If one entry should fail to be found, an error will be */
6963 /* returned and no further ones removed. */
6964 /* An entry with a NULL name is used as the indicator of the last entry in */
6965 /* the array. */
6966 /* ------------------------------------------------------------------------ */
6967 int
6968 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
6969 {
6970 ipftuneable_t *ot;
6971 int error = 0;
6972
6973 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
6974 error = ipf_tune_del(softc, ot);
6975 if (error != 0)
6976 break;
6977 }
6978
6979 return error;
6980
6981 }
6982
6983
6984 /* ------------------------------------------------------------------------ */
6985 /* Function: ipf_tune */
6986 /* Returns: int - 0 == success, else failure */
6987 /* Parameters: cmd(I) - ioctl command number */
6988 /* data(I) - pointer to ioctl data structure */
6989 /* */
6990 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
6991 /* three ioctls provide the means to access and control global variables */
6992 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
6993 /* changed without rebooting, reloading or recompiling. The initialisation */
6994 /* and 'destruction' routines of the various components of ipfilter are all */
6995 /* each responsible for handling their own values being too big. */
6996 /* ------------------------------------------------------------------------ */
6997 int
6998 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
6999 {
7000 ipftuneable_t *ta;
7001 ipftune_t tu;
7002 void *cookie;
7003 int error;
7004
7005 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7006 if (error != 0)
7007 return error;
7008
7009 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7010 cookie = tu.ipft_cookie;
7011 ta = NULL;
7012
7013 switch (cmd)
7014 {
7015 case SIOCIPFGETNEXT :
7016 /*
7017 * If cookie is non-NULL, assume it to be a pointer to the last
7018 * entry we looked at, so find it (if possible) and return a
7019 * pointer to the next one after it. The last entry in the
7020 * the table is a NULL entry, so when we get to it, set cookie
7021 * to NULL and return that, indicating end of list, erstwhile
7022 * if we come in with cookie set to NULL, we are starting anew
7023 * at the front of the list.
7024 */
7025 if (cookie != NULL) {
7026 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7027 cookie, &tu.ipft_cookie);
7028 } else {
7029 ta = softc->ipf_tuners;
7030 tu.ipft_cookie = ta + 1;
7031 }
7032 if (ta != NULL) {
7033 /*
7034 * Entry found, but does the data pointed to by that
7035 * row fit in what we can return?
7036 */
7037 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7038 IPFERROR(76);
7039 return EINVAL;
7040 }
7041
7042 tu.ipft_vlong = 0;
7043 if (ta->ipft_sz == sizeof(u_long))
7044 tu.ipft_vlong = *ta->ipft_plong;
7045 else if (ta->ipft_sz == sizeof(u_int))
7046 tu.ipft_vint = *ta->ipft_pint;
7047 else if (ta->ipft_sz == sizeof(u_short))
7048 tu.ipft_vshort = *ta->ipft_pshort;
7049 else if (ta->ipft_sz == sizeof(u_char))
7050 tu.ipft_vchar = *ta->ipft_pchar;
7051
7052 tu.ipft_sz = ta->ipft_sz;
7053 tu.ipft_min = ta->ipft_min;
7054 tu.ipft_max = ta->ipft_max;
7055 tu.ipft_flags = ta->ipft_flags;
7056 bcopy(ta->ipft_name, tu.ipft_name,
7057 MIN(sizeof(tu.ipft_name),
7058 strlen(ta->ipft_name) + 1));
7059 }
7060 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7061 break;
7062
7063 case SIOCIPFGET :
7064 case SIOCIPFSET :
7065 /*
7066 * Search by name or by cookie value for a particular entry
7067 * in the tuning paramter table.
7068 */
7069 IPFERROR(77);
7070 error = ESRCH;
7071 if (cookie != NULL) {
7072 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7073 cookie, NULL);
7074 if (ta != NULL)
7075 error = 0;
7076 } else if (tu.ipft_name[0] != '\0') {
7077 ta = ipf_tune_findbyname(softc->ipf_tuners,
7078 tu.ipft_name);
7079 if (ta != NULL)
7080 error = 0;
7081 }
7082 if (error != 0)
7083 break;
7084
7085 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7086 /*
7087 * Fetch the tuning parameters for a particular value
7088 */
7089 tu.ipft_vlong = 0;
7090 if (ta->ipft_sz == sizeof(u_long))
7091 tu.ipft_vlong = *ta->ipft_plong;
7092 else if (ta->ipft_sz == sizeof(u_int))
7093 tu.ipft_vint = *ta->ipft_pint;
7094 else if (ta->ipft_sz == sizeof(u_short))
7095 tu.ipft_vshort = *ta->ipft_pshort;
7096 else if (ta->ipft_sz == sizeof(u_char))
7097 tu.ipft_vchar = *ta->ipft_pchar;
7098 tu.ipft_cookie = ta;
7099 tu.ipft_sz = ta->ipft_sz;
7100 tu.ipft_min = ta->ipft_min;
7101 tu.ipft_max = ta->ipft_max;
7102 tu.ipft_flags = ta->ipft_flags;
7103 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7104
7105 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7106 /*
7107 * Set an internal parameter. The hard part here is
7108 * getting the new value safely and correctly out of
7109 * the kernel (given we only know its size, not type.)
7110 */
7111 u_long in;
7112
7113 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7114 (softc->ipf_running > 0)) {
7115 IPFERROR(78);
7116 error = EBUSY;
7117 break;
7118 }
7119
7120 in = tu.ipft_vlong;
7121 if (in < ta->ipft_min || in > ta->ipft_max) {
7122 IPFERROR(79);
7123 error = EINVAL;
7124 break;
7125 }
7126
7127 if (ta->ipft_func != NULL) {
7128 SPL_INT(s);
7129
7130 SPL_NET(s);
7131 error = (*ta->ipft_func)(softc, ta,
7132 &tu.ipft_un);
7133 SPL_X(s);
7134
7135 } else if (ta->ipft_sz == sizeof(u_long)) {
7136 tu.ipft_vlong = *ta->ipft_plong;
7137 *ta->ipft_plong = in;
7138
7139 } else if (ta->ipft_sz == sizeof(u_int)) {
7140 tu.ipft_vint = *ta->ipft_pint;
7141 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7142
7143 } else if (ta->ipft_sz == sizeof(u_short)) {
7144 tu.ipft_vshort = *ta->ipft_pshort;
7145 *ta->ipft_pshort = (u_short)(in & 0xffff);
7146
7147 } else if (ta->ipft_sz == sizeof(u_char)) {
7148 tu.ipft_vchar = *ta->ipft_pchar;
7149 *ta->ipft_pchar = (u_char)(in & 0xff);
7150 }
7151 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7152 }
7153 break;
7154
7155 default :
7156 IPFERROR(80);
7157 error = EINVAL;
7158 break;
7159 }
7160
7161 return error;
7162 }
7163
7164
7165 /* ------------------------------------------------------------------------ */
7166 /* Function: ipf_zerostats */
7167 /* Returns: int - 0 = success, else failure */
7168 /* Parameters: data(O) - pointer to pointer for copying data back to */
7169 /* */
7170 /* Copies the current statistics out to userspace and then zero's the */
7171 /* current ones in the kernel. The lock is only held across the bzero() as */
7172 /* the copyout may result in paging (ie network activity.) */
7173 /* ------------------------------------------------------------------------ */
7174 int
7175 ipf_zerostats(ipf_main_softc_t *softc, void *data)
7176 {
7177 friostat_t fio;
7178 ipfobj_t obj;
7179 int error;
7180
7181 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7182 if (error != 0)
7183 return error;
7184 ipf_getstat(softc, &fio, obj.ipfo_rev);
7185 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7186 if (error != 0)
7187 return error;
7188
7189 WRITE_ENTER(&softc->ipf_mutex);
7190 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7191 RWLOCK_EXIT(&softc->ipf_mutex);
7192
7193 return 0;
7194 }
7195
7196
7197 /* ------------------------------------------------------------------------ */
7198 /* Function: ipf_resolvedest */
7199 /* Returns: Nil */
7200 /* Parameters: softc(I) - pointer to soft context main structure */
7201 /* base(I) - where strings are stored */
7202 /* fdp(IO) - pointer to destination information to resolve */
7203 /* v(I) - IP protocol version to match */
7204 /* */
7205 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7206 /* if a matching name can be found for the particular IP protocol version */
7207 /* then store the interface pointer in the frdest struct. If no match is */
7208 /* found, then set the interface pointer to be -1 as NULL is considered to */
7209 /* indicate there is no information at all in the structure. */
7210 /* ------------------------------------------------------------------------ */
7211 int
7212 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7213 {
7214 int errval = 0;
7215 void *ifp;
7216
7217 ifp = NULL;
7218
7219 if (fdp->fd_name != -1) {
7220 if (fdp->fd_type == FRD_DSTLIST) {
7221 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7222 IPLT_DSTLIST,
7223 base + fdp->fd_name,
7224 NULL);
7225 if (ifp == NULL) {
7226 IPFERROR(144);
7227 errval = ESRCH;
7228 }
7229 } else {
7230 ifp = GETIFP(base + fdp->fd_name, v);
7231 if (ifp == NULL)
7232 ifp = (void *)-1;
7233 if ((ifp != NULL) && (ifp != (void *)-1))
7234 fdp->fd_local = ipf_deliverlocal(softc, v, ifp,
7235 &fdp->fd_ip6);
7236 }
7237 }
7238 fdp->fd_ptr = ifp;
7239
7240 return errval;
7241 }
7242
7243
7244 /* ------------------------------------------------------------------------ */
7245 /* Function: ipf_resolvenic */
7246 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7247 /* pointer to interface structure for NIC */
7248 /* Parameters: softc(I)- pointer to soft context main structure */
7249 /* name(I) - complete interface name */
7250 /* v(I) - IP protocol version */
7251 /* */
7252 /* Look for a network interface structure that firstly has a matching name */
7253 /* to that passed in and that is also being used for that IP protocol */
7254 /* version (necessary on some platforms where there are separate listings */
7255 /* for both IPv4 and IPv6 on the same physical NIC. */
7256 /* */
7257 /* ------------------------------------------------------------------------ */
7258 void *
7259 ipf_resolvenic(ipf_main_softc_t *softc, char *name, int v)
7260 {
7261 void *nic;
7262
7263 softc = softc; /* gcc -Wextra */
7264 if (name[0] == '\0')
7265 return NULL;
7266
7267 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7268 return NULL;
7269 }
7270
7271 nic = GETIFP(name, v);
7272 if (nic == NULL)
7273 nic = (void *)-1;
7274 return nic;
7275 }
7276
7277
7278 /* ------------------------------------------------------------------------ */
7279 /* Function: ipf_token_expire */
7280 /* Returns: None. */
7281 /* Parameters: softc(I) - pointer to soft context main structure */
7282 /* */
7283 /* This function is run every ipf tick to see if there are any tokens that */
7284 /* have been held for too long and need to be freed up. */
7285 /* ------------------------------------------------------------------------ */
7286 void
7287 ipf_token_expire(ipf_main_softc_t *softc)
7288 {
7289 ipftoken_t *it;
7290
7291 WRITE_ENTER(&softc->ipf_tokens);
7292 while ((it = softc->ipf_token_head) != NULL) {
7293 if (it->ipt_die > softc->ipf_ticks)
7294 break;
7295
7296 ipf_token_deref(softc, it);
7297 }
7298 RWLOCK_EXIT(&softc->ipf_tokens);
7299 }
7300
7301
7302 /* ------------------------------------------------------------------------ */
7303 /* Function: ipf_token_flush */
7304 /* Returns: None. */
7305 /* Parameters: softc(I) - pointer to soft context main structure */
7306 /* */
7307 /* Loop through all of the existing tokens and call deref to see if they */
7308 /* can be freed. Normally a function like this might just loop on */
7309 /* ipf_token_head but there is a chance that a token might have a ref count */
7310 /* of greater than one and in that case the the reference would drop twice */
7311 /* by code that is only entitled to drop it once. */
7312 /* ------------------------------------------------------------------------ */
7313 static void
7314 ipf_token_flush(ipf_main_softc_t *softc)
7315 {
7316 ipftoken_t *it, *next;
7317
7318 WRITE_ENTER(&softc->ipf_tokens);
7319 for (it = softc->ipf_token_head; it != NULL; it = next) {
7320 next = it->ipt_next;
7321 (void) ipf_token_deref(softc, it);
7322 }
7323 RWLOCK_EXIT(&softc->ipf_tokens);
7324 }
7325
7326
7327 /* ------------------------------------------------------------------------ */
7328 /* Function: ipf_token_del */
7329 /* Returns: int - 0 = success, else error */
7330 /* Parameters: softc(I)- pointer to soft context main structure */
7331 /* type(I) - the token type to match */
7332 /* uid(I) - uid owning the token */
7333 /* ptr(I) - context pointer for the token */
7334 /* */
7335 /* This function looks for a a token in the current list that matches up */
7336 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7337 /* call ipf_token_dewref() to remove it from the list. In the event that */
7338 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7339 /* enables debugging to distinguish between the two paths that ultimately */
7340 /* lead to a token to be deleted. */
7341 /* ------------------------------------------------------------------------ */
7342 int
7343 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7344 {
7345 ipftoken_t *it;
7346 int error;
7347
7348 IPFERROR(82);
7349 error = ESRCH;
7350
7351 WRITE_ENTER(&softc->ipf_tokens);
7352 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7353 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7354 uid == it->ipt_uid) {
7355 it->ipt_complete = 2;
7356 ipf_token_deref(softc, it);
7357 error = 0;
7358 break;
7359 }
7360 }
7361 RWLOCK_EXIT(&softc->ipf_tokens);
7362
7363 return error;
7364 }
7365
7366
7367 /* ------------------------------------------------------------------------ */
7368 /* Function: ipf_token_mark_complete */
7369 /* Returns: None. */
7370 /* Parameters: token(I) - pointer to token structure */
7371 /* */
7372 /* Mark a token as being ineligable for being found with ipf_token_find. */
7373 /* ------------------------------------------------------------------------ */
7374 void
7375 ipf_token_mark_complete(ipftoken_t *token)
7376 {
7377 if (token->ipt_complete == 0)
7378 token->ipt_complete = 1;
7379 }
7380
7381
7382 /* ------------------------------------------------------------------------ */
7383 /* Function: ipf_token_find */
7384 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7385 /* Parameters: softc(I)- pointer to soft context main structure */
7386 /* type(I) - the token type to match */
7387 /* uid(I) - uid owning the token */
7388 /* ptr(I) - context pointer for the token */
7389 /* */
7390 /* This function looks for a live token in the list of current tokens that */
7391 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7392 /* allocated. If one is found then it is moved to the top of the list of */
7393 /* currently active tokens. */
7394 /* ------------------------------------------------------------------------ */
7395 ipftoken_t *
7396 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7397 {
7398 ipftoken_t *it, *new;
7399
7400 KMALLOC(new, ipftoken_t *);
7401 if (new != NULL)
7402 bzero((char *)new, sizeof(*new));
7403
7404 WRITE_ENTER(&softc->ipf_tokens);
7405 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7406 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7407 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7408 break;
7409 }
7410
7411 if (it == NULL) {
7412 it = new;
7413 new = NULL;
7414 if (it == NULL) {
7415 RWLOCK_EXIT(&softc->ipf_tokens);
7416 return NULL;
7417 }
7418 it->ipt_ctx = ptr;
7419 it->ipt_uid = uid;
7420 it->ipt_type = type;
7421 it->ipt_ref = 1;
7422 } else {
7423 if (new != NULL) {
7424 KFREE(new);
7425 new = NULL;
7426 }
7427
7428 if (it->ipt_complete > 0)
7429 it = NULL;
7430 else
7431 ipf_token_unlink(softc, it);
7432 }
7433
7434 if (it != NULL) {
7435 it->ipt_pnext = softc->ipf_token_tail;
7436 *softc->ipf_token_tail = it;
7437 softc->ipf_token_tail = &it->ipt_next;
7438 it->ipt_next = NULL;
7439 it->ipt_ref++;
7440
7441 it->ipt_die = softc->ipf_ticks + 20;
7442 }
7443
7444 RWLOCK_EXIT(&softc->ipf_tokens);
7445
7446 return it;
7447 }
7448
7449
7450 /* ------------------------------------------------------------------------ */
7451 /* Function: ipf_token_unlink */
7452 /* Returns: None. */
7453 /* Parameters: softc(I) - pointer to soft context main structure */
7454 /* token(I) - pointer to token structure */
7455 /* Write Locks: ipf_tokens */
7456 /* */
7457 /* This function unlinks a token structure from the linked list of tokens */
7458 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7459 /* but the tail does due to the linked list implementation. */
7460 /* ------------------------------------------------------------------------ */
7461 static void
7462 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7463 {
7464
7465 if (softc->ipf_token_tail == &token->ipt_next)
7466 softc->ipf_token_tail = token->ipt_pnext;
7467
7468 *token->ipt_pnext = token->ipt_next;
7469 if (token->ipt_next != NULL)
7470 token->ipt_next->ipt_pnext = token->ipt_pnext;
7471 token->ipt_next = NULL;
7472 token->ipt_pnext = NULL;
7473 }
7474
7475
7476 /* ------------------------------------------------------------------------ */
7477 /* Function: ipf_token_deref */
7478 /* Returns: int - 0 == token freed, else reference count */
7479 /* Parameters: softc(I) - pointer to soft context main structure */
7480 /* token(I) - pointer to token structure */
7481 /* Write Locks: ipf_tokens */
7482 /* */
7483 /* Drop the reference count on the token structure and if it drops to zero, */
7484 /* call the dereference function for the token type because it is then */
7485 /* possible to free the token data structure. */
7486 /* ------------------------------------------------------------------------ */
7487 int
7488 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7489 {
7490 void *data, **datap;
7491
7492 ASSERT(token->ipt_ref > 0);
7493 token->ipt_ref--;
7494 if (token->ipt_ref > 0)
7495 return token->ipt_ref;
7496
7497 data = token->ipt_data;
7498 datap = &data;
7499
7500 if ((data != NULL) && (data != (void *)-1)) {
7501 switch (token->ipt_type)
7502 {
7503 case IPFGENITER_IPF :
7504 (void) ipf_derefrule(softc, (frentry_t **)datap);
7505 break;
7506 case IPFGENITER_IPNAT :
7507 WRITE_ENTER(&softc->ipf_nat);
7508 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7509 RWLOCK_EXIT(&softc->ipf_nat);
7510 break;
7511 case IPFGENITER_NAT :
7512 ipf_nat_deref(softc, (nat_t **)datap);
7513 break;
7514 case IPFGENITER_STATE :
7515 ipf_state_deref(softc, (ipstate_t **)datap);
7516 break;
7517 case IPFGENITER_FRAG :
7518 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7519 break;
7520 case IPFGENITER_NATFRAG :
7521 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7522 break;
7523 case IPFGENITER_HOSTMAP :
7524 WRITE_ENTER(&softc->ipf_nat);
7525 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7526 RWLOCK_EXIT(&softc->ipf_nat);
7527 break;
7528 default :
7529 ipf_lookup_iterderef(softc, token->ipt_type, data);
7530 break;
7531 }
7532 }
7533
7534 ipf_token_unlink(softc, token);
7535 KFREE(token);
7536 return 0;
7537 }
7538
7539
7540 /* ------------------------------------------------------------------------ */
7541 /* Function: ipf_nextrule */
7542 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7543 /* Parameters: softc(I) - pointer to soft context main structure */
7544 /* fr(I) - pointer to filter rule */
7545 /* out(I) - 1 == out rules, 0 == input rules */
7546 /* */
7547 /* Starting with "fr", find the next rule to visit. This includes visiting */
7548 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7549 /* last rule in the list. When walking rule lists, it is either input or */
7550 /* output rules that are returned, never both. */
7551 /* ------------------------------------------------------------------------ */
7552 static frentry_t *
7553 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit,
7554 frentry_t *fr, int out)
7555 {
7556 frentry_t *next;
7557 frgroup_t *fg;
7558
7559 if (fr != NULL && fr->fr_group != -1) {
7560 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7561 unit, active, NULL);
7562 if (fg != NULL)
7563 fg = fg->fg_next;
7564 } else {
7565 fg = softc->ipf_groups[unit][active];
7566 }
7567
7568 while (fg != NULL) {
7569 next = fg->fg_start;
7570 while (next != NULL) {
7571 if (out) {
7572 if (next->fr_flags & FR_OUTQUE)
7573 return next;
7574 } else if (next->fr_flags & FR_INQUE) {
7575 return next;
7576 }
7577 next = next->fr_next;
7578 }
7579 if (next == NULL)
7580 fg = fg->fg_next;
7581 }
7582
7583 return NULL;
7584 }
7585
7586 /* ------------------------------------------------------------------------ */
7587 /* Function: ipf_getnextrule */
7588 /* Returns: int - 0 = success, else error */
7589 /* Parameters: softc(I)- pointer to soft context main structure */
7590 /* t(I) - pointer to destination information to resolve */
7591 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7592 /* */
7593 /* This function's first job is to bring in the ipfruleiter_t structure via */
7594 /* the ipfobj_t structure to determine what should be the next rule to */
7595 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7596 /* find the 'next rule'. This may include searching rule group lists or */
7597 /* just be as simple as looking at the 'next' field in the rule structure. */
7598 /* When we have found the rule to return, increase its reference count and */
7599 /* if we used an existing rule to get here, decrease its reference count. */
7600 /* ------------------------------------------------------------------------ */
7601 int
7602 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7603 {
7604 frentry_t *fr, *next, zero;
7605 ipfruleiter_t it;
7606 int error, out;
7607 frgroup_t *fg;
7608 ipfobj_t obj;
7609 int predict;
7610 char *dst;
7611 int unit;
7612
7613 if (t == NULL || ptr == NULL) {
7614 IPFERROR(84);
7615 return EFAULT;
7616 }
7617
7618 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7619 if (error != 0)
7620 return error;
7621
7622 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7623 IPFERROR(85);
7624 return EINVAL;
7625 }
7626 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7627 IPFERROR(86);
7628 return EINVAL;
7629 }
7630 if (it.iri_nrules == 0) {
7631 IPFERROR(87);
7632 return ENOSPC;
7633 }
7634 if (it.iri_rule == NULL) {
7635 IPFERROR(88);
7636 return EFAULT;
7637 }
7638
7639 fg = NULL;
7640 fr = t->ipt_data;
7641 if ((it.iri_inout & F_OUT) != 0)
7642 out = 1;
7643 else
7644 out = 0;
7645 if ((it.iri_inout & F_ACIN) != 0)
7646 unit = IPL_LOGCOUNT;
7647 else
7648 unit = IPL_LOGIPF;
7649
7650 READ_ENTER(&softc->ipf_mutex);
7651 if (fr == NULL) {
7652 if (*it.iri_group == '\0') {
7653 if (unit == IPL_LOGCOUNT) {
7654 next = softc->ipf_acct[out][it.iri_active];
7655 } else {
7656 next = softc->ipf_rules[out][it.iri_active];
7657 }
7658 if (next == NULL)
7659 next = ipf_nextrule(softc, it.iri_active,
7660 unit, NULL, out);
7661 } else {
7662 fg = ipf_findgroup(softc, it.iri_group, unit,
7663 it.iri_active, NULL);
7664 if (fg != NULL)
7665 next = fg->fg_start;
7666 else
7667 next = NULL;
7668 }
7669 } else {
7670 next = fr->fr_next;
7671 if (next == NULL)
7672 next = ipf_nextrule(softc, it.iri_active, unit,
7673 fr, out);
7674 }
7675
7676 if (next != NULL && next->fr_next != NULL)
7677 predict = 1;
7678 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7679 predict = 1;
7680 else
7681 predict = 0;
7682
7683 if (fr != NULL)
7684 (void) ipf_derefrule(softc, &fr);
7685
7686 obj.ipfo_type = IPFOBJ_FRENTRY;
7687 dst = (char *)it.iri_rule;
7688
7689 if (next != NULL) {
7690 obj.ipfo_size = next->fr_size;
7691 MUTEX_ENTER(&next->fr_lock);
7692 next->fr_ref++;
7693 MUTEX_EXIT(&next->fr_lock);
7694 t->ipt_data = next;
7695 } else {
7696 obj.ipfo_size = sizeof(frentry_t);
7697 bzero(&zero, sizeof(zero));
7698 next = &zero;
7699 t->ipt_data = NULL;
7700 }
7701 it.iri_rule = predict ? next : NULL;
7702 if (predict == 0)
7703 ipf_token_mark_complete(t);
7704
7705 RWLOCK_EXIT(&softc->ipf_mutex);
7706
7707 obj.ipfo_ptr = dst;
7708 error = ipf_outobjk(softc, &obj, next);
7709 if (error == 0 && t->ipt_data != NULL) {
7710 dst += obj.ipfo_size;
7711 if (next->fr_data != NULL) {
7712 ipfobj_t dobj;
7713
7714 if (next->fr_type == FR_T_IPFEXPR)
7715 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7716 else
7717 dobj.ipfo_type = IPFOBJ_FRIPF;
7718 dobj.ipfo_size = next->fr_dsize;
7719 dobj.ipfo_rev = obj.ipfo_rev;
7720 dobj.ipfo_ptr = dst;
7721 error = ipf_outobjk(softc, &dobj, next->fr_data);
7722 }
7723 }
7724
7725 if ((fr != NULL) && (next == &zero))
7726 (void) ipf_derefrule(softc, &fr);
7727
7728 return error;
7729 }
7730
7731
7732 /* ------------------------------------------------------------------------ */
7733 /* Function: ipf_frruleiter */
7734 /* Returns: int - 0 = success, else error */
7735 /* Parameters: softc(I)- pointer to soft context main structure */
7736 /* data(I) - the token type to match */
7737 /* uid(I) - uid owning the token */
7738 /* ptr(I) - context pointer for the token */
7739 /* */
7740 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
7741 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
7742 /* the process doing the ioctl and use that to ask for the next rule. */
7743 /* ------------------------------------------------------------------------ */
7744 static int
7745 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7746 {
7747 ipftoken_t *token;
7748 ipfruleiter_t it;
7749 ipfobj_t obj;
7750 int error;
7751
7752 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7753 if (token != NULL) {
7754 error = ipf_getnextrule(softc, token, data);
7755 WRITE_ENTER(&softc->ipf_tokens);
7756 ipf_token_deref(softc, token);
7757 RWLOCK_EXIT(&softc->ipf_tokens);
7758 } else {
7759 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7760 if (error != 0)
7761 return error;
7762 it.iri_rule = NULL;
7763 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7764 }
7765
7766 return error;
7767 }
7768
7769
7770 /* ------------------------------------------------------------------------ */
7771 /* Function: ipf_geniter */
7772 /* Returns: int - 0 = success, else error */
7773 /* Parameters: softc(I) - pointer to soft context main structure */
7774 /* token(I) - pointer to ipftoken_t structure */
7775 /* itp(I) - pointer to iterator data */
7776 /* */
7777 /* Decide which iterator function to call using information passed through */
7778 /* the ipfgeniter_t structure at itp. */
7779 /* ------------------------------------------------------------------------ */
7780 static int
7781 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7782 {
7783 int error;
7784
7785 switch (itp->igi_type)
7786 {
7787 case IPFGENITER_FRAG :
7788 error = ipf_frag_pkt_next(softc, token, itp);
7789 break;
7790 default :
7791 IPFERROR(92);
7792 error = EINVAL;
7793 break;
7794 }
7795
7796 return error;
7797 }
7798
7799
7800 /* ------------------------------------------------------------------------ */
7801 /* Function: ipf_genericiter */
7802 /* Returns: int - 0 = success, else error */
7803 /* Parameters: softc(I)- pointer to soft context main structure */
7804 /* data(I) - the token type to match */
7805 /* uid(I) - uid owning the token */
7806 /* ptr(I) - context pointer for the token */
7807 /* */
7808 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
7809 /* ------------------------------------------------------------------------ */
7810 int
7811 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7812 {
7813 ipftoken_t *token;
7814 ipfgeniter_t iter;
7815 int error;
7816
7817 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7818 if (error != 0)
7819 return error;
7820
7821 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7822 if (token != NULL) {
7823 token->ipt_subtype = iter.igi_type;
7824 error = ipf_geniter(softc, token, &iter);
7825 WRITE_ENTER(&softc->ipf_tokens);
7826 ipf_token_deref(softc, token);
7827 RWLOCK_EXIT(&softc->ipf_tokens);
7828 } else {
7829 IPFERROR(93);
7830 error = 0;
7831 }
7832
7833 return error;
7834 }
7835
7836
7837 /* ------------------------------------------------------------------------ */
7838 /* Function: ipf_ipf_ioctl */
7839 /* Returns: int - 0 = success, else error */
7840 /* Parameters: softc(I)- pointer to soft context main structure */
7841 /* data(I) - the token type to match */
7842 /* cmd(I) - the ioctl command number */
7843 /* mode(I) - mode flags for the ioctl */
7844 /* uid(I) - uid owning the token */
7845 /* ptr(I) - context pointer for the token */
7846 /* */
7847 /* This function handles all of the ioctl command that are actually isssued */
7848 /* to the /dev/ipl device. */
7849 /* ------------------------------------------------------------------------ */
7850 int
7851 ipf_ipf_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
7852 int uid, void *ctx)
7853 {
7854 friostat_t fio;
7855 int error, tmp;
7856 ipfobj_t obj;
7857 SPL_INT(s);
7858
7859 switch (cmd)
7860 {
7861 case SIOCFRENB :
7862 if (!(mode & FWRITE)) {
7863 IPFERROR(94);
7864 error = EPERM;
7865 } else {
7866 error = BCOPYIN(data, &tmp, sizeof(tmp));
7867 if (error != 0) {
7868 IPFERROR(95);
7869 error = EFAULT;
7870 break;
7871 }
7872
7873 WRITE_ENTER(&softc->ipf_global);
7874 if (tmp) {
7875 if (softc->ipf_running > 0)
7876 error = 0;
7877 else
7878 error = ipfattach(softc);
7879 if (error == 0)
7880 softc->ipf_running = 1;
7881 else
7882 (void) ipfdetach(softc);
7883 } else {
7884 if (softc->ipf_running == 1)
7885 error = ipfdetach(softc);
7886 else
7887 error = 0;
7888 if (error == 0)
7889 softc->ipf_running = -1;
7890 }
7891 RWLOCK_EXIT(&softc->ipf_global);
7892 }
7893 break;
7894
7895 case SIOCIPFSET :
7896 if (!(mode & FWRITE)) {
7897 IPFERROR(96);
7898 error = EPERM;
7899 break;
7900 }
7901 /* FALLTHRU */
7902 case SIOCIPFGETNEXT :
7903 case SIOCIPFGET :
7904 error = ipf_ipftune(softc, cmd, (void *)data);
7905 break;
7906
7907 case SIOCSETFF :
7908 if (!(mode & FWRITE)) {
7909 IPFERROR(97);
7910 error = EPERM;
7911 } else {
7912 error = BCOPYIN(data, &softc->ipf_flags,
7913 sizeof(softc->ipf_flags));
7914 if (error != 0) {
7915 IPFERROR(98);
7916 error = EFAULT;
7917 }
7918 }
7919 break;
7920
7921 case SIOCGETFF :
7922 error = BCOPYOUT(&softc->ipf_flags, data,
7923 sizeof(softc->ipf_flags));
7924 if (error != 0) {
7925 IPFERROR(99);
7926 error = EFAULT;
7927 }
7928 break;
7929
7930 case SIOCFUNCL :
7931 error = ipf_resolvefunc(softc, (void *)data);
7932 break;
7933
7934 case SIOCINAFR :
7935 case SIOCRMAFR :
7936 case SIOCADAFR :
7937 case SIOCZRLST :
7938 if (!(mode & FWRITE)) {
7939 IPFERROR(100);
7940 error = EPERM;
7941 } else {
7942 error = frrequest(softc, IPL_LOGIPF, cmd, data,
7943 softc->ipf_active, 1);
7944 }
7945 break;
7946
7947 case SIOCINIFR :
7948 case SIOCRMIFR :
7949 case SIOCADIFR :
7950 if (!(mode & FWRITE)) {
7951 IPFERROR(101);
7952 error = EPERM;
7953 } else {
7954 error = frrequest(softc, IPL_LOGIPF, cmd, data,
7955 1 - softc->ipf_active, 1);
7956 }
7957 break;
7958
7959 case SIOCSWAPA :
7960 if (!(mode & FWRITE)) {
7961 IPFERROR(102);
7962 error = EPERM;
7963 } else {
7964 WRITE_ENTER(&softc->ipf_mutex);
7965 error = BCOPYOUT(&softc->ipf_active, data,
7966 sizeof(softc->ipf_active));
7967 if (error != 0) {
7968 IPFERROR(103);
7969 error = EFAULT;
7970 } else {
7971 softc->ipf_active = 1 - softc->ipf_active;
7972 }
7973 RWLOCK_EXIT(&softc->ipf_mutex);
7974 }
7975 break;
7976
7977 case SIOCGETFS :
7978 error = ipf_inobj(softc, (void *)data, &obj, &fio,
7979 IPFOBJ_IPFSTAT);
7980 if (error != 0)
7981 break;
7982 ipf_getstat(softc, &fio, obj.ipfo_rev);
7983 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
7984 break;
7985
7986 case SIOCFRZST :
7987 if (!(mode & FWRITE)) {
7988 IPFERROR(104);
7989 error = EPERM;
7990 } else
7991 error = ipf_zerostats(softc, data);
7992 break;
7993
7994 case SIOCIPFFL :
7995 if (!(mode & FWRITE)) {
7996 IPFERROR(105);
7997 error = EPERM;
7998 } else {
7999 error = BCOPYIN(data, &tmp, sizeof(tmp));
8000 if (!error) {
8001 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8002 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8003 if (error != 0) {
8004 IPFERROR(106);
8005 error = EFAULT;
8006 }
8007 } else {
8008 IPFERROR(107);
8009 error = EFAULT;
8010 }
8011 }
8012 break;
8013
8014 #ifdef USE_INET6
8015 case SIOCIPFL6 :
8016 if (!(mode & FWRITE)) {
8017 IPFERROR(108);
8018 error = EPERM;
8019 } else {
8020 error = BCOPYIN(data, &tmp, sizeof(tmp));
8021 if (!error) {
8022 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8023 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8024 if (error != 0) {
8025 IPFERROR(109);
8026 error = EFAULT;
8027 }
8028 } else {
8029 IPFERROR(110);
8030 error = EFAULT;
8031 }
8032 }
8033 break;
8034 #endif
8035
8036 case SIOCSTLCK :
8037 if (!(mode & FWRITE)) {
8038 IPFERROR(122);
8039 error = EPERM;
8040 } else {
8041 error = BCOPYIN(data, &tmp, sizeof(tmp));
8042 if (error == 0) {
8043 ipf_state_setlock(softc->ipf_state_soft, tmp);
8044 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8045 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8046 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8047 } else {
8048 IPFERROR(111);
8049 error = EFAULT;
8050 }
8051 }
8052 break;
8053
8054 #ifdef IPFILTER_LOG
8055 case SIOCIPFFB :
8056 if (!(mode & FWRITE)) {
8057 IPFERROR(112);
8058 error = EPERM;
8059 } else {
8060 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8061 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8062 if (error) {
8063 IPFERROR(113);
8064 error = EFAULT;
8065 }
8066 }
8067 break;
8068 #endif /* IPFILTER_LOG */
8069
8070 case SIOCFRSYN :
8071 if (!(mode & FWRITE)) {
8072 IPFERROR(114);
8073 error = EPERM;
8074 } else {
8075 WRITE_ENTER(&softc->ipf_global);
8076 #if (defined(MENTAT) && defined(_KERNEL)) && !defined(INSTANCES)
8077 error = ipfsync();
8078 #else
8079 ipf_sync(softc, NULL);
8080 error = 0;
8081 #endif
8082 RWLOCK_EXIT(&softc->ipf_global);
8083
8084 }
8085 break;
8086
8087 case SIOCGFRST :
8088 error = ipf_outobj(softc, (void *)data,
8089 ipf_frag_stats(softc->ipf_frag_soft),
8090 IPFOBJ_FRAGSTAT);
8091 break;
8092
8093 #ifdef IPFILTER_LOG
8094 case FIONREAD :
8095 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8096 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8097 break;
8098 #endif
8099
8100 case SIOCIPFITER :
8101 SPL_SCHED(s);
8102 error = ipf_frruleiter(softc, data, uid, ctx);
8103 SPL_X(s);
8104 break;
8105
8106 case SIOCGENITER :
8107 SPL_SCHED(s);
8108 error = ipf_genericiter(softc, data, uid, ctx);
8109 SPL_X(s);
8110 break;
8111
8112 case SIOCIPFDELTOK :
8113 error = BCOPYIN(data, &tmp, sizeof(tmp));
8114 if (error == 0) {
8115 SPL_SCHED(s);
8116 error = ipf_token_del(softc, tmp, uid, ctx);
8117 SPL_X(s);
8118 }
8119 break;
8120
8121 default :
8122 IPFERROR(115);
8123 error = EINVAL;
8124 break;
8125 }
8126
8127 return error;
8128 }
8129
8130
8131 /* ------------------------------------------------------------------------ */
8132 /* Function: ipf_decaps */
8133 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8134 /* flags indicating packet filtering decision. */
8135 /* Parameters: fin(I) - pointer to packet information */
8136 /* pass(I) - IP protocol version to match */
8137 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8138 /* */
8139 /* This function is called for packets that are wrapt up in other packets, */
8140 /* for example, an IP packet that is the entire data segment for another IP */
8141 /* packet. If the basic constraints for this are satisfied, change the */
8142 /* buffer to point to the start of the inner packet and start processing */
8143 /* rules belonging to the head group this rule specifies. */
8144 /* ------------------------------------------------------------------------ */
8145 u_32_t
8146 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8147 {
8148 fr_info_t fin2, *fino = NULL;
8149 int elen, hlen, nh;
8150 grehdr_t gre;
8151 ip_t *ip;
8152 mb_t *m;
8153
8154 if ((fin->fin_flx & FI_COALESCE) == 0)
8155 if (ipf_coalesce(fin) == -1)
8156 goto cantdecaps;
8157
8158 m = fin->fin_m;
8159 hlen = fin->fin_hlen;
8160
8161 switch (fin->fin_p)
8162 {
8163 case IPPROTO_UDP :
8164 /*
8165 * In this case, the specific protocol being decapsulated
8166 * inside UDP frames comes from the rule.
8167 */
8168 nh = fin->fin_fr->fr_icode;
8169 break;
8170
8171 case IPPROTO_GRE : /* 47 */
8172 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8173 hlen += sizeof(grehdr_t);
8174 if (gre.gr_R|gre.gr_s)
8175 goto cantdecaps;
8176 if (gre.gr_C)
8177 hlen += 4;
8178 if (gre.gr_K)
8179 hlen += 4;
8180 if (gre.gr_S)
8181 hlen += 4;
8182
8183 nh = IPPROTO_IP;
8184
8185 /*
8186 * If the routing options flag is set, validate that it is
8187 * there and bounce over it.
8188 */
8189 #if 0
8190 /* This is really heavy weight and lots of room for error, */
8191 /* so for now, put it off and get the simple stuff right. */
8192 if (gre.gr_R) {
8193 u_char off, len, *s;
8194 u_short af;
8195 int end;
8196
8197 end = 0;
8198 s = fin->fin_dp;
8199 s += hlen;
8200 aplen = fin->fin_plen - hlen;
8201 while (aplen > 3) {
8202 af = (s[0] << 8) | s[1];
8203 off = s[2];
8204 len = s[3];
8205 aplen -= 4;
8206 s += 4;
8207 if (af == 0 && len == 0) {
8208 end = 1;
8209 break;
8210 }
8211 if (aplen < len)
8212 break;
8213 s += len;
8214 aplen -= len;
8215 }
8216 if (end != 1)
8217 goto cantdecaps;
8218 hlen = s - (u_char *)fin->fin_dp;
8219 }
8220 #endif
8221 break;
8222
8223 #ifdef IPPROTO_IPIP
8224 case IPPROTO_IPIP : /* 4 */
8225 #endif
8226 nh = IPPROTO_IP;
8227 break;
8228
8229 default : /* Includes ESP, AH is special for IPv4 */
8230 goto cantdecaps;
8231 }
8232
8233 switch (nh)
8234 {
8235 case IPPROTO_IP :
8236 case IPPROTO_IPV6 :
8237 break;
8238 default :
8239 goto cantdecaps;
8240 }
8241
8242 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8243 fino = fin;
8244 fin = &fin2;
8245 elen = hlen;
8246 #if defined(MENTAT) && defined(_KERNEL)
8247 m->b_rptr += elen;
8248 #else
8249 m->m_data += elen;
8250 m->m_len -= elen;
8251 #endif
8252 fin->fin_plen -= elen;
8253
8254 ip = (ip_t *)((char *)fin->fin_ip + elen);
8255
8256 /*
8257 * Make sure we have at least enough data for the network layer
8258 * header.
8259 */
8260 if (IP_V(ip) == 4)
8261 hlen = IP_HL(ip) << 2;
8262 #ifdef USE_INET6
8263 else if (IP_V(ip) == 6)
8264 hlen = sizeof(ip6_t);
8265 #endif
8266 else
8267 goto cantdecaps2;
8268
8269 if (fin->fin_plen < hlen)
8270 goto cantdecaps2;
8271
8272 fin->fin_dp = (char *)ip + hlen;
8273
8274 if (IP_V(ip) == 4) {
8275 /*
8276 * Perform IPv4 header checksum validation.
8277 */
8278 if (ipf_cksum((u_short *)ip, hlen))
8279 goto cantdecaps2;
8280 }
8281
8282 if (ipf_makefrip(hlen, ip, fin) == -1) {
8283 cantdecaps2:
8284 if (m != NULL) {
8285 #if defined(MENTAT) && defined(_KERNEL)
8286 m->b_rptr -= elen;
8287 #else
8288 m->m_data -= elen;
8289 m->m_len += elen;
8290 #endif
8291 }
8292 cantdecaps:
8293 DT1(frb_decapfrip, fr_info_t *, fin);
8294 pass &= ~FR_CMDMASK;
8295 pass |= FR_BLOCK|FR_QUICK;
8296 fin->fin_reason = FRB_DECAPFRIP;
8297 return -1;
8298 }
8299
8300 pass = ipf_scanlist(fin, pass);
8301
8302 /*
8303 * Copy the packet filter "result" fields out of the fr_info_t struct
8304 * that is local to the decapsulation processing and back into the
8305 * one we were called with.
8306 */
8307 fino->fin_flx = fin->fin_flx;
8308 fino->fin_rev = fin->fin_rev;
8309 fino->fin_icode = fin->fin_icode;
8310 fino->fin_rule = fin->fin_rule;
8311 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8312 fino->fin_fr = fin->fin_fr;
8313 fino->fin_error = fin->fin_error;
8314 fino->fin_mp = fin->fin_mp;
8315 fino->fin_m = fin->fin_m;
8316 m = fin->fin_m;
8317 if (m != NULL) {
8318 #if defined(MENTAT) && defined(_KERNEL)
8319 m->b_rptr -= elen;
8320 #else
8321 m->m_data -= elen;
8322 m->m_len += elen;
8323 #endif
8324 }
8325 return pass;
8326 }
8327
8328
8329 /* ------------------------------------------------------------------------ */
8330 /* Function: ipf_matcharray_load */
8331 /* Returns: int - 0 = success, else error */
8332 /* Parameters: softc(I) - pointer to soft context main structure */
8333 /* data(I) - pointer to ioctl data */
8334 /* objp(I) - ipfobj_t structure to load data into */
8335 /* arrayptr(I) - pointer to location to store array pointer */
8336 /* */
8337 /* This function loads in a mathing array through the ipfobj_t struct that */
8338 /* describes it. Sanity checking and array size limitations are enforced */
8339 /* in this function to prevent userspace from trying to load in something */
8340 /* that is insanely big. Once the size of the array is known, the memory */
8341 /* required is malloc'd and returned through changing *arrayptr. The */
8342 /* contents of the array are verified before returning. Only in the event */
8343 /* of a successful call is the caller required to free up the malloc area. */
8344 /* ------------------------------------------------------------------------ */
8345 int
8346 ipf_matcharray_load(ipf_main_softc_t *softc, void *data, ipfobj_t *objp,
8347 int **arrayptr)
8348 {
8349 int arraysize, *array, error;
8350
8351 *arrayptr = NULL;
8352
8353 error = BCOPYIN(data, objp, sizeof(*objp));
8354 if (error != 0) {
8355 IPFERROR(116);
8356 return EFAULT;
8357 }
8358
8359 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8360 IPFERROR(117);
8361 return EINVAL;
8362 }
8363
8364 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8365 (objp->ipfo_size > 1024)) {
8366 IPFERROR(118);
8367 return EINVAL;
8368 }
8369
8370 arraysize = objp->ipfo_size * sizeof(*array);
8371 KMALLOCS(array, int *, arraysize);
8372 if (array == NULL) {
8373 IPFERROR(119);
8374 return ENOMEM;
8375 }
8376
8377 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8378 if (error != 0) {
8379 KFREES(array, arraysize);
8380 IPFERROR(120);
8381 return EFAULT;
8382 }
8383
8384 if (ipf_matcharray_verify(array, arraysize) != 0) {
8385 KFREES(array, arraysize);
8386 IPFERROR(121);
8387 return EINVAL;
8388 }
8389
8390 *arrayptr = array;
8391 return 0;
8392 }
8393
8394
8395 /* ------------------------------------------------------------------------ */
8396 /* Function: ipf_matcharray_verify */
8397 /* Returns: Nil */
8398 /* Parameters: array(I) - pointer to matching array */
8399 /* arraysize(I) - number of elements in the array */
8400 /* */
8401 /* Verify the contents of a matching array by stepping through each element */
8402 /* in it. The actual commands in the array are not verified for */
8403 /* correctness, only that all of the sizes are correctly within limits. */
8404 /* ------------------------------------------------------------------------ */
8405 int
8406 ipf_matcharray_verify(int *array, int arraysize)
8407 {
8408 int i, nelem, maxidx;
8409 ipfexp_t *e;
8410
8411 nelem = arraysize / sizeof(*array);
8412
8413 /*
8414 * Currently, it makes no sense to have an array less than 6
8415 * elements long - the initial size at the from, a single operation
8416 * (minimum 4 in length) and a trailer, for a total of 6.
8417 */
8418 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8419 return -1;
8420 }
8421
8422 /*
8423 * Verify the size of data pointed to by array with how long
8424 * the array claims to be itself.
8425 */
8426 if (array[0] * sizeof(*array) != arraysize) {
8427 return -1;
8428 }
8429
8430 maxidx = nelem - 1;
8431 /*
8432 * The last opcode in this array should be an IPF_EXP_END.
8433 */
8434 if (array[maxidx] != IPF_EXP_END) {
8435 return -1;
8436 }
8437
8438 for (i = 1; i < maxidx; ) {
8439 e = (ipfexp_t *)(array + i);
8440
8441 /*
8442 * The length of the bits to check must be at least 1
8443 * (or else there is nothing to comapre with!) and it
8444 * cannot exceed the length of the data present.
8445 */
8446 if ((e->ipfe_size < 1 ) ||
8447 (e->ipfe_size + i > maxidx)) {
8448 return -1;
8449 }
8450 i += e->ipfe_size;
8451 }
8452 return 0;
8453 }
8454
8455
8456 /* ------------------------------------------------------------------------ */
8457 /* Function: ipf_fr_matcharray */
8458 /* Returns: int - 0 = match failed, else positive match */
8459 /* Parameters: fin(I) - pointer to packet information */
8460 /* array(I) - pointer to matching array */
8461 /* */
8462 /* This function is used to apply a matching array against a packet and */
8463 /* return an indication of whether or not the packet successfully matches */
8464 /* all of the commands in it. */
8465 /* ------------------------------------------------------------------------ */
8466 static int
8467 ipf_fr_matcharray(fr_info_t *fin, int *array)
8468 {
8469 int i, n, *x, rv, p;
8470 ipfexp_t *e;
8471
8472 rv = 0;
8473 n = array[0];
8474 x = array + 1;
8475
8476 for (; n > 0; x += 3 + x[3], rv = 0) {
8477 e = (ipfexp_t *)x;
8478 if (e->ipfe_cmd == IPF_EXP_END)
8479 break;
8480 n -= e->ipfe_size;
8481
8482 /*
8483 * The upper 16 bits currently store the protocol value.
8484 * This is currently used with TCP and UDP port compares and
8485 * allows "tcp.port = 80" without requiring an explicit
8486 " "ip.pr = tcp" first.
8487 */
8488 p = e->ipfe_cmd >> 16;
8489 if ((p != 0) && (p != fin->fin_p))
8490 break;
8491
8492 switch (e->ipfe_cmd)
8493 {
8494 case IPF_EXP_IP_PR :
8495 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8496 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8497 }
8498 break;
8499
8500 case IPF_EXP_IP_SRCADDR :
8501 if (fin->fin_v != 4)
8502 break;
8503 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8504 rv |= ((fin->fin_saddr &
8505 e->ipfe_arg0[i * 2 + 1]) ==
8506 e->ipfe_arg0[i * 2]);
8507 }
8508 break;
8509
8510 case IPF_EXP_IP_DSTADDR :
8511 if (fin->fin_v != 4)
8512 break;
8513 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8514 rv |= ((fin->fin_daddr &
8515 e->ipfe_arg0[i * 2 + 1]) ==
8516 e->ipfe_arg0[i * 2]);
8517 }
8518 break;
8519
8520 case IPF_EXP_IP_ADDR :
8521 if (fin->fin_v != 4)
8522 break;
8523 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8524 rv |= ((fin->fin_saddr &
8525 e->ipfe_arg0[i * 2 + 1]) ==
8526 e->ipfe_arg0[i * 2]) ||
8527 ((fin->fin_daddr &
8528 e->ipfe_arg0[i * 2 + 1]) ==
8529 e->ipfe_arg0[i * 2]);
8530 }
8531 break;
8532
8533 #ifdef USE_INET6
8534 case IPF_EXP_IP6_SRCADDR :
8535 if (fin->fin_v != 6)
8536 break;
8537 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8538 rv |= IP6_MASKEQ(&fin->fin_src6,
8539 &e->ipfe_arg0[i * 8 + 4],
8540 &e->ipfe_arg0[i * 8]);
8541 }
8542 break;
8543
8544 case IPF_EXP_IP6_DSTADDR :
8545 if (fin->fin_v != 6)
8546 break;
8547 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8548 rv |= IP6_MASKEQ(&fin->fin_dst6,
8549 &e->ipfe_arg0[i * 8 + 4],
8550 &e->ipfe_arg0[i * 8]);
8551 }
8552 break;
8553
8554 case IPF_EXP_IP6_ADDR :
8555 if (fin->fin_v != 6)
8556 break;
8557 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8558 rv |= IP6_MASKEQ(&fin->fin_src6,
8559 &e->ipfe_arg0[i * 8 + 4],
8560 &e->ipfe_arg0[i * 8]) ||
8561 IP6_MASKEQ(&fin->fin_dst6,
8562 &e->ipfe_arg0[i * 8 + 4],
8563 &e->ipfe_arg0[i * 8]);
8564 }
8565 break;
8566 #endif
8567
8568 case IPF_EXP_UDP_PORT :
8569 case IPF_EXP_TCP_PORT :
8570 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8571 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8572 (fin->fin_dport == e->ipfe_arg0[i]);
8573 }
8574 break;
8575
8576 case IPF_EXP_UDP_SPORT :
8577 case IPF_EXP_TCP_SPORT :
8578 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8579 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8580 }
8581 break;
8582
8583 case IPF_EXP_UDP_DPORT :
8584 case IPF_EXP_TCP_DPORT :
8585 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8586 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8587 }
8588 break;
8589
8590 case IPF_EXP_TCP_FLAGS :
8591 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8592 rv |= ((fin->fin_tcpf &
8593 e->ipfe_arg0[i * 2 + 1]) ==
8594 e->ipfe_arg0[i * 2]);
8595 }
8596 break;
8597 }
8598 rv ^= e->ipfe_not;
8599
8600 if (rv == 0)
8601 break;
8602 }
8603
8604 return rv;
8605 }
8606
8607
8608 /* ------------------------------------------------------------------------ */
8609 /* Function: ipf_queueflush */
8610 /* Returns: int - number of entries flushed (0 = none) */
8611 /* Parameters: softc(I) - pointer to soft context main structure */
8612 /* deletefn(I) - function to call to delete entry */
8613 /* ipfqs(I) - top of the list of ipf internal queues */
8614 /* userqs(I) - top of the list of user defined timeouts */
8615 /* */
8616 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8617 /* need to try a bit harder to free up some space. The algorithm used here */
8618 /* split into two parts but both halves have the same goal: to reduce the */
8619 /* number of connections considered to be "active" to the low watermark. */
8620 /* There are two steps in doing this: */
8621 /* 1) Remove any TCP connections that are already considered to be "closed" */
8622 /* but have not yet been removed from the state table. The two states */
8623 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8624 /* candidates for this style of removal. If freeing up entries in */
8625 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8626 /* we do not go on to step 2. */
8627 /* */
8628 /* 2) Look for the oldest entries on each timeout queue and free them if */
8629 /* they are within the given window we are considering. Where the */
8630 /* window starts and the steps taken to increase its size depend upon */
8631 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8632 /* last 30 seconds is not touched. */
8633 /* touched */
8634 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8635 /* | | | | | | */
8636 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8637 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8638 /* */
8639 /* Points to note: */
8640 /* - tqe_die is the time, in the future, when entries die. */
8641 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8642 /* ticks. */
8643 /* - tqe_touched is when the entry was last used by NAT/state */
8644 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8645 /* ipf_ticks any given timeout queue and vice versa. */
8646 /* - both tqe_die and tqe_touched increase over time */
8647 /* - timeout queues are sorted with the highest value of tqe_die at the */
8648 /* bottom and therefore the smallest values of each are at the top */
8649 /* - the pointer passed in as ipfqs should point to an array of timeout */
8650 /* queues representing each of the TCP states */
8651 /* */
8652 /* We start by setting up a maximum range to scan for things to move of */
8653 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8654 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8655 /* we start again with a new value for "iend" and "istart". This is */
8656 /* continued until we either finish the scan of 30 second intervals or the */
8657 /* low water mark is reached. */
8658 /* ------------------------------------------------------------------------ */
8659 int
8660 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8661 ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8662 {
8663 u_long interval, istart, iend;
8664 ipftq_t *ifq, *ifqnext;
8665 ipftqent_t *tqe, *tqn;
8666 int removed = 0;
8667
8668 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8669 tqn = tqe->tqe_next;
8670 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8671 removed++;
8672 }
8673 if ((*activep * 100 / size) > low) {
8674 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8675 ((tqe = tqn) != NULL); ) {
8676 tqn = tqe->tqe_next;
8677 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8678 removed++;
8679 }
8680 }
8681
8682 if ((*activep * 100 / size) <= low) {
8683 return removed;
8684 }
8685
8686 /*
8687 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8688 * used then the operations are upgraded to floating point
8689 * and kernels don't like floating point...
8690 */
8691 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8692 istart = IPF_TTLVAL(86400 * 4);
8693 interval = IPF_TTLVAL(43200);
8694 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8695 istart = IPF_TTLVAL(43200);
8696 interval = IPF_TTLVAL(1800);
8697 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8698 istart = IPF_TTLVAL(1800);
8699 interval = IPF_TTLVAL(30);
8700 } else {
8701 return 0;
8702 }
8703 if (istart > softc->ipf_ticks) {
8704 if (softc->ipf_ticks - interval < interval)
8705 istart = interval;
8706 else
8707 istart = (softc->ipf_ticks / interval) * interval;
8708 }
8709
8710 iend = softc->ipf_ticks - interval;
8711
8712 while ((*activep * 100 / size) > low) {
8713 u_long try;
8714
8715 try = softc->ipf_ticks - istart;
8716
8717 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8718 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8719 if (try < tqe->tqe_touched)
8720 break;
8721 tqn = tqe->tqe_next;
8722 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8723 removed++;
8724 }
8725 }
8726
8727 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8728 ifqnext = ifq->ifq_next;
8729
8730 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8731 if (try < tqe->tqe_touched)
8732 break;
8733 tqn = tqe->tqe_next;
8734 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8735 removed++;
8736 }
8737 }
8738
8739 if (try >= iend) {
8740 if (interval == IPF_TTLVAL(43200)) {
8741 interval = IPF_TTLVAL(1800);
8742 } else if (interval == IPF_TTLVAL(1800)) {
8743 interval = IPF_TTLVAL(30);
8744 } else {
8745 break;
8746 }
8747 if (interval >= softc->ipf_ticks)
8748 break;
8749
8750 iend = softc->ipf_ticks - interval;
8751 }
8752 istart -= interval;
8753 }
8754
8755 return removed;
8756 }
8757
8758
8759 /* ------------------------------------------------------------------------ */
8760 /* Function: ipf_deliverlocal */
8761 /* Returns: int - 1 = local address, 0 = non-local address */
8762 /* Parameters: softc(I) - pointer to soft context main structure */
8763 /* ipversion(I) - IP protocol version (4 or 6) */
8764 /* ifp(I) - network interface pointer */
8765 /* ipaddr(I) - IPv4/6 destination address */
8766 /* */
8767 /* This fucntion is used to determine in the address "ipaddr" belongs to */
8768 /* the network interface represented by ifp. */
8769 /* ------------------------------------------------------------------------ */
8770 int
8771 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8772 i6addr_t *ipaddr)
8773 {
8774 i6addr_t addr;
8775 int islocal = 0;
8776
8777 if (ipversion == 4) {
8778 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8779 if (addr.in4.s_addr == ipaddr->in4.s_addr)
8780 islocal = 1;
8781 }
8782
8783 #ifdef USE_INET6
8784 } else if (ipversion == 6) {
8785 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8786 if (IP6_EQ(&addr, ipaddr))
8787 islocal = 1;
8788 }
8789 #endif
8790 }
8791
8792 return islocal;
8793 }
8794
8795
8796 /* ------------------------------------------------------------------------ */
8797 /* Function: ipf_settimeout */
8798 /* Returns: int - 0 = success, -1 = failure */
8799 /* Parameters: softc(I) - pointer to soft context main structure */
8800 /* t(I) - pointer to tuneable array entry */
8801 /* p(I) - pointer to values passed in to apply */
8802 /* */
8803 /* This function is called to set the timeout values for each distinct */
8804 /* queue timeout that is available. When called, it calls into both the */
8805 /* state and NAT code, telling them to update their timeout queues. */
8806 /* ------------------------------------------------------------------------ */
8807 static int
8808 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8809 ipftuneval_t *p)
8810 {
8811
8812 /*
8813 * ipf_interror should be set by the functions called here, not
8814 * by this function - it's just a middle man.
8815 */
8816 if (ipf_state_settimeout(softc, t, p) == -1)
8817 return -1;
8818 if (ipf_nat_settimeout(softc, t, p) == -1)
8819 return -1;
8820 return 0;
8821 }
8822
8823
8824 /* ------------------------------------------------------------------------ */
8825 /* Function: ipf_apply_timeout */
8826 /* Returns: int - 0 = success, -1 = failure */
8827 /* Parameters: head(I) - pointer to tuneable array entry */
8828 /* seconds(I) - pointer to values passed in to apply */
8829 /* */
8830 /* This function applies a timeout of "seconds" to the timeout queue that */
8831 /* is pointed to by "head". All entries on this list have an expiration */
8832 /* set to be the current tick value of ipf plus the ttl. Given that this */
8833 /* function should only be called when the delta is non-zero, the task is */
8834 /* to walk the entire list and apply the change. The sort order will not */
8835 /* change. The only catch is that this is O(n) across the list, so if the */
8836 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
8837 /* could take a relatively long time to work through them all. */
8838 /* ------------------------------------------------------------------------ */
8839 void
8840 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8841 {
8842 u_int oldtimeout, newtimeout;
8843 ipftqent_t *tqe;
8844 int delta;
8845
8846 MUTEX_ENTER(&head->ifq_lock);
8847 oldtimeout = head->ifq_ttl;
8848 newtimeout = IPF_TTLVAL(seconds);
8849 delta = oldtimeout - newtimeout;
8850
8851 head->ifq_ttl = newtimeout;
8852
8853 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8854 tqe->tqe_die += delta;
8855 }
8856 MUTEX_EXIT(&head->ifq_lock);
8857 }
8858
8859
8860 /* ------------------------------------------------------------------------ */
8861 /* Function: ipf_settimeout_tcp */
8862 /* Returns: int - 0 = successfully applied, -1 = failed */
8863 /* Parameters: t(I) - pointer to tuneable to change */
8864 /* p(I) - pointer to new timeout information */
8865 /* tab(I) - pointer to table of TCP queues */
8866 /* */
8867 /* This function applies the new timeout (p) to the TCP tunable (t) and */
8868 /* updates all of the entries on the relevant timeout queue by calling */
8869 /* ipf_apply_timeout(). */
8870 /* ------------------------------------------------------------------------ */
8871 int
8872 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8873 {
8874 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8875 !strcmp(t->ipft_name, "tcp_established")) {
8876 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8877 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8878 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8879 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8880 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8881 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8882 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8883 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8884 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8885 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
8886 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8887 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8888 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8889 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
8890 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8891 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8892 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8893 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
8894 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
8895 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
8896 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8897 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
8898 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
8899 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
8900 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
8901 } else {
8902 /*
8903 * ipf_interror isn't set here because it should be set
8904 * by whatever called this function.
8905 */
8906 return -1;
8907 }
8908 return 0;
8909 }
8910
8911
8912 /* ------------------------------------------------------------------------ */
8913 /* Function: ipf_main_soft_create */
8914 /* Returns: NULL = failure, else success */
8915 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
8916 /* */
8917 /* Create the foundation soft context structure. In circumstances where it */
8918 /* is not required to dynamically allocate the context, a pointer can be */
8919 /* passed in (rather than NULL) to a structure to be initialised. */
8920 /* The main thing of interest is that a number of locks are initialised */
8921 /* here instead of in the where might be expected - in the relevant create */
8922 /* function elsewhere. This is done because the current locking design has */
8923 /* some areas where these locks are used outside of their module. */
8924 /* Possibly the most important exercise that is done here is setting of all */
8925 /* the timeout values, allowing them to be changed before init(). */
8926 /* ------------------------------------------------------------------------ */
8927 void *
8928 ipf_main_soft_create(void *arg)
8929 {
8930 ipf_main_softc_t *softc;
8931
8932 if (arg == NULL) {
8933 KMALLOC(softc, ipf_main_softc_t *);
8934 if (softc == NULL)
8935 return NULL;
8936 } else {
8937 softc = arg;
8938 }
8939
8940 bzero((char *)softc, sizeof(*softc));
8941
8942 /*
8943 * This serves as a flag as to whether or not the softc should be
8944 * free'd when _destroy is called.
8945 */
8946 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
8947
8948 softc->ipf_tuners = ipf_tune_array_copy(softc,
8949 sizeof(ipf_main_tuneables),
8950 ipf_main_tuneables);
8951 if (softc->ipf_tuners == NULL) {
8952 ipf_main_soft_destroy(softc);
8953 return NULL;
8954 }
8955
8956 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
8957 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
8958 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
8959 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
8960 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
8961 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
8962 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
8963 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
8964 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
8965
8966 softc->ipf_token_head = NULL;
8967 softc->ipf_token_tail = &softc->ipf_token_head;
8968
8969 softc->ipf_tcpidletimeout = FIVE_DAYS;
8970 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
8971 softc->ipf_tcplastack = IPF_TTLVAL(30);
8972 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
8973 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
8974 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
8975 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
8976 softc->ipf_tcpclosed = IPF_TTLVAL(30);
8977 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
8978 softc->ipf_udptimeout = IPF_TTLVAL(120);
8979 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
8980 softc->ipf_icmptimeout = IPF_TTLVAL(60);
8981 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
8982 softc->ipf_iptimeout = IPF_TTLVAL(60);
8983
8984 #if defined(IPFILTER_DEFAULT_BLOCK)
8985 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
8986 #else
8987 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
8988 #endif
8989 softc->ipf_minttl = 4;
8990 softc->ipf_icmpminfragmtu = 68;
8991 softc->ipf_flags = IPF_LOGGING;
8992
8993 return softc;
8994 }
8995
8996 /* ------------------------------------------------------------------------ */
8997 /* Function: ipf_main_soft_init */
8998 /* Returns: 0 = success, -1 = failure */
8999 /* Parameters: softc(I) - pointer to soft context main structure */
9000 /* */
9001 /* A null-op function that exists as a placeholder so that the flow in */
9002 /* other functions is obvious. */
9003 /* ------------------------------------------------------------------------ */
9004 /*ARGSUSED*/
9005 int
9006 ipf_main_soft_init(ipf_main_softc_t *softc)
9007 {
9008 return 0;
9009 }
9010
9011
9012 /* ------------------------------------------------------------------------ */
9013 /* Function: ipf_main_soft_destroy */
9014 /* Returns: void */
9015 /* Parameters: softc(I) - pointer to soft context main structure */
9016 /* */
9017 /* Undo everything that we did in ipf_main_soft_create. */
9018 /* */
9019 /* The most important check that needs to be made here is whether or not */
9020 /* the structure was allocated by ipf_main_soft_create() by checking what */
9021 /* value is stored in ipf_dynamic_main. */
9022 /* ------------------------------------------------------------------------ */
9023 /*ARGSUSED*/
9024 void
9025 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9026 {
9027
9028 RW_DESTROY(&softc->ipf_frag);
9029 RW_DESTROY(&softc->ipf_poolrw);
9030 RW_DESTROY(&softc->ipf_nat);
9031 RW_DESTROY(&softc->ipf_state);
9032 RW_DESTROY(&softc->ipf_tokens);
9033 RW_DESTROY(&softc->ipf_mutex);
9034 RW_DESTROY(&softc->ipf_global);
9035 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9036 MUTEX_DESTROY(&softc->ipf_rw);
9037
9038 if (softc->ipf_tuners != NULL) {
9039 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9040 }
9041 if (softc->ipf_dynamic_softc == 1) {
9042 KFREE(softc);
9043 }
9044 }
9045
9046
9047 /* ------------------------------------------------------------------------ */
9048 /* Function: ipf_main_soft_fini */
9049 /* Returns: 0 = success, -1 = failure */
9050 /* Parameters: softc(I) - pointer to soft context main structure */
9051 /* */
9052 /* Clean out the rules which have been added since _init was last called, */
9053 /* the only dynamic part of the mainline. */
9054 /* ------------------------------------------------------------------------ */
9055 int
9056 ipf_main_soft_fini(ipf_main_softc_t *softc)
9057 {
9058 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9059 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9060 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9061 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9062
9063 return 0;
9064 }
9065
9066
9067 /* ------------------------------------------------------------------------ */
9068 /* Function: ipf_main_load */
9069 /* Returns: 0 = success, -1 = failure */
9070 /* Parameters: none */
9071 /* */
9072 /* Handle global initialisation that needs to be done for the base part of */
9073 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9074 /* arrays that get used by the state/NAT code. */
9075 /* ------------------------------------------------------------------------ */
9076 int
9077 ipf_main_load(void)
9078 {
9079 int i;
9080
9081 /* fill icmp reply type table */
9082 for (i = 0; i <= ICMP_MAXTYPE; i++)
9083 icmpreplytype4[i] = -1;
9084 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9085 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9086 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9087 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9088
9089 #ifdef USE_INET6
9090 /* fill icmp reply type table */
9091 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9092 icmpreplytype6[i] = -1;
9093 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9094 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9095 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9096 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9097 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9098 #endif
9099
9100 return 0;
9101 }
9102
9103
9104 /* ------------------------------------------------------------------------ */
9105 /* Function: ipf_main_unload */
9106 /* Returns: 0 = success, -1 = failure */
9107 /* Parameters: none */
9108 /* */
9109 /* A null-op function that exists as a placeholder so that the flow in */
9110 /* other functions is obvious. */
9111 /* ------------------------------------------------------------------------ */
9112 int
9113 ipf_main_unload(void)
9114 {
9115 return 0;
9116 }
9117
9118
9119 /* ------------------------------------------------------------------------ */
9120 /* Function: ipf_load_all */
9121 /* Returns: 0 = success, -1 = failure */
9122 /* Parameters: none */
9123 /* */
9124 /* Work through all of the subsystems inside IPFilter and call the load */
9125 /* function for each in an order that won't lead to a crash :) */
9126 /* ------------------------------------------------------------------------ */
9127 int
9128 ipf_load_all(void)
9129 {
9130 if (ipf_main_load() == -1)
9131 return -1;
9132
9133 if (ipf_state_main_load() == -1)
9134 return -1;
9135
9136 if (ipf_nat_main_load() == -1)
9137 return -1;
9138
9139 if (ipf_frag_main_load() == -1)
9140 return -1;
9141
9142 if (ipf_auth_main_load() == -1)
9143 return -1;
9144
9145 if (ipf_proxy_main_load() == -1)
9146 return -1;
9147
9148 return 0;
9149 }
9150
9151
9152 /* ------------------------------------------------------------------------ */
9153 /* Function: ipf_unload_all */
9154 /* Returns: 0 = success, -1 = failure */
9155 /* Parameters: none */
9156 /* */
9157 /* Work through all of the subsystems inside IPFilter and call the unload */
9158 /* function for each in an order that won't lead to a crash :) */
9159 /* ------------------------------------------------------------------------ */
9160 int
9161 ipf_unload_all(void)
9162 {
9163 if (ipf_proxy_main_unload() == -1)
9164 return -1;
9165
9166 if (ipf_auth_main_unload() == -1)
9167 return -1;
9168
9169 if (ipf_frag_main_unload() == -1)
9170 return -1;
9171
9172 if (ipf_nat_main_unload() == -1)
9173 return -1;
9174
9175 if (ipf_state_main_unload() == -1)
9176 return -1;
9177
9178 if (ipf_main_unload() == -1)
9179 return -1;
9180
9181 return 0;
9182 }
9183
9184
9185 /* ------------------------------------------------------------------------ */
9186 /* Function: ipf_create_all */
9187 /* Returns: NULL = failure, else success */
9188 /* Parameters: arg(I) - pointer to soft context main structure */
9189 /* */
9190 /* Work through all of the subsystems inside IPFilter and call the create */
9191 /* function for each in an order that won't lead to a crash :) */
9192 /* ------------------------------------------------------------------------ */
9193 ipf_main_softc_t *
9194 ipf_create_all(void *arg)
9195 {
9196 ipf_main_softc_t *softc;
9197
9198 softc = ipf_main_soft_create(arg);
9199 if (softc == NULL)
9200 return NULL;
9201
9202 #ifdef IPFILTER_LOG
9203 softc->ipf_log_soft = ipf_log_soft_create(softc);
9204 if (softc->ipf_log_soft == NULL) {
9205 ipf_destroy_all(softc);
9206 return NULL;
9207 }
9208 #endif
9209
9210 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9211 if (softc->ipf_lookup_soft == NULL) {
9212 ipf_destroy_all(softc);
9213 return NULL;
9214 }
9215
9216 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9217 if (softc->ipf_sync_soft == NULL) {
9218 ipf_destroy_all(softc);
9219 return NULL;
9220 }
9221
9222 softc->ipf_state_soft = ipf_state_soft_create(softc);
9223 if (softc->ipf_state_soft == NULL) {
9224 ipf_destroy_all(softc);
9225 return NULL;
9226 }
9227
9228 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9229 if (softc->ipf_nat_soft == NULL) {
9230 ipf_destroy_all(softc);
9231 return NULL;
9232 }
9233
9234 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9235 if (softc->ipf_frag_soft == NULL) {
9236 ipf_destroy_all(softc);
9237 return NULL;
9238 }
9239
9240 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9241 if (softc->ipf_auth_soft == NULL) {
9242 ipf_destroy_all(softc);
9243 return NULL;
9244 }
9245
9246 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9247 if (softc->ipf_proxy_soft == NULL) {
9248 ipf_destroy_all(softc);
9249 return NULL;
9250 }
9251
9252 return softc;
9253 }
9254
9255
9256 /* ------------------------------------------------------------------------ */
9257 /* Function: ipf_destroy_all */
9258 /* Returns: void */
9259 /* Parameters: softc(I) - pointer to soft context main structure */
9260 /* */
9261 /* Work through all of the subsystems inside IPFilter and call the destroy */
9262 /* function for each in an order that won't lead to a crash :) */
9263 /* */
9264 /* Every one of these functions is expected to succeed, so there is no */
9265 /* checking of return values. */
9266 /* ------------------------------------------------------------------------ */
9267 void
9268 ipf_destroy_all(ipf_main_softc_t *softc)
9269 {
9270
9271 if (softc->ipf_state_soft != NULL) {
9272 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9273 softc->ipf_state_soft = NULL;
9274 }
9275
9276 if (softc->ipf_nat_soft != NULL) {
9277 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9278 softc->ipf_nat_soft = NULL;
9279 }
9280
9281 if (softc->ipf_frag_soft != NULL) {
9282 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9283 softc->ipf_frag_soft = NULL;
9284 }
9285
9286 if (softc->ipf_auth_soft != NULL) {
9287 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9288 softc->ipf_auth_soft = NULL;
9289 }
9290
9291 if (softc->ipf_proxy_soft != NULL) {
9292 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9293 softc->ipf_proxy_soft = NULL;
9294 }
9295
9296 if (softc->ipf_sync_soft != NULL) {
9297 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9298 softc->ipf_sync_soft = NULL;
9299 }
9300
9301 if (softc->ipf_lookup_soft != NULL) {
9302 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9303 softc->ipf_lookup_soft = NULL;
9304 }
9305
9306 #ifdef IPFILTER_LOG
9307 if (softc->ipf_log_soft != NULL) {
9308 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9309 softc->ipf_log_soft = NULL;
9310 }
9311 #endif
9312
9313 ipf_main_soft_destroy(softc);
9314 }
9315
9316
9317 /* ------------------------------------------------------------------------ */
9318 /* Function: ipf_init_all */
9319 /* Returns: 0 = success, -1 = failure */
9320 /* Parameters: softc(I) - pointer to soft context main structure */
9321 /* */
9322 /* Work through all of the subsystems inside IPFilter and call the init */
9323 /* function for each in an order that won't lead to a crash :) */
9324 /* ------------------------------------------------------------------------ */
9325 int
9326 ipf_init_all(ipf_main_softc_t *softc)
9327 {
9328
9329 if (ipf_main_soft_init(softc) == -1)
9330 return -1;
9331
9332 #ifdef IPFILTER_LOG
9333 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9334 return -1;
9335 #endif
9336
9337 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9338 return -1;
9339
9340 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9341 return -1;
9342
9343 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9344 return -1;
9345
9346 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9347 return -1;
9348
9349 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9350 return -1;
9351
9352 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9353 return -1;
9354
9355 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9356 return -1;
9357
9358 return 0;
9359 }
9360
9361
9362 /* ------------------------------------------------------------------------ */
9363 /* Function: ipf_fini_all */
9364 /* Returns: 0 = success, -1 = failure */
9365 /* Parameters: softc(I) - pointer to soft context main structure */
9366 /* */
9367 /* Work through all of the subsystems inside IPFilter and call the fini */
9368 /* function for each in an order that won't lead to a crash :) */
9369 /* ------------------------------------------------------------------------ */
9370 int
9371 ipf_fini_all(ipf_main_softc_t *softc)
9372 {
9373
9374 ipf_token_flush(softc);
9375
9376 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9377 return -1;
9378
9379 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9380 return -1;
9381
9382 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9383 return -1;
9384
9385 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9386 return -1;
9387
9388 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9389 return -1;
9390
9391 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9392 return -1;
9393
9394 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9395 return -1;
9396
9397 #ifdef IPFILTER_LOG
9398 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9399 return -1;
9400 #endif
9401
9402 if (ipf_main_soft_fini(softc) == -1)
9403 return -1;
9404
9405 return 0;
9406 }
9407
9408
9409 /* ------------------------------------------------------------------------ */
9410 /* Function: ipf_rule_expire */
9411 /* Returns: Nil */
9412 /* Parameters: softc(I) - pointer to soft context main structure */
9413 /* */
9414 /* At present this function exists just to support temporary addition of */
9415 /* firewall rules. Both inactive and active lists are scanned for items to */
9416 /* purge, as by rights, the expiration is computed as soon as the rule is */
9417 /* loaded in. */
9418 /* ------------------------------------------------------------------------ */
9419 void
9420 ipf_rule_expire(ipf_main_softc_t *softc)
9421 {
9422 frentry_t *fr;
9423
9424 if ((softc->ipf_rule_explist[0] == NULL) &&
9425 (softc->ipf_rule_explist[1] == NULL))
9426 return;
9427
9428 WRITE_ENTER(&softc->ipf_mutex);
9429
9430 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9431 /*
9432 * Because the list is kept sorted on insertion, the fist
9433 * one that dies in the future means no more work to do.
9434 */
9435 if (fr->fr_die > softc->ipf_ticks)
9436 break;
9437 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9438 }
9439
9440 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9441 /*
9442 * Because the list is kept sorted on insertion, the fist
9443 * one that dies in the future means no more work to do.
9444 */
9445 if (fr->fr_die > softc->ipf_ticks)
9446 break;
9447 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9448 }
9449
9450 RWLOCK_EXIT(&softc->ipf_mutex);
9451 }
9452
9453
9454 static int ipf_ht_node_cmp(const struct host_node_s *, const struct host_node_s *);
9455 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9456 i6addr_t *);
9457
9458 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9459
9460
9461 /* ------------------------------------------------------------------------ */
9462 /* Function: ipf_ht_node_cmp */
9463 /* Returns: int - 0 == nodes are the same, .. */
9464 /* Parameters: k1(I) - pointer to first key to compare */
9465 /* k2(I) - pointer to second key to compare */
9466 /* */
9467 /* The "key" for the node is a combination of two fields: the address */
9468 /* family and the address itself. */
9469 /* */
9470 /* Because we're not actually interpreting the address data, it isn't */
9471 /* necessary to convert them to/from network/host byte order. The mask is */
9472 /* just used to remove bits that aren't significant - it doesn't matter */
9473 /* where they are, as long as they're always in the same place. */
9474 /* */
9475 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9476 /* this is where individual ones will differ the most - but not true for */
9477 /* for /48's, etc. */
9478 /* ------------------------------------------------------------------------ */
9479 static int
9480 ipf_ht_node_cmp(const struct host_node_s *k1, const struct host_node_s *k2)
9481 {
9482 int i;
9483
9484 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9485 if (i != 0)
9486 return i;
9487
9488 if (k1->hn_addr.adf_family == AF_INET)
9489 return (k2->hn_addr.adf_addr.in4.s_addr -
9490 k1->hn_addr.adf_addr.in4.s_addr);
9491
9492 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9493 if (i != 0)
9494 return i;
9495 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9496 if (i != 0)
9497 return i;
9498 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9499 if (i != 0)
9500 return i;
9501 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9502 return i;
9503 }
9504
9505
9506 /* ------------------------------------------------------------------------ */
9507 /* Function: ipf_ht_node_make_key */
9508 /* Returns: Nil */
9509 /* parameters: htp(I) - pointer to address tracking structure */
9510 /* key(I) - where to store masked address for lookup */
9511 /* family(I) - protocol family of address */
9512 /* addr(I) - pointer to network address */
9513 /* */
9514 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9515 /* copy the address passed in into the key structure whilst masking out the */
9516 /* bits that we don't want. */
9517 /* */
9518 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9519 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9520 /* have to be wary of that and not allow 32-128 to happen. */
9521 /* ------------------------------------------------------------------------ */
9522 static void
9523 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9524 i6addr_t *addr)
9525 {
9526 key->hn_addr.adf_family = family;
9527 if (family == AF_INET) {
9528 u_32_t mask;
9529 int bits;
9530
9531 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9532 bits = htp->ht_netmask;
9533 if (bits >= 32) {
9534 mask = 0xffffffff;
9535 } else {
9536 mask = htonl(0xffffffff << (32 - bits));
9537 }
9538 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9539 #ifdef USE_INET6
9540 } else {
9541 int bits = htp->ht_netmask;
9542
9543 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9544 if (bits > 96) {
9545 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9546 htonl(0xffffffff << (128 - bits));
9547 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9548 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9549 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9550 } else if (bits > 64) {
9551 key->hn_addr.adf_addr.i6[3] = 0;
9552 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9553 htonl(0xffffffff << (96 - bits));
9554 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9555 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9556 } else if (bits > 32) {
9557 key->hn_addr.adf_addr.i6[3] = 0;
9558 key->hn_addr.adf_addr.i6[2] = 0;
9559 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9560 htonl(0xffffffff << (64 - bits));
9561 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9562 } else {
9563 key->hn_addr.adf_addr.i6[3] = 0;
9564 key->hn_addr.adf_addr.i6[2] = 0;
9565 key->hn_addr.adf_addr.i6[1] = 0;
9566 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9567 htonl(0xffffffff << (32 - bits));
9568 }
9569 #endif
9570 }
9571 }
9572
9573
9574 /* ------------------------------------------------------------------------ */
9575 /* Function: ipf_ht_node_add */
9576 /* Returns: int - 0 == success, -1 == failure */
9577 /* Parameters: softc(I) - pointer to soft context main structure */
9578 /* htp(I) - pointer to address tracking structure */
9579 /* family(I) - protocol family of address */
9580 /* addr(I) - pointer to network address */
9581 /* */
9582 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9583 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9584 /* */
9585 /* After preparing the key with the address information to find, look in */
9586 /* the red-black tree to see if the address is known. A successful call to */
9587 /* this function can mean one of two things: a new node was added to the */
9588 /* tree or a matching node exists and we're able to bump up its activity. */
9589 /* ------------------------------------------------------------------------ */
9590 int
9591 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9592 i6addr_t *addr)
9593 {
9594 host_node_t *h;
9595 host_node_t k;
9596
9597 ipf_ht_node_make_key(htp, &k, family, addr);
9598
9599 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9600 if (h == NULL) {
9601 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9602 return -1;
9603 KMALLOC(h, host_node_t *);
9604 if (h == NULL) {
9605 DT(ipf_rb_no_mem);
9606 LBUMP(ipf_rb_no_mem);
9607 return -1;
9608 }
9609
9610 /*
9611 * If there was a macro to initialise the RB node then that
9612 * would get used here, but there isn't...
9613 */
9614 bzero((char *)h, sizeof(*h));
9615 h->hn_addr = k.hn_addr;
9616 h->hn_addr.adf_family = k.hn_addr.adf_family;
9617 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9618 htp->ht_cur_nodes++;
9619 } else {
9620 if ((htp->ht_max_per_node != 0) &&
9621 (h->hn_active >= htp->ht_max_per_node)) {
9622 DT(ipf_rb_node_max);
9623 LBUMP(ipf_rb_node_max);
9624 return -1;
9625 }
9626 }
9627
9628 h->hn_active++;
9629
9630 return 0;
9631 }
9632
9633
9634 /* ------------------------------------------------------------------------ */
9635 /* Function: ipf_ht_node_del */
9636 /* Returns: int - 0 == success, -1 == failure */
9637 /* parameters: htp(I) - pointer to address tracking structure */
9638 /* family(I) - protocol family of address */
9639 /* addr(I) - pointer to network address */
9640 /* */
9641 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9642 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9643 /* */
9644 /* Try and find the address passed in amongst the leaves on this tree to */
9645 /* be friend. If found then drop the active account for that node drops by */
9646 /* one. If that count reaches 0, it is time to free it all up. */
9647 /* ------------------------------------------------------------------------ */
9648 int
9649 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9650 {
9651 host_node_t *h;
9652 host_node_t k;
9653
9654 ipf_ht_node_make_key(htp, &k, family, addr);
9655
9656 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9657 if (h == NULL) {
9658 return -1;
9659 } else {
9660 h->hn_active--;
9661 if (h->hn_active == 0) {
9662 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9663 htp->ht_cur_nodes--;
9664 KFREE(h);
9665 }
9666 }
9667
9668 return 0;
9669 }
9670
9671
9672 /* ------------------------------------------------------------------------ */
9673 /* Function: ipf_rb_ht_init */
9674 /* Returns: Nil */
9675 /* Parameters: head(I) - pointer to host tracking structure */
9676 /* */
9677 /* Initialise the host tracking structure to be ready for use above. */
9678 /* ------------------------------------------------------------------------ */
9679 void
9680 ipf_rb_ht_init(host_track_t *head)
9681 {
9682 memset(head, 0, sizeof(*head));
9683 RBI_INIT(ipf_rb, &head->ht_root);
9684 }
9685
9686
9687 /* ------------------------------------------------------------------------ */
9688 /* Function: ipf_rb_ht_freenode */
9689 /* Returns: Nil */
9690 /* Parameters: head(I) - pointer to host tracking structure */
9691 /* arg(I) - additional argument from walk caller */
9692 /* */
9693 /* Free an actual host_node_t structure. */
9694 /* ------------------------------------------------------------------------ */
9695 void
9696 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9697 {
9698 KFREE(node);
9699 }
9700
9701
9702 /* ------------------------------------------------------------------------ */
9703 /* Function: ipf_rb_ht_flush */
9704 /* Returns: Nil */
9705 /* Parameters: head(I) - pointer to host tracking structure */
9706 /* */
9707 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
9708 /* and free'ing each one. */
9709 /* ------------------------------------------------------------------------ */
9710 void
9711 ipf_rb_ht_flush(host_track_t *head)
9712 {
9713 /* XXX - May use node members after freeing the node. */
9714 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9715 }
9716
9717
9718 /* ------------------------------------------------------------------------ */
9719 /* Function: ipf_slowtimer */
9720 /* Returns: Nil */
9721 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
9722 /* */
9723 /* Slowly expire held state for fragments. Timeouts are set * in */
9724 /* expectation of this being called twice per second. */
9725 /* ------------------------------------------------------------------------ */
9726 void
9727 ipf_slowtimer(ipf_main_softc_t *softc)
9728 {
9729
9730 ipf_token_expire(softc);
9731 ipf_frag_expire(softc);
9732 ipf_state_expire(softc);
9733 ipf_nat_expire(softc);
9734 ipf_auth_expire(softc);
9735 ipf_lookup_expire(softc);
9736 ipf_rule_expire(softc);
9737 ipf_sync_expire(softc);
9738 softc->ipf_ticks++;
9739 # if defined(__OpenBSD__)
9740 timeout_add(&ipf_slowtimer_ch, hz/2);
9741 # endif
9742 }
9743
9744
9745 /* ------------------------------------------------------------------------ */
9746 /* Function: ipf_inet_mask_add */
9747 /* Returns: Nil */
9748 /* Parameters: bits(I) - pointer to nat context information */
9749 /* mtab(I) - pointer to mask hash table structure */
9750 /* */
9751 /* When called, bits represents the mask of a new NAT rule that has just */
9752 /* been added. This function inserts a bitmask into the array of masks to */
9753 /* search when searching for a matching NAT rule for a packet. */
9754 /* Prevention of duplicate masks is achieved by checking the use count for */
9755 /* a given netmask. */
9756 /* ------------------------------------------------------------------------ */
9757 void
9758 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9759 {
9760 u_32_t mask;
9761 int i, j;
9762
9763 mtab->imt4_masks[bits]++;
9764 if (mtab->imt4_masks[bits] > 1)
9765 return;
9766
9767 if (bits == 0)
9768 mask = 0;
9769 else
9770 mask = 0xffffffff << (32 - bits);
9771
9772 for (i = 0; i < 33; i++) {
9773 if (ntohl(mtab->imt4_active[i]) < mask) {
9774 for (j = 32; j > i; j--)
9775 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9776 mtab->imt4_active[i] = htonl(mask);
9777 break;
9778 }
9779 }
9780 mtab->imt4_max++;
9781 }
9782
9783
9784 /* ------------------------------------------------------------------------ */
9785 /* Function: ipf_inet_mask_del */
9786 /* Returns: Nil */
9787 /* Parameters: bits(I) - number of bits set in the netmask */
9788 /* mtab(I) - pointer to mask hash table structure */
9789 /* */
9790 /* Remove the 32bit bitmask represented by "bits" from the collection of */
9791 /* netmasks stored inside of mtab. */
9792 /* ------------------------------------------------------------------------ */
9793 void
9794 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9795 {
9796 u_32_t mask;
9797 int i, j;
9798
9799 mtab->imt4_masks[bits]--;
9800 if (mtab->imt4_masks[bits] > 0)
9801 return;
9802
9803 mask = htonl(0xffffffff << (32 - bits));
9804 for (i = 0; i < 33; i++) {
9805 if (mtab->imt4_active[i] == mask) {
9806 for (j = i + 1; j < 33; j++)
9807 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9808 break;
9809 }
9810 }
9811 mtab->imt4_max--;
9812 ASSERT(mtab->imt4_max >= 0);
9813 }
9814
9815
9816 #ifdef USE_INET6
9817 /* ------------------------------------------------------------------------ */
9818 /* Function: ipf_inet6_mask_add */
9819 /* Returns: Nil */
9820 /* Parameters: bits(I) - number of bits set in mask */
9821 /* mask(I) - pointer to mask to add */
9822 /* mtab(I) - pointer to mask hash table structure */
9823 /* */
9824 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
9825 /* has just been added. This function inserts a bitmask into the array of */
9826 /* masks to search when searching for a matching NAT rule for a packet. */
9827 /* Prevention of duplicate masks is achieved by checking the use count for */
9828 /* a given netmask. */
9829 /* ------------------------------------------------------------------------ */
9830 void
9831 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9832 {
9833 i6addr_t zero;
9834 int i, j;
9835
9836 mtab->imt6_masks[bits]++;
9837 if (mtab->imt6_masks[bits] > 1)
9838 return;
9839
9840 if (bits == 0) {
9841 mask = &zero;
9842 zero.i6[0] = 0;
9843 zero.i6[1] = 0;
9844 zero.i6[2] = 0;
9845 zero.i6[3] = 0;
9846 }
9847
9848 for (i = 0; i < 129; i++) {
9849 if (IP6_LT(&mtab->imt6_active[i], mask)) {
9850 for (j = 128; j > i; j--)
9851 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9852 mtab->imt6_active[i] = *mask;
9853 break;
9854 }
9855 }
9856 mtab->imt6_max++;
9857 }
9858
9859
9860 /* ------------------------------------------------------------------------ */
9861 /* Function: ipf_inet6_mask_del */
9862 /* Returns: Nil */
9863 /* Parameters: bits(I) - number of bits set in mask */
9864 /* mask(I) - pointer to mask to remove */
9865 /* mtab(I) - pointer to mask hash table structure */
9866 /* */
9867 /* Remove the 128bit bitmask represented by "bits" from the collection of */
9868 /* netmasks stored inside of mtab. */
9869 /* ------------------------------------------------------------------------ */
9870 void
9871 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9872 {
9873 i6addr_t zero;
9874 int i, j;
9875
9876 mtab->imt6_masks[bits]--;
9877 if (mtab->imt6_masks[bits] > 0)
9878 return;
9879
9880 if (bits == 0)
9881 mask = &zero;
9882 zero.i6[0] = 0;
9883 zero.i6[1] = 0;
9884 zero.i6[2] = 0;
9885 zero.i6[3] = 0;
9886
9887 for (i = 0; i < 129; i++) {
9888 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9889 for (j = i + 1; j < 129; j++) {
9890 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9891 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
9892 break;
9893 }
9894 break;
9895 }
9896 }
9897 mtab->imt6_max--;
9898 ASSERT(mtab->imt6_max >= 0);
9899 }
9900 #endif
9901