1
2 /*
3 * Copyright (C) 2012 by Darren Reed.
4 *
5 * See the IPFILTER.LICENCE file for details on licencing.
6 *
7 * Copyright 2008 Sun Microsystems.
8 *
9 * $Id$
10 *
11 */
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define KERNEL 1
16 # define _KERNEL 1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #if defined(_KERNEL) && defined(__FreeBSD__)
23 # if !defined(IPFILTER_LKM)
24 # include "opt_inet6.h"
25 # endif
26 # include <sys/filio.h>
27 #else
28 # include <sys/ioctl.h>
29 #endif
30 #if defined(__SVR4) || defined(sun) /* SOLARIS */
31 # include <sys/filio.h>
32 #endif
33 # include <sys/fcntl.h>
34 #if defined(_KERNEL)
35 # include <sys/systm.h>
36 # include <sys/file.h>
37 #else
38 # include <stdio.h>
39 # include <string.h>
40 # include <stdlib.h>
41 # include <stddef.h>
42 # include <sys/file.h>
43 # define _KERNEL
44 # include <sys/uio.h>
45 # undef _KERNEL
46 #endif
47 #if !defined(__SVR4)
48 # include <sys/mbuf.h>
49 #else
50 # include <sys/byteorder.h>
51 # if (SOLARIS2 < 5) && defined(sun)
52 # include <sys/dditypes.h>
53 # endif
54 #endif
55 # include <sys/protosw.h>
56 #include <sys/socket.h>
57 #include <net/if.h>
58 #ifdef sun
59 # include <net/af.h>
60 #endif
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/tcp.h>
65 # include <netinet/udp.h>
66 # include <netinet/ip_icmp.h>
67 #include "netinet/ip_compat.h"
68 #ifdef USE_INET6
69 # include <netinet/icmp6.h>
70 # if !SOLARIS && defined(_KERNEL)
71 # include <netinet6/in6_var.h>
72 # endif
73 #endif
74 #include "netinet/ip_fil.h"
75 #include "netinet/ip_nat.h"
76 #include "netinet/ip_frag.h"
77 #include "netinet/ip_state.h"
78 #include "netinet/ip_proxy.h"
79 #include "netinet/ip_auth.h"
80 #ifdef IPFILTER_SCAN
81 # include "netinet/ip_scan.h"
82 #endif
83 #include "netinet/ip_sync.h"
84 #include "netinet/ip_lookup.h"
85 #include "netinet/ip_pool.h"
86 #include "netinet/ip_htable.h"
87 #ifdef IPFILTER_COMPILED
88 # include "netinet/ip_rules.h"
89 #endif
90 #if defined(IPFILTER_BPF) && defined(_KERNEL)
91 # include <net/bpf.h>
92 #endif
93 #if defined(__FreeBSD__)
94 # include <sys/malloc.h>
95 #endif
96 #include "netinet/ipl.h"
97
98 #if defined(__NetBSD__) && (__NetBSD_Version__ >= 104230000)
99 # include <sys/callout.h>
100 extern struct callout ipf_slowtimer_ch;
101 #endif
102 /* END OF INCLUDES */
103
104
105 #ifndef _KERNEL
106 # include "ipf.h"
107 # include "ipt.h"
108 extern int opts;
109 extern int blockreason;
110 #endif /* _KERNEL */
111
112 #define FASTROUTE_RECURSION
113
114 #define LBUMP(x) softc->x++
115 #define LBUMPD(x, y) do { softc->x.y++; DT(y); } while (0)
116
117 static inline int ipf_check_ipf(fr_info_t *, frentry_t *, int);
118 static u_32_t ipf_checkcipso(fr_info_t *, u_char *, int);
119 static u_32_t ipf_checkripso(u_char *);
120 static u_32_t ipf_decaps(fr_info_t *, u_32_t, int);
121 #ifdef IPFILTER_LOG
122 static frentry_t *ipf_dolog(fr_info_t *, u_32_t *);
123 #endif
124 static int ipf_flushlist(ipf_main_softc_t *, int *, frentry_t **);
125 static int ipf_flush_groups(ipf_main_softc_t *, frgroup_t **,
126 int);
127 static ipfunc_t ipf_findfunc(ipfunc_t);
128 static void *ipf_findlookup(ipf_main_softc_t *, int, frentry_t *,
129 i6addr_t *, i6addr_t *);
130 static frentry_t *ipf_firewall(fr_info_t *, u_32_t *);
131 static int ipf_fr_matcharray(fr_info_t *, int *);
132 static int ipf_frruleiter(ipf_main_softc_t *, void *, int,
133 void *);
134 static void ipf_funcfini(ipf_main_softc_t *, frentry_t *);
135 static int ipf_funcinit(ipf_main_softc_t *, frentry_t *);
136 static int ipf_geniter(ipf_main_softc_t *, ipftoken_t *,
137 ipfgeniter_t *);
138 static void ipf_getstat(ipf_main_softc_t *,
139 struct friostat *, int);
140 static int ipf_group_flush(ipf_main_softc_t *, frgroup_t *);
141 static void ipf_group_free(frgroup_t *);
142 static int ipf_grpmapfini(struct ipf_main_softc_s *,
143 frentry_t *);
144 static int ipf_grpmapinit(struct ipf_main_softc_s *,
145 frentry_t *);
146 static frentry_t *ipf_nextrule(ipf_main_softc_t *, int, int,
147 frentry_t *, int);
148 static int ipf_portcheck(frpcmp_t *, u_32_t);
149 static inline int ipf_pr_ah(fr_info_t *);
150 static inline void ipf_pr_esp(fr_info_t *);
151 static inline void ipf_pr_gre(fr_info_t *);
152 static inline void ipf_pr_udp(fr_info_t *);
153 static inline void ipf_pr_tcp(fr_info_t *);
154 static inline void ipf_pr_icmp(fr_info_t *);
155 static inline void ipf_pr_ipv4hdr(fr_info_t *);
156 static inline void ipf_pr_short(fr_info_t *, int);
157 static inline int ipf_pr_tcpcommon(fr_info_t *);
158 static inline int ipf_pr_udpcommon(fr_info_t *);
159 static void ipf_rule_delete(ipf_main_softc_t *, frentry_t *f,
160 int, int);
161 static void ipf_rule_expire_insert(ipf_main_softc_t *,
162 frentry_t *, int);
163 static int ipf_synclist(ipf_main_softc_t *, frentry_t *,
164 void *);
165 static void ipf_token_flush(ipf_main_softc_t *);
166 static void ipf_token_unlink(ipf_main_softc_t *,
167 ipftoken_t *);
168 static ipftuneable_t *ipf_tune_findbyname(ipftuneable_t *,
169 const char *);
170 static ipftuneable_t *ipf_tune_findbycookie(ipftuneable_t **, void *,
171 void **);
172 static int ipf_updateipid(fr_info_t *);
173 static int ipf_settimeout(struct ipf_main_softc_s *,
174 struct ipftuneable *,
175 ipftuneval_t *);
176 #if !defined(_KERNEL) || SOLARIS
177 static int ppsratecheck(struct timeval *, int *, int);
178 #endif
179
180
181 /*
182 * bit values for identifying presence of individual IP options
183 * All of these tables should be ordered by increasing key value on the left
184 * hand side to allow for binary searching of the array and include a trailer
185 * with a 0 for the bitmask for linear searches to easily find the end with.
186 */
187 static const struct optlist ipopts[] = {
188 { IPOPT_NOP, 0x000001 },
189 { IPOPT_RR, 0x000002 },
190 { IPOPT_ZSU, 0x000004 },
191 { IPOPT_MTUP, 0x000008 },
192 { IPOPT_MTUR, 0x000010 },
193 { IPOPT_ENCODE, 0x000020 },
194 { IPOPT_TS, 0x000040 },
195 { IPOPT_TR, 0x000080 },
196 { IPOPT_SECURITY, 0x000100 },
197 { IPOPT_LSRR, 0x000200 },
198 { IPOPT_E_SEC, 0x000400 },
199 { IPOPT_CIPSO, 0x000800 },
200 { IPOPT_SATID, 0x001000 },
201 { IPOPT_SSRR, 0x002000 },
202 { IPOPT_ADDEXT, 0x004000 },
203 { IPOPT_VISA, 0x008000 },
204 { IPOPT_IMITD, 0x010000 },
205 { IPOPT_EIP, 0x020000 },
206 { IPOPT_FINN, 0x040000 },
207 { 0, 0x000000 }
208 };
209
210 #ifdef USE_INET6
211 static const struct optlist ip6exthdr[] = {
212 { IPPROTO_HOPOPTS, 0x000001 },
213 { IPPROTO_IPV6, 0x000002 },
214 { IPPROTO_ROUTING, 0x000004 },
215 { IPPROTO_FRAGMENT, 0x000008 },
216 { IPPROTO_ESP, 0x000010 },
217 { IPPROTO_AH, 0x000020 },
218 { IPPROTO_NONE, 0x000040 },
219 { IPPROTO_DSTOPTS, 0x000080 },
220 { IPPROTO_MOBILITY, 0x000100 },
221 { 0, 0 }
222 };
223 #endif
224
225 /*
226 * bit values for identifying presence of individual IP security options
227 */
228 static const struct optlist secopt[] = {
229 { IPSO_CLASS_RES4, 0x01 },
230 { IPSO_CLASS_TOPS, 0x02 },
231 { IPSO_CLASS_SECR, 0x04 },
232 { IPSO_CLASS_RES3, 0x08 },
233 { IPSO_CLASS_CONF, 0x10 },
234 { IPSO_CLASS_UNCL, 0x20 },
235 { IPSO_CLASS_RES2, 0x40 },
236 { IPSO_CLASS_RES1, 0x80 }
237 };
238
239 char ipfilter_version[] = IPL_VERSION;
240
241 int ipf_features = 0
242 #ifdef IPFILTER_LKM
243 | IPF_FEAT_LKM
244 #endif
245 #ifdef IPFILTER_LOG
246 | IPF_FEAT_LOG
247 #endif
248 | IPF_FEAT_LOOKUP
249 #ifdef IPFILTER_BPF
250 | IPF_FEAT_BPF
251 #endif
252 #ifdef IPFILTER_COMPILED
253 | IPF_FEAT_COMPILED
254 #endif
255 #ifdef IPFILTER_CKSUM
256 | IPF_FEAT_CKSUM
257 #endif
258 | IPF_FEAT_SYNC
259 #ifdef IPFILTER_SCAN
260 | IPF_FEAT_SCAN
261 #endif
262 #ifdef USE_INET6
263 | IPF_FEAT_IPV6
264 #endif
265 ;
266
267
268 /*
269 * Table of functions available for use with call rules.
270 */
271 static ipfunc_resolve_t ipf_availfuncs[] = {
272 { "srcgrpmap", ipf_srcgrpmap, ipf_grpmapinit, ipf_grpmapfini },
273 { "dstgrpmap", ipf_dstgrpmap, ipf_grpmapinit, ipf_grpmapfini },
274 { "", NULL, NULL, NULL }
275 };
276
277 static ipftuneable_t ipf_main_tuneables[] = {
278 { { (void *)offsetof(struct ipf_main_softc_s, ipf_flags) },
279 "ipf_flags", 0, 0xffffffff,
280 stsizeof(ipf_main_softc_t, ipf_flags),
281 0, NULL, NULL },
282 { { (void *)offsetof(struct ipf_main_softc_s, ipf_active) },
283 "active", 0, 0,
284 stsizeof(ipf_main_softc_t, ipf_active),
285 IPFT_RDONLY, NULL, NULL },
286 { { (void *)offsetof(ipf_main_softc_t, ipf_control_forwarding) },
287 "control_forwarding", 0, 1,
288 stsizeof(ipf_main_softc_t, ipf_control_forwarding),
289 0, NULL, NULL },
290 { { (void *)offsetof(ipf_main_softc_t, ipf_update_ipid) },
291 "update_ipid", 0, 1,
292 stsizeof(ipf_main_softc_t, ipf_update_ipid),
293 0, NULL, NULL },
294 { { (void *)offsetof(ipf_main_softc_t, ipf_chksrc) },
295 "chksrc", 0, 1,
296 stsizeof(ipf_main_softc_t, ipf_chksrc),
297 0, NULL, NULL },
298 { { (void *)offsetof(ipf_main_softc_t, ipf_minttl) },
299 "min_ttl", 0, 1,
300 stsizeof(ipf_main_softc_t, ipf_minttl),
301 0, NULL, NULL },
302 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpminfragmtu) },
303 "icmp_minfragmtu", 0, 1,
304 stsizeof(ipf_main_softc_t, ipf_icmpminfragmtu),
305 0, NULL, NULL },
306 { { (void *)offsetof(ipf_main_softc_t, ipf_pass) },
307 "default_pass", 0, 0xffffffff,
308 stsizeof(ipf_main_softc_t, ipf_pass),
309 0, NULL, NULL },
310 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpidletimeout) },
311 "tcp_idle_timeout", 1, 0x7fffffff,
312 stsizeof(ipf_main_softc_t, ipf_tcpidletimeout),
313 0, NULL, ipf_settimeout },
314 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosewait) },
315 "tcp_close_wait", 1, 0x7fffffff,
316 stsizeof(ipf_main_softc_t, ipf_tcpclosewait),
317 0, NULL, ipf_settimeout },
318 { { (void *)offsetof(ipf_main_softc_t, ipf_tcplastack) },
319 "tcp_last_ack", 1, 0x7fffffff,
320 stsizeof(ipf_main_softc_t, ipf_tcplastack),
321 0, NULL, ipf_settimeout },
322 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimeout) },
323 "tcp_timeout", 1, 0x7fffffff,
324 stsizeof(ipf_main_softc_t, ipf_tcptimeout),
325 0, NULL, ipf_settimeout },
326 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynsent) },
327 "tcp_syn_sent", 1, 0x7fffffff,
328 stsizeof(ipf_main_softc_t, ipf_tcpsynsent),
329 0, NULL, ipf_settimeout },
330 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpsynrecv) },
331 "tcp_syn_received", 1, 0x7fffffff,
332 stsizeof(ipf_main_softc_t, ipf_tcpsynrecv),
333 0, NULL, ipf_settimeout },
334 { { (void *)offsetof(ipf_main_softc_t, ipf_tcpclosed) },
335 "tcp_closed", 1, 0x7fffffff,
336 stsizeof(ipf_main_softc_t, ipf_tcpclosed),
337 0, NULL, ipf_settimeout },
338 { { (void *)offsetof(ipf_main_softc_t, ipf_tcphalfclosed) },
339 "tcp_half_closed", 1, 0x7fffffff,
340 stsizeof(ipf_main_softc_t, ipf_tcphalfclosed),
341 0, NULL, ipf_settimeout },
342 { { (void *)offsetof(ipf_main_softc_t, ipf_tcptimewait) },
343 "tcp_time_wait", 1, 0x7fffffff,
344 stsizeof(ipf_main_softc_t, ipf_tcptimewait),
345 0, NULL, ipf_settimeout },
346 { { (void *)offsetof(ipf_main_softc_t, ipf_udptimeout) },
347 "udp_timeout", 1, 0x7fffffff,
348 stsizeof(ipf_main_softc_t, ipf_udptimeout),
349 0, NULL, ipf_settimeout },
350 { { (void *)offsetof(ipf_main_softc_t, ipf_udpacktimeout) },
351 "udp_ack_timeout", 1, 0x7fffffff,
352 stsizeof(ipf_main_softc_t, ipf_udpacktimeout),
353 0, NULL, ipf_settimeout },
354 { { (void *)offsetof(ipf_main_softc_t, ipf_icmptimeout) },
355 "icmp_timeout", 1, 0x7fffffff,
356 stsizeof(ipf_main_softc_t, ipf_icmptimeout),
357 0, NULL, ipf_settimeout },
358 { { (void *)offsetof(ipf_main_softc_t, ipf_icmpacktimeout) },
359 "icmp_ack_timeout", 1, 0x7fffffff,
360 stsizeof(ipf_main_softc_t, ipf_icmpacktimeout),
361 0, NULL, ipf_settimeout },
362 { { (void *)offsetof(ipf_main_softc_t, ipf_iptimeout) },
363 "ip_timeout", 1, 0x7fffffff,
364 stsizeof(ipf_main_softc_t, ipf_iptimeout),
365 0, NULL, ipf_settimeout },
366 { { (void *)offsetof(ipf_main_softc_t, ipf_max_namelen) },
367 "max_namelen", 0, 0x7fffffff,
368 stsizeof(ipf_main_softc_t, ipf_max_namelen),
369 0, NULL, NULL },
370 #if defined(INSTANCES) && defined(_KERNEL)
371 { { (void *)offsetof(ipf_main_softc_t, ipf_get_loopback) },
372 "intercept_loopback", 0, 1,
373 stsizeof(ipf_main_softc_t, ipf_get_loopback),
374 0, NULL, ipf_set_loopback },
375 #endif
376 { { 0 },
377 NULL, 0, 0,
378 0,
379 0, NULL, NULL }
380 };
381
382
383 /*
384 * The next section of code is a collection of small routines that set
385 * fields in the fr_info_t structure passed based on properties of the
386 * current packet. There are different routines for the same protocol
387 * for each of IPv4 and IPv6. Adding a new protocol, for which there
388 * will "special" inspection for setup, is now more easily done by adding
389 * a new routine and expanding the ipf_pr_ipinit*() function rather than by
390 * adding more code to a growing switch statement.
391 */
392 #ifdef USE_INET6
393 static inline int ipf_pr_ah6(fr_info_t *);
394 static inline void ipf_pr_esp6(fr_info_t *);
395 static inline void ipf_pr_gre6(fr_info_t *);
396 static inline void ipf_pr_udp6(fr_info_t *);
397 static inline void ipf_pr_tcp6(fr_info_t *);
398 static inline void ipf_pr_icmp6(fr_info_t *);
399 static inline void ipf_pr_ipv6hdr(fr_info_t *);
400 static inline void ipf_pr_short6(fr_info_t *, int);
401 static inline int ipf_pr_hopopts6(fr_info_t *);
402 static inline int ipf_pr_mobility6(fr_info_t *);
403 static inline int ipf_pr_routing6(fr_info_t *);
404 static inline int ipf_pr_dstopts6(fr_info_t *);
405 static inline int ipf_pr_fragment6(fr_info_t *);
406 static inline struct ip6_ext *ipf_pr_ipv6exthdr(fr_info_t *, int, int);
407
408
409 /* ------------------------------------------------------------------------ */
410 /* Function: ipf_pr_short6 */
411 /* Returns: void */
412 /* Parameters: fin(I) - pointer to packet information */
413 /* xmin(I) - minimum header size */
414 /* */
415 /* IPv6 Only */
416 /* This is function enforces the 'is a packet too short to be legit' rule */
417 /* for IPv6 and marks the packet with FI_SHORT if so. See function comment */
418 /* for ipf_pr_short() for more details. */
419 /* ------------------------------------------------------------------------ */
420 static inline void
ipf_pr_short6(fr_info_t * fin,int xmin)421 ipf_pr_short6(fr_info_t *fin, int xmin)
422 {
423
424 if (fin->fin_dlen < xmin)
425 fin->fin_flx |= FI_SHORT;
426 }
427
428
429 /* ------------------------------------------------------------------------ */
430 /* Function: ipf_pr_ipv6hdr */
431 /* Returns: void */
432 /* Parameters: fin(I) - pointer to packet information */
433 /* */
434 /* IPv6 Only */
435 /* Copy values from the IPv6 header into the fr_info_t struct and call the */
436 /* per-protocol analyzer if it exists. In validating the packet, a protocol*/
437 /* analyzer may pullup or free the packet itself so we need to be vigiliant */
438 /* of that possibility arising. */
439 /* ------------------------------------------------------------------------ */
440 static inline void
ipf_pr_ipv6hdr(fr_info_t * fin)441 ipf_pr_ipv6hdr(fr_info_t *fin)
442 {
443 ip6_t *ip6 = (ip6_t *)fin->fin_ip;
444 int p, go = 1, i;
445 fr_ip_t *fi = &fin->fin_fi;
446
447 fin->fin_off = 0;
448
449 fi->fi_tos = 0;
450 fi->fi_optmsk = 0;
451 fi->fi_secmsk = 0;
452 fi->fi_auth = 0;
453
454 p = ip6->ip6_nxt;
455 fin->fin_crc = p;
456 fi->fi_ttl = ip6->ip6_hlim;
457 fi->fi_src.in6 = ip6->ip6_src;
458 fin->fin_crc += fi->fi_src.i6[0];
459 fin->fin_crc += fi->fi_src.i6[1];
460 fin->fin_crc += fi->fi_src.i6[2];
461 fin->fin_crc += fi->fi_src.i6[3];
462 fi->fi_dst.in6 = ip6->ip6_dst;
463 fin->fin_crc += fi->fi_dst.i6[0];
464 fin->fin_crc += fi->fi_dst.i6[1];
465 fin->fin_crc += fi->fi_dst.i6[2];
466 fin->fin_crc += fi->fi_dst.i6[3];
467 fin->fin_id = 0;
468 if (IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
469 fin->fin_flx |= FI_MULTICAST|FI_MBCAST;
470
471 while (go && !(fin->fin_flx & FI_SHORT)) {
472 switch (p)
473 {
474 case IPPROTO_UDP :
475 ipf_pr_udp6(fin);
476 go = 0;
477 break;
478
479 case IPPROTO_TCP :
480 ipf_pr_tcp6(fin);
481 go = 0;
482 break;
483
484 case IPPROTO_ICMPV6 :
485 ipf_pr_icmp6(fin);
486 go = 0;
487 break;
488
489 case IPPROTO_GRE :
490 ipf_pr_gre6(fin);
491 go = 0;
492 break;
493
494 case IPPROTO_HOPOPTS :
495 p = ipf_pr_hopopts6(fin);
496 break;
497
498 case IPPROTO_MOBILITY :
499 p = ipf_pr_mobility6(fin);
500 break;
501
502 case IPPROTO_DSTOPTS :
503 p = ipf_pr_dstopts6(fin);
504 break;
505
506 case IPPROTO_ROUTING :
507 p = ipf_pr_routing6(fin);
508 break;
509
510 case IPPROTO_AH :
511 p = ipf_pr_ah6(fin);
512 break;
513
514 case IPPROTO_ESP :
515 ipf_pr_esp6(fin);
516 go = 0;
517 break;
518
519 case IPPROTO_IPV6 :
520 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
521 if (ip6exthdr[i].ol_val == p) {
522 fin->fin_flx |= ip6exthdr[i].ol_bit;
523 break;
524 }
525 go = 0;
526 break;
527
528 case IPPROTO_NONE :
529 go = 0;
530 break;
531
532 case IPPROTO_FRAGMENT :
533 p = ipf_pr_fragment6(fin);
534 /*
535 * Given that the only fragments we want to let through
536 * (where fin_off != 0) are those where the non-first
537 * fragments only have data, we can safely stop looking
538 * at headers if this is a non-leading fragment.
539 */
540 if (fin->fin_off != 0)
541 go = 0;
542 break;
543
544 default :
545 go = 0;
546 break;
547 }
548
549 /*
550 * It is important to note that at this point, for the
551 * extension headers (go != 0), the entire header may not have
552 * been pulled up when the code gets to this point. This is
553 * only done for "go != 0" because the other header handlers
554 * will all pullup their complete header. The other indicator
555 * of an incomplete packet is that this was just an extension
556 * header.
557 */
558 if ((go != 0) && (p != IPPROTO_NONE) &&
559 (ipf_pr_pullup(fin, 0) == -1)) {
560 p = IPPROTO_NONE;
561 break;
562 }
563 }
564
565 /*
566 * Some of the above functions, like ipf_pr_esp6(), can call ipf_pullup
567 * and destroy whatever packet was here. The caller of this function
568 * expects us to return if there is a problem with ipf_pullup.
569 */
570 if (fin->fin_m == NULL) {
571 ipf_main_softc_t *softc = fin->fin_main_soft;
572
573 LBUMPD(ipf_stats[fin->fin_out], fr_v6_bad);
574 return;
575 }
576
577 fi->fi_p = p;
578
579 /*
580 * IPv6 fragment case 1 - see comment for ipf_pr_fragment6().
581 * "go != 0" implies the above loop hasn't arrived at a layer 4 header.
582 */
583 if ((go != 0) && (fin->fin_flx & FI_FRAG) && (fin->fin_off == 0)) {
584 ipf_main_softc_t *softc = fin->fin_main_soft;
585
586 fin->fin_flx |= FI_BAD;
587 DT2(ipf_fi_bad_ipv6_frag_1, fr_info_t *, fin, int, go);
588 LBUMPD(ipf_stats[fin->fin_out], fr_v6_badfrag);
589 LBUMP(ipf_stats[fin->fin_out].fr_v6_bad);
590 }
591 }
592
593
594 /* ------------------------------------------------------------------------ */
595 /* Function: ipf_pr_ipv6exthdr */
596 /* Returns: struct ip6_ext * - pointer to the start of the next header */
597 /* or NULL if there is a prolblem. */
598 /* Parameters: fin(I) - pointer to packet information */
599 /* multiple(I) - flag indicating yes/no if multiple occurances */
600 /* of this extension header are allowed. */
601 /* proto(I) - protocol number for this extension header */
602 /* */
603 /* IPv6 Only */
604 /* This function embodies a number of common checks that all IPv6 extension */
605 /* headers must be subjected to. For example, making sure the packet is */
606 /* big enough for it to be in, checking if it is repeated and setting a */
607 /* flag to indicate its presence. */
608 /* ------------------------------------------------------------------------ */
609 static inline struct ip6_ext *
ipf_pr_ipv6exthdr(fr_info_t * fin,int multiple,int proto)610 ipf_pr_ipv6exthdr(fr_info_t *fin, int multiple, int proto)
611 {
612 ipf_main_softc_t *softc = fin->fin_main_soft;
613 struct ip6_ext *hdr;
614 u_short shift;
615 int i;
616
617 fin->fin_flx |= FI_V6EXTHDR;
618
619 /* 8 is default length of extension hdr */
620 if ((fin->fin_dlen - 8) < 0) {
621 fin->fin_flx |= FI_SHORT;
622 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_short);
623 return (NULL);
624 }
625
626 if (ipf_pr_pullup(fin, 8) == -1) {
627 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_pullup);
628 return (NULL);
629 }
630
631 hdr = fin->fin_dp;
632 switch (proto)
633 {
634 case IPPROTO_FRAGMENT :
635 shift = 8;
636 break;
637 default :
638 shift = 8 + (hdr->ip6e_len << 3);
639 break;
640 }
641
642 if (shift > fin->fin_dlen) { /* Nasty extension header length? */
643 fin->fin_flx |= FI_BAD;
644 DT3(ipf_fi_bad_pr_ipv6exthdr_len, fr_info_t *, fin, u_short, shift, u_short, fin->fin_dlen);
645 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ext_hlen);
646 return (NULL);
647 }
648
649 fin->fin_dp = (char *)fin->fin_dp + shift;
650 fin->fin_dlen -= shift;
651
652 /*
653 * If we have seen a fragment header, do not set any flags to indicate
654 * the presence of this extension header as it has no impact on the
655 * end result until after it has been defragmented.
656 */
657 if (fin->fin_flx & FI_FRAG)
658 return (hdr);
659
660 for (i = 0; ip6exthdr[i].ol_bit != 0; i++)
661 if (ip6exthdr[i].ol_val == proto) {
662 /*
663 * Most IPv6 extension headers are only allowed once.
664 */
665 if ((multiple == 0) &&
666 ((fin->fin_optmsk & ip6exthdr[i].ol_bit) != 0)) {
667 fin->fin_flx |= FI_BAD;
668 DT2(ipf_fi_bad_ipv6exthdr_once, fr_info_t *, fin, u_int, (fin->fin_optmsk & ip6exthdr[i].ol_bit));
669 } else
670 fin->fin_optmsk |= ip6exthdr[i].ol_bit;
671 break;
672 }
673
674 return (hdr);
675 }
676
677
678 /* ------------------------------------------------------------------------ */
679 /* Function: ipf_pr_hopopts6 */
680 /* Returns: int - value of the next header or IPPROTO_NONE if error */
681 /* Parameters: fin(I) - pointer to packet information */
682 /* */
683 /* IPv6 Only */
684 /* This is function checks pending hop by hop options extension header */
685 /* ------------------------------------------------------------------------ */
686 static inline int
ipf_pr_hopopts6(fr_info_t * fin)687 ipf_pr_hopopts6(fr_info_t *fin)
688 {
689 struct ip6_ext *hdr;
690
691 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
692 if (hdr == NULL)
693 return (IPPROTO_NONE);
694 return (hdr->ip6e_nxt);
695 }
696
697
698 /* ------------------------------------------------------------------------ */
699 /* Function: ipf_pr_mobility6 */
700 /* Returns: int - value of the next header or IPPROTO_NONE if error */
701 /* Parameters: fin(I) - pointer to packet information */
702 /* */
703 /* IPv6 Only */
704 /* This is function checks the IPv6 mobility extension header */
705 /* ------------------------------------------------------------------------ */
706 static inline int
ipf_pr_mobility6(fr_info_t * fin)707 ipf_pr_mobility6(fr_info_t *fin)
708 {
709 struct ip6_ext *hdr;
710
711 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_MOBILITY);
712 if (hdr == NULL)
713 return (IPPROTO_NONE);
714 return (hdr->ip6e_nxt);
715 }
716
717
718 /* ------------------------------------------------------------------------ */
719 /* Function: ipf_pr_routing6 */
720 /* Returns: int - value of the next header or IPPROTO_NONE if error */
721 /* Parameters: fin(I) - pointer to packet information */
722 /* */
723 /* IPv6 Only */
724 /* This is function checks pending routing extension header */
725 /* ------------------------------------------------------------------------ */
726 static inline int
ipf_pr_routing6(fr_info_t * fin)727 ipf_pr_routing6(fr_info_t *fin)
728 {
729 struct ip6_routing *hdr;
730
731 hdr = (struct ip6_routing *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_ROUTING);
732 if (hdr == NULL)
733 return (IPPROTO_NONE);
734
735 switch (hdr->ip6r_type)
736 {
737 case 0 :
738 /*
739 * Nasty extension header length?
740 */
741 if (((hdr->ip6r_len >> 1) < hdr->ip6r_segleft) ||
742 (hdr->ip6r_segleft && (hdr->ip6r_len & 1))) {
743 ipf_main_softc_t *softc = fin->fin_main_soft;
744
745 fin->fin_flx |= FI_BAD;
746 DT1(ipf_fi_bad_routing6, fr_info_t *, fin);
747 LBUMPD(ipf_stats[fin->fin_out], fr_v6_rh_bad);
748 return (IPPROTO_NONE);
749 }
750 break;
751
752 default :
753 break;
754 }
755
756 return (hdr->ip6r_nxt);
757 }
758
759
760 /* ------------------------------------------------------------------------ */
761 /* Function: ipf_pr_fragment6 */
762 /* Returns: int - value of the next header or IPPROTO_NONE if error */
763 /* Parameters: fin(I) - pointer to packet information */
764 /* */
765 /* IPv6 Only */
766 /* Examine the IPv6 fragment header and extract fragment offset information.*/
767 /* */
768 /* Fragments in IPv6 are extraordinarily difficult to deal with - much more */
769 /* so than in IPv4. There are 5 cases of fragments with IPv6 that all */
770 /* packets with a fragment header can fit into. They are as follows: */
771 /* */
772 /* 1. [IPv6][0-n EH][FH][0-n EH] (no L4HDR present) */
773 /* 2. [IPV6][0-n EH][FH][0-n EH][L4HDR part] (short) */
774 /* 3. [IPV6][0-n EH][FH][L4HDR part][0-n data] (short) */
775 /* 4. [IPV6][0-n EH][FH][0-n EH][L4HDR][0-n data] */
776 /* 5. [IPV6][0-n EH][FH][data] */
777 /* */
778 /* IPV6 = IPv6 header, FH = Fragment Header, */
779 /* 0-n EH = 0 or more extension headers, 0-n data = 0 or more bytes of data */
780 /* */
781 /* Packets that match 1, 2, 3 will be dropped as the only reasonable */
782 /* scenario in which they happen is in extreme circumstances that are most */
783 /* likely to be an indication of an attack rather than normal traffic. */
784 /* A type 3 packet may be sent by an attacked after a type 4 packet. There */
785 /* are two rules that can be used to guard against type 3 packets: L4 */
786 /* headers must always be in a packet that has the offset field set to 0 */
787 /* and no packet is allowed to overlay that where offset = 0. */
788 /* ------------------------------------------------------------------------ */
789 static inline int
ipf_pr_fragment6(fr_info_t * fin)790 ipf_pr_fragment6(fr_info_t *fin)
791 {
792 ipf_main_softc_t *softc = fin->fin_main_soft;
793 struct ip6_frag *frag;
794
795 fin->fin_flx |= FI_FRAG;
796
797 frag = (struct ip6_frag *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_FRAGMENT);
798 if (frag == NULL) {
799 LBUMPD(ipf_stats[fin->fin_out], fr_v6_frag_bad);
800 return (IPPROTO_NONE);
801 }
802
803 if ((frag->ip6f_offlg & IP6F_MORE_FRAG) != 0) {
804 /*
805 * Any fragment that isn't the last fragment must have its
806 * length as a multiple of 8.
807 */
808 if ((fin->fin_plen & 7) != 0) {
809 fin->fin_flx |= FI_BAD;
810 DT2(ipf_fi_bad_frag_not_8, fr_info_t *, fin, u_int, (fin->fin_plen & 7));
811 }
812 }
813
814 fin->fin_fraghdr = frag;
815 fin->fin_id = frag->ip6f_ident;
816 fin->fin_off = ntohs(frag->ip6f_offlg & IP6F_OFF_MASK);
817 if (fin->fin_off != 0)
818 fin->fin_flx |= FI_FRAGBODY;
819
820 /*
821 * Jumbograms aren't handled, so the max. length is 64k
822 */
823 if ((fin->fin_off << 3) + fin->fin_dlen > 65535) {
824 fin->fin_flx |= FI_BAD;
825 DT2(ipf_fi_bad_jumbogram, fr_info_t *, fin, u_int, ((fin->fin_off << 3) + fin->fin_dlen));
826 }
827
828 /*
829 * We don't know where the transport layer header (or whatever is next
830 * is), as it could be behind destination options (amongst others) so
831 * return the fragment header as the type of packet this is. Note that
832 * this effectively disables the fragment cache for > 1 protocol at a
833 * time.
834 */
835 return (frag->ip6f_nxt);
836 }
837
838
839 /* ------------------------------------------------------------------------ */
840 /* Function: ipf_pr_dstopts6 */
841 /* Returns: int - value of the next header or IPPROTO_NONE if error */
842 /* Parameters: fin(I) - pointer to packet information */
843 /* */
844 /* IPv6 Only */
845 /* This is function checks pending destination options extension header */
846 /* ------------------------------------------------------------------------ */
847 static inline int
ipf_pr_dstopts6(fr_info_t * fin)848 ipf_pr_dstopts6(fr_info_t *fin)
849 {
850 ipf_main_softc_t *softc = fin->fin_main_soft;
851 struct ip6_ext *hdr;
852
853 hdr = ipf_pr_ipv6exthdr(fin, 0, IPPROTO_DSTOPTS);
854 if (hdr == NULL) {
855 LBUMPD(ipf_stats[fin->fin_out], fr_v6_dst_bad);
856 return (IPPROTO_NONE);
857 }
858 return (hdr->ip6e_nxt);
859 }
860
861
862 /* ------------------------------------------------------------------------ */
863 /* Function: ipf_pr_icmp6 */
864 /* Returns: void */
865 /* Parameters: fin(I) - pointer to packet information */
866 /* */
867 /* IPv6 Only */
868 /* This routine is mainly concerned with determining the minimum valid size */
869 /* for an ICMPv6 packet. */
870 /* ------------------------------------------------------------------------ */
871 static inline void
ipf_pr_icmp6(fr_info_t * fin)872 ipf_pr_icmp6(fr_info_t *fin)
873 {
874 int minicmpsz = sizeof(struct icmp6_hdr);
875 struct icmp6_hdr *icmp6;
876
877 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN - sizeof(ip6_t)) == -1) {
878 ipf_main_softc_t *softc = fin->fin_main_soft;
879
880 LBUMPD(ipf_stats[fin->fin_out], fr_v6_icmp6_pullup);
881 return;
882 }
883
884 if (fin->fin_dlen > 1) {
885 ip6_t *ip6;
886
887 icmp6 = fin->fin_dp;
888
889 fin->fin_data[0] = *(u_short *)icmp6;
890
891 if ((icmp6->icmp6_type & ICMP6_INFOMSG_MASK) != 0)
892 fin->fin_flx |= FI_ICMPQUERY;
893
894 switch (icmp6->icmp6_type)
895 {
896 case ICMP6_ECHO_REPLY :
897 case ICMP6_ECHO_REQUEST :
898 if (fin->fin_dlen >= 6)
899 fin->fin_data[1] = icmp6->icmp6_id;
900 minicmpsz = ICMP6ERR_MINPKTLEN - sizeof(ip6_t);
901 break;
902
903 case ICMP6_DST_UNREACH :
904 case ICMP6_PACKET_TOO_BIG :
905 case ICMP6_TIME_EXCEEDED :
906 case ICMP6_PARAM_PROB :
907 fin->fin_flx |= FI_ICMPERR;
908 minicmpsz = ICMP6ERR_IPICMPHLEN - sizeof(ip6_t);
909 if (fin->fin_plen < ICMP6ERR_IPICMPHLEN)
910 break;
911
912 if (M_LEN(fin->fin_m) < fin->fin_plen) {
913 if (ipf_coalesce(fin) != 1)
914 return;
915 }
916
917 if (ipf_pr_pullup(fin, ICMP6ERR_MINPKTLEN) == -1)
918 return;
919
920 /*
921 * If the destination of this packet doesn't match the
922 * source of the original packet then this packet is
923 * not correct.
924 */
925 icmp6 = fin->fin_dp;
926 ip6 = (ip6_t *)((char *)icmp6 + ICMPERR_ICMPHLEN);
927 if (IP6_NEQ(&fin->fin_fi.fi_dst,
928 (i6addr_t *)&ip6->ip6_src)) {
929 fin->fin_flx |= FI_BAD;
930 DT1(ipf_fi_bad_icmp6, fr_info_t *, fin);
931 }
932 break;
933 default :
934 break;
935 }
936 }
937
938 ipf_pr_short6(fin, minicmpsz);
939 if ((fin->fin_flx & (FI_SHORT|FI_BAD)) == 0) {
940 u_char p = fin->fin_p;
941
942 fin->fin_p = IPPROTO_ICMPV6;
943 ipf_checkv6sum(fin);
944 fin->fin_p = p;
945 }
946 }
947
948
949 /* ------------------------------------------------------------------------ */
950 /* Function: ipf_pr_udp6 */
951 /* Returns: void */
952 /* Parameters: fin(I) - pointer to packet information */
953 /* */
954 /* IPv6 Only */
955 /* Analyse the packet for IPv6/UDP properties. */
956 /* Is not expected to be called for fragmented packets. */
957 /* ------------------------------------------------------------------------ */
958 static inline void
ipf_pr_udp6(fr_info_t * fin)959 ipf_pr_udp6(fr_info_t *fin)
960 {
961
962 if (ipf_pr_udpcommon(fin) == 0) {
963 u_char p = fin->fin_p;
964
965 fin->fin_p = IPPROTO_UDP;
966 ipf_checkv6sum(fin);
967 fin->fin_p = p;
968 }
969 }
970
971
972 /* ------------------------------------------------------------------------ */
973 /* Function: ipf_pr_tcp6 */
974 /* Returns: void */
975 /* Parameters: fin(I) - pointer to packet information */
976 /* */
977 /* IPv6 Only */
978 /* Analyse the packet for IPv6/TCP properties. */
979 /* Is not expected to be called for fragmented packets. */
980 /* ------------------------------------------------------------------------ */
981 static inline void
ipf_pr_tcp6(fr_info_t * fin)982 ipf_pr_tcp6(fr_info_t *fin)
983 {
984
985 if (ipf_pr_tcpcommon(fin) == 0) {
986 u_char p = fin->fin_p;
987
988 fin->fin_p = IPPROTO_TCP;
989 ipf_checkv6sum(fin);
990 fin->fin_p = p;
991 }
992 }
993
994
995 /* ------------------------------------------------------------------------ */
996 /* Function: ipf_pr_esp6 */
997 /* Returns: void */
998 /* Parameters: fin(I) - pointer to packet information */
999 /* */
1000 /* IPv6 Only */
1001 /* Analyse the packet for ESP properties. */
1002 /* The minimum length is taken to be the SPI (32bits) plus a tail (32bits) */
1003 /* even though the newer ESP packets must also have a sequence number that */
1004 /* is 32bits as well, it is not possible(?) to determine the version from a */
1005 /* simple packet header. */
1006 /* ------------------------------------------------------------------------ */
1007 static inline void
ipf_pr_esp6(fr_info_t * fin)1008 ipf_pr_esp6(fr_info_t *fin)
1009 {
1010
1011 if ((fin->fin_off == 0) && (ipf_pr_pullup(fin, 8) == -1)) {
1012 ipf_main_softc_t *softc = fin->fin_main_soft;
1013
1014 LBUMPD(ipf_stats[fin->fin_out], fr_v6_esp_pullup);
1015 return;
1016 }
1017 }
1018
1019
1020 /* ------------------------------------------------------------------------ */
1021 /* Function: ipf_pr_ah6 */
1022 /* Returns: int - value of the next header or IPPROTO_NONE if error */
1023 /* Parameters: fin(I) - pointer to packet information */
1024 /* */
1025 /* IPv6 Only */
1026 /* Analyse the packet for AH properties. */
1027 /* The minimum length is taken to be the combination of all fields in the */
1028 /* header being present and no authentication data (null algorithm used.) */
1029 /* ------------------------------------------------------------------------ */
1030 static inline int
ipf_pr_ah6(fr_info_t * fin)1031 ipf_pr_ah6(fr_info_t *fin)
1032 {
1033 authhdr_t *ah;
1034
1035 fin->fin_flx |= FI_AH;
1036
1037 ah = (authhdr_t *)ipf_pr_ipv6exthdr(fin, 0, IPPROTO_HOPOPTS);
1038 if (ah == NULL) {
1039 ipf_main_softc_t *softc = fin->fin_main_soft;
1040
1041 LBUMPD(ipf_stats[fin->fin_out], fr_v6_ah_bad);
1042 return (IPPROTO_NONE);
1043 }
1044
1045 ipf_pr_short6(fin, sizeof(*ah));
1046
1047 /*
1048 * No need for another pullup, ipf_pr_ipv6exthdr() will pullup
1049 * enough data to satisfy ah_next (the very first one.)
1050 */
1051 return (ah->ah_next);
1052 }
1053
1054
1055 /* ------------------------------------------------------------------------ */
1056 /* Function: ipf_pr_gre6 */
1057 /* Returns: void */
1058 /* Parameters: fin(I) - pointer to packet information */
1059 /* */
1060 /* Analyse the packet for GRE properties. */
1061 /* ------------------------------------------------------------------------ */
1062 static inline void
ipf_pr_gre6(fr_info_t * fin)1063 ipf_pr_gre6(fr_info_t *fin)
1064 {
1065 grehdr_t *gre;
1066
1067 if (ipf_pr_pullup(fin, sizeof(grehdr_t)) == -1) {
1068 ipf_main_softc_t *softc = fin->fin_main_soft;
1069
1070 LBUMPD(ipf_stats[fin->fin_out], fr_v6_gre_pullup);
1071 return;
1072 }
1073
1074 gre = fin->fin_dp;
1075 if (GRE_REV(gre->gr_flags) == 1)
1076 fin->fin_data[0] = gre->gr_call;
1077 }
1078 #endif /* USE_INET6 */
1079
1080
1081 /* ------------------------------------------------------------------------ */
1082 /* Function: ipf_pr_pullup */
1083 /* Returns: int - 0 == pullup succeeded, -1 == failure */
1084 /* Parameters: fin(I) - pointer to packet information */
1085 /* plen(I) - length (excluding L3 header) to pullup */
1086 /* */
1087 /* Short inline function to cut down on code duplication to perform a call */
1088 /* to ipf_pullup to ensure there is the required amount of data, */
1089 /* consecutively in the packet buffer. */
1090 /* */
1091 /* This function pulls up 'extra' data at the location of fin_dp. fin_dp */
1092 /* points to the first byte after the complete layer 3 header, which will */
1093 /* include all of the known extension headers for IPv6 or options for IPv4. */
1094 /* */
1095 /* Since fr_pullup() expects the total length of bytes to be pulled up, it */
1096 /* is necessary to add those we can already assume to be pulled up (fin_dp */
1097 /* - fin_ip) to what is passed through. */
1098 /* ------------------------------------------------------------------------ */
1099 int
ipf_pr_pullup(fr_info_t * fin,int plen)1100 ipf_pr_pullup(fr_info_t *fin, int plen)
1101 {
1102 ipf_main_softc_t *softc = fin->fin_main_soft;
1103
1104 if (fin->fin_m != NULL) {
1105 if (fin->fin_dp != NULL)
1106 plen += (char *)fin->fin_dp -
1107 ((char *)fin->fin_ip + fin->fin_hlen);
1108 plen += fin->fin_hlen;
1109 if (M_LEN(fin->fin_m) < plen + fin->fin_ipoff) {
1110 #if defined(_KERNEL)
1111 if (ipf_pullup(fin->fin_m, fin, plen) == NULL) {
1112 DT1(ipf_pullup_fail, fr_info_t *, fin);
1113 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1114 fin->fin_reason = FRB_PULLUP;
1115 fin->fin_flx |= FI_BAD;
1116 return (-1);
1117 }
1118 LBUMP(ipf_stats[fin->fin_out].fr_pull[0]);
1119 #else
1120 LBUMP(ipf_stats[fin->fin_out].fr_pull[1]);
1121 /*
1122 * Fake ipf_pullup failing
1123 */
1124 fin->fin_reason = FRB_PULLUP;
1125 *fin->fin_mp = NULL;
1126 fin->fin_m = NULL;
1127 fin->fin_ip = NULL;
1128 fin->fin_flx |= FI_BAD;
1129 return (-1);
1130 #endif
1131 }
1132 }
1133 return (0);
1134 }
1135
1136
1137 /* ------------------------------------------------------------------------ */
1138 /* Function: ipf_pr_short */
1139 /* Returns: void */
1140 /* Parameters: fin(I) - pointer to packet information */
1141 /* xmin(I) - minimum header size */
1142 /* */
1143 /* Check if a packet is "short" as defined by xmin. The rule we are */
1144 /* applying here is that the packet must not be fragmented within the layer */
1145 /* 4 header. That is, it must not be a fragment that has its offset set to */
1146 /* start within the layer 4 header (hdrmin) or if it is at offset 0, the */
1147 /* entire layer 4 header must be present (min). */
1148 /* ------------------------------------------------------------------------ */
1149 static inline void
ipf_pr_short(fr_info_t * fin,int xmin)1150 ipf_pr_short(fr_info_t *fin, int xmin)
1151 {
1152
1153 if (fin->fin_off == 0) {
1154 if (fin->fin_dlen < xmin)
1155 fin->fin_flx |= FI_SHORT;
1156 } else if (fin->fin_off < xmin) {
1157 fin->fin_flx |= FI_SHORT;
1158 }
1159 }
1160
1161
1162 /* ------------------------------------------------------------------------ */
1163 /* Function: ipf_pr_icmp */
1164 /* Returns: void */
1165 /* Parameters: fin(I) - pointer to packet information */
1166 /* */
1167 /* IPv4 Only */
1168 /* Do a sanity check on the packet for ICMP (v4). In nearly all cases, */
1169 /* except extrememly bad packets, both type and code will be present. */
1170 /* The expected minimum size of an ICMP packet is very much dependent on */
1171 /* the type of it. */
1172 /* */
1173 /* XXX - other ICMP sanity checks? */
1174 /* ------------------------------------------------------------------------ */
1175 static inline void
ipf_pr_icmp(fr_info_t * fin)1176 ipf_pr_icmp(fr_info_t *fin)
1177 {
1178 ipf_main_softc_t *softc = fin->fin_main_soft;
1179 int minicmpsz = sizeof(struct icmp);
1180 icmphdr_t *icmp;
1181 ip_t *oip;
1182
1183 ipf_pr_short(fin, ICMPERR_ICMPHLEN);
1184
1185 if (fin->fin_off != 0) {
1186 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_frag);
1187 return;
1188 }
1189
1190 if (ipf_pr_pullup(fin, ICMPERR_ICMPHLEN) == -1) {
1191 LBUMPD(ipf_stats[fin->fin_out], fr_v4_icmp_pullup);
1192 return;
1193 }
1194
1195 icmp = fin->fin_dp;
1196
1197 fin->fin_data[0] = *(u_short *)icmp;
1198 fin->fin_data[1] = icmp->icmp_id;
1199
1200 switch (icmp->icmp_type)
1201 {
1202 case ICMP_ECHOREPLY :
1203 case ICMP_ECHO :
1204 /* Router discovery messaes - RFC 1256 */
1205 case ICMP_ROUTERADVERT :
1206 case ICMP_ROUTERSOLICIT :
1207 fin->fin_flx |= FI_ICMPQUERY;
1208 minicmpsz = ICMP_MINLEN;
1209 break;
1210 /*
1211 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1212 * 3 * timestamp(3 * 4)
1213 */
1214 case ICMP_TSTAMP :
1215 case ICMP_TSTAMPREPLY :
1216 fin->fin_flx |= FI_ICMPQUERY;
1217 minicmpsz = 20;
1218 break;
1219 /*
1220 * type(1) + code(1) + cksum(2) + id(2) seq(2) +
1221 * mask(4)
1222 */
1223 case ICMP_IREQ :
1224 case ICMP_IREQREPLY :
1225 case ICMP_MASKREQ :
1226 case ICMP_MASKREPLY :
1227 fin->fin_flx |= FI_ICMPQUERY;
1228 minicmpsz = 12;
1229 break;
1230 /*
1231 * type(1) + code(1) + cksum(2) + id(2) seq(2) + ip(20+)
1232 */
1233 case ICMP_UNREACH :
1234 #ifdef icmp_nextmtu
1235 if (icmp->icmp_code == ICMP_UNREACH_NEEDFRAG) {
1236 if (icmp->icmp_nextmtu < softc->ipf_icmpminfragmtu) {
1237 fin->fin_flx |= FI_BAD;
1238 DT3(ipf_fi_bad_icmp_nextmtu, fr_info_t *, fin, u_int, icmp->icmp_nextmtu, u_int, softc->ipf_icmpminfragmtu);
1239 }
1240 }
1241 #endif
1242 /* FALLTHROUGH */
1243 case ICMP_SOURCEQUENCH :
1244 case ICMP_REDIRECT :
1245 case ICMP_TIMXCEED :
1246 case ICMP_PARAMPROB :
1247 fin->fin_flx |= FI_ICMPERR;
1248 if (ipf_coalesce(fin) != 1) {
1249 LBUMPD(ipf_stats[fin->fin_out], fr_icmp_coalesce);
1250 return;
1251 }
1252
1253 /*
1254 * ICMP error packets should not be generated for IP
1255 * packets that are a fragment that isn't the first
1256 * fragment.
1257 */
1258 oip = (ip_t *)((char *)fin->fin_dp + ICMPERR_ICMPHLEN);
1259 if ((ntohs(oip->ip_off) & IP_OFFMASK) != 0) {
1260 fin->fin_flx |= FI_BAD;
1261 DT2(ipf_fi_bad_icmp_err, fr_info_t, fin, u_int, (ntohs(oip->ip_off) & IP_OFFMASK));
1262 }
1263
1264 /*
1265 * If the destination of this packet doesn't match the
1266 * source of the original packet then this packet is
1267 * not correct.
1268 */
1269 if (oip->ip_src.s_addr != fin->fin_daddr) {
1270 fin->fin_flx |= FI_BAD;
1271 DT1(ipf_fi_bad_src_ne_dst, fr_info_t *, fin);
1272 }
1273 break;
1274 default :
1275 break;
1276 }
1277
1278 ipf_pr_short(fin, minicmpsz);
1279
1280 ipf_checkv4sum(fin);
1281 }
1282
1283
1284 /* ------------------------------------------------------------------------ */
1285 /* Function: ipf_pr_tcpcommon */
1286 /* Returns: int - 0 = header ok, 1 = bad packet, -1 = buffer error */
1287 /* Parameters: fin(I) - pointer to packet information */
1288 /* */
1289 /* TCP header sanity checking. Look for bad combinations of TCP flags, */
1290 /* and make some checks with how they interact with other fields. */
1291 /* If compiled with IPFILTER_CKSUM, check to see if the TCP checksum is */
1292 /* valid and mark the packet as bad if not. */
1293 /* ------------------------------------------------------------------------ */
1294 static inline int
ipf_pr_tcpcommon(fr_info_t * fin)1295 ipf_pr_tcpcommon(fr_info_t *fin)
1296 {
1297 ipf_main_softc_t *softc = fin->fin_main_soft;
1298 int flags, tlen;
1299 tcphdr_t *tcp;
1300
1301 fin->fin_flx |= FI_TCPUDP;
1302 if (fin->fin_off != 0) {
1303 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_frag);
1304 return (0);
1305 }
1306
1307 if (ipf_pr_pullup(fin, sizeof(*tcp)) == -1) {
1308 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_pullup);
1309 return (-1);
1310 }
1311
1312 tcp = fin->fin_dp;
1313 if (fin->fin_dlen > 3) {
1314 fin->fin_sport = ntohs(tcp->th_sport);
1315 fin->fin_dport = ntohs(tcp->th_dport);
1316 }
1317
1318 if ((fin->fin_flx & FI_SHORT) != 0) {
1319 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_short);
1320 return (1);
1321 }
1322
1323 /*
1324 * Use of the TCP data offset *must* result in a value that is at
1325 * least the same size as the TCP header.
1326 */
1327 tlen = TCP_OFF(tcp) << 2;
1328 if (tlen < sizeof(tcphdr_t)) {
1329 LBUMPD(ipf_stats[fin->fin_out], fr_tcp_small);
1330 fin->fin_flx |= FI_BAD;
1331 DT3(ipf_fi_bad_tlen, fr_info_t, fin, u_int, tlen, u_int, sizeof(tcphdr_t));
1332 return (1);
1333 }
1334
1335 flags = tcp_get_flags(tcp);
1336 fin->fin_tcpf = tcp_get_flags(tcp);
1337
1338 /*
1339 * If the urgent flag is set, then the urgent pointer must
1340 * also be set and vice versa. Good TCP packets do not have
1341 * just one of these set.
1342 */
1343 if ((flags & TH_URG) != 0 && (tcp->th_urp == 0)) {
1344 fin->fin_flx |= FI_BAD;
1345 DT3(ipf_fi_bad_th_urg, fr_info_t*, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1346 #if 0
1347 } else if ((flags & TH_URG) == 0 && (tcp->th_urp != 0)) {
1348 /*
1349 * Ignore this case (#if 0) as it shows up in "real"
1350 * traffic with bogus values in the urgent pointer field.
1351 */
1352 fin->fin_flx |= FI_BAD;
1353 DT3(ipf_fi_bad_th_urg0, fr_info_t *, fin, u_int, (flags & TH_URG), u_int, tcp->th_urp);
1354 #endif
1355 } else if (((flags & (TH_SYN|TH_FIN)) != 0) &&
1356 ((flags & (TH_RST|TH_ACK)) == TH_RST)) {
1357 /* TH_FIN|TH_RST|TH_ACK seems to appear "naturally" */
1358 fin->fin_flx |= FI_BAD;
1359 DT1(ipf_fi_bad_th_fin_rst_ack, fr_info_t, fin);
1360 #if 1
1361 } else if (((flags & TH_SYN) != 0) &&
1362 ((flags & (TH_URG|TH_PUSH)) != 0)) {
1363 /*
1364 * SYN with URG and PUSH set is not for normal TCP but it is
1365 * possible(?) with T/TCP...but who uses T/TCP?
1366 */
1367 fin->fin_flx |= FI_BAD;
1368 DT1(ipf_fi_bad_th_syn_urg_psh, fr_info_t *, fin);
1369 #endif
1370 } else if (!(flags & TH_ACK)) {
1371 /*
1372 * If the ack bit isn't set, then either the SYN or
1373 * RST bit must be set. If the SYN bit is set, then
1374 * we expect the ACK field to be 0. If the ACK is
1375 * not set and if URG, PSH or FIN are set, consdier
1376 * that to indicate a bad TCP packet.
1377 */
1378 if ((flags == TH_SYN) && (tcp->th_ack != 0)) {
1379 /*
1380 * Cisco PIX sets the ACK field to a random value.
1381 * In light of this, do not set FI_BAD until a patch
1382 * is available from Cisco to ensure that
1383 * interoperability between existing systems is
1384 * achieved.
1385 */
1386 /*fin->fin_flx |= FI_BAD*/;
1387 /*DT1(ipf_fi_bad_th_syn_ack, fr_info_t *, fin);*/
1388 } else if (!(flags & (TH_RST|TH_SYN))) {
1389 fin->fin_flx |= FI_BAD;
1390 DT1(ipf_fi_bad_th_rst_syn, fr_info_t *, fin);
1391 } else if ((flags & (TH_URG|TH_PUSH|TH_FIN)) != 0) {
1392 fin->fin_flx |= FI_BAD;
1393 DT1(ipf_fi_bad_th_urg_push_fin, fr_info_t *, fin);
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
ipf_pr_udpcommon(fr_info_t * fin)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
ipf_pr_tcp(fr_info_t * fin)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
ipf_pr_udp(fr_info_t * fin)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
ipf_pr_esp(fr_info_t * fin)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
ipf_pr_ah(fr_info_t * fin)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
ipf_pr_gre(fr_info_t * fin)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
ipf_pr_ipv4hdr(fr_info_t * fin)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 = ntohs(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_MULTICAST(ntohl(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 == 1 && p == IPPROTO_TCP) {
1702 fin->fin_flx |= FI_SHORT; /* RFC 3128 */
1703 DT1(ipf_fi_tcp_frag_off_1, fr_info_t *, fin);
1704 }
1705 if (off != 0) {
1706 fin->fin_flx |= FI_FRAGBODY;
1707 off <<= 3;
1708 if ((off + fin->fin_dlen > 65535) ||
1709 (fin->fin_dlen == 0) ||
1710 ((morefrag != 0) && ((fin->fin_dlen & 7) != 0))) {
1711 /*
1712 * The length of the packet, starting at its
1713 * offset cannot exceed 65535 (0xffff) as the
1714 * length of an IP packet is only 16 bits.
1715 *
1716 * Any fragment that isn't the last fragment
1717 * must have a length greater than 0 and it
1718 * must be an even multiple of 8.
1719 */
1720 fi->fi_flx |= FI_BAD;
1721 DT1(ipf_fi_bad_fragbody_gt_65535, fr_info_t *, fin);
1722 }
1723 }
1724 }
1725 fin->fin_off = off;
1726
1727 /*
1728 * Call per-protocol setup and checking
1729 */
1730 if (p == IPPROTO_AH) {
1731 /*
1732 * Treat AH differently because we expect there to be another
1733 * layer 4 header after it.
1734 */
1735 p = ipf_pr_ah(fin);
1736 }
1737
1738 switch (p)
1739 {
1740 case IPPROTO_UDP :
1741 ipf_pr_udp(fin);
1742 break;
1743 case IPPROTO_TCP :
1744 ipf_pr_tcp(fin);
1745 break;
1746 case IPPROTO_ICMP :
1747 ipf_pr_icmp(fin);
1748 break;
1749 case IPPROTO_ESP :
1750 ipf_pr_esp(fin);
1751 break;
1752 case IPPROTO_GRE :
1753 ipf_pr_gre(fin);
1754 break;
1755 }
1756
1757 ip = fin->fin_ip;
1758 if (ip == NULL)
1759 return;
1760
1761 /*
1762 * If it is a standard IP header (no options), set the flag fields
1763 * which relate to options to 0.
1764 */
1765 if (hlen == sizeof(*ip)) {
1766 fi->fi_optmsk = 0;
1767 fi->fi_secmsk = 0;
1768 fi->fi_auth = 0;
1769 return;
1770 }
1771
1772 /*
1773 * So the IP header has some IP options attached. Walk the entire
1774 * list of options present with this packet and set flags to indicate
1775 * which ones are here and which ones are not. For the somewhat out
1776 * of date and obscure security classification options, set a flag to
1777 * represent which classification is present.
1778 */
1779 fi->fi_flx |= FI_OPTIONS;
1780
1781 for (s = (u_char *)(ip + 1), hlen -= (int)sizeof(*ip); hlen > 0; ) {
1782 opt = *s;
1783 if (opt == '\0')
1784 break;
1785 else if (opt == IPOPT_NOP)
1786 ol = 1;
1787 else {
1788 if (hlen < 2)
1789 break;
1790 ol = (int)*(s + 1);
1791 if (ol < 2 || ol > hlen)
1792 break;
1793 }
1794 for (i = 9, mv = 4; mv >= 0; ) {
1795 op = ipopts + i;
1796
1797 if ((opt == (u_char)op->ol_val) && (ol > 4)) {
1798 u_32_t doi;
1799
1800 switch (opt)
1801 {
1802 case IPOPT_SECURITY :
1803 if (optmsk & op->ol_bit) {
1804 fin->fin_flx |= FI_BAD;
1805 DT2(ipf_fi_bad_ipopt_security, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1806 } else {
1807 doi = ipf_checkripso(s);
1808 secmsk = doi >> 16;
1809 auth = doi & 0xffff;
1810 }
1811 break;
1812
1813 case IPOPT_CIPSO :
1814
1815 if (optmsk & op->ol_bit) {
1816 fin->fin_flx |= FI_BAD;
1817 DT2(ipf_fi_bad_ipopt_cipso, fr_info_t *, fin, u_short, (optmsk & op->ol_bit));
1818 } else {
1819 doi = ipf_checkcipso(fin,
1820 s, ol);
1821 secmsk = doi >> 16;
1822 auth = doi & 0xffff;
1823 }
1824 break;
1825 }
1826 optmsk |= op->ol_bit;
1827 }
1828
1829 if (opt < op->ol_val)
1830 i -= mv;
1831 else
1832 i += mv;
1833 mv--;
1834 }
1835 hlen -= ol;
1836 s += ol;
1837 }
1838
1839 /*
1840 *
1841 */
1842 if (auth && !(auth & 0x0100))
1843 auth &= 0xff00;
1844 fi->fi_optmsk = optmsk;
1845 fi->fi_secmsk = secmsk;
1846 fi->fi_auth = auth;
1847 }
1848
1849
1850 /* ------------------------------------------------------------------------ */
1851 /* Function: ipf_checkripso */
1852 /* Returns: void */
1853 /* Parameters: s(I) - pointer to start of RIPSO option */
1854 /* */
1855 /* ------------------------------------------------------------------------ */
1856 static u_32_t
ipf_checkripso(u_char * s)1857 ipf_checkripso(u_char *s)
1858 {
1859 const struct optlist *sp;
1860 u_short secmsk = 0, auth = 0;
1861 u_char sec;
1862 int j, m;
1863
1864 sec = *(s + 2); /* classification */
1865 for (j = 3, m = 2; m >= 0; ) {
1866 sp = secopt + j;
1867 if (sec == sp->ol_val) {
1868 secmsk |= sp->ol_bit;
1869 auth = *(s + 3);
1870 auth *= 256;
1871 auth += *(s + 4);
1872 break;
1873 }
1874 if (sec < sp->ol_val)
1875 j -= m;
1876 else
1877 j += m;
1878 m--;
1879 }
1880
1881 return (secmsk << 16) | auth;
1882 }
1883
1884
1885 /* ------------------------------------------------------------------------ */
1886 /* Function: ipf_checkcipso */
1887 /* Returns: u_32_t - 0 = failure, else the doi from the header */
1888 /* Parameters: fin(IO) - pointer to packet information */
1889 /* s(I) - pointer to start of CIPSO option */
1890 /* ol(I) - length of CIPSO option field */
1891 /* */
1892 /* This function returns the domain of integrity (DOI) field from the CIPSO */
1893 /* header and returns that whilst also storing the highest sensitivity */
1894 /* value found in the fr_info_t structure. */
1895 /* */
1896 /* No attempt is made to extract the category bitmaps as these are defined */
1897 /* by the user (rather than the protocol) and can be rather numerous on the */
1898 /* end nodes. */
1899 /* ------------------------------------------------------------------------ */
1900 static u_32_t
ipf_checkcipso(fr_info_t * fin,u_char * s,int ol)1901 ipf_checkcipso(fr_info_t *fin, u_char *s, int ol)
1902 {
1903 ipf_main_softc_t *softc = fin->fin_main_soft;
1904 fr_ip_t *fi;
1905 u_32_t doi;
1906 u_char *t, tag, tlen, sensitivity;
1907 int len;
1908
1909 if (ol < 6 || ol > 40) {
1910 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_bad);
1911 fin->fin_flx |= FI_BAD;
1912 DT2(ipf_fi_bad_checkcipso_ol, fr_info_t *, fin, u_int, ol);
1913 return (0);
1914 }
1915
1916 fi = &fin->fin_fi;
1917 fi->fi_sensitivity = 0;
1918 /*
1919 * The DOI field MUST be there.
1920 */
1921 bcopy(s + 2, &doi, sizeof(doi));
1922
1923 t = (u_char *)s + 6;
1924 for (len = ol - 6; len >= 2; len -= tlen, t+= tlen) {
1925 tag = *t;
1926 tlen = *(t + 1);
1927 if (tlen > len || tlen < 4 || tlen > 34) {
1928 LBUMPD(ipf_stats[fin->fin_out], fr_v4_cipso_tlen);
1929 fin->fin_flx |= FI_BAD;
1930 DT2(ipf_fi_bad_checkcipso_tlen, fr_info_t *, fin, u_int, tlen);
1931 return (0);
1932 }
1933
1934 sensitivity = 0;
1935 /*
1936 * Tag numbers 0, 1, 2, 5 are laid out in the CIPSO Internet
1937 * draft (16 July 1992) that has expired.
1938 */
1939 if (tag == 0) {
1940 fin->fin_flx |= FI_BAD;
1941 DT2(ipf_fi_bad_checkcipso_tag, fr_info_t *, fin, u_int, tag);
1942 continue;
1943 } else if (tag == 1) {
1944 if (*(t + 2) != 0) {
1945 fin->fin_flx |= FI_BAD;
1946 DT2(ipf_fi_bad_checkcipso_tag1_t2, fr_info_t *, fin, u_int, (*t + 2));
1947 continue;
1948 }
1949 sensitivity = *(t + 3);
1950 /* Category bitmap for categories 0-239 */
1951
1952 } else if (tag == 4) {
1953 if (*(t + 2) != 0) {
1954 fin->fin_flx |= FI_BAD;
1955 DT2(ipf_fi_bad_checkcipso_tag4_t2, fr_info_t *, fin, u_int, (*t + 2));
1956 continue;
1957 }
1958 sensitivity = *(t + 3);
1959 /* Enumerated categories, 16bits each, upto 15 */
1960
1961 } else if (tag == 5) {
1962 if (*(t + 2) != 0) {
1963 fin->fin_flx |= FI_BAD;
1964 DT2(ipf_fi_bad_checkcipso_tag5_t2, fr_info_t *, fin, u_int, (*t + 2));
1965 continue;
1966 }
1967 sensitivity = *(t + 3);
1968 /* Range of categories (2*16bits), up to 7 pairs */
1969
1970 } else if (tag > 127) {
1971 /* Custom defined DOI */
1972 ;
1973 } else {
1974 fin->fin_flx |= FI_BAD;
1975 DT2(ipf_fi_bad_checkcipso_tag127, fr_info_t *, fin, u_int, tag);
1976 continue;
1977 }
1978
1979 if (sensitivity > fi->fi_sensitivity)
1980 fi->fi_sensitivity = sensitivity;
1981 }
1982
1983 return (doi);
1984 }
1985
1986
1987 /* ------------------------------------------------------------------------ */
1988 /* Function: ipf_makefrip */
1989 /* Returns: int - 0 == packet ok, -1 == packet freed */
1990 /* Parameters: hlen(I) - length of IP packet header */
1991 /* ip(I) - pointer to the IP header */
1992 /* fin(IO) - pointer to packet information */
1993 /* */
1994 /* Compact the IP header into a structure which contains just the info. */
1995 /* which is useful for comparing IP headers with and store this information */
1996 /* in the fr_info_t structure pointer to by fin. At present, it is assumed */
1997 /* this function will be called with either an IPv4 or IPv6 packet. */
1998 /* ------------------------------------------------------------------------ */
1999 int
ipf_makefrip(int hlen,ip_t * ip,fr_info_t * fin)2000 ipf_makefrip(int hlen, ip_t *ip, fr_info_t *fin)
2001 {
2002 ipf_main_softc_t *softc = fin->fin_main_soft;
2003 int v;
2004
2005 fin->fin_depth = 0;
2006 fin->fin_hlen = (u_short)hlen;
2007 fin->fin_ip = ip;
2008 fin->fin_rule = 0xffffffff;
2009 fin->fin_group[0] = -1;
2010 fin->fin_group[1] = '\0';
2011 fin->fin_dp = (char *)ip + hlen;
2012
2013 v = fin->fin_v;
2014 if (v == 4) {
2015 fin->fin_plen = ntohs(ip->ip_len);
2016 fin->fin_dlen = fin->fin_plen - hlen;
2017 ipf_pr_ipv4hdr(fin);
2018 #ifdef USE_INET6
2019 } else if (v == 6) {
2020 fin->fin_plen = ntohs(((ip6_t *)ip)->ip6_plen);
2021 fin->fin_dlen = fin->fin_plen;
2022 fin->fin_plen += hlen;
2023
2024 ipf_pr_ipv6hdr(fin);
2025 #endif
2026 }
2027 if (fin->fin_ip == NULL) {
2028 LBUMP(ipf_stats[fin->fin_out].fr_ip_freed);
2029 return (-1);
2030 }
2031 return (0);
2032 }
2033
2034
2035 /* ------------------------------------------------------------------------ */
2036 /* Function: ipf_portcheck */
2037 /* Returns: int - 1 == port matched, 0 == port match failed */
2038 /* Parameters: frp(I) - pointer to port check `expression' */
2039 /* pop(I) - port number to evaluate */
2040 /* */
2041 /* Perform a comparison of a port number against some other(s), using a */
2042 /* structure with compare information stored in it. */
2043 /* ------------------------------------------------------------------------ */
2044 static inline int
ipf_portcheck(frpcmp_t * frp,u_32_t pop)2045 ipf_portcheck(frpcmp_t *frp, u_32_t pop)
2046 {
2047 int err = 1;
2048 u_32_t po;
2049
2050 po = frp->frp_port;
2051
2052 /*
2053 * Do opposite test to that required and continue if that succeeds.
2054 */
2055 switch (frp->frp_cmp)
2056 {
2057 case FR_EQUAL :
2058 if (pop != po) /* EQUAL */
2059 err = 0;
2060 break;
2061 case FR_NEQUAL :
2062 if (pop == po) /* NOTEQUAL */
2063 err = 0;
2064 break;
2065 case FR_LESST :
2066 if (pop >= po) /* LESSTHAN */
2067 err = 0;
2068 break;
2069 case FR_GREATERT :
2070 if (pop <= po) /* GREATERTHAN */
2071 err = 0;
2072 break;
2073 case FR_LESSTE :
2074 if (pop > po) /* LT or EQ */
2075 err = 0;
2076 break;
2077 case FR_GREATERTE :
2078 if (pop < po) /* GT or EQ */
2079 err = 0;
2080 break;
2081 case FR_OUTRANGE :
2082 if (pop >= po && pop <= frp->frp_top) /* Out of range */
2083 err = 0;
2084 break;
2085 case FR_INRANGE :
2086 if (pop <= po || pop >= frp->frp_top) /* In range */
2087 err = 0;
2088 break;
2089 case FR_INCRANGE :
2090 if (pop < po || pop > frp->frp_top) /* Inclusive range */
2091 err = 0;
2092 break;
2093 default :
2094 break;
2095 }
2096 return (err);
2097 }
2098
2099
2100 /* ------------------------------------------------------------------------ */
2101 /* Function: ipf_tcpudpchk */
2102 /* Returns: int - 1 == protocol matched, 0 == check failed */
2103 /* Parameters: fda(I) - pointer to packet information */
2104 /* ft(I) - pointer to structure with comparison data */
2105 /* */
2106 /* Compares the current pcket (assuming it is TCP/UDP) information with a */
2107 /* structure containing information that we want to match against. */
2108 /* ------------------------------------------------------------------------ */
2109 int
ipf_tcpudpchk(fr_ip_t * fi,frtuc_t * ft)2110 ipf_tcpudpchk(fr_ip_t *fi, frtuc_t *ft)
2111 {
2112 int err = 1;
2113
2114 /*
2115 * Both ports should *always* be in the first fragment.
2116 * So far, I cannot find any cases where they can not be.
2117 *
2118 * compare destination ports
2119 */
2120 if (ft->ftu_dcmp)
2121 err = ipf_portcheck(&ft->ftu_dst, fi->fi_ports[1]);
2122
2123 /*
2124 * compare source ports
2125 */
2126 if (err && ft->ftu_scmp)
2127 err = ipf_portcheck(&ft->ftu_src, fi->fi_ports[0]);
2128
2129 /*
2130 * If we don't have all the TCP/UDP header, then how can we
2131 * expect to do any sort of match on it ? If we were looking for
2132 * TCP flags, then NO match. If not, then match (which should
2133 * satisfy the "short" class too).
2134 */
2135 if (err && (fi->fi_p == IPPROTO_TCP)) {
2136 if (fi->fi_flx & FI_SHORT)
2137 return (!(ft->ftu_tcpf | ft->ftu_tcpfm));
2138 /*
2139 * Match the flags ? If not, abort this match.
2140 */
2141 if (ft->ftu_tcpfm &&
2142 ft->ftu_tcpf != (fi->fi_tcpf & ft->ftu_tcpfm)) {
2143 FR_DEBUG(("f. %#x & %#x != %#x\n", fi->fi_tcpf,
2144 ft->ftu_tcpfm, ft->ftu_tcpf));
2145 err = 0;
2146 }
2147 }
2148 return (err);
2149 }
2150
2151
2152 /* ------------------------------------------------------------------------ */
2153 /* Function: ipf_check_ipf */
2154 /* Returns: int - 0 == match, else no match */
2155 /* Parameters: fin(I) - pointer to packet information */
2156 /* fr(I) - pointer to filter rule */
2157 /* portcmp(I) - flag indicating whether to attempt matching on */
2158 /* TCP/UDP port data. */
2159 /* */
2160 /* Check to see if a packet matches an IPFilter rule. Checks of addresses, */
2161 /* port numbers, etc, for "standard" IPFilter rules are all orchestrated in */
2162 /* this function. */
2163 /* ------------------------------------------------------------------------ */
2164 static inline int
ipf_check_ipf(fr_info_t * fin,frentry_t * fr,int portcmp)2165 ipf_check_ipf(fr_info_t *fin, frentry_t *fr, int portcmp)
2166 {
2167 u_32_t *ld, *lm, *lip;
2168 fripf_t *fri;
2169 fr_ip_t *fi;
2170 int i;
2171
2172 fi = &fin->fin_fi;
2173 fri = fr->fr_ipf;
2174 lip = (u_32_t *)fi;
2175 lm = (u_32_t *)&fri->fri_mip;
2176 ld = (u_32_t *)&fri->fri_ip;
2177
2178 /*
2179 * first 32 bits to check coversion:
2180 * IP version, TOS, TTL, protocol
2181 */
2182 i = ((*lip & *lm) != *ld);
2183 FR_DEBUG(("0. %#08x & %#08x != %#08x\n",
2184 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2185 if (i)
2186 return (1);
2187
2188 /*
2189 * Next 32 bits is a constructed bitmask indicating which IP options
2190 * are present (if any) in this packet.
2191 */
2192 lip++, lm++, ld++;
2193 i = ((*lip & *lm) != *ld);
2194 FR_DEBUG(("1. %#08x & %#08x != %#08x\n",
2195 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2196 if (i != 0)
2197 return (1);
2198
2199 lip++, lm++, ld++;
2200 /*
2201 * Unrolled loops (4 each, for 32 bits) for address checks.
2202 */
2203 /*
2204 * Check the source address.
2205 */
2206 if (fr->fr_satype == FRI_LOOKUP) {
2207 i = (*fr->fr_srcfunc)(fin->fin_main_soft, fr->fr_srcptr,
2208 fi->fi_v, lip, fin->fin_plen);
2209 if (i == -1)
2210 return (1);
2211 lip += 3;
2212 lm += 3;
2213 ld += 3;
2214 } else {
2215 i = ((*lip & *lm) != *ld);
2216 FR_DEBUG(("2a. %#08x & %#08x != %#08x\n",
2217 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2218 if (fi->fi_v == 6) {
2219 lip++, lm++, ld++;
2220 i |= ((*lip & *lm) != *ld);
2221 FR_DEBUG(("2b. %#08x & %#08x != %#08x\n",
2222 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2223 lip++, lm++, ld++;
2224 i |= ((*lip & *lm) != *ld);
2225 FR_DEBUG(("2c. %#08x & %#08x != %#08x\n",
2226 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2227 lip++, lm++, ld++;
2228 i |= ((*lip & *lm) != *ld);
2229 FR_DEBUG(("2d. %#08x & %#08x != %#08x\n",
2230 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2231 } else {
2232 lip += 3;
2233 lm += 3;
2234 ld += 3;
2235 }
2236 }
2237 i ^= (fr->fr_flags & FR_NOTSRCIP) >> 6;
2238 if (i != 0)
2239 return (1);
2240
2241 /*
2242 * Check the destination address.
2243 */
2244 lip++, lm++, ld++;
2245 if (fr->fr_datype == FRI_LOOKUP) {
2246 i = (*fr->fr_dstfunc)(fin->fin_main_soft, fr->fr_dstptr,
2247 fi->fi_v, lip, fin->fin_plen);
2248 if (i == -1)
2249 return (1);
2250 lip += 3;
2251 lm += 3;
2252 ld += 3;
2253 } else {
2254 i = ((*lip & *lm) != *ld);
2255 FR_DEBUG(("3a. %#08x & %#08x != %#08x\n",
2256 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2257 if (fi->fi_v == 6) {
2258 lip++, lm++, ld++;
2259 i |= ((*lip & *lm) != *ld);
2260 FR_DEBUG(("3b. %#08x & %#08x != %#08x\n",
2261 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2262 lip++, lm++, ld++;
2263 i |= ((*lip & *lm) != *ld);
2264 FR_DEBUG(("3c. %#08x & %#08x != %#08x\n",
2265 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2266 lip++, lm++, ld++;
2267 i |= ((*lip & *lm) != *ld);
2268 FR_DEBUG(("3d. %#08x & %#08x != %#08x\n",
2269 ntohl(*lip), ntohl(*lm), ntohl(*ld)));
2270 } else {
2271 lip += 3;
2272 lm += 3;
2273 ld += 3;
2274 }
2275 }
2276 i ^= (fr->fr_flags & FR_NOTDSTIP) >> 7;
2277 if (i != 0)
2278 return (1);
2279 /*
2280 * IP addresses matched. The next 32bits contains:
2281 * mast of old IP header security & authentication bits.
2282 */
2283 lip++, lm++, ld++;
2284 i = (*ld - (*lip & *lm));
2285 FR_DEBUG(("4. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2286
2287 /*
2288 * Next we have 32 bits of packet flags.
2289 */
2290 lip++, lm++, ld++;
2291 i |= (*ld - (*lip & *lm));
2292 FR_DEBUG(("5. %#08x & %#08x != %#08x\n", *lip, *lm, *ld));
2293
2294 if (i == 0) {
2295 /*
2296 * If a fragment, then only the first has what we're
2297 * looking for here...
2298 */
2299 if (portcmp) {
2300 if (!ipf_tcpudpchk(&fin->fin_fi, &fr->fr_tuc))
2301 i = 1;
2302 } else {
2303 if (fr->fr_dcmp || fr->fr_scmp ||
2304 fr->fr_tcpf || fr->fr_tcpfm)
2305 i = 1;
2306 if (fr->fr_icmpm || fr->fr_icmp) {
2307 if (((fi->fi_p != IPPROTO_ICMP) &&
2308 (fi->fi_p != IPPROTO_ICMPV6)) ||
2309 fin->fin_off || (fin->fin_dlen < 2))
2310 i = 1;
2311 else if ((fin->fin_data[0] & fr->fr_icmpm) !=
2312 fr->fr_icmp) {
2313 FR_DEBUG(("i. %#x & %#x != %#x\n",
2314 fin->fin_data[0],
2315 fr->fr_icmpm, fr->fr_icmp));
2316 i = 1;
2317 }
2318 }
2319 }
2320 }
2321 return (i);
2322 }
2323
2324
2325 /* ------------------------------------------------------------------------ */
2326 /* Function: ipf_scanlist */
2327 /* Returns: int - result flags of scanning filter list */
2328 /* Parameters: fin(I) - pointer to packet information */
2329 /* pass(I) - default result to return for filtering */
2330 /* */
2331 /* Check the input/output list of rules for a match to the current packet. */
2332 /* If a match is found, the value of fr_flags from the rule becomes the */
2333 /* return value and fin->fin_fr points to the matched rule. */
2334 /* */
2335 /* This function may be called recursively upto 16 times (limit inbuilt.) */
2336 /* When unwinding, it should finish up with fin_depth as 0. */
2337 /* */
2338 /* Could be per interface, but this gets real nasty when you don't have, */
2339 /* or can't easily change, the kernel source code to . */
2340 /* ------------------------------------------------------------------------ */
2341 int
ipf_scanlist(fr_info_t * fin,u_32_t pass)2342 ipf_scanlist(fr_info_t *fin, u_32_t pass)
2343 {
2344 ipf_main_softc_t *softc = fin->fin_main_soft;
2345 int rulen, portcmp, off, skip;
2346 struct frentry *fr, *fnext;
2347 u_32_t passt, passo;
2348
2349 /*
2350 * Do not allow nesting deeper than 16 levels.
2351 */
2352 if (fin->fin_depth >= 16)
2353 return (pass);
2354
2355 fr = fin->fin_fr;
2356
2357 /*
2358 * If there are no rules in this list, return now.
2359 */
2360 if (fr == NULL)
2361 return (pass);
2362
2363 skip = 0;
2364 portcmp = 0;
2365 fin->fin_depth++;
2366 fin->fin_fr = NULL;
2367 off = fin->fin_off;
2368
2369 if ((fin->fin_flx & FI_TCPUDP) && (fin->fin_dlen > 3) && !off)
2370 portcmp = 1;
2371
2372 for (rulen = 0; fr; fr = fnext, rulen++) {
2373 fnext = fr->fr_next;
2374 if (skip != 0) {
2375 FR_VERBOSE(("SKIP %d (%#x)\n", skip, fr->fr_flags));
2376 skip--;
2377 continue;
2378 }
2379
2380 /*
2381 * In all checks below, a null (zero) value in the
2382 * filter struture is taken to mean a wildcard.
2383 *
2384 * check that we are working for the right interface
2385 */
2386 #ifdef _KERNEL
2387 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2388 continue;
2389 #else
2390 if (opts & (OPT_VERBOSE|OPT_DEBUG))
2391 printf("\n");
2392 FR_VERBOSE(("%c", FR_ISSKIP(pass) ? 's' :
2393 FR_ISPASS(pass) ? 'p' :
2394 FR_ISACCOUNT(pass) ? 'A' :
2395 FR_ISAUTH(pass) ? 'a' :
2396 (pass & FR_NOMATCH) ? 'n' :'b'));
2397 if (fr->fr_ifa && fr->fr_ifa != fin->fin_ifp)
2398 continue;
2399 FR_VERBOSE((":i"));
2400 #endif
2401
2402 switch (fr->fr_type)
2403 {
2404 case FR_T_IPF :
2405 case FR_T_IPF_BUILTIN :
2406 if (ipf_check_ipf(fin, fr, portcmp))
2407 continue;
2408 break;
2409 #if defined(IPFILTER_BPF)
2410 case FR_T_BPFOPC :
2411 case FR_T_BPFOPC_BUILTIN :
2412 {
2413 u_char *mc;
2414 int wlen;
2415
2416 if (*fin->fin_mp == NULL)
2417 continue;
2418 if (fin->fin_family != fr->fr_family)
2419 continue;
2420 mc = (u_char *)fin->fin_m;
2421 wlen = fin->fin_dlen + fin->fin_hlen;
2422 if (!bpf_filter(fr->fr_data, mc, wlen, 0))
2423 continue;
2424 break;
2425 }
2426 #endif
2427 case FR_T_CALLFUNC_BUILTIN :
2428 {
2429 frentry_t *f;
2430
2431 f = (*fr->fr_func)(fin, &pass);
2432 if (f != NULL)
2433 fr = f;
2434 else
2435 continue;
2436 break;
2437 }
2438
2439 case FR_T_IPFEXPR :
2440 case FR_T_IPFEXPR_BUILTIN :
2441 if (fin->fin_family != fr->fr_family)
2442 continue;
2443 if (ipf_fr_matcharray(fin, fr->fr_data) == 0)
2444 continue;
2445 break;
2446
2447 default :
2448 break;
2449 }
2450
2451 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
2452 if (fin->fin_nattag == NULL)
2453 continue;
2454 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag) == 0)
2455 continue;
2456 }
2457 FR_VERBOSE(("=%d/%d.%d *", fr->fr_grhead, fr->fr_group, rulen));
2458
2459 passt = fr->fr_flags;
2460
2461 /*
2462 * If the rule is a "call now" rule, then call the function
2463 * in the rule, if it exists and use the results from that.
2464 * If the function pointer is bad, just make like we ignore
2465 * it, except for increasing the hit counter.
2466 */
2467 if ((passt & FR_CALLNOW) != 0) {
2468 frentry_t *frs;
2469
2470 ATOMIC_INC64(fr->fr_hits);
2471 if ((fr->fr_func == NULL) ||
2472 (fr->fr_func == (ipfunc_t)-1))
2473 continue;
2474
2475 frs = fin->fin_fr;
2476 fin->fin_fr = fr;
2477 fr = (*fr->fr_func)(fin, &passt);
2478 if (fr == NULL) {
2479 fin->fin_fr = frs;
2480 continue;
2481 }
2482 passt = fr->fr_flags;
2483 }
2484 fin->fin_fr = fr;
2485
2486 #ifdef IPFILTER_LOG
2487 /*
2488 * Just log this packet...
2489 */
2490 if ((passt & FR_LOGMASK) == FR_LOG) {
2491 if (ipf_log_pkt(fin, passt) == -1) {
2492 if (passt & FR_LOGORBLOCK) {
2493 DT(frb_logfail);
2494 passt &= ~FR_CMDMASK;
2495 passt |= FR_BLOCK|FR_QUICK;
2496 fin->fin_reason = FRB_LOGFAIL;
2497 }
2498 }
2499 }
2500 #endif /* IPFILTER_LOG */
2501
2502 MUTEX_ENTER(&fr->fr_lock);
2503 fr->fr_bytes += (U_QUAD_T)fin->fin_plen;
2504 fr->fr_hits++;
2505 MUTEX_EXIT(&fr->fr_lock);
2506 fin->fin_rule = rulen;
2507
2508 passo = pass;
2509 if (FR_ISSKIP(passt)) {
2510 skip = fr->fr_arg;
2511 continue;
2512 } else if (((passt & FR_LOGMASK) != FR_LOG) &&
2513 ((passt & FR_LOGMASK) != FR_DECAPSULATE)) {
2514 pass = passt;
2515 }
2516
2517 if (passt & (FR_RETICMP|FR_FAKEICMP))
2518 fin->fin_icode = fr->fr_icode;
2519
2520 if (fr->fr_group != -1) {
2521 (void) strncpy(fin->fin_group,
2522 FR_NAME(fr, fr_group),
2523 strlen(FR_NAME(fr, fr_group)));
2524 } else {
2525 fin->fin_group[0] = '\0';
2526 }
2527
2528 FR_DEBUG(("pass %#x/%#x/%x\n", passo, pass, passt));
2529
2530 if (fr->fr_grphead != NULL) {
2531 fin->fin_fr = fr->fr_grphead->fg_start;
2532 FR_VERBOSE(("group %s\n", FR_NAME(fr, fr_grhead)));
2533
2534 if (FR_ISDECAPS(passt))
2535 passt = ipf_decaps(fin, pass, fr->fr_icode);
2536 else
2537 passt = ipf_scanlist(fin, pass);
2538
2539 if (fin->fin_fr == NULL) {
2540 fin->fin_rule = rulen;
2541 if (fr->fr_group != -1)
2542 (void) strncpy(fin->fin_group,
2543 fr->fr_names +
2544 fr->fr_group,
2545 strlen(fr->fr_names +
2546 fr->fr_group));
2547 fin->fin_fr = fr;
2548 passt = pass;
2549 }
2550 pass = passt;
2551 }
2552
2553 if (pass & FR_QUICK) {
2554 /*
2555 * Finally, if we've asked to track state for this
2556 * packet, set it up. Add state for "quick" rules
2557 * here so that if the action fails we can consider
2558 * the rule to "not match" and keep on processing
2559 * filter rules.
2560 */
2561 if ((pass & FR_KEEPSTATE) && !FR_ISAUTH(pass) &&
2562 !(fin->fin_flx & FI_STATE)) {
2563 int out = fin->fin_out;
2564
2565 fin->fin_fr = fr;
2566 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2567 LBUMPD(ipf_stats[out], fr_ads);
2568 } else {
2569 LBUMPD(ipf_stats[out], fr_bads);
2570 pass = passo;
2571 continue;
2572 }
2573 }
2574 break;
2575 }
2576 }
2577 fin->fin_depth--;
2578 return (pass);
2579 }
2580
2581
2582 /* ------------------------------------------------------------------------ */
2583 /* Function: ipf_acctpkt */
2584 /* Returns: frentry_t* - always returns NULL */
2585 /* Parameters: fin(I) - pointer to packet information */
2586 /* passp(IO) - pointer to current/new filter decision (unused) */
2587 /* */
2588 /* Checks a packet against accounting rules, if there are any for the given */
2589 /* IP protocol version. */
2590 /* */
2591 /* N.B.: this function returns NULL to match the prototype used by other */
2592 /* functions called from the IPFilter "mainline" in ipf_check(). */
2593 /* ------------------------------------------------------------------------ */
2594 frentry_t *
ipf_acctpkt(fr_info_t * fin,u_32_t * passp __unused)2595 ipf_acctpkt(fr_info_t *fin, u_32_t *passp __unused)
2596 {
2597 ipf_main_softc_t *softc = fin->fin_main_soft;
2598 char group[FR_GROUPLEN];
2599 frentry_t *fr, *frsave;
2600 u_32_t pass, rulen;
2601
2602 fr = softc->ipf_acct[fin->fin_out][softc->ipf_active];
2603
2604 if (fr != NULL) {
2605 frsave = fin->fin_fr;
2606 bcopy(fin->fin_group, group, FR_GROUPLEN);
2607 rulen = fin->fin_rule;
2608 fin->fin_fr = fr;
2609 pass = ipf_scanlist(fin, FR_NOMATCH);
2610 if (FR_ISACCOUNT(pass)) {
2611 LBUMPD(ipf_stats[0], fr_acct);
2612 }
2613 fin->fin_fr = frsave;
2614 bcopy(group, fin->fin_group, FR_GROUPLEN);
2615 fin->fin_rule = rulen;
2616 }
2617 return (NULL);
2618 }
2619
2620
2621 /* ------------------------------------------------------------------------ */
2622 /* Function: ipf_firewall */
2623 /* Returns: frentry_t* - returns pointer to matched rule, if no matches */
2624 /* were found, returns NULL. */
2625 /* Parameters: fin(I) - pointer to packet information */
2626 /* passp(IO) - pointer to current/new filter decision (unused) */
2627 /* */
2628 /* Applies an appropriate set of firewall rules to the packet, to see if */
2629 /* there are any matches. The first check is to see if a match can be seen */
2630 /* in the cache. If not, then search an appropriate list of rules. Once a */
2631 /* matching rule is found, take any appropriate actions as defined by the */
2632 /* rule - except logging. */
2633 /* ------------------------------------------------------------------------ */
2634 static frentry_t *
ipf_firewall(fr_info_t * fin,u_32_t * passp)2635 ipf_firewall(fr_info_t *fin, u_32_t *passp)
2636 {
2637 ipf_main_softc_t *softc = fin->fin_main_soft;
2638 frentry_t *fr;
2639 u_32_t pass;
2640 int out;
2641
2642 out = fin->fin_out;
2643 pass = *passp;
2644
2645 /*
2646 * This rule cache will only affect packets that are not being
2647 * statefully filtered.
2648 */
2649 fin->fin_fr = softc->ipf_rules[out][softc->ipf_active];
2650 if (fin->fin_fr != NULL)
2651 pass = ipf_scanlist(fin, softc->ipf_pass);
2652
2653 if ((pass & FR_NOMATCH)) {
2654 LBUMPD(ipf_stats[out], fr_nom);
2655 }
2656 fr = fin->fin_fr;
2657
2658 /*
2659 * Apply packets per second rate-limiting to a rule as required.
2660 */
2661 if ((fr != NULL) && (fr->fr_pps != 0) &&
2662 !ppsratecheck(&fr->fr_lastpkt, &fr->fr_curpps, fr->fr_pps)) {
2663 DT2(frb_ppsrate, fr_info_t *, fin, frentry_t *, fr);
2664 pass &= ~(FR_CMDMASK|FR_RETICMP|FR_RETRST);
2665 pass |= FR_BLOCK;
2666 LBUMPD(ipf_stats[out], fr_ppshit);
2667 fin->fin_reason = FRB_PPSRATE;
2668 }
2669
2670 /*
2671 * If we fail to add a packet to the authorization queue, then we
2672 * drop the packet later. However, if it was added then pretend
2673 * we've dropped it already.
2674 */
2675 if (FR_ISAUTH(pass)) {
2676 if (ipf_auth_new(fin->fin_m, fin) != 0) {
2677 DT1(frb_authnew, fr_info_t *, fin);
2678 fin->fin_m = *fin->fin_mp = NULL;
2679 fin->fin_reason = FRB_AUTHNEW;
2680 fin->fin_error = 0;
2681 } else {
2682 IPFERROR(1);
2683 fin->fin_error = ENOSPC;
2684 }
2685 }
2686
2687 if ((fr != NULL) && (fr->fr_func != NULL) &&
2688 (fr->fr_func != (ipfunc_t)-1) && !(pass & FR_CALLNOW))
2689 (void) (*fr->fr_func)(fin, &pass);
2690
2691 /*
2692 * If a rule is a pre-auth rule, check again in the list of rules
2693 * loaded for authenticated use. It does not particulary matter
2694 * if this search fails because a "preauth" result, from a rule,
2695 * is treated as "not a pass", hence the packet is blocked.
2696 */
2697 if (FR_ISPREAUTH(pass)) {
2698 pass = ipf_auth_pre_scanlist(softc, fin, pass);
2699 }
2700
2701 /*
2702 * If the rule has "keep frag" and the packet is actually a fragment,
2703 * then create a fragment state entry.
2704 */
2705 if (pass & FR_KEEPFRAG) {
2706 if (fin->fin_flx & FI_FRAG) {
2707 if (ipf_frag_new(softc, fin, pass) == -1) {
2708 LBUMP(ipf_stats[out].fr_bnfr);
2709 } else {
2710 LBUMP(ipf_stats[out].fr_nfr);
2711 }
2712 } else {
2713 LBUMP(ipf_stats[out].fr_cfr);
2714 }
2715 }
2716
2717 fr = fin->fin_fr;
2718 *passp = pass;
2719
2720 return (fr);
2721 }
2722
2723
2724 /* ------------------------------------------------------------------------ */
2725 /* Function: ipf_check */
2726 /* Returns: int - 0 == packet allowed through, */
2727 /* User space: */
2728 /* -1 == packet blocked */
2729 /* 1 == packet not matched */
2730 /* -2 == requires authentication */
2731 /* Kernel: */
2732 /* > 0 == filter error # for packet */
2733 /* Parameters: ctx(I) - pointer to the instance context */
2734 /* ip(I) - pointer to start of IPv4/6 packet */
2735 /* hlen(I) - length of header */
2736 /* ifp(I) - pointer to interface this packet is on */
2737 /* out(I) - 0 == packet going in, 1 == packet going out */
2738 /* mp(IO) - pointer to caller's buffer pointer that holds this */
2739 /* IP packet. */
2740 /* Solaris: */
2741 /* qpi(I) - pointer to STREAMS queue information for this */
2742 /* interface & direction. */
2743 /* */
2744 /* ipf_check() is the master function for all IPFilter packet processing. */
2745 /* It orchestrates: Network Address Translation (NAT), checking for packet */
2746 /* authorisation (or pre-authorisation), presence of related state info., */
2747 /* generating log entries, IP packet accounting, routing of packets as */
2748 /* directed by firewall rules and of course whether or not to allow the */
2749 /* packet to be further processed by the kernel. */
2750 /* */
2751 /* For packets blocked, the contents of "mp" will be NULL'd and the buffer */
2752 /* freed. Packets passed may be returned with the pointer pointed to by */
2753 /* by "mp" changed to a new buffer. */
2754 /* ------------------------------------------------------------------------ */
2755 int
ipf_check(void * ctx,ip_t * ip,int hlen,struct ifnet * ifp,int out,void * qif,mb_t ** mp)2756 ipf_check(void *ctx, ip_t *ip, int hlen, struct ifnet *ifp, int out
2757 #if defined(_KERNEL) && SOLARIS
2758 , void* qif, mb_t **mp)
2759 #else
2760 , mb_t **mp)
2761 #endif
2762 {
2763 /*
2764 * The above really sucks, but short of writing a diff
2765 */
2766 ipf_main_softc_t *softc = ctx;
2767 fr_info_t frinfo;
2768 fr_info_t *fin = &frinfo;
2769 u_32_t pass = softc->ipf_pass;
2770 frentry_t *fr = NULL;
2771 int v = IP_V(ip);
2772 mb_t *mc = NULL;
2773 mb_t *m;
2774 /*
2775 * The first part of ipf_check() deals with making sure that what goes
2776 * into the filtering engine makes some sense. Information about the
2777 * the packet is distilled, collected into a fr_info_t structure and
2778 * the an attempt to ensure the buffer the packet is in is big enough
2779 * to hold all the required packet headers.
2780 */
2781 #ifdef _KERNEL
2782 # if SOLARIS
2783 qpktinfo_t *qpi = qif;
2784
2785 # ifdef __sparc
2786 if ((u_int)ip & 0x3)
2787 return (2);
2788 # endif
2789 # else
2790 SPL_INT(s);
2791 # endif
2792
2793 if (softc->ipf_running <= 0) {
2794 return (0);
2795 }
2796
2797 bzero((char *)fin, sizeof(*fin));
2798
2799 # if SOLARIS
2800 if (qpi->qpi_flags & QF_BROADCAST)
2801 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2802 if (qpi->qpi_flags & QF_MULTICAST)
2803 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2804 m = qpi->qpi_m;
2805 fin->fin_qfm = m;
2806 fin->fin_qpi = qpi;
2807 # else /* SOLARIS */
2808
2809 m = *mp;
2810
2811 # if defined(M_MCAST)
2812 if ((m->m_flags & M_MCAST) != 0)
2813 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2814 # endif
2815 # if defined(M_MLOOP)
2816 if ((m->m_flags & M_MLOOP) != 0)
2817 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2818 # endif
2819 # if defined(M_BCAST)
2820 if ((m->m_flags & M_BCAST) != 0)
2821 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2822 # endif
2823 # ifdef M_CANFASTFWD
2824 /*
2825 * XXX For now, IP Filter and fast-forwarding of cached flows
2826 * XXX are mutually exclusive. Eventually, IP Filter should
2827 * XXX get a "can-fast-forward" filter rule.
2828 */
2829 m->m_flags &= ~M_CANFASTFWD;
2830 # endif /* M_CANFASTFWD */
2831 # if defined(CSUM_DELAY_DATA) && !defined(__FreeBSD__)
2832 /*
2833 * disable delayed checksums.
2834 */
2835 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2836 in_delayed_cksum(m);
2837 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
2838 }
2839 # endif /* CSUM_DELAY_DATA */
2840 # endif /* SOLARIS */
2841 #else
2842 bzero((char *)fin, sizeof(*fin));
2843 m = *mp;
2844 # if defined(M_MCAST)
2845 if ((m->m_flags & M_MCAST) != 0)
2846 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2847 # endif
2848 # if defined(M_MLOOP)
2849 if ((m->m_flags & M_MLOOP) != 0)
2850 fin->fin_flx |= FI_MBCAST|FI_MULTICAST;
2851 # endif
2852 # if defined(M_BCAST)
2853 if ((m->m_flags & M_BCAST) != 0)
2854 fin->fin_flx |= FI_MBCAST|FI_BROADCAST;
2855 # endif
2856 #endif /* _KERNEL */
2857
2858 fin->fin_v = v;
2859 fin->fin_m = m;
2860 fin->fin_ip = ip;
2861 fin->fin_mp = mp;
2862 fin->fin_out = out;
2863 fin->fin_ifp = ifp;
2864 fin->fin_error = ENETUNREACH;
2865 fin->fin_hlen = (u_short)hlen;
2866 fin->fin_dp = (char *)ip + hlen;
2867 fin->fin_main_soft = softc;
2868
2869 fin->fin_ipoff = (char *)ip - MTOD(m, char *);
2870
2871 SPL_NET(s);
2872
2873 #ifdef USE_INET6
2874 if (v == 6) {
2875 LBUMP(ipf_stats[out].fr_ipv6);
2876 /*
2877 * Jumbo grams are quite likely too big for internal buffer
2878 * structures to handle comfortably, for now, so just drop
2879 * them.
2880 */
2881 if (((ip6_t *)ip)->ip6_plen == 0) {
2882 DT1(frb_jumbo, ip6_t *, (ip6_t *)ip);
2883 pass = FR_BLOCK|FR_NOMATCH;
2884 fin->fin_reason = FRB_JUMBO;
2885 goto finished;
2886 }
2887 fin->fin_family = AF_INET6;
2888 } else
2889 #endif
2890 {
2891 fin->fin_family = AF_INET;
2892 }
2893
2894 if (ipf_makefrip(hlen, ip, fin) == -1) {
2895 DT1(frb_makefrip, fr_info_t *, fin);
2896 pass = FR_BLOCK|FR_NOMATCH;
2897 fin->fin_reason = FRB_MAKEFRIP;
2898 goto finished;
2899 }
2900
2901 /*
2902 * For at least IPv6 packets, if a m_pullup() fails then this pointer
2903 * becomes NULL and so we have no packet to free.
2904 */
2905 if (*fin->fin_mp == NULL)
2906 goto finished;
2907
2908 if (!out) {
2909 if (v == 4) {
2910 if (softc->ipf_chksrc && !ipf_verifysrc(fin)) {
2911 LBUMPD(ipf_stats[0], fr_v4_badsrc);
2912 fin->fin_flx |= FI_BADSRC;
2913 }
2914 if (fin->fin_ip->ip_ttl < softc->ipf_minttl) {
2915 LBUMPD(ipf_stats[0], fr_v4_badttl);
2916 fin->fin_flx |= FI_LOWTTL;
2917 }
2918 }
2919 #ifdef USE_INET6
2920 else if (v == 6) {
2921 if (((ip6_t *)ip)->ip6_hlim < softc->ipf_minttl) {
2922 LBUMPD(ipf_stats[0], fr_v6_badttl);
2923 fin->fin_flx |= FI_LOWTTL;
2924 }
2925 }
2926 #endif
2927 }
2928
2929 if (fin->fin_flx & FI_SHORT) {
2930 LBUMPD(ipf_stats[out], fr_short);
2931 }
2932
2933 READ_ENTER(&softc->ipf_mutex);
2934
2935 if (!out) {
2936 switch (fin->fin_v)
2937 {
2938 case 4 :
2939 if (ipf_nat_checkin(fin, &pass) == -1) {
2940 goto filterdone;
2941 }
2942 break;
2943 #ifdef USE_INET6
2944 case 6 :
2945 if (ipf_nat6_checkin(fin, &pass) == -1) {
2946 goto filterdone;
2947 }
2948 break;
2949 #endif
2950 default :
2951 break;
2952 }
2953 }
2954 /*
2955 * Check auth now.
2956 * If a packet is found in the auth table, then skip checking
2957 * the access lists for permission but we do need to consider
2958 * the result as if it were from the ACL's. In addition, being
2959 * found in the auth table means it has been seen before, so do
2960 * not pass it through accounting (again), lest it be counted twice.
2961 */
2962 fr = ipf_auth_check(fin, &pass);
2963 if (!out && (fr == NULL))
2964 (void) ipf_acctpkt(fin, NULL);
2965
2966 if (fr == NULL) {
2967 if ((fin->fin_flx & FI_FRAG) != 0)
2968 fr = ipf_frag_known(fin, &pass);
2969
2970 if (fr == NULL)
2971 fr = ipf_state_check(fin, &pass);
2972 }
2973
2974 if ((pass & FR_NOMATCH) || (fr == NULL))
2975 fr = ipf_firewall(fin, &pass);
2976
2977 /*
2978 * If we've asked to track state for this packet, set it up.
2979 * Here rather than ipf_firewall because ipf_checkauth may decide
2980 * to return a packet for "keep state"
2981 */
2982 if ((pass & FR_KEEPSTATE) && (fin->fin_m != NULL) &&
2983 !(fin->fin_flx & FI_STATE)) {
2984 if (ipf_state_add(softc, fin, NULL, 0) == 0) {
2985 LBUMP(ipf_stats[out].fr_ads);
2986 } else {
2987 LBUMP(ipf_stats[out].fr_bads);
2988 if (FR_ISPASS(pass)) {
2989 DT(frb_stateadd);
2990 pass &= ~FR_CMDMASK;
2991 pass |= FR_BLOCK;
2992 fin->fin_reason = FRB_STATEADD;
2993 }
2994 }
2995 }
2996
2997 fin->fin_fr = fr;
2998 if ((fr != NULL) && !(fin->fin_flx & FI_STATE)) {
2999 fin->fin_dif = &fr->fr_dif;
3000 fin->fin_tif = &fr->fr_tifs[fin->fin_rev];
3001 }
3002
3003 /*
3004 * Only count/translate packets which will be passed on, out the
3005 * interface.
3006 */
3007 if (out && FR_ISPASS(pass)) {
3008 (void) ipf_acctpkt(fin, NULL);
3009
3010 switch (fin->fin_v)
3011 {
3012 case 4 :
3013 if (ipf_nat_checkout(fin, &pass) == -1) {
3014 ;
3015 } else if ((softc->ipf_update_ipid != 0) && (v == 4)) {
3016 if (ipf_updateipid(fin) == -1) {
3017 DT(frb_updateipid);
3018 LBUMP(ipf_stats[1].fr_ipud);
3019 pass &= ~FR_CMDMASK;
3020 pass |= FR_BLOCK;
3021 fin->fin_reason = FRB_UPDATEIPID;
3022 } else {
3023 LBUMP(ipf_stats[0].fr_ipud);
3024 }
3025 }
3026 break;
3027 #ifdef USE_INET6
3028 case 6 :
3029 (void) ipf_nat6_checkout(fin, &pass);
3030 break;
3031 #endif
3032 default :
3033 break;
3034 }
3035 }
3036
3037 filterdone:
3038 #ifdef IPFILTER_LOG
3039 if ((softc->ipf_flags & FF_LOGGING) || (pass & FR_LOGMASK)) {
3040 (void) ipf_dolog(fin, &pass);
3041 }
3042 #endif
3043
3044 /*
3045 * The FI_STATE flag is cleared here so that calling ipf_state_check
3046 * will work when called from inside of fr_fastroute. Although
3047 * there is a similar flag, FI_NATED, for NAT, it does have the same
3048 * impact on code execution.
3049 */
3050 fin->fin_flx &= ~FI_STATE;
3051
3052 #if defined(FASTROUTE_RECURSION)
3053 /*
3054 * Up the reference on fr_lock and exit ipf_mutex. The generation of
3055 * a packet below can sometimes cause a recursive call into IPFilter.
3056 * On those platforms where that does happen, we need to hang onto
3057 * the filter rule just in case someone decides to remove or flush it
3058 * in the meantime.
3059 */
3060 if (fr != NULL) {
3061 MUTEX_ENTER(&fr->fr_lock);
3062 fr->fr_ref++;
3063 MUTEX_EXIT(&fr->fr_lock);
3064 }
3065
3066 RWLOCK_EXIT(&softc->ipf_mutex);
3067 #endif
3068
3069 if ((pass & FR_RETMASK) != 0) {
3070 /*
3071 * Should we return an ICMP packet to indicate error
3072 * status passing through the packet filter ?
3073 * WARNING: ICMP error packets AND TCP RST packets should
3074 * ONLY be sent in repsonse to incoming packets. Sending
3075 * them in response to outbound packets can result in a
3076 * panic on some operating systems.
3077 */
3078 if (!out) {
3079 if (pass & FR_RETICMP) {
3080 int dst;
3081
3082 if ((pass & FR_RETMASK) == FR_FAKEICMP)
3083 dst = 1;
3084 else
3085 dst = 0;
3086 (void) ipf_send_icmp_err(ICMP_UNREACH, fin,
3087 dst);
3088 LBUMP(ipf_stats[0].fr_ret);
3089 } else if (((pass & FR_RETMASK) == FR_RETRST) &&
3090 !(fin->fin_flx & FI_SHORT)) {
3091 if (((fin->fin_flx & FI_OOW) != 0) ||
3092 (ipf_send_reset(fin) == 0)) {
3093 LBUMP(ipf_stats[1].fr_ret);
3094 }
3095 }
3096
3097 /*
3098 * When using return-* with auth rules, the auth code
3099 * takes over disposing of this packet.
3100 */
3101 if (FR_ISAUTH(pass) && (fin->fin_m != NULL)) {
3102 DT1(frb_authcapture, fr_info_t *, fin);
3103 fin->fin_m = *fin->fin_mp = NULL;
3104 fin->fin_reason = FRB_AUTHCAPTURE;
3105 m = NULL;
3106 }
3107 } else {
3108 if (pass & FR_RETRST) {
3109 fin->fin_error = ECONNRESET;
3110 }
3111 }
3112 }
3113
3114 /*
3115 * After the above so that ICMP unreachables and TCP RSTs get
3116 * created properly.
3117 */
3118 if (FR_ISBLOCK(pass) && (fin->fin_flx & FI_NEWNAT))
3119 ipf_nat_uncreate(fin);
3120
3121 /*
3122 * If we didn't drop off the bottom of the list of rules (and thus
3123 * the 'current' rule fr is not NULL), then we may have some extra
3124 * instructions about what to do with a packet.
3125 * Once we're finished return to our caller, freeing the packet if
3126 * we are dropping it.
3127 */
3128 if (fr != NULL) {
3129 frdest_t *fdp;
3130
3131 /*
3132 * Generate a duplicated packet first because ipf_fastroute
3133 * can lead to fin_m being free'd... not good.
3134 */
3135 fdp = fin->fin_dif;
3136 if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3137 (fdp->fd_ptr != (void *)-1)) {
3138 mc = M_COPY(fin->fin_m);
3139 if (mc != NULL)
3140 ipf_fastroute(mc, &mc, fin, fdp);
3141 }
3142
3143 fdp = fin->fin_tif;
3144 if (!out && (pass & FR_FASTROUTE)) {
3145 /*
3146 * For fastroute rule, no destination interface defined
3147 * so pass NULL as the frdest_t parameter
3148 */
3149 (void) ipf_fastroute(fin->fin_m, mp, fin, NULL);
3150 m = *mp = NULL;
3151 } else if ((fdp != NULL) && (fdp->fd_ptr != NULL) &&
3152 (fdp->fd_ptr != (struct ifnet *)-1)) {
3153 /* this is for to rules: */
3154 ipf_fastroute(fin->fin_m, mp, fin, fdp);
3155 m = *mp = NULL;
3156 }
3157
3158 #if defined(FASTROUTE_RECURSION)
3159 (void) ipf_derefrule(softc, &fr);
3160 #endif
3161 }
3162 #if !defined(FASTROUTE_RECURSION)
3163 RWLOCK_EXIT(&softc->ipf_mutex);
3164 #endif
3165
3166 finished:
3167 if (!FR_ISPASS(pass)) {
3168 LBUMP(ipf_stats[out].fr_block);
3169 if (*mp != NULL) {
3170 #ifdef _KERNEL
3171 FREE_MB_T(*mp);
3172 #endif
3173 m = *mp = NULL;
3174 }
3175 } else {
3176 LBUMP(ipf_stats[out].fr_pass);
3177 }
3178
3179 SPL_X(s);
3180
3181 if (fin->fin_m == NULL && fin->fin_flx & FI_BAD &&
3182 fin->fin_reason == FRB_PULLUP) {
3183 /* m_pullup() has freed the mbuf */
3184 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3185 return (-1);
3186 }
3187
3188
3189 #ifdef _KERNEL
3190 if (FR_ISPASS(pass))
3191 return (0);
3192 LBUMP(ipf_stats[out].fr_blocked[fin->fin_reason]);
3193 return (fin->fin_error);
3194 #else /* _KERNEL */
3195 if (*mp != NULL)
3196 (*mp)->mb_ifp = fin->fin_ifp;
3197 blockreason = fin->fin_reason;
3198 FR_VERBOSE(("fin_flx %#x pass %#x ", fin->fin_flx, pass));
3199 /*if ((pass & FR_CMDMASK) == (softc->ipf_pass & FR_CMDMASK))*/
3200 if ((pass & FR_NOMATCH) != 0)
3201 return (1);
3202
3203 if ((pass & FR_RETMASK) != 0)
3204 switch (pass & FR_RETMASK)
3205 {
3206 case FR_RETRST :
3207 return (3);
3208 case FR_RETICMP :
3209 return (4);
3210 case FR_FAKEICMP :
3211 return (5);
3212 }
3213
3214 switch (pass & FR_CMDMASK)
3215 {
3216 case FR_PASS :
3217 return (0);
3218 case FR_BLOCK :
3219 return (-1);
3220 case FR_AUTH :
3221 return (-2);
3222 case FR_ACCOUNT :
3223 return (-3);
3224 case FR_PREAUTH :
3225 return (-4);
3226 }
3227 return (2);
3228 #endif /* _KERNEL */
3229 }
3230
3231
3232 #ifdef IPFILTER_LOG
3233 /* ------------------------------------------------------------------------ */
3234 /* Function: ipf_dolog */
3235 /* Returns: frentry_t* - returns contents of fin_fr (no change made) */
3236 /* Parameters: fin(I) - pointer to packet information */
3237 /* passp(IO) - pointer to current/new filter decision (unused) */
3238 /* */
3239 /* Checks flags set to see how a packet should be logged, if it is to be */
3240 /* logged. Adjust statistics based on its success or not. */
3241 /* ------------------------------------------------------------------------ */
3242 frentry_t *
ipf_dolog(fr_info_t * fin,u_32_t * passp)3243 ipf_dolog(fr_info_t *fin, u_32_t *passp)
3244 {
3245 ipf_main_softc_t *softc = fin->fin_main_soft;
3246 u_32_t pass;
3247 int out;
3248
3249 out = fin->fin_out;
3250 pass = *passp;
3251
3252 if ((softc->ipf_flags & FF_LOGNOMATCH) && (pass & FR_NOMATCH)) {
3253 pass |= FF_LOGNOMATCH;
3254 LBUMPD(ipf_stats[out], fr_npkl);
3255 goto logit;
3256
3257 } else if (((pass & FR_LOGMASK) == FR_LOGP) ||
3258 (FR_ISPASS(pass) && (softc->ipf_flags & FF_LOGPASS))) {
3259 if ((pass & FR_LOGMASK) != FR_LOGP)
3260 pass |= FF_LOGPASS;
3261 LBUMPD(ipf_stats[out], fr_ppkl);
3262 goto logit;
3263
3264 } else if (((pass & FR_LOGMASK) == FR_LOGB) ||
3265 (FR_ISBLOCK(pass) && (softc->ipf_flags & FF_LOGBLOCK))) {
3266 if ((pass & FR_LOGMASK) != FR_LOGB)
3267 pass |= FF_LOGBLOCK;
3268 LBUMPD(ipf_stats[out], fr_bpkl);
3269
3270 logit:
3271 if (ipf_log_pkt(fin, pass) == -1) {
3272 /*
3273 * If the "or-block" option has been used then
3274 * block the packet if we failed to log it.
3275 */
3276 if ((pass & FR_LOGORBLOCK) && FR_ISPASS(pass)) {
3277 DT1(frb_logfail2, u_int, pass);
3278 pass &= ~FR_CMDMASK;
3279 pass |= FR_BLOCK;
3280 fin->fin_reason = FRB_LOGFAIL2;
3281 }
3282 }
3283 *passp = pass;
3284 }
3285
3286 return (fin->fin_fr);
3287 }
3288 #endif /* IPFILTER_LOG */
3289
3290
3291 /* ------------------------------------------------------------------------ */
3292 /* Function: ipf_cksum */
3293 /* Returns: u_short - IP header checksum */
3294 /* Parameters: addr(I) - pointer to start of buffer to checksum */
3295 /* len(I) - length of buffer in bytes */
3296 /* */
3297 /* Calculate the two's complement 16 bit checksum of the buffer passed. */
3298 /* */
3299 /* N.B.: addr should be 16bit aligned. */
3300 /* ------------------------------------------------------------------------ */
3301 u_short
ipf_cksum(u_short * addr,int len)3302 ipf_cksum(u_short *addr, int len)
3303 {
3304 u_32_t sum = 0;
3305
3306 for (sum = 0; len > 1; len -= 2)
3307 sum += *addr++;
3308
3309 /* mop up an odd byte, if necessary */
3310 if (len == 1)
3311 sum += *(u_char *)addr;
3312
3313 /*
3314 * add back carry outs from top 16 bits to low 16 bits
3315 */
3316 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
3317 sum += (sum >> 16); /* add carry */
3318 return (u_short)(~sum);
3319 }
3320
3321
3322 /* ------------------------------------------------------------------------ */
3323 /* Function: fr_cksum */
3324 /* Returns: u_short - layer 4 checksum */
3325 /* Parameters: fin(I) - pointer to packet information */
3326 /* ip(I) - pointer to IP header */
3327 /* l4proto(I) - protocol to caclulate checksum for */
3328 /* l4hdr(I) - pointer to layer 4 header */
3329 /* */
3330 /* Calculates the TCP checksum for the packet held in "m", using the data */
3331 /* in the IP header "ip" to seed it. */
3332 /* */
3333 /* NB: This function assumes we've pullup'd enough for all of the IP header */
3334 /* and the TCP header. We also assume that data blocks aren't allocated in */
3335 /* odd sizes. */
3336 /* */
3337 /* Expects ip_len and ip_off to be in network byte order when called. */
3338 /* ------------------------------------------------------------------------ */
3339 u_short
fr_cksum(fr_info_t * fin,ip_t * ip,int l4proto,void * l4hdr)3340 fr_cksum(fr_info_t *fin, ip_t *ip, int l4proto, void *l4hdr)
3341 {
3342 u_short *sp, slen, sumsave, *csump;
3343 u_int sum, sum2;
3344 int hlen;
3345 int off;
3346 #ifdef USE_INET6
3347 ip6_t *ip6;
3348 #endif
3349
3350 csump = NULL;
3351 sumsave = 0;
3352 sp = NULL;
3353 slen = 0;
3354 hlen = 0;
3355 sum = 0;
3356
3357 sum = htons((u_short)l4proto);
3358 /*
3359 * Add up IP Header portion
3360 */
3361 #ifdef USE_INET6
3362 if (IP_V(ip) == 4) {
3363 #endif
3364 hlen = IP_HL(ip) << 2;
3365 off = hlen;
3366 sp = (u_short *)&ip->ip_src;
3367 sum += *sp++; /* ip_src */
3368 sum += *sp++;
3369 sum += *sp++; /* ip_dst */
3370 sum += *sp++;
3371 slen = fin->fin_plen - off;
3372 sum += htons(slen);
3373 #ifdef USE_INET6
3374 } else if (IP_V(ip) == 6) {
3375 mb_t *m;
3376
3377 m = fin->fin_m;
3378 ip6 = (ip6_t *)ip;
3379 off = ((caddr_t)ip6 - m->m_data) + sizeof(struct ip6_hdr);
3380 int len = ntohs(ip6->ip6_plen) - (off - sizeof(*ip6));
3381 return (ipf_pcksum6(m, ip6, off, len));
3382 } else {
3383 return (0xffff);
3384 }
3385 #endif
3386
3387 switch (l4proto)
3388 {
3389 case IPPROTO_UDP :
3390 csump = &((udphdr_t *)l4hdr)->uh_sum;
3391 break;
3392
3393 case IPPROTO_TCP :
3394 csump = &((tcphdr_t *)l4hdr)->th_sum;
3395 break;
3396 case IPPROTO_ICMP :
3397 csump = &((icmphdr_t *)l4hdr)->icmp_cksum;
3398 sum = 0; /* Pseudo-checksum is not included */
3399 break;
3400 #ifdef USE_INET6
3401 case IPPROTO_ICMPV6 :
3402 csump = &((struct icmp6_hdr *)l4hdr)->icmp6_cksum;
3403 break;
3404 #endif
3405 default :
3406 break;
3407 }
3408
3409 if (csump != NULL) {
3410 sumsave = *csump;
3411 *csump = 0;
3412 }
3413
3414 sum2 = ipf_pcksum(fin, off, sum);
3415 if (csump != NULL)
3416 *csump = sumsave;
3417 return (sum2);
3418 }
3419
3420
3421 /* ------------------------------------------------------------------------ */
3422 /* Function: ipf_findgroup */
3423 /* Returns: frgroup_t * - NULL = group not found, else pointer to group */
3424 /* Parameters: softc(I) - pointer to soft context main structure */
3425 /* group(I) - group name to search for */
3426 /* unit(I) - device to which this group belongs */
3427 /* set(I) - which set of rules (inactive/inactive) this is */
3428 /* fgpp(O) - pointer to place to store pointer to the pointer */
3429 /* to where to add the next (last) group or where */
3430 /* to delete group from. */
3431 /* */
3432 /* Search amongst the defined groups for a particular group number. */
3433 /* ------------------------------------------------------------------------ */
3434 frgroup_t *
ipf_findgroup(ipf_main_softc_t * softc,char * group,minor_t unit,int set,frgroup_t *** fgpp)3435 ipf_findgroup(ipf_main_softc_t *softc, char *group, minor_t unit, int set,
3436 frgroup_t ***fgpp)
3437 {
3438 frgroup_t *fg, **fgp;
3439
3440 /*
3441 * Which list of groups to search in is dependent on which list of
3442 * rules are being operated on.
3443 */
3444 fgp = &softc->ipf_groups[unit][set];
3445
3446 while ((fg = *fgp) != NULL) {
3447 if (strncmp(group, fg->fg_name, FR_GROUPLEN) == 0)
3448 break;
3449 else
3450 fgp = &fg->fg_next;
3451 }
3452 if (fgpp != NULL)
3453 *fgpp = fgp;
3454 return (fg);
3455 }
3456
3457
3458 /* ------------------------------------------------------------------------ */
3459 /* Function: ipf_group_add */
3460 /* Returns: frgroup_t * - NULL == did not create group, */
3461 /* != NULL == pointer to the group */
3462 /* Parameters: softc(I) - pointer to soft context main structure */
3463 /* num(I) - group number to add */
3464 /* head(I) - rule pointer that is using this as the head */
3465 /* flags(I) - rule flags which describe the type of rule it is */
3466 /* unit(I) - device to which this group will belong to */
3467 /* set(I) - which set of rules (inactive/inactive) this is */
3468 /* Write Locks: ipf_mutex */
3469 /* */
3470 /* Add a new group head, or if it already exists, increase the reference */
3471 /* count to it. */
3472 /* ------------------------------------------------------------------------ */
3473 frgroup_t *
ipf_group_add(ipf_main_softc_t * softc,char * group,void * head,u_32_t flags,minor_t unit,int set)3474 ipf_group_add(ipf_main_softc_t *softc, char *group, void *head, u_32_t flags,
3475 minor_t unit, int set)
3476 {
3477 frgroup_t *fg, **fgp;
3478 u_32_t gflags;
3479
3480 if (group == NULL)
3481 return (NULL);
3482
3483 if (unit == IPL_LOGIPF && *group == '\0')
3484 return (NULL);
3485
3486 fgp = NULL;
3487 gflags = flags & FR_INOUT;
3488
3489 fg = ipf_findgroup(softc, group, unit, set, &fgp);
3490 if (fg != NULL) {
3491 if (fg->fg_head == NULL && head != NULL)
3492 fg->fg_head = head;
3493 if (fg->fg_flags == 0)
3494 fg->fg_flags = gflags;
3495 else if (gflags != fg->fg_flags)
3496 return (NULL);
3497 fg->fg_ref++;
3498 return (fg);
3499 }
3500
3501 KMALLOC(fg, frgroup_t *);
3502 if (fg != NULL) {
3503 fg->fg_head = head;
3504 fg->fg_start = NULL;
3505 fg->fg_next = *fgp;
3506 bcopy(group, fg->fg_name, strlen(group) + 1);
3507 fg->fg_flags = gflags;
3508 fg->fg_ref = 1;
3509 fg->fg_set = &softc->ipf_groups[unit][set];
3510 *fgp = fg;
3511 }
3512 return (fg);
3513 }
3514
3515
3516 /* ------------------------------------------------------------------------ */
3517 /* Function: ipf_group_del */
3518 /* Returns: int - number of rules deleted */
3519 /* Parameters: softc(I) - pointer to soft context main structure */
3520 /* group(I) - group name to delete */
3521 /* fr(I) - filter rule from which group is referenced */
3522 /* Write Locks: ipf_mutex */
3523 /* */
3524 /* This function is called whenever a reference to a group is to be dropped */
3525 /* and thus its reference count needs to be lowered and the group free'd if */
3526 /* the reference count reaches zero. Passing in fr is really for the sole */
3527 /* purpose of knowing when the head rule is being deleted. */
3528 /* ------------------------------------------------------------------------ */
3529 void
ipf_group_del(ipf_main_softc_t * softc,frgroup_t * group,frentry_t * fr)3530 ipf_group_del(ipf_main_softc_t *softc, frgroup_t *group, frentry_t *fr)
3531 {
3532
3533 if (group->fg_head == fr)
3534 group->fg_head = NULL;
3535
3536 group->fg_ref--;
3537 if ((group->fg_ref == 0) && (group->fg_start == NULL))
3538 ipf_group_free(group);
3539 }
3540
3541
3542 /* ------------------------------------------------------------------------ */
3543 /* Function: ipf_group_free */
3544 /* Returns: Nil */
3545 /* Parameters: group(I) - pointer to filter rule group */
3546 /* */
3547 /* Remove the group from the list of groups and free it. */
3548 /* ------------------------------------------------------------------------ */
3549 static void
ipf_group_free(frgroup_t * group)3550 ipf_group_free(frgroup_t *group)
3551 {
3552 frgroup_t **gp;
3553
3554 for (gp = group->fg_set; *gp != NULL; gp = &(*gp)->fg_next) {
3555 if (*gp == group) {
3556 *gp = group->fg_next;
3557 break;
3558 }
3559 }
3560 KFREE(group);
3561 }
3562
3563
3564 /* ------------------------------------------------------------------------ */
3565 /* Function: ipf_group_flush */
3566 /* Returns: int - number of rules flush from group */
3567 /* Parameters: softc(I) - pointer to soft context main structure */
3568 /* Parameters: group(I) - pointer to filter rule group */
3569 /* */
3570 /* Remove all of the rules that currently are listed under the given group. */
3571 /* ------------------------------------------------------------------------ */
3572 static int
ipf_group_flush(ipf_main_softc_t * softc,frgroup_t * group)3573 ipf_group_flush(ipf_main_softc_t *softc, frgroup_t *group)
3574 {
3575 int gone = 0;
3576
3577 (void) ipf_flushlist(softc, &gone, &group->fg_start);
3578
3579 return (gone);
3580 }
3581
3582
3583 /* ------------------------------------------------------------------------ */
3584 /* Function: ipf_getrulen */
3585 /* Returns: frentry_t * - NULL == not found, else pointer to rule n */
3586 /* Parameters: softc(I) - pointer to soft context main structure */
3587 /* Parameters: unit(I) - device for which to count the rule's number */
3588 /* flags(I) - which set of rules to find the rule in */
3589 /* group(I) - group name */
3590 /* n(I) - rule number to find */
3591 /* */
3592 /* Find rule # n in group # g and return a pointer to it. Return NULl if */
3593 /* group # g doesn't exist or there are less than n rules in the group. */
3594 /* ------------------------------------------------------------------------ */
3595 frentry_t *
ipf_getrulen(ipf_main_softc_t * softc,int unit,char * group,u_32_t n)3596 ipf_getrulen(ipf_main_softc_t *softc, int unit, char *group, u_32_t n)
3597 {
3598 frentry_t *fr;
3599 frgroup_t *fg;
3600
3601 fg = ipf_findgroup(softc, group, unit, softc->ipf_active, NULL);
3602 if (fg == NULL)
3603 return (NULL);
3604 for (fr = fg->fg_start; fr && n; fr = fr->fr_next, n--)
3605 ;
3606 if (n != 0)
3607 return (NULL);
3608 return (fr);
3609 }
3610
3611
3612 /* ------------------------------------------------------------------------ */
3613 /* Function: ipf_flushlist */
3614 /* Returns: int - >= 0 - number of flushed rules */
3615 /* Parameters: softc(I) - pointer to soft context main structure */
3616 /* nfreedp(O) - pointer to int where flush count is stored */
3617 /* listp(I) - pointer to list to flush pointer */
3618 /* Write Locks: ipf_mutex */
3619 /* */
3620 /* Recursively flush rules from the list, descending groups as they are */
3621 /* encountered. if a rule is the head of a group and it has lost all its */
3622 /* group members, then also delete the group reference. nfreedp is needed */
3623 /* to store the accumulating count of rules removed, whereas the returned */
3624 /* value is just the number removed from the current list. The latter is */
3625 /* needed to correctly adjust reference counts on rules that define groups. */
3626 /* */
3627 /* NOTE: Rules not loaded from user space cannot be flushed. */
3628 /* ------------------------------------------------------------------------ */
3629 static int
ipf_flushlist(ipf_main_softc_t * softc,int * nfreedp,frentry_t ** listp)3630 ipf_flushlist(ipf_main_softc_t *softc, int *nfreedp, frentry_t **listp)
3631 {
3632 int freed = 0;
3633 frentry_t *fp;
3634
3635 while ((fp = *listp) != NULL) {
3636 if ((fp->fr_type & FR_T_BUILTIN) ||
3637 !(fp->fr_flags & FR_COPIED)) {
3638 listp = &fp->fr_next;
3639 continue;
3640 }
3641 *listp = fp->fr_next;
3642 if (fp->fr_next != NULL)
3643 fp->fr_next->fr_pnext = fp->fr_pnext;
3644 fp->fr_pnext = NULL;
3645
3646 if (fp->fr_grphead != NULL) {
3647 freed += ipf_group_flush(softc, fp->fr_grphead);
3648 fp->fr_names[fp->fr_grhead] = '\0';
3649 }
3650
3651 if (fp->fr_icmpgrp != NULL) {
3652 freed += ipf_group_flush(softc, fp->fr_icmpgrp);
3653 fp->fr_names[fp->fr_icmphead] = '\0';
3654 }
3655
3656 if (fp->fr_srctrack.ht_max_nodes)
3657 ipf_rb_ht_flush(&fp->fr_srctrack);
3658
3659 fp->fr_next = NULL;
3660
3661 ASSERT(fp->fr_ref > 0);
3662 if (ipf_derefrule(softc, &fp) == 0)
3663 freed++;
3664 }
3665 *nfreedp += freed;
3666 return (freed);
3667 }
3668
3669
3670 /* ------------------------------------------------------------------------ */
3671 /* Function: ipf_flush */
3672 /* Returns: int - >= 0 - number of flushed rules */
3673 /* Parameters: softc(I) - pointer to soft context main structure */
3674 /* unit(I) - device for which to flush rules */
3675 /* flags(I) - which set of rules to flush */
3676 /* */
3677 /* Calls flushlist() for all filter rules (accounting, firewall - both IPv4 */
3678 /* and IPv6) as defined by the value of flags. */
3679 /* ------------------------------------------------------------------------ */
3680 int
ipf_flush(ipf_main_softc_t * softc,minor_t unit,int flags)3681 ipf_flush(ipf_main_softc_t *softc, minor_t unit, int flags)
3682 {
3683 int flushed = 0, set;
3684
3685 WRITE_ENTER(&softc->ipf_mutex);
3686
3687 set = softc->ipf_active;
3688 if ((flags & FR_INACTIVE) == FR_INACTIVE)
3689 set = 1 - set;
3690
3691 if (flags & FR_OUTQUE) {
3692 ipf_flushlist(softc, &flushed, &softc->ipf_rules[1][set]);
3693 ipf_flushlist(softc, &flushed, &softc->ipf_acct[1][set]);
3694 }
3695 if (flags & FR_INQUE) {
3696 ipf_flushlist(softc, &flushed, &softc->ipf_rules[0][set]);
3697 ipf_flushlist(softc, &flushed, &softc->ipf_acct[0][set]);
3698 }
3699
3700 flushed += ipf_flush_groups(softc, &softc->ipf_groups[unit][set],
3701 flags & (FR_INQUE|FR_OUTQUE));
3702
3703 RWLOCK_EXIT(&softc->ipf_mutex);
3704
3705 if (unit == IPL_LOGIPF) {
3706 int tmp;
3707
3708 tmp = ipf_flush(softc, IPL_LOGCOUNT, flags);
3709 if (tmp >= 0)
3710 flushed += tmp;
3711 }
3712 return (flushed);
3713 }
3714
3715
3716 /* ------------------------------------------------------------------------ */
3717 /* Function: ipf_flush_groups */
3718 /* Returns: int - >= 0 - number of flushed rules */
3719 /* Parameters: softc(I) - soft context pointerto work with */
3720 /* grhead(I) - pointer to the start of the group list to flush */
3721 /* flags(I) - which set of rules to flush */
3722 /* */
3723 /* Walk through all of the groups under the given group head and remove all */
3724 /* of those that match the flags passed in. The for loop here is bit more */
3725 /* complicated than usual because the removal of a rule with ipf_derefrule */
3726 /* may end up removing not only the structure pointed to by "fg" but also */
3727 /* what is fg_next and fg_next after that. So if a filter rule is actually */
3728 /* removed from the group then it is necessary to start again. */
3729 /* ------------------------------------------------------------------------ */
3730 static int
ipf_flush_groups(ipf_main_softc_t * softc,frgroup_t ** grhead,int flags)3731 ipf_flush_groups(ipf_main_softc_t *softc, frgroup_t **grhead, int flags)
3732 {
3733 frentry_t *fr, **frp;
3734 frgroup_t *fg, **fgp;
3735 int flushed = 0;
3736 int removed = 0;
3737
3738 for (fgp = grhead; (fg = *fgp) != NULL; ) {
3739 while ((fg != NULL) && ((fg->fg_flags & flags) == 0))
3740 fg = fg->fg_next;
3741 if (fg == NULL)
3742 break;
3743 removed = 0;
3744 frp = &fg->fg_start;
3745 while ((removed == 0) && ((fr = *frp) != NULL)) {
3746 if ((fr->fr_flags & flags) == 0) {
3747 frp = &fr->fr_next;
3748 } else {
3749 if (fr->fr_next != NULL)
3750 fr->fr_next->fr_pnext = fr->fr_pnext;
3751 *frp = fr->fr_next;
3752 fr->fr_pnext = NULL;
3753 fr->fr_next = NULL;
3754 (void) ipf_derefrule(softc, &fr);
3755 flushed++;
3756 removed++;
3757 }
3758 }
3759 if (removed == 0)
3760 fgp = &fg->fg_next;
3761 }
3762 return (flushed);
3763 }
3764
3765
3766 /* ------------------------------------------------------------------------ */
3767 /* Function: memstr */
3768 /* Returns: char * - NULL if failed, != NULL pointer to matching bytes */
3769 /* Parameters: src(I) - pointer to byte sequence to match */
3770 /* dst(I) - pointer to byte sequence to search */
3771 /* slen(I) - match length */
3772 /* dlen(I) - length available to search in */
3773 /* */
3774 /* Search dst for a sequence of bytes matching those at src and extend for */
3775 /* slen bytes. */
3776 /* ------------------------------------------------------------------------ */
3777 char *
memstr(const char * src,char * dst,size_t slen,size_t dlen)3778 memstr(const char *src, char *dst, size_t slen, size_t dlen)
3779 {
3780 char *s = NULL;
3781
3782 while (dlen >= slen) {
3783 if (bcmp(src, dst, slen) == 0) {
3784 s = dst;
3785 break;
3786 }
3787 dst++;
3788 dlen--;
3789 }
3790 return (s);
3791 }
3792 /* ------------------------------------------------------------------------ */
3793 /* Function: ipf_fixskip */
3794 /* Returns: Nil */
3795 /* Parameters: listp(IO) - pointer to start of list with skip rule */
3796 /* rp(I) - rule added/removed with skip in it. */
3797 /* addremove(I) - adjustment (-1/+1) to make to skip count, */
3798 /* depending on whether a rule was just added */
3799 /* or removed. */
3800 /* */
3801 /* Adjust all the rules in a list which would have skip'd past the position */
3802 /* where we are inserting to skip to the right place given the change. */
3803 /* ------------------------------------------------------------------------ */
3804 void
ipf_fixskip(frentry_t ** listp,frentry_t * rp,int addremove)3805 ipf_fixskip(frentry_t **listp, frentry_t *rp, int addremove)
3806 {
3807 int rules, rn;
3808 frentry_t *fp;
3809
3810 rules = 0;
3811 for (fp = *listp; (fp != NULL) && (fp != rp); fp = fp->fr_next)
3812 rules++;
3813
3814 if (fp == NULL)
3815 return;
3816
3817 for (rn = 0, fp = *listp; fp && (fp != rp); fp = fp->fr_next, rn++)
3818 if (FR_ISSKIP(fp->fr_flags) && (rn + fp->fr_arg >= rules))
3819 fp->fr_arg += addremove;
3820 }
3821
3822
3823 #ifdef _KERNEL
3824 /* ------------------------------------------------------------------------ */
3825 /* Function: count4bits */
3826 /* Returns: int - >= 0 - number of consecutive bits in input */
3827 /* Parameters: ip(I) - 32bit IP address */
3828 /* */
3829 /* IPv4 ONLY */
3830 /* count consecutive 1's in bit mask. If the mask generated by counting */
3831 /* consecutive 1's is different to that passed, return -1, else return # */
3832 /* of bits. */
3833 /* ------------------------------------------------------------------------ */
3834 int
count4bits(u_32_t ip)3835 count4bits(u_32_t ip)
3836 {
3837 u_32_t ipn;
3838 int cnt = 0, i, j;
3839
3840 ip = ipn = ntohl(ip);
3841 for (i = 32; i; i--, ipn *= 2)
3842 if (ipn & 0x80000000)
3843 cnt++;
3844 else
3845 break;
3846 ipn = 0;
3847 for (i = 32, j = cnt; i; i--, j--) {
3848 ipn *= 2;
3849 if (j > 0)
3850 ipn++;
3851 }
3852 if (ipn == ip)
3853 return (cnt);
3854 return (-1);
3855 }
3856
3857
3858 /* ------------------------------------------------------------------------ */
3859 /* Function: count6bits */
3860 /* Returns: int - >= 0 - number of consecutive bits in input */
3861 /* Parameters: msk(I) - pointer to start of IPv6 bitmask */
3862 /* */
3863 /* IPv6 ONLY */
3864 /* count consecutive 1's in bit mask. */
3865 /* ------------------------------------------------------------------------ */
3866 # ifdef USE_INET6
3867 int
count6bits(u_32_t * msk)3868 count6bits(u_32_t *msk)
3869 {
3870 int i = 0, k;
3871 u_32_t j;
3872
3873 for (k = 3; k >= 0; k--)
3874 if (msk[k] == 0xffffffff)
3875 i += 32;
3876 else {
3877 for (j = msk[k]; j; j <<= 1)
3878 if (j & 0x80000000)
3879 i++;
3880 }
3881 return (i);
3882 }
3883 # endif
3884 #endif /* _KERNEL */
3885
3886
3887 /* ------------------------------------------------------------------------ */
3888 /* Function: ipf_synclist */
3889 /* Returns: int - 0 = no failures, else indication of first failure */
3890 /* Parameters: fr(I) - start of filter list to sync interface names for */
3891 /* ifp(I) - interface pointer for limiting sync lookups */
3892 /* Write Locks: ipf_mutex */
3893 /* */
3894 /* Walk through a list of filter rules and resolve any interface names into */
3895 /* pointers. Where dynamic addresses are used, also update the IP address */
3896 /* used in the rule. The interface pointer is used to limit the lookups to */
3897 /* a specific set of matching names if it is non-NULL. */
3898 /* Errors can occur when resolving the destination name of to/dup-to fields */
3899 /* when the name points to a pool and that pool doest not exist. If this */
3900 /* does happen then it is necessary to check if there are any lookup refs */
3901 /* that need to be dropped before returning with an error. */
3902 /* ------------------------------------------------------------------------ */
3903 static int
ipf_synclist(ipf_main_softc_t * softc,frentry_t * fr,void * ifp)3904 ipf_synclist(ipf_main_softc_t *softc, frentry_t *fr, void *ifp)
3905 {
3906 frentry_t *frt, *start = fr;
3907 frdest_t *fdp;
3908 char *name;
3909 int error;
3910 void *ifa;
3911 int v, i;
3912
3913 error = 0;
3914
3915 for (; fr; fr = fr->fr_next) {
3916 if (fr->fr_family == AF_INET)
3917 v = 4;
3918 else if (fr->fr_family == AF_INET6)
3919 v = 6;
3920 else
3921 v = 0;
3922
3923 /*
3924 * Lookup all the interface names that are part of the rule.
3925 */
3926 for (i = 0; i < FR_NUM(fr->fr_ifas); i++) {
3927 if ((ifp != NULL) && (fr->fr_ifas[i] != ifp))
3928 continue;
3929 if (fr->fr_ifnames[i] == -1)
3930 continue;
3931 name = FR_NAME(fr, fr_ifnames[i]);
3932 fr->fr_ifas[i] = ipf_resolvenic(softc, name, v);
3933 }
3934
3935 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
3936 if (fr->fr_satype != FRI_NORMAL &&
3937 fr->fr_satype != FRI_LOOKUP) {
3938 ifa = ipf_resolvenic(softc, fr->fr_names +
3939 fr->fr_sifpidx, v);
3940 ipf_ifpaddr(softc, v, fr->fr_satype, ifa,
3941 &fr->fr_src6, &fr->fr_smsk6);
3942 }
3943 if (fr->fr_datype != FRI_NORMAL &&
3944 fr->fr_datype != FRI_LOOKUP) {
3945 ifa = ipf_resolvenic(softc, fr->fr_names +
3946 fr->fr_sifpidx, v);
3947 ipf_ifpaddr(softc, v, fr->fr_datype, ifa,
3948 &fr->fr_dst6, &fr->fr_dmsk6);
3949 }
3950 }
3951
3952 fdp = &fr->fr_tifs[0];
3953 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3954 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3955 if (error != 0)
3956 goto unwind;
3957 }
3958
3959 fdp = &fr->fr_tifs[1];
3960 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3961 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3962 if (error != 0)
3963 goto unwind;
3964 }
3965
3966 fdp = &fr->fr_dif;
3967 if ((ifp == NULL) || (fdp->fd_ptr == ifp)) {
3968 error = ipf_resolvedest(softc, fr->fr_names, fdp, v);
3969 if (error != 0)
3970 goto unwind;
3971 }
3972
3973 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3974 (fr->fr_satype == FRI_LOOKUP) && (fr->fr_srcptr == NULL)) {
3975 fr->fr_srcptr = ipf_lookup_res_num(softc,
3976 fr->fr_srctype,
3977 IPL_LOGIPF,
3978 fr->fr_srcnum,
3979 &fr->fr_srcfunc);
3980 }
3981 if (((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3982 (fr->fr_datype == FRI_LOOKUP) && (fr->fr_dstptr == NULL)) {
3983 fr->fr_dstptr = ipf_lookup_res_num(softc,
3984 fr->fr_dsttype,
3985 IPL_LOGIPF,
3986 fr->fr_dstnum,
3987 &fr->fr_dstfunc);
3988 }
3989 }
3990 return (0);
3991
3992 unwind:
3993 for (frt = start; frt != fr; fr = fr->fr_next) {
3994 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3995 (frt->fr_satype == FRI_LOOKUP) && (frt->fr_srcptr != NULL))
3996 ipf_lookup_deref(softc, frt->fr_srctype,
3997 frt->fr_srcptr);
3998 if (((frt->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) &&
3999 (frt->fr_datype == FRI_LOOKUP) && (frt->fr_dstptr != NULL))
4000 ipf_lookup_deref(softc, frt->fr_dsttype,
4001 frt->fr_dstptr);
4002 }
4003 return (error);
4004 }
4005
4006
4007 /* ------------------------------------------------------------------------ */
4008 /* Function: ipf_sync */
4009 /* Returns: void */
4010 /* Parameters: Nil */
4011 /* */
4012 /* ipf_sync() is called when we suspect that the interface list or */
4013 /* information about interfaces (like IP#) has changed. Go through all */
4014 /* filter rules, NAT entries and the state table and check if anything */
4015 /* needs to be changed/updated. */
4016 /* ------------------------------------------------------------------------ */
4017 int
ipf_sync(ipf_main_softc_t * softc,void * ifp)4018 ipf_sync(ipf_main_softc_t *softc, void *ifp)
4019 {
4020 int i;
4021
4022 #if !SOLARIS
4023 ipf_nat_sync(softc, ifp);
4024 ipf_state_sync(softc, ifp);
4025 ipf_lookup_sync(softc, ifp);
4026 #endif
4027
4028 WRITE_ENTER(&softc->ipf_mutex);
4029 (void) ipf_synclist(softc, softc->ipf_acct[0][softc->ipf_active], ifp);
4030 (void) ipf_synclist(softc, softc->ipf_acct[1][softc->ipf_active], ifp);
4031 (void) ipf_synclist(softc, softc->ipf_rules[0][softc->ipf_active], ifp);
4032 (void) ipf_synclist(softc, softc->ipf_rules[1][softc->ipf_active], ifp);
4033
4034 for (i = 0; i < IPL_LOGSIZE; i++) {
4035 frgroup_t *g;
4036
4037 for (g = softc->ipf_groups[i][0]; g != NULL; g = g->fg_next)
4038 (void) ipf_synclist(softc, g->fg_start, ifp);
4039 for (g = softc->ipf_groups[i][1]; g != NULL; g = g->fg_next)
4040 (void) ipf_synclist(softc, g->fg_start, ifp);
4041 }
4042 RWLOCK_EXIT(&softc->ipf_mutex);
4043
4044 return (0);
4045 }
4046
4047
4048 /*
4049 * In the functions below, bcopy() is called because the pointer being
4050 * copied _from_ in this instance is a pointer to a char buf (which could
4051 * end up being unaligned) and on the kernel's local stack.
4052 */
4053 /* ------------------------------------------------------------------------ */
4054 /* Function: copyinptr */
4055 /* Returns: int - 0 = success, else failure */
4056 /* Parameters: src(I) - pointer to the source address */
4057 /* dst(I) - destination address */
4058 /* size(I) - number of bytes to copy */
4059 /* */
4060 /* Copy a block of data in from user space, given a pointer to the pointer */
4061 /* to start copying from (src) and a pointer to where to store it (dst). */
4062 /* NB: src - pointer to user space pointer, dst - kernel space pointer */
4063 /* ------------------------------------------------------------------------ */
4064 int
copyinptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4065 copyinptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4066 {
4067 caddr_t ca;
4068 int error;
4069
4070 #if SOLARIS
4071 error = COPYIN(src, &ca, sizeof(ca));
4072 if (error != 0)
4073 return (error);
4074 #else
4075 bcopy(src, (caddr_t)&ca, sizeof(ca));
4076 #endif
4077 error = COPYIN(ca, dst, size);
4078 if (error != 0) {
4079 IPFERROR(3);
4080 error = EFAULT;
4081 }
4082 return (error);
4083 }
4084
4085
4086 /* ------------------------------------------------------------------------ */
4087 /* Function: copyoutptr */
4088 /* Returns: int - 0 = success, else failure */
4089 /* Parameters: src(I) - pointer to the source address */
4090 /* dst(I) - destination address */
4091 /* size(I) - number of bytes to copy */
4092 /* */
4093 /* Copy a block of data out to user space, given a pointer to the pointer */
4094 /* to start copying from (src) and a pointer to where to store it (dst). */
4095 /* NB: src - kernel space pointer, dst - pointer to user space pointer. */
4096 /* ------------------------------------------------------------------------ */
4097 int
copyoutptr(ipf_main_softc_t * softc,void * src,void * dst,size_t size)4098 copyoutptr(ipf_main_softc_t *softc, void *src, void *dst, size_t size)
4099 {
4100 caddr_t ca;
4101 int error;
4102
4103 bcopy(dst, (caddr_t)&ca, sizeof(ca));
4104 error = COPYOUT(src, ca, size);
4105 if (error != 0) {
4106 IPFERROR(4);
4107 error = EFAULT;
4108 }
4109 return (error);
4110 }
4111
4112
4113 /* ------------------------------------------------------------------------ */
4114 /* Function: ipf_lock */
4115 /* Returns: int - 0 = success, else error */
4116 /* Parameters: data(I) - pointer to lock value to set */
4117 /* lockp(O) - pointer to location to store old lock value */
4118 /* */
4119 /* Get the new value for the lock integer, set it and return the old value */
4120 /* in *lockp. */
4121 /* ------------------------------------------------------------------------ */
4122 int
ipf_lock(caddr_t data,int * lockp)4123 ipf_lock(caddr_t data, int *lockp)
4124 {
4125 int arg, err;
4126
4127 err = BCOPYIN(data, &arg, sizeof(arg));
4128 if (err != 0)
4129 return (EFAULT);
4130 err = BCOPYOUT(lockp, data, sizeof(*lockp));
4131 if (err != 0)
4132 return (EFAULT);
4133 *lockp = arg;
4134 return (0);
4135 }
4136
4137
4138 /* ------------------------------------------------------------------------ */
4139 /* Function: ipf_getstat */
4140 /* Returns: Nil */
4141 /* Parameters: softc(I) - pointer to soft context main structure */
4142 /* fiop(I) - pointer to ipfilter stats structure */
4143 /* rev(I) - version claim by program doing ioctl */
4144 /* */
4145 /* Stores a copy of current pointers, counters, etc, in the friostat */
4146 /* structure. */
4147 /* If IPFILTER_COMPAT is compiled, we pretend to be whatever version the */
4148 /* program is looking for. This ensure that validation of the version it */
4149 /* expects will always succeed. Thus kernels with IPFILTER_COMPAT will */
4150 /* allow older binaries to work but kernels without it will not. */
4151 /* ------------------------------------------------------------------------ */
4152 /*ARGSUSED*/
4153 static void
ipf_getstat(ipf_main_softc_t * softc,friostat_t * fiop,int rev)4154 ipf_getstat(ipf_main_softc_t *softc, friostat_t *fiop, int rev)
4155 {
4156 int i;
4157
4158 bcopy((char *)softc->ipf_stats, (char *)fiop->f_st,
4159 sizeof(ipf_statistics_t) * 2);
4160 fiop->f_locks[IPL_LOGSTATE] = -1;
4161 fiop->f_locks[IPL_LOGNAT] = -1;
4162 fiop->f_locks[IPL_LOGIPF] = -1;
4163 fiop->f_locks[IPL_LOGAUTH] = -1;
4164
4165 fiop->f_ipf[0][0] = softc->ipf_rules[0][0];
4166 fiop->f_acct[0][0] = softc->ipf_acct[0][0];
4167 fiop->f_ipf[0][1] = softc->ipf_rules[0][1];
4168 fiop->f_acct[0][1] = softc->ipf_acct[0][1];
4169 fiop->f_ipf[1][0] = softc->ipf_rules[1][0];
4170 fiop->f_acct[1][0] = softc->ipf_acct[1][0];
4171 fiop->f_ipf[1][1] = softc->ipf_rules[1][1];
4172 fiop->f_acct[1][1] = softc->ipf_acct[1][1];
4173
4174 fiop->f_ticks = softc->ipf_ticks;
4175 fiop->f_active = softc->ipf_active;
4176 fiop->f_froute[0] = softc->ipf_frouteok[0];
4177 fiop->f_froute[1] = softc->ipf_frouteok[1];
4178 fiop->f_rb_no_mem = softc->ipf_rb_no_mem;
4179 fiop->f_rb_node_max = softc->ipf_rb_node_max;
4180
4181 fiop->f_running = softc->ipf_running;
4182 for (i = 0; i < IPL_LOGSIZE; i++) {
4183 fiop->f_groups[i][0] = softc->ipf_groups[i][0];
4184 fiop->f_groups[i][1] = softc->ipf_groups[i][1];
4185 }
4186 #ifdef IPFILTER_LOG
4187 fiop->f_log_ok = ipf_log_logok(softc, IPL_LOGIPF);
4188 fiop->f_log_fail = ipf_log_failures(softc, IPL_LOGIPF);
4189 fiop->f_logging = 1;
4190 #else
4191 fiop->f_log_ok = 0;
4192 fiop->f_log_fail = 0;
4193 fiop->f_logging = 0;
4194 #endif
4195 fiop->f_defpass = softc->ipf_pass;
4196 fiop->f_features = ipf_features;
4197
4198 #ifdef IPFILTER_COMPAT
4199 snprintf(fiop->f_version, sizeof(friostat.f_version), "IP Filter: v%d.%d.%d",
4200 (rev / 1000000) % 100,
4201 (rev / 10000) % 100,
4202 (rev / 100) % 100);
4203 #else
4204 (void)rev; /* UNUSED */
4205 (void) strncpy(fiop->f_version, ipfilter_version,
4206 sizeof(fiop->f_version));
4207 #endif
4208 }
4209
4210
4211 #ifdef USE_INET6
4212 int icmptoicmp6types[ICMP_MAXTYPE+1] = {
4213 ICMP6_ECHO_REPLY, /* 0: ICMP_ECHOREPLY */
4214 -1, /* 1: UNUSED */
4215 -1, /* 2: UNUSED */
4216 ICMP6_DST_UNREACH, /* 3: ICMP_UNREACH */
4217 -1, /* 4: ICMP_SOURCEQUENCH */
4218 ND_REDIRECT, /* 5: ICMP_REDIRECT */
4219 -1, /* 6: UNUSED */
4220 -1, /* 7: UNUSED */
4221 ICMP6_ECHO_REQUEST, /* 8: ICMP_ECHO */
4222 -1, /* 9: UNUSED */
4223 -1, /* 10: UNUSED */
4224 ICMP6_TIME_EXCEEDED, /* 11: ICMP_TIMXCEED */
4225 ICMP6_PARAM_PROB, /* 12: ICMP_PARAMPROB */
4226 -1, /* 13: ICMP_TSTAMP */
4227 -1, /* 14: ICMP_TSTAMPREPLY */
4228 -1, /* 15: ICMP_IREQ */
4229 -1, /* 16: ICMP_IREQREPLY */
4230 -1, /* 17: ICMP_MASKREQ */
4231 -1, /* 18: ICMP_MASKREPLY */
4232 };
4233
4234
4235 int icmptoicmp6unreach[ICMP_MAX_UNREACH] = {
4236 ICMP6_DST_UNREACH_ADDR, /* 0: ICMP_UNREACH_NET */
4237 ICMP6_DST_UNREACH_ADDR, /* 1: ICMP_UNREACH_HOST */
4238 -1, /* 2: ICMP_UNREACH_PROTOCOL */
4239 ICMP6_DST_UNREACH_NOPORT, /* 3: ICMP_UNREACH_PORT */
4240 -1, /* 4: ICMP_UNREACH_NEEDFRAG */
4241 ICMP6_DST_UNREACH_NOTNEIGHBOR, /* 5: ICMP_UNREACH_SRCFAIL */
4242 ICMP6_DST_UNREACH_ADDR, /* 6: ICMP_UNREACH_NET_UNKNOWN */
4243 ICMP6_DST_UNREACH_ADDR, /* 7: ICMP_UNREACH_HOST_UNKNOWN */
4244 -1, /* 8: ICMP_UNREACH_ISOLATED */
4245 ICMP6_DST_UNREACH_ADMIN, /* 9: ICMP_UNREACH_NET_PROHIB */
4246 ICMP6_DST_UNREACH_ADMIN, /* 10: ICMP_UNREACH_HOST_PROHIB */
4247 -1, /* 11: ICMP_UNREACH_TOSNET */
4248 -1, /* 12: ICMP_UNREACH_TOSHOST */
4249 ICMP6_DST_UNREACH_ADMIN, /* 13: ICMP_UNREACH_ADMIN_PROHIBIT */
4250 };
4251 int icmpreplytype6[ICMP6_MAXTYPE + 1];
4252 #endif
4253
4254 int icmpreplytype4[ICMP_MAXTYPE + 1];
4255
4256
4257 /* ------------------------------------------------------------------------ */
4258 /* Function: ipf_matchicmpqueryreply */
4259 /* Returns: int - 1 if "icmp" is a valid reply to "ic" else 0. */
4260 /* Parameters: v(I) - IP protocol version (4 or 6) */
4261 /* ic(I) - ICMP information */
4262 /* icmp(I) - ICMP packet header */
4263 /* rev(I) - direction (0 = forward/1 = reverse) of packet */
4264 /* */
4265 /* Check if the ICMP packet defined by the header pointed to by icmp is a */
4266 /* reply to one as described by what's in ic. If it is a match, return 1, */
4267 /* else return 0 for no match. */
4268 /* ------------------------------------------------------------------------ */
4269 int
ipf_matchicmpqueryreply(int v,icmpinfo_t * ic,icmphdr_t * icmp,int rev)4270 ipf_matchicmpqueryreply(int v, icmpinfo_t *ic, icmphdr_t *icmp, int rev)
4271 {
4272 int ictype;
4273
4274 ictype = ic->ici_type;
4275
4276 if (v == 4) {
4277 /*
4278 * If we matched its type on the way in, then when going out
4279 * it will still be the same type.
4280 */
4281 if ((!rev && (icmp->icmp_type == ictype)) ||
4282 (rev && (icmpreplytype4[ictype] == icmp->icmp_type))) {
4283 if (icmp->icmp_type != ICMP_ECHOREPLY)
4284 return (1);
4285 if (icmp->icmp_id == ic->ici_id)
4286 return (1);
4287 }
4288 }
4289 #ifdef USE_INET6
4290 else if (v == 6) {
4291 if ((!rev && (icmp->icmp_type == ictype)) ||
4292 (rev && (icmpreplytype6[ictype] == icmp->icmp_type))) {
4293 if (icmp->icmp_type != ICMP6_ECHO_REPLY)
4294 return (1);
4295 if (icmp->icmp_id == ic->ici_id)
4296 return (1);
4297 }
4298 }
4299 #endif
4300 return (0);
4301 }
4302
4303
4304 /*
4305 * IFNAMES are located in the variable length field starting at
4306 * frentry.fr_names. As pointers within the struct cannot be passed
4307 * to the kernel from ipf(8), an offset is used. An offset of -1 means it
4308 * is unused (invalid). If it is used (valid) it is an offset to the
4309 * character string of an interface name or a comment. The following
4310 * macros will assist those who follow to understand the code.
4311 */
4312 #define IPF_IFNAME_VALID(_a) (_a != -1)
4313 #define IPF_IFNAME_INVALID(_a) (_a == -1)
4314 #define IPF_IFNAMES_DIFFERENT(_a) \
4315 !((IPF_IFNAME_INVALID(fr1->_a) && \
4316 IPF_IFNAME_INVALID(fr2->_a)) || \
4317 (IPF_IFNAME_VALID(fr1->_a) && \
4318 IPF_IFNAME_VALID(fr2->_a) && \
4319 !strcmp(FR_NAME(fr1, _a), FR_NAME(fr2, _a))))
4320 #define IPF_FRDEST_DIFFERENT(_a) \
4321 (memcmp(&fr1->_a.fd_addr, &fr2->_a.fd_addr, \
4322 offsetof(frdest_t, fd_name) - offsetof(frdest_t, fd_addr)) || \
4323 IPF_IFNAMES_DIFFERENT(_a.fd_name))
4324
4325
4326 /* ------------------------------------------------------------------------ */
4327 /* Function: ipf_rule_compare */
4328 /* Parameters: fr1(I) - first rule structure to compare */
4329 /* fr2(I) - second rule structure to compare */
4330 /* Returns: int - 0 == rules are the same, else mismatch */
4331 /* */
4332 /* Compare two rules and return 0 if they match or a number indicating */
4333 /* which of the individual checks failed. */
4334 /* ------------------------------------------------------------------------ */
4335 static int
ipf_rule_compare(frentry_t * fr1,frentry_t * fr2)4336 ipf_rule_compare(frentry_t *fr1, frentry_t *fr2)
4337 {
4338 int i;
4339
4340 if (fr1->fr_cksum != fr2->fr_cksum)
4341 return (1);
4342 if (fr1->fr_size != fr2->fr_size)
4343 return (2);
4344 if (fr1->fr_dsize != fr2->fr_dsize)
4345 return (3);
4346 if (bcmp((char *)&fr1->fr_func, (char *)&fr2->fr_func, FR_CMPSIZ)
4347 != 0)
4348 return (4);
4349 /*
4350 * XXX: There is still a bug here as different rules with the
4351 * the same interfaces but in a different order will compare
4352 * differently. But since multiple interfaces in a rule doesn't
4353 * work anyway a simple straightforward compare is performed
4354 * here. Ultimately frentry_t creation will need to be
4355 * revisited in ipf_y.y. While the other issue, recognition
4356 * of only the first interface in a list of interfaces will
4357 * need to be separately addressed along with why only four.
4358 */
4359 for (i = 0; i < FR_NUM(fr1->fr_ifnames); i++) {
4360 /*
4361 * XXX: It's either the same index or uninitialized.
4362 * We assume this because multiple interfaces
4363 * referenced by the same rule doesn't work anyway.
4364 */
4365 if (IPF_IFNAMES_DIFFERENT(fr_ifnames[i]))
4366 return (5);
4367 }
4368
4369 if (IPF_FRDEST_DIFFERENT(fr_tif))
4370 return (6);
4371 if (IPF_FRDEST_DIFFERENT(fr_rif))
4372 return (7);
4373 if (IPF_FRDEST_DIFFERENT(fr_dif))
4374 return (8);
4375 if (!fr1->fr_data && !fr2->fr_data)
4376 return (0); /* move along, nothing to see here */
4377 if (fr1->fr_data && fr2->fr_data) {
4378 if (bcmp(fr1->fr_caddr, fr2->fr_caddr, fr1->fr_dsize) == 0)
4379 return (0); /* same */
4380 }
4381 return (9);
4382 }
4383
4384
4385 /* ------------------------------------------------------------------------ */
4386 /* Function: frrequest */
4387 /* Returns: int - 0 == success, > 0 == errno value */
4388 /* Parameters: unit(I) - device for which this is for */
4389 /* req(I) - ioctl command (SIOC*) */
4390 /* data(I) - pointr to ioctl data */
4391 /* set(I) - 1 or 0 (filter set) */
4392 /* makecopy(I) - flag indicating whether data points to a rule */
4393 /* in kernel space & hence doesn't need copying. */
4394 /* */
4395 /* This function handles all the requests which operate on the list of */
4396 /* filter rules. This includes adding, deleting, insertion. It is also */
4397 /* responsible for creating groups when a "head" rule is loaded. Interface */
4398 /* names are resolved here and other sanity checks are made on the content */
4399 /* of the rule structure being loaded. If a rule has user defined timeouts */
4400 /* then make sure they are created and initialised before exiting. */
4401 /* ------------------------------------------------------------------------ */
4402 int
frrequest(ipf_main_softc_t * softc,int unit,ioctlcmd_t req,caddr_t data,int set,int makecopy)4403 frrequest(ipf_main_softc_t *softc, int unit, ioctlcmd_t req, caddr_t data,
4404 int set, int makecopy)
4405 {
4406 int error = 0, in, family, need_free = 0, interr, i;
4407 int interr_tbl[3] = { 152, 156, 153};
4408 enum { OP_ADD, /* add rule */
4409 OP_REM, /* remove rule */
4410 OP_ZERO /* zero statistics and counters */ }
4411 addrem = OP_ADD;
4412 frentry_t frd, *fp, *f, **fprev, **ftail;
4413 void *ptr, *uptr;
4414 u_int *p, *pp;
4415 frgroup_t *fg;
4416 char *group;
4417
4418 ptr = NULL;
4419 fg = NULL;
4420 fp = &frd;
4421 if (makecopy != 0) {
4422 bzero(fp, sizeof(frd));
4423 error = ipf_inobj(softc, data, NULL, fp, IPFOBJ_FRENTRY);
4424 if (error) {
4425 return (error);
4426 }
4427 if ((fp->fr_type & FR_T_BUILTIN) != 0) {
4428 IPFERROR(6);
4429 return (EINVAL);
4430 }
4431 if (fp->fr_size < sizeof(frd)) {
4432 return (EINVAL);
4433 }
4434 if (sizeof(frd) + fp->fr_namelen != fp->fr_size ) {
4435 IPFERROR(155);
4436 return (EINVAL);
4437 }
4438 if (fp->fr_namelen < 0 || fp->fr_namelen > softc->ipf_max_namelen) {
4439 IPFERROR(156);
4440 return (EINVAL);
4441 }
4442 KMALLOCS(f, frentry_t *, fp->fr_size);
4443 if (f == NULL) {
4444 IPFERROR(131);
4445 return (ENOMEM);
4446 }
4447 bzero(f, fp->fr_size);
4448 error = ipf_inobjsz(softc, data, f, IPFOBJ_FRENTRY,
4449 fp->fr_size);
4450 if (error) {
4451 KFREES(f, fp->fr_size);
4452 return (error);
4453 }
4454
4455 fp = f;
4456 f = NULL;
4457 fp->fr_next = NULL;
4458 fp->fr_dnext = NULL;
4459 fp->fr_pnext = NULL;
4460 fp->fr_pdnext = NULL;
4461 fp->fr_grp = NULL;
4462 fp->fr_grphead = NULL;
4463 fp->fr_icmpgrp = NULL;
4464 fp->fr_isc = (void *)-1;
4465 fp->fr_ptr = NULL;
4466 fp->fr_ref = 0;
4467 fp->fr_flags |= FR_COPIED;
4468
4469 for (i = 0; i <= 3; i++) {
4470 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_ifnames[i])) != 0) {
4471 IPFERROR(interr_tbl[interr-1]);
4472 error = EINVAL;
4473 goto donenolock;
4474 }
4475 }
4476 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_comment)) != 0) {
4477 IPFERROR(interr_tbl[interr-1]);
4478 error = EINVAL;
4479 goto donenolock;
4480 }
4481 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_group)) != 0) {
4482 IPFERROR(interr_tbl[interr-1]);
4483 error = EINVAL;
4484 goto donenolock;
4485 }
4486 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_grhead)) != 0) {
4487 IPFERROR(interr_tbl[interr-1]);
4488 error = EINVAL;
4489 goto donenolock;
4490 }
4491 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_tif.fd_name)) != 0) {
4492 IPFERROR(interr_tbl[interr-1]);
4493 error = EINVAL;
4494 goto donenolock;
4495 }
4496 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_rif.fd_name)) != 0) {
4497 IPFERROR(interr_tbl[interr-1]);
4498 error = EINVAL;
4499 goto donenolock;
4500 }
4501 if ((interr = ipf_check_names_string(fp->fr_names, fp->fr_namelen, fp->fr_dif.fd_name)) != 0) {
4502 IPFERROR(interr_tbl[interr-1]);
4503 error = EINVAL;
4504 goto donenolock;
4505 }
4506 } else {
4507 fp = (frentry_t *)data;
4508 if ((fp->fr_type & FR_T_BUILTIN) == 0) {
4509 IPFERROR(7);
4510 return (EINVAL);
4511 }
4512 fp->fr_flags &= ~FR_COPIED;
4513 }
4514
4515 if (((fp->fr_dsize == 0) && (fp->fr_data != NULL)) ||
4516 ((fp->fr_dsize != 0) && (fp->fr_data == NULL))) {
4517 IPFERROR(8);
4518 error = EINVAL;
4519 goto donenolock;
4520 }
4521
4522 family = fp->fr_family;
4523 uptr = fp->fr_data;
4524
4525 if (req == (ioctlcmd_t)SIOCINAFR || req == (ioctlcmd_t)SIOCINIFR ||
4526 req == (ioctlcmd_t)SIOCADAFR || req == (ioctlcmd_t)SIOCADIFR)
4527 addrem = OP_ADD; /* Add rule */
4528 else if (req == (ioctlcmd_t)SIOCRMAFR || req == (ioctlcmd_t)SIOCRMIFR)
4529 addrem = OP_REM; /* Remove rule */
4530 else if (req == (ioctlcmd_t)SIOCZRLST)
4531 addrem = OP_ZERO; /* Zero statistics and counters */
4532 else {
4533 IPFERROR(9);
4534 error = EINVAL;
4535 goto donenolock;
4536 }
4537
4538 /*
4539 * Only filter rules for IPv4 or IPv6 are accepted.
4540 */
4541 if (family == AF_INET) {
4542 /*EMPTY*/;
4543 #ifdef USE_INET6
4544 } else if (family == AF_INET6) {
4545 /*EMPTY*/;
4546 #endif
4547 } else if (family != 0) {
4548 IPFERROR(10);
4549 error = EINVAL;
4550 goto donenolock;
4551 }
4552
4553 /*
4554 * If the rule is being loaded from user space, i.e. we had to copy it
4555 * into kernel space, then do not trust the function pointer in the
4556 * rule.
4557 */
4558 if ((makecopy == 1) && (fp->fr_func != NULL)) {
4559 if (ipf_findfunc(fp->fr_func) == NULL) {
4560 IPFERROR(11);
4561 error = ESRCH;
4562 goto donenolock;
4563 }
4564
4565 if (addrem == OP_ADD) {
4566 error = ipf_funcinit(softc, fp);
4567 if (error != 0)
4568 goto donenolock;
4569 }
4570 }
4571 if ((fp->fr_flags & FR_CALLNOW) &&
4572 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4573 IPFERROR(142);
4574 error = ESRCH;
4575 goto donenolock;
4576 }
4577 if (((fp->fr_flags & FR_CMDMASK) == FR_CALL) &&
4578 ((fp->fr_func == NULL) || (fp->fr_func == (ipfunc_t)-1))) {
4579 IPFERROR(143);
4580 error = ESRCH;
4581 goto donenolock;
4582 }
4583
4584 ptr = NULL;
4585
4586 if (FR_ISACCOUNT(fp->fr_flags))
4587 unit = IPL_LOGCOUNT;
4588
4589 /*
4590 * Check that each group name in the rule has a start index that
4591 * is valid.
4592 */
4593 if (fp->fr_icmphead != -1) {
4594 if ((fp->fr_icmphead < 0) ||
4595 (fp->fr_icmphead >= fp->fr_namelen)) {
4596 IPFERROR(136);
4597 error = EINVAL;
4598 goto donenolock;
4599 }
4600 if (!strcmp(FR_NAME(fp, fr_icmphead), "0"))
4601 fp->fr_names[fp->fr_icmphead] = '\0';
4602 }
4603
4604 if (fp->fr_grhead != -1) {
4605 if ((fp->fr_grhead < 0) ||
4606 (fp->fr_grhead >= fp->fr_namelen)) {
4607 IPFERROR(137);
4608 error = EINVAL;
4609 goto donenolock;
4610 }
4611 if (!strcmp(FR_NAME(fp, fr_grhead), "0"))
4612 fp->fr_names[fp->fr_grhead] = '\0';
4613 }
4614
4615 if (fp->fr_group != -1) {
4616 if ((fp->fr_group < 0) ||
4617 (fp->fr_group >= fp->fr_namelen)) {
4618 IPFERROR(138);
4619 error = EINVAL;
4620 goto donenolock;
4621 }
4622 if ((req != (int)SIOCZRLST) && (fp->fr_group != -1)) {
4623 /*
4624 * Allow loading rules that are in groups to cause
4625 * them to be created if they don't already exit.
4626 */
4627 group = FR_NAME(fp, fr_group);
4628 if (addrem == OP_ADD) {
4629 fg = ipf_group_add(softc, group, NULL,
4630 fp->fr_flags, unit, set);
4631 fp->fr_grp = fg;
4632 } else {
4633 fg = ipf_findgroup(softc, group, unit,
4634 set, NULL);
4635 if (fg == NULL) {
4636 IPFERROR(12);
4637 error = ESRCH;
4638 goto donenolock;
4639 }
4640 }
4641
4642 if (fg->fg_flags == 0) {
4643 fg->fg_flags = fp->fr_flags & FR_INOUT;
4644 } else if (fg->fg_flags != (fp->fr_flags & FR_INOUT)) {
4645 IPFERROR(13);
4646 error = ESRCH;
4647 goto donenolock;
4648 }
4649 }
4650 } else {
4651 /*
4652 * If a rule is going to be part of a group then it does
4653 * not matter whether it is an in or out rule, but if it
4654 * isn't in a group, then it does...
4655 */
4656 if ((fp->fr_flags & (FR_INQUE|FR_OUTQUE)) == 0) {
4657 IPFERROR(14);
4658 error = EINVAL;
4659 goto donenolock;
4660 }
4661 }
4662 in = (fp->fr_flags & FR_INQUE) ? 0 : 1;
4663
4664 /*
4665 * Work out which rule list this change is being applied to.
4666 */
4667 ftail = NULL;
4668 fprev = NULL;
4669 if (unit == IPL_LOGAUTH) {
4670 if ((fp->fr_tifs[0].fd_ptr != NULL) ||
4671 (fp->fr_tifs[1].fd_ptr != NULL) ||
4672 (fp->fr_dif.fd_ptr != NULL) ||
4673 (fp->fr_flags & FR_FASTROUTE)) {
4674 softc->ipf_interror = 145;
4675 error = EINVAL;
4676 goto donenolock;
4677 }
4678 fprev = ipf_auth_rulehead(softc);
4679 } else {
4680 if (FR_ISACCOUNT(fp->fr_flags))
4681 fprev = &softc->ipf_acct[in][set];
4682 else if ((fp->fr_flags & (FR_OUTQUE|FR_INQUE)) != 0)
4683 fprev = &softc->ipf_rules[in][set];
4684 }
4685 if (fprev == NULL) {
4686 IPFERROR(15);
4687 error = ESRCH;
4688 goto donenolock;
4689 }
4690
4691 if (fg != NULL)
4692 fprev = &fg->fg_start;
4693
4694 /*
4695 * Copy in extra data for the rule.
4696 */
4697 if (fp->fr_dsize != 0) {
4698 if (makecopy != 0) {
4699 KMALLOCS(ptr, void *, fp->fr_dsize);
4700 if (ptr == NULL) {
4701 IPFERROR(16);
4702 error = ENOMEM;
4703 goto donenolock;
4704 }
4705
4706 /*
4707 * The bcopy case is for when the data is appended
4708 * to the rule by ipf_in_compat().
4709 */
4710 if (uptr >= (void *)fp &&
4711 uptr < (void *)((char *)fp + fp->fr_size)) {
4712 bcopy(uptr, ptr, fp->fr_dsize);
4713 error = 0;
4714 } else {
4715 error = COPYIN(uptr, ptr, fp->fr_dsize);
4716 if (error != 0) {
4717 IPFERROR(17);
4718 error = EFAULT;
4719 goto donenolock;
4720 }
4721 }
4722 } else {
4723 ptr = uptr;
4724 }
4725 fp->fr_data = ptr;
4726 } else {
4727 fp->fr_data = NULL;
4728 }
4729
4730 /*
4731 * Perform per-rule type sanity checks of their members.
4732 * All code after this needs to be aware that allocated memory
4733 * may need to be free'd before exiting.
4734 */
4735 switch (fp->fr_type & ~FR_T_BUILTIN)
4736 {
4737 #if defined(IPFILTER_BPF)
4738 case FR_T_BPFOPC :
4739 if (fp->fr_dsize == 0) {
4740 IPFERROR(19);
4741 error = EINVAL;
4742 break;
4743 }
4744 if (!bpf_validate(ptr, fp->fr_dsize/sizeof(struct bpf_insn))) {
4745 IPFERROR(20);
4746 error = EINVAL;
4747 break;
4748 }
4749 break;
4750 #endif
4751 case FR_T_IPF :
4752 /*
4753 * Preparation for error case at the bottom of this function.
4754 */
4755 if (fp->fr_datype == FRI_LOOKUP)
4756 fp->fr_dstptr = NULL;
4757 if (fp->fr_satype == FRI_LOOKUP)
4758 fp->fr_srcptr = NULL;
4759
4760 if (fp->fr_dsize != sizeof(fripf_t)) {
4761 IPFERROR(21);
4762 error = EINVAL;
4763 break;
4764 }
4765
4766 /*
4767 * Allowing a rule with both "keep state" and "with oow" is
4768 * pointless because adding a state entry to the table will
4769 * fail with the out of window (oow) flag set.
4770 */
4771 if ((fp->fr_flags & FR_KEEPSTATE) && (fp->fr_flx & FI_OOW)) {
4772 IPFERROR(22);
4773 error = EINVAL;
4774 break;
4775 }
4776
4777 switch (fp->fr_satype)
4778 {
4779 case FRI_BROADCAST :
4780 case FRI_DYNAMIC :
4781 case FRI_NETWORK :
4782 case FRI_NETMASKED :
4783 case FRI_PEERADDR :
4784 if (fp->fr_sifpidx < 0) {
4785 IPFERROR(23);
4786 error = EINVAL;
4787 }
4788 break;
4789 case FRI_LOOKUP :
4790 fp->fr_srcptr = ipf_findlookup(softc, unit, fp,
4791 &fp->fr_src6,
4792 &fp->fr_smsk6);
4793 if (fp->fr_srcfunc == NULL) {
4794 IPFERROR(132);
4795 error = ESRCH;
4796 break;
4797 }
4798 break;
4799 case FRI_NORMAL :
4800 break;
4801 default :
4802 IPFERROR(133);
4803 error = EINVAL;
4804 break;
4805 }
4806 if (error != 0)
4807 break;
4808
4809 switch (fp->fr_datype)
4810 {
4811 case FRI_BROADCAST :
4812 case FRI_DYNAMIC :
4813 case FRI_NETWORK :
4814 case FRI_NETMASKED :
4815 case FRI_PEERADDR :
4816 if (fp->fr_difpidx < 0) {
4817 IPFERROR(24);
4818 error = EINVAL;
4819 }
4820 break;
4821 case FRI_LOOKUP :
4822 fp->fr_dstptr = ipf_findlookup(softc, unit, fp,
4823 &fp->fr_dst6,
4824 &fp->fr_dmsk6);
4825 if (fp->fr_dstfunc == NULL) {
4826 IPFERROR(134);
4827 error = ESRCH;
4828 }
4829 break;
4830 case FRI_NORMAL :
4831 break;
4832 default :
4833 IPFERROR(135);
4834 error = EINVAL;
4835 }
4836 break;
4837
4838 case FR_T_NONE :
4839 case FR_T_CALLFUNC :
4840 case FR_T_COMPIPF :
4841 break;
4842
4843 case FR_T_IPFEXPR :
4844 if (ipf_matcharray_verify(fp->fr_data, fp->fr_dsize) == -1) {
4845 IPFERROR(25);
4846 error = EINVAL;
4847 }
4848 break;
4849
4850 default :
4851 IPFERROR(26);
4852 error = EINVAL;
4853 break;
4854 }
4855 if (error != 0)
4856 goto donenolock;
4857
4858 if (fp->fr_tif.fd_name != -1) {
4859 if ((fp->fr_tif.fd_name < 0) ||
4860 (fp->fr_tif.fd_name >= fp->fr_namelen)) {
4861 IPFERROR(139);
4862 error = EINVAL;
4863 goto donenolock;
4864 }
4865 }
4866
4867 if (fp->fr_dif.fd_name != -1) {
4868 if ((fp->fr_dif.fd_name < 0) ||
4869 (fp->fr_dif.fd_name >= fp->fr_namelen)) {
4870 IPFERROR(140);
4871 error = EINVAL;
4872 goto donenolock;
4873 }
4874 }
4875
4876 if (fp->fr_rif.fd_name != -1) {
4877 if ((fp->fr_rif.fd_name < 0) ||
4878 (fp->fr_rif.fd_name >= fp->fr_namelen)) {
4879 IPFERROR(141);
4880 error = EINVAL;
4881 goto donenolock;
4882 }
4883 }
4884
4885 /*
4886 * Lookup all the interface names that are part of the rule.
4887 */
4888 error = ipf_synclist(softc, fp, NULL);
4889 if (error != 0)
4890 goto donenolock;
4891 fp->fr_statecnt = 0;
4892 if (fp->fr_srctrack.ht_max_nodes != 0)
4893 ipf_rb_ht_init(&fp->fr_srctrack);
4894
4895 /*
4896 * Look for an existing matching filter rule, but don't include the
4897 * next or interface pointer in the comparison (fr_next, fr_ifa).
4898 * This elminates rules which are indentical being loaded. Checksum
4899 * the constant part of the filter rule to make comparisons quicker
4900 * (this meaning no pointers are included).
4901 */
4902 pp = (u_int *)(fp->fr_caddr + fp->fr_dsize);
4903 for (fp->fr_cksum = 0, p = (u_int *)fp->fr_data; p < pp; p++)
4904 fp->fr_cksum += *p;
4905
4906 WRITE_ENTER(&softc->ipf_mutex);
4907
4908 /*
4909 * Now that the filter rule lists are locked, we can walk the
4910 * chain of them without fear.
4911 */
4912 ftail = fprev;
4913 for (f = *ftail; (f = *ftail) != NULL; ftail = &f->fr_next) {
4914 if (fp->fr_collect <= f->fr_collect) {
4915 ftail = fprev;
4916 f = NULL;
4917 break;
4918 }
4919 fprev = ftail;
4920 }
4921
4922 for (; (f = *ftail) != NULL; ftail = &f->fr_next) {
4923 if (ipf_rule_compare(fp, f) == 0)
4924 break;
4925 }
4926
4927 /*
4928 * If zero'ing statistics, copy current to caller and zero.
4929 */
4930 if (addrem == OP_ZERO) {
4931 if (f == NULL) {
4932 IPFERROR(27);
4933 error = ESRCH;
4934 } else {
4935 /*
4936 * Copy and reduce lock because of impending copyout.
4937 * Well we should, but if we do then the atomicity of
4938 * this call and the correctness of fr_hits and
4939 * fr_bytes cannot be guaranteed. As it is, this code
4940 * only resets them to 0 if they are successfully
4941 * copied out into user space.
4942 */
4943 bcopy((char *)f, (char *)fp, f->fr_size);
4944 /* MUTEX_DOWNGRADE(&softc->ipf_mutex); */
4945
4946 /*
4947 * When we copy this rule back out, set the data
4948 * pointer to be what it was in user space.
4949 */
4950 fp->fr_data = uptr;
4951 error = ipf_outobj(softc, data, fp, IPFOBJ_FRENTRY);
4952
4953 if (error == 0) {
4954 if ((f->fr_dsize != 0) && (uptr != NULL)) {
4955 error = COPYOUT(f->fr_data, uptr,
4956 f->fr_dsize);
4957 if (error == 0) {
4958 f->fr_hits = 0;
4959 f->fr_bytes = 0;
4960 } else {
4961 IPFERROR(28);
4962 error = EFAULT;
4963 }
4964 }
4965 }
4966 }
4967
4968 if (makecopy != 0) {
4969 if (ptr != NULL) {
4970 KFREES(ptr, fp->fr_dsize);
4971 }
4972 KFREES(fp, fp->fr_size);
4973 }
4974 RWLOCK_EXIT(&softc->ipf_mutex);
4975 return (error);
4976 }
4977
4978 if (f == NULL) {
4979 /*
4980 * At the end of this, ftail must point to the place where the
4981 * new rule is to be saved/inserted/added.
4982 * For SIOCAD*FR, this should be the last rule in the group of
4983 * rules that have equal fr_collect fields.
4984 * For SIOCIN*FR, ...
4985 */
4986 if (req == (ioctlcmd_t)SIOCADAFR ||
4987 req == (ioctlcmd_t)SIOCADIFR) {
4988
4989 for (ftail = fprev; (f = *ftail) != NULL; ) {
4990 if (f->fr_collect > fp->fr_collect)
4991 break;
4992 ftail = &f->fr_next;
4993 fprev = ftail;
4994 }
4995 ftail = fprev;
4996 f = NULL;
4997 ptr = NULL;
4998 } else if (req == (ioctlcmd_t)SIOCINAFR ||
4999 req == (ioctlcmd_t)SIOCINIFR) {
5000 while ((f = *fprev) != NULL) {
5001 if (f->fr_collect >= fp->fr_collect)
5002 break;
5003 fprev = &f->fr_next;
5004 }
5005 ftail = fprev;
5006 if (fp->fr_hits != 0) {
5007 while (fp->fr_hits && (f = *ftail)) {
5008 if (f->fr_collect != fp->fr_collect)
5009 break;
5010 fprev = ftail;
5011 ftail = &f->fr_next;
5012 fp->fr_hits--;
5013 }
5014 }
5015 f = NULL;
5016 ptr = NULL;
5017 }
5018 }
5019
5020 /*
5021 * Request to remove a rule.
5022 */
5023 if (addrem == OP_REM) {
5024 if (f == NULL) {
5025 IPFERROR(29);
5026 error = ESRCH;
5027 } else {
5028 /*
5029 * Do not allow activity from user space to interfere
5030 * with rules not loaded that way.
5031 */
5032 if ((makecopy == 1) && !(f->fr_flags & FR_COPIED)) {
5033 IPFERROR(30);
5034 error = EPERM;
5035 goto done;
5036 }
5037
5038 /*
5039 * Return EBUSY if the rule is being reference by
5040 * something else (eg state information.)
5041 */
5042 if (f->fr_ref > 1) {
5043 IPFERROR(31);
5044 error = EBUSY;
5045 goto done;
5046 }
5047 #ifdef IPFILTER_SCAN
5048 if (f->fr_isctag != -1 &&
5049 (f->fr_isc != (struct ipscan *)-1))
5050 ipf_scan_detachfr(f);
5051 #endif
5052
5053 if (unit == IPL_LOGAUTH) {
5054 error = ipf_auth_precmd(softc, req, f, ftail);
5055 goto done;
5056 }
5057
5058 ipf_rule_delete(softc, f, unit, set);
5059
5060 need_free = makecopy;
5061 }
5062 } else {
5063 /*
5064 * Not removing, so we must be adding/inserting a rule.
5065 */
5066 if (f != NULL) {
5067 IPFERROR(32);
5068 error = EEXIST;
5069 goto done;
5070 }
5071 if (unit == IPL_LOGAUTH) {
5072 error = ipf_auth_precmd(softc, req, fp, ftail);
5073 goto done;
5074 }
5075
5076 MUTEX_NUKE(&fp->fr_lock);
5077 MUTEX_INIT(&fp->fr_lock, "filter rule lock");
5078 if (fp->fr_die != 0)
5079 ipf_rule_expire_insert(softc, fp, set);
5080
5081 fp->fr_hits = 0;
5082 if (makecopy != 0)
5083 fp->fr_ref = 1;
5084 fp->fr_pnext = ftail;
5085 fp->fr_next = *ftail;
5086 if (fp->fr_next != NULL)
5087 fp->fr_next->fr_pnext = &fp->fr_next;
5088 *ftail = fp;
5089 ipf_fixskip(ftail, fp, 1);
5090
5091 fp->fr_icmpgrp = NULL;
5092 if (fp->fr_icmphead != -1) {
5093 group = FR_NAME(fp, fr_icmphead);
5094 fg = ipf_group_add(softc, group, fp, 0, unit, set);
5095 fp->fr_icmpgrp = fg;
5096 }
5097
5098 fp->fr_grphead = NULL;
5099 if (fp->fr_grhead != -1) {
5100 group = FR_NAME(fp, fr_grhead);
5101 fg = ipf_group_add(softc, group, fp, fp->fr_flags,
5102 unit, set);
5103 fp->fr_grphead = fg;
5104 }
5105 }
5106 done:
5107 RWLOCK_EXIT(&softc->ipf_mutex);
5108 donenolock:
5109 if (need_free || (error != 0)) {
5110 if ((fp->fr_type & ~FR_T_BUILTIN) == FR_T_IPF) {
5111 if ((fp->fr_satype == FRI_LOOKUP) &&
5112 (fp->fr_srcptr != NULL))
5113 ipf_lookup_deref(softc, fp->fr_srctype,
5114 fp->fr_srcptr);
5115 if ((fp->fr_datype == FRI_LOOKUP) &&
5116 (fp->fr_dstptr != NULL))
5117 ipf_lookup_deref(softc, fp->fr_dsttype,
5118 fp->fr_dstptr);
5119 }
5120 if (fp->fr_grp != NULL) {
5121 WRITE_ENTER(&softc->ipf_mutex);
5122 ipf_group_del(softc, fp->fr_grp, fp);
5123 RWLOCK_EXIT(&softc->ipf_mutex);
5124 }
5125 if ((ptr != NULL) && (makecopy != 0)) {
5126 KFREES(ptr, fp->fr_dsize);
5127 }
5128 KFREES(fp, fp->fr_size);
5129 }
5130 return (error);
5131 }
5132
5133
5134 /* ------------------------------------------------------------------------ */
5135 /* Function: ipf_rule_delete */
5136 /* Returns: Nil */
5137 /* Parameters: softc(I) - pointer to soft context main structure */
5138 /* f(I) - pointer to the rule being deleted */
5139 /* ftail(I) - pointer to the pointer to f */
5140 /* unit(I) - device for which this is for */
5141 /* set(I) - 1 or 0 (filter set) */
5142 /* */
5143 /* This function attempts to do what it can to delete a filter rule: remove */
5144 /* it from any linked lists and remove any groups it is responsible for. */
5145 /* But in the end, removing a rule can only drop the reference count - we */
5146 /* must use that as the guide for whether or not it can be freed. */
5147 /* ------------------------------------------------------------------------ */
5148 static void
ipf_rule_delete(ipf_main_softc_t * softc,frentry_t * f,int unit,int set)5149 ipf_rule_delete(ipf_main_softc_t *softc, frentry_t *f, int unit, int set)
5150 {
5151
5152 /*
5153 * If fr_pdnext is set, then the rule is on the expire list, so
5154 * remove it from there.
5155 */
5156 if (f->fr_pdnext != NULL) {
5157 *f->fr_pdnext = f->fr_dnext;
5158 if (f->fr_dnext != NULL)
5159 f->fr_dnext->fr_pdnext = f->fr_pdnext;
5160 f->fr_pdnext = NULL;
5161 f->fr_dnext = NULL;
5162 }
5163
5164 ipf_fixskip(f->fr_pnext, f, -1);
5165 if (f->fr_pnext != NULL)
5166 *f->fr_pnext = f->fr_next;
5167 if (f->fr_next != NULL)
5168 f->fr_next->fr_pnext = f->fr_pnext;
5169 f->fr_pnext = NULL;
5170 f->fr_next = NULL;
5171
5172 (void) ipf_derefrule(softc, &f);
5173 }
5174
5175 /* ------------------------------------------------------------------------ */
5176 /* Function: ipf_rule_expire_insert */
5177 /* Returns: Nil */
5178 /* Parameters: softc(I) - pointer to soft context main structure */
5179 /* f(I) - pointer to rule to be added to expire list */
5180 /* set(I) - 1 or 0 (filter set) */
5181 /* */
5182 /* If the new rule has a given expiration time, insert it into the list of */
5183 /* expiring rules with the ones to be removed first added to the front of */
5184 /* the list. The insertion is O(n) but it is kept sorted for quick scans at */
5185 /* expiration interval checks. */
5186 /* ------------------------------------------------------------------------ */
5187 static void
ipf_rule_expire_insert(ipf_main_softc_t * softc,frentry_t * f,int set)5188 ipf_rule_expire_insert(ipf_main_softc_t *softc, frentry_t *f, int set)
5189 {
5190 frentry_t *fr;
5191
5192 /*
5193 */
5194
5195 f->fr_die = softc->ipf_ticks + IPF_TTLVAL(f->fr_die);
5196 for (fr = softc->ipf_rule_explist[set]; fr != NULL;
5197 fr = fr->fr_dnext) {
5198 if (f->fr_die < fr->fr_die)
5199 break;
5200 if (fr->fr_dnext == NULL) {
5201 /*
5202 * We've got to the last rule and everything
5203 * wanted to be expired before this new node,
5204 * so we have to tack it on the end...
5205 */
5206 fr->fr_dnext = f;
5207 f->fr_pdnext = &fr->fr_dnext;
5208 fr = NULL;
5209 break;
5210 }
5211 }
5212
5213 if (softc->ipf_rule_explist[set] == NULL) {
5214 softc->ipf_rule_explist[set] = f;
5215 f->fr_pdnext = &softc->ipf_rule_explist[set];
5216 } else if (fr != NULL) {
5217 f->fr_dnext = fr;
5218 f->fr_pdnext = fr->fr_pdnext;
5219 fr->fr_pdnext = &f->fr_dnext;
5220 }
5221 }
5222
5223
5224 /* ------------------------------------------------------------------------ */
5225 /* Function: ipf_findlookup */
5226 /* Returns: NULL = failure, else success */
5227 /* Parameters: softc(I) - pointer to soft context main structure */
5228 /* unit(I) - ipf device we want to find match for */
5229 /* fp(I) - rule for which lookup is for */
5230 /* addrp(I) - pointer to lookup information in address struct */
5231 /* maskp(O) - pointer to lookup information for storage */
5232 /* */
5233 /* When using pools and hash tables to store addresses for matching in */
5234 /* rules, it is necessary to resolve both the object referred to by the */
5235 /* name or address (and return that pointer) and also provide the means by */
5236 /* which to determine if an address belongs to that object to make the */
5237 /* packet matching quicker. */
5238 /* ------------------------------------------------------------------------ */
5239 static void *
ipf_findlookup(ipf_main_softc_t * softc,int unit,frentry_t * fr,i6addr_t * addrp,i6addr_t * maskp)5240 ipf_findlookup(ipf_main_softc_t *softc, int unit, frentry_t *fr,
5241 i6addr_t *addrp, i6addr_t *maskp)
5242 {
5243 void *ptr = NULL;
5244
5245 switch (addrp->iplookupsubtype)
5246 {
5247 case 0 :
5248 ptr = ipf_lookup_res_num(softc, unit, addrp->iplookuptype,
5249 addrp->iplookupnum,
5250 &maskp->iplookupfunc);
5251 break;
5252 case 1 :
5253 if (addrp->iplookupname < 0)
5254 break;
5255 if (addrp->iplookupname >= fr->fr_namelen)
5256 break;
5257 ptr = ipf_lookup_res_name(softc, unit, addrp->iplookuptype,
5258 fr->fr_names + addrp->iplookupname,
5259 &maskp->iplookupfunc);
5260 break;
5261 default :
5262 break;
5263 }
5264
5265 return (ptr);
5266 }
5267
5268
5269 /* ------------------------------------------------------------------------ */
5270 /* Function: ipf_funcinit */
5271 /* Returns: int - 0 == success, else ESRCH: cannot resolve rule details */
5272 /* Parameters: softc(I) - pointer to soft context main structure */
5273 /* fr(I) - pointer to filter rule */
5274 /* */
5275 /* If a rule is a call rule, then check if the function it points to needs */
5276 /* an init function to be called now the rule has been loaded. */
5277 /* ------------------------------------------------------------------------ */
5278 static int
ipf_funcinit(ipf_main_softc_t * softc,frentry_t * fr)5279 ipf_funcinit(ipf_main_softc_t *softc, frentry_t *fr)
5280 {
5281 ipfunc_resolve_t *ft;
5282 int err;
5283
5284 IPFERROR(34);
5285 err = ESRCH;
5286
5287 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5288 if (ft->ipfu_addr == fr->fr_func) {
5289 err = 0;
5290 if (ft->ipfu_init != NULL)
5291 err = (*ft->ipfu_init)(softc, fr);
5292 break;
5293 }
5294 return (err);
5295 }
5296
5297
5298 /* ------------------------------------------------------------------------ */
5299 /* Function: ipf_funcfini */
5300 /* Returns: Nil */
5301 /* Parameters: softc(I) - pointer to soft context main structure */
5302 /* fr(I) - pointer to filter rule */
5303 /* */
5304 /* For a given filter rule, call the matching "fini" function if the rule */
5305 /* is using a known function that would have resulted in the "init" being */
5306 /* called for ealier. */
5307 /* ------------------------------------------------------------------------ */
5308 static void
ipf_funcfini(ipf_main_softc_t * softc,frentry_t * fr)5309 ipf_funcfini(ipf_main_softc_t *softc, frentry_t *fr)
5310 {
5311 ipfunc_resolve_t *ft;
5312
5313 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5314 if (ft->ipfu_addr == fr->fr_func) {
5315 if (ft->ipfu_fini != NULL)
5316 (void) (*ft->ipfu_fini)(softc, fr);
5317 break;
5318 }
5319 }
5320
5321
5322 /* ------------------------------------------------------------------------ */
5323 /* Function: ipf_findfunc */
5324 /* Returns: ipfunc_t - pointer to function if found, else NULL */
5325 /* Parameters: funcptr(I) - function pointer to lookup */
5326 /* */
5327 /* Look for a function in the table of known functions. */
5328 /* ------------------------------------------------------------------------ */
5329 static ipfunc_t
ipf_findfunc(ipfunc_t funcptr)5330 ipf_findfunc(ipfunc_t funcptr)
5331 {
5332 ipfunc_resolve_t *ft;
5333
5334 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5335 if (ft->ipfu_addr == funcptr)
5336 return (funcptr);
5337 return (NULL);
5338 }
5339
5340
5341 /* ------------------------------------------------------------------------ */
5342 /* Function: ipf_resolvefunc */
5343 /* Returns: int - 0 == success, else error */
5344 /* Parameters: data(IO) - ioctl data pointer to ipfunc_resolve_t struct */
5345 /* */
5346 /* Copy in a ipfunc_resolve_t structure and then fill in the missing field. */
5347 /* This will either be the function name (if the pointer is set) or the */
5348 /* function pointer if the name is set. When found, fill in the other one */
5349 /* so that the entire, complete, structure can be copied back to user space.*/
5350 /* ------------------------------------------------------------------------ */
5351 int
ipf_resolvefunc(ipf_main_softc_t * softc,void * data)5352 ipf_resolvefunc(ipf_main_softc_t *softc, void *data)
5353 {
5354 ipfunc_resolve_t res, *ft;
5355 int error;
5356
5357 error = BCOPYIN(data, &res, sizeof(res));
5358 if (error != 0) {
5359 IPFERROR(123);
5360 return (EFAULT);
5361 }
5362
5363 if (res.ipfu_addr == NULL && res.ipfu_name[0] != '\0') {
5364 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5365 if (strncmp(res.ipfu_name, ft->ipfu_name,
5366 sizeof(res.ipfu_name)) == 0) {
5367 res.ipfu_addr = ft->ipfu_addr;
5368 res.ipfu_init = ft->ipfu_init;
5369 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5370 IPFERROR(35);
5371 return (EFAULT);
5372 }
5373 return (0);
5374 }
5375 }
5376 if (res.ipfu_addr != NULL && res.ipfu_name[0] == '\0') {
5377 for (ft = ipf_availfuncs; ft->ipfu_addr != NULL; ft++)
5378 if (ft->ipfu_addr == res.ipfu_addr) {
5379 (void) strncpy(res.ipfu_name, ft->ipfu_name,
5380 sizeof(res.ipfu_name));
5381 res.ipfu_init = ft->ipfu_init;
5382 if (COPYOUT(&res, data, sizeof(res)) != 0) {
5383 IPFERROR(36);
5384 return (EFAULT);
5385 }
5386 return (0);
5387 }
5388 }
5389 IPFERROR(37);
5390 return (ESRCH);
5391 }
5392
5393
5394 #if !defined(_KERNEL) || SOLARIS
5395 /*
5396 * From: NetBSD
5397 * ppsratecheck(): packets (or events) per second limitation.
5398 */
5399 int
ppsratecheck(struct timeval * lasttime,int * curpps,int maxpps)5400 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
5401 /* maxpps: maximum pps allowed */
5402 {
5403 struct timeval tv, delta;
5404 int rv;
5405
5406 GETKTIME(&tv);
5407
5408 delta.tv_sec = tv.tv_sec - lasttime->tv_sec;
5409 delta.tv_usec = tv.tv_usec - lasttime->tv_usec;
5410 if (delta.tv_usec < 0) {
5411 delta.tv_sec--;
5412 delta.tv_usec += 1000000;
5413 }
5414
5415 /*
5416 * check for 0,0 is so that the message will be seen at least once.
5417 * if more than one second have passed since the last update of
5418 * lasttime, reset the counter.
5419 *
5420 * we do increment *curpps even in *curpps < maxpps case, as some may
5421 * try to use *curpps for stat purposes as well.
5422 */
5423 if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
5424 delta.tv_sec >= 1) {
5425 *lasttime = tv;
5426 *curpps = 0;
5427 rv = 1;
5428 } else if (maxpps < 0)
5429 rv = 1;
5430 else if (*curpps < maxpps)
5431 rv = 1;
5432 else
5433 rv = 0;
5434 *curpps = *curpps + 1;
5435
5436 return (rv);
5437 }
5438 #endif
5439
5440
5441 /* ------------------------------------------------------------------------ */
5442 /* Function: ipf_derefrule */
5443 /* Returns: int - 0 == rule freed up, else rule not freed */
5444 /* Parameters: fr(I) - pointer to filter rule */
5445 /* */
5446 /* Decrement the reference counter to a rule by one. If it reaches zero, */
5447 /* free it and any associated storage space being used by it. */
5448 /* ------------------------------------------------------------------------ */
5449 int
ipf_derefrule(ipf_main_softc_t * softc,frentry_t ** frp)5450 ipf_derefrule(ipf_main_softc_t *softc, frentry_t **frp)
5451 {
5452 frentry_t *fr;
5453 frdest_t *fdp;
5454
5455 fr = *frp;
5456 *frp = NULL;
5457
5458 MUTEX_ENTER(&fr->fr_lock);
5459 fr->fr_ref--;
5460 if (fr->fr_ref == 0) {
5461 MUTEX_EXIT(&fr->fr_lock);
5462 MUTEX_DESTROY(&fr->fr_lock);
5463
5464 ipf_funcfini(softc, fr);
5465
5466 fdp = &fr->fr_tif;
5467 if (fdp->fd_type == FRD_DSTLIST)
5468 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5469
5470 fdp = &fr->fr_rif;
5471 if (fdp->fd_type == FRD_DSTLIST)
5472 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5473
5474 fdp = &fr->fr_dif;
5475 if (fdp->fd_type == FRD_DSTLIST)
5476 ipf_lookup_deref(softc, IPLT_DSTLIST, fdp->fd_ptr);
5477
5478 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5479 fr->fr_satype == FRI_LOOKUP)
5480 ipf_lookup_deref(softc, fr->fr_srctype, fr->fr_srcptr);
5481 if ((fr->fr_type & ~FR_T_BUILTIN) == FR_T_IPF &&
5482 fr->fr_datype == FRI_LOOKUP)
5483 ipf_lookup_deref(softc, fr->fr_dsttype, fr->fr_dstptr);
5484
5485 if (fr->fr_grp != NULL)
5486 ipf_group_del(softc, fr->fr_grp, fr);
5487
5488 if (fr->fr_grphead != NULL)
5489 ipf_group_del(softc, fr->fr_grphead, fr);
5490
5491 if (fr->fr_icmpgrp != NULL)
5492 ipf_group_del(softc, fr->fr_icmpgrp, fr);
5493
5494 if ((fr->fr_flags & FR_COPIED) != 0) {
5495 if (fr->fr_dsize) {
5496 KFREES(fr->fr_data, fr->fr_dsize);
5497 }
5498 KFREES(fr, fr->fr_size);
5499 return (0);
5500 }
5501 return (1);
5502 } else {
5503 MUTEX_EXIT(&fr->fr_lock);
5504 }
5505 return (-1);
5506 }
5507
5508
5509 /* ------------------------------------------------------------------------ */
5510 /* Function: ipf_grpmapinit */
5511 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5512 /* Parameters: fr(I) - pointer to rule to find hash table for */
5513 /* */
5514 /* Looks for group hash table fr_arg and stores a pointer to it in fr_ptr. */
5515 /* fr_ptr is later used by ipf_srcgrpmap and ipf_dstgrpmap. */
5516 /* ------------------------------------------------------------------------ */
5517 static int
ipf_grpmapinit(ipf_main_softc_t * softc,frentry_t * fr)5518 ipf_grpmapinit(ipf_main_softc_t *softc, frentry_t *fr)
5519 {
5520 char name[FR_GROUPLEN];
5521 iphtable_t *iph;
5522
5523 (void) snprintf(name, sizeof(name), "%d", fr->fr_arg);
5524 iph = ipf_lookup_find_htable(softc, IPL_LOGIPF, name);
5525 if (iph == NULL) {
5526 IPFERROR(38);
5527 return (ESRCH);
5528 }
5529 if ((iph->iph_flags & FR_INOUT) != (fr->fr_flags & FR_INOUT)) {
5530 IPFERROR(39);
5531 return (ESRCH);
5532 }
5533 iph->iph_ref++;
5534 fr->fr_ptr = iph;
5535 return (0);
5536 }
5537
5538
5539 /* ------------------------------------------------------------------------ */
5540 /* Function: ipf_grpmapfini */
5541 /* Returns: int - 0 == success, else ESRCH because table entry not found*/
5542 /* Parameters: softc(I) - pointer to soft context main structure */
5543 /* fr(I) - pointer to rule to release hash table for */
5544 /* */
5545 /* For rules that have had ipf_grpmapinit called, ipf_lookup_deref needs to */
5546 /* be called to undo what ipf_grpmapinit caused to be done. */
5547 /* ------------------------------------------------------------------------ */
5548 static int
ipf_grpmapfini(ipf_main_softc_t * softc,frentry_t * fr)5549 ipf_grpmapfini(ipf_main_softc_t *softc, frentry_t *fr)
5550 {
5551 iphtable_t *iph;
5552 iph = fr->fr_ptr;
5553 if (iph != NULL)
5554 ipf_lookup_deref(softc, IPLT_HASH, iph);
5555 return (0);
5556 }
5557
5558
5559 /* ------------------------------------------------------------------------ */
5560 /* Function: ipf_srcgrpmap */
5561 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5562 /* Parameters: fin(I) - pointer to packet information */
5563 /* passp(IO) - pointer to current/new filter decision (unused) */
5564 /* */
5565 /* Look for a rule group head in a hash table, using the source address as */
5566 /* the key, and descend into that group and continue matching rules against */
5567 /* the packet. */
5568 /* ------------------------------------------------------------------------ */
5569 frentry_t *
ipf_srcgrpmap(fr_info_t * fin,u_32_t * passp)5570 ipf_srcgrpmap(fr_info_t *fin, u_32_t *passp)
5571 {
5572 frgroup_t *fg;
5573 void *rval;
5574
5575 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5576 &fin->fin_src);
5577 if (rval == NULL)
5578 return (NULL);
5579
5580 fg = rval;
5581 fin->fin_fr = fg->fg_start;
5582 (void) ipf_scanlist(fin, *passp);
5583 return (fin->fin_fr);
5584 }
5585
5586
5587 /* ------------------------------------------------------------------------ */
5588 /* Function: ipf_dstgrpmap */
5589 /* Returns: frentry_t * - pointer to "new last matching" rule or NULL */
5590 /* Parameters: fin(I) - pointer to packet information */
5591 /* passp(IO) - pointer to current/new filter decision (unused) */
5592 /* */
5593 /* Look for a rule group head in a hash table, using the destination */
5594 /* address as the key, and descend into that group and continue matching */
5595 /* rules against the packet. */
5596 /* ------------------------------------------------------------------------ */
5597 frentry_t *
ipf_dstgrpmap(fr_info_t * fin,u_32_t * passp)5598 ipf_dstgrpmap(fr_info_t *fin, u_32_t *passp)
5599 {
5600 frgroup_t *fg;
5601 void *rval;
5602
5603 rval = ipf_iphmfindgroup(fin->fin_main_soft, fin->fin_fr->fr_ptr,
5604 &fin->fin_dst);
5605 if (rval == NULL)
5606 return (NULL);
5607
5608 fg = rval;
5609 fin->fin_fr = fg->fg_start;
5610 (void) ipf_scanlist(fin, *passp);
5611 return (fin->fin_fr);
5612 }
5613
5614 /*
5615 * Queue functions
5616 * ===============
5617 * These functions manage objects on queues for efficient timeouts. There
5618 * are a number of system defined queues as well as user defined timeouts.
5619 * It is expected that a lock is held in the domain in which the queue
5620 * belongs (i.e. either state or NAT) when calling any of these functions
5621 * that prevents ipf_freetimeoutqueue() from being called at the same time
5622 * as any other.
5623 */
5624
5625
5626 /* ------------------------------------------------------------------------ */
5627 /* Function: ipf_addtimeoutqueue */
5628 /* Returns: struct ifqtq * - NULL if malloc fails, else pointer to */
5629 /* timeout queue with given interval. */
5630 /* Parameters: parent(I) - pointer to pointer to parent node of this list */
5631 /* of interface queues. */
5632 /* seconds(I) - timeout value in seconds for this queue. */
5633 /* */
5634 /* This routine first looks for a timeout queue that matches the interval */
5635 /* being requested. If it finds one, increments the reference counter and */
5636 /* returns a pointer to it. If none are found, it allocates a new one and */
5637 /* inserts it at the top of the list. */
5638 /* */
5639 /* Locking. */
5640 /* It is assumed that the caller of this function has an appropriate lock */
5641 /* held (exclusively) in the domain that encompases 'parent'. */
5642 /* ------------------------------------------------------------------------ */
5643 ipftq_t *
ipf_addtimeoutqueue(ipf_main_softc_t * softc,ipftq_t ** parent,u_int seconds)5644 ipf_addtimeoutqueue(ipf_main_softc_t *softc, ipftq_t **parent, u_int seconds)
5645 {
5646 ipftq_t *ifq;
5647 u_int period;
5648
5649 period = seconds * IPF_HZ_DIVIDE;
5650
5651 MUTEX_ENTER(&softc->ipf_timeoutlock);
5652 for (ifq = *parent; ifq != NULL; ifq = ifq->ifq_next) {
5653 if (ifq->ifq_ttl == period) {
5654 /*
5655 * Reset the delete flag, if set, so the structure
5656 * gets reused rather than freed and reallocated.
5657 */
5658 MUTEX_ENTER(&ifq->ifq_lock);
5659 ifq->ifq_flags &= ~IFQF_DELETE;
5660 ifq->ifq_ref++;
5661 MUTEX_EXIT(&ifq->ifq_lock);
5662 MUTEX_EXIT(&softc->ipf_timeoutlock);
5663
5664 return (ifq);
5665 }
5666 }
5667
5668 KMALLOC(ifq, ipftq_t *);
5669 if (ifq != NULL) {
5670 MUTEX_NUKE(&ifq->ifq_lock);
5671 IPFTQ_INIT(ifq, period, "ipftq mutex");
5672 ifq->ifq_next = *parent;
5673 ifq->ifq_pnext = parent;
5674 ifq->ifq_flags = IFQF_USER;
5675 ifq->ifq_ref++;
5676 *parent = ifq;
5677 softc->ipf_userifqs++;
5678 }
5679 MUTEX_EXIT(&softc->ipf_timeoutlock);
5680 return (ifq);
5681 }
5682
5683
5684 /* ------------------------------------------------------------------------ */
5685 /* Function: ipf_deletetimeoutqueue */
5686 /* Returns: int - new reference count value of the timeout queue */
5687 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5688 /* Locks: ifq->ifq_lock */
5689 /* */
5690 /* This routine must be called when we're discarding a pointer to a timeout */
5691 /* queue object, taking care of the reference counter. */
5692 /* */
5693 /* Now that this just sets a DELETE flag, it requires the expire code to */
5694 /* check the list of user defined timeout queues and call the free function */
5695 /* below (currently commented out) to stop memory leaking. It is done this */
5696 /* way because the locking may not be sufficient to safely do a free when */
5697 /* this function is called. */
5698 /* ------------------------------------------------------------------------ */
5699 int
ipf_deletetimeoutqueue(ipftq_t * ifq)5700 ipf_deletetimeoutqueue(ipftq_t *ifq)
5701 {
5702
5703 ifq->ifq_ref--;
5704 if ((ifq->ifq_ref == 0) && ((ifq->ifq_flags & IFQF_USER) != 0)) {
5705 ifq->ifq_flags |= IFQF_DELETE;
5706 }
5707
5708 return (ifq->ifq_ref);
5709 }
5710
5711
5712 /* ------------------------------------------------------------------------ */
5713 /* Function: ipf_freetimeoutqueue */
5714 /* Parameters: ifq(I) - timeout queue which is losing a reference. */
5715 /* Returns: Nil */
5716 /* */
5717 /* Locking: */
5718 /* It is assumed that the caller of this function has an appropriate lock */
5719 /* held (exclusively) in the domain that encompases the callers "domain". */
5720 /* The ifq_lock for this structure should not be held. */
5721 /* */
5722 /* Remove a user defined timeout queue from the list of queues it is in and */
5723 /* tidy up after this is done. */
5724 /* ------------------------------------------------------------------------ */
5725 void
ipf_freetimeoutqueue(ipf_main_softc_t * softc,ipftq_t * ifq)5726 ipf_freetimeoutqueue(ipf_main_softc_t *softc, ipftq_t *ifq)
5727 {
5728
5729 if (((ifq->ifq_flags & IFQF_DELETE) == 0) || (ifq->ifq_ref != 0) ||
5730 ((ifq->ifq_flags & IFQF_USER) == 0)) {
5731 printf("ipf_freetimeoutqueue(%lx) flags 0x%x ttl %d ref %d\n",
5732 (u_long)ifq, ifq->ifq_flags, ifq->ifq_ttl,
5733 ifq->ifq_ref);
5734 return;
5735 }
5736
5737 /*
5738 * Remove from its position in the list.
5739 */
5740 *ifq->ifq_pnext = ifq->ifq_next;
5741 if (ifq->ifq_next != NULL)
5742 ifq->ifq_next->ifq_pnext = ifq->ifq_pnext;
5743 ifq->ifq_next = NULL;
5744 ifq->ifq_pnext = NULL;
5745
5746 MUTEX_DESTROY(&ifq->ifq_lock);
5747 ATOMIC_DEC(softc->ipf_userifqs);
5748 KFREE(ifq);
5749 }
5750
5751
5752 /* ------------------------------------------------------------------------ */
5753 /* Function: ipf_deletequeueentry */
5754 /* Returns: Nil */
5755 /* Parameters: tqe(I) - timeout queue entry to delete */
5756 /* */
5757 /* Remove a tail queue entry from its queue and make it an orphan. */
5758 /* ipf_deletetimeoutqueue is called to make sure the reference count on the */
5759 /* queue is correct. We can't, however, call ipf_freetimeoutqueue because */
5760 /* the correct lock(s) may not be held that would make it safe to do so. */
5761 /* ------------------------------------------------------------------------ */
5762 void
ipf_deletequeueentry(ipftqent_t * tqe)5763 ipf_deletequeueentry(ipftqent_t *tqe)
5764 {
5765 ipftq_t *ifq;
5766
5767 ifq = tqe->tqe_ifq;
5768
5769 MUTEX_ENTER(&ifq->ifq_lock);
5770
5771 if (tqe->tqe_pnext != NULL) {
5772 *tqe->tqe_pnext = tqe->tqe_next;
5773 if (tqe->tqe_next != NULL)
5774 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5775 else /* we must be the tail anyway */
5776 ifq->ifq_tail = tqe->tqe_pnext;
5777
5778 tqe->tqe_pnext = NULL;
5779 tqe->tqe_ifq = NULL;
5780 }
5781
5782 (void) ipf_deletetimeoutqueue(ifq);
5783 ASSERT(ifq->ifq_ref > 0);
5784
5785 MUTEX_EXIT(&ifq->ifq_lock);
5786 }
5787
5788
5789 /* ------------------------------------------------------------------------ */
5790 /* Function: ipf_queuefront */
5791 /* Returns: Nil */
5792 /* Parameters: tqe(I) - pointer to timeout queue entry */
5793 /* */
5794 /* Move a queue entry to the front of the queue, if it isn't already there. */
5795 /* ------------------------------------------------------------------------ */
5796 void
ipf_queuefront(ipftqent_t * tqe)5797 ipf_queuefront(ipftqent_t *tqe)
5798 {
5799 ipftq_t *ifq;
5800
5801 ifq = tqe->tqe_ifq;
5802 if (ifq == NULL)
5803 return;
5804
5805 MUTEX_ENTER(&ifq->ifq_lock);
5806 if (ifq->ifq_head != tqe) {
5807 *tqe->tqe_pnext = tqe->tqe_next;
5808 if (tqe->tqe_next)
5809 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5810 else
5811 ifq->ifq_tail = tqe->tqe_pnext;
5812
5813 tqe->tqe_next = ifq->ifq_head;
5814 ifq->ifq_head->tqe_pnext = &tqe->tqe_next;
5815 ifq->ifq_head = tqe;
5816 tqe->tqe_pnext = &ifq->ifq_head;
5817 }
5818 MUTEX_EXIT(&ifq->ifq_lock);
5819 }
5820
5821
5822 /* ------------------------------------------------------------------------ */
5823 /* Function: ipf_queueback */
5824 /* Returns: Nil */
5825 /* Parameters: ticks(I) - ipf tick time to use with this call */
5826 /* tqe(I) - pointer to timeout queue entry */
5827 /* */
5828 /* Move a queue entry to the back of the queue, if it isn't already there. */
5829 /* We use use ticks to calculate the expiration and mark for when we last */
5830 /* touched the structure. */
5831 /* ------------------------------------------------------------------------ */
5832 void
ipf_queueback(u_long ticks,ipftqent_t * tqe)5833 ipf_queueback(u_long ticks, ipftqent_t *tqe)
5834 {
5835 ipftq_t *ifq;
5836
5837 ifq = tqe->tqe_ifq;
5838 if (ifq == NULL)
5839 return;
5840 tqe->tqe_die = ticks + ifq->ifq_ttl;
5841 tqe->tqe_touched = ticks;
5842
5843 MUTEX_ENTER(&ifq->ifq_lock);
5844 if (tqe->tqe_next != NULL) { /* at the end already ? */
5845 /*
5846 * Remove from list
5847 */
5848 *tqe->tqe_pnext = tqe->tqe_next;
5849 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5850
5851 /*
5852 * Make it the last entry.
5853 */
5854 tqe->tqe_next = NULL;
5855 tqe->tqe_pnext = ifq->ifq_tail;
5856 *ifq->ifq_tail = tqe;
5857 ifq->ifq_tail = &tqe->tqe_next;
5858 }
5859 MUTEX_EXIT(&ifq->ifq_lock);
5860 }
5861
5862
5863 /* ------------------------------------------------------------------------ */
5864 /* Function: ipf_queueappend */
5865 /* Returns: Nil */
5866 /* Parameters: ticks(I) - ipf tick time to use with this call */
5867 /* tqe(I) - pointer to timeout queue entry */
5868 /* ifq(I) - pointer to timeout queue */
5869 /* parent(I) - owing object pointer */
5870 /* */
5871 /* Add a new item to this queue and put it on the very end. */
5872 /* We use use ticks to calculate the expiration and mark for when we last */
5873 /* touched the structure. */
5874 /* ------------------------------------------------------------------------ */
5875 void
ipf_queueappend(u_long ticks,ipftqent_t * tqe,ipftq_t * ifq,void * parent)5876 ipf_queueappend(u_long ticks, ipftqent_t *tqe, ipftq_t *ifq, void *parent)
5877 {
5878
5879 MUTEX_ENTER(&ifq->ifq_lock);
5880 tqe->tqe_parent = parent;
5881 tqe->tqe_pnext = ifq->ifq_tail;
5882 *ifq->ifq_tail = tqe;
5883 ifq->ifq_tail = &tqe->tqe_next;
5884 tqe->tqe_next = NULL;
5885 tqe->tqe_ifq = ifq;
5886 tqe->tqe_die = ticks + ifq->ifq_ttl;
5887 tqe->tqe_touched = ticks;
5888 ifq->ifq_ref++;
5889 MUTEX_EXIT(&ifq->ifq_lock);
5890 }
5891
5892
5893 /* ------------------------------------------------------------------------ */
5894 /* Function: ipf_movequeue */
5895 /* Returns: Nil */
5896 /* Parameters: tq(I) - pointer to timeout queue information */
5897 /* oifp(I) - old timeout queue entry was on */
5898 /* nifp(I) - new timeout queue to put entry on */
5899 /* */
5900 /* Move a queue entry from one timeout queue to another timeout queue. */
5901 /* If it notices that the current entry is already last and does not need */
5902 /* to move queue, the return. */
5903 /* ------------------------------------------------------------------------ */
5904 void
ipf_movequeue(u_long ticks,ipftqent_t * tqe,ipftq_t * oifq,ipftq_t * nifq)5905 ipf_movequeue(u_long ticks, ipftqent_t *tqe, ipftq_t *oifq, ipftq_t *nifq)
5906 {
5907
5908 /*
5909 * If the queue hasn't changed and we last touched this entry at the
5910 * same ipf time, then we're not going to achieve anything by either
5911 * changing the ttl or moving it on the queue.
5912 */
5913 if (oifq == nifq && tqe->tqe_touched == ticks)
5914 return;
5915
5916 /*
5917 * For any of this to be outside the lock, there is a risk that two
5918 * packets entering simultaneously, with one changing to a different
5919 * queue and one not, could end up with things in a bizarre state.
5920 */
5921 MUTEX_ENTER(&oifq->ifq_lock);
5922
5923 tqe->tqe_touched = ticks;
5924 tqe->tqe_die = ticks + nifq->ifq_ttl;
5925 /*
5926 * Is the operation here going to be a no-op ?
5927 */
5928 if (oifq == nifq) {
5929 if ((tqe->tqe_next == NULL) ||
5930 (tqe->tqe_next->tqe_die == tqe->tqe_die)) {
5931 MUTEX_EXIT(&oifq->ifq_lock);
5932 return;
5933 }
5934 }
5935
5936 /*
5937 * Remove from the old queue
5938 */
5939 *tqe->tqe_pnext = tqe->tqe_next;
5940 if (tqe->tqe_next)
5941 tqe->tqe_next->tqe_pnext = tqe->tqe_pnext;
5942 else
5943 oifq->ifq_tail = tqe->tqe_pnext;
5944 tqe->tqe_next = NULL;
5945
5946 /*
5947 * If we're moving from one queue to another, release the
5948 * lock on the old queue and get a lock on the new queue.
5949 * For user defined queues, if we're moving off it, call
5950 * delete in case it can now be freed.
5951 */
5952 if (oifq != nifq) {
5953 tqe->tqe_ifq = NULL;
5954
5955 (void) ipf_deletetimeoutqueue(oifq);
5956
5957 MUTEX_EXIT(&oifq->ifq_lock);
5958
5959 MUTEX_ENTER(&nifq->ifq_lock);
5960
5961 tqe->tqe_ifq = nifq;
5962 nifq->ifq_ref++;
5963 }
5964
5965 /*
5966 * Add to the bottom of the new queue
5967 */
5968 tqe->tqe_pnext = nifq->ifq_tail;
5969 *nifq->ifq_tail = tqe;
5970 nifq->ifq_tail = &tqe->tqe_next;
5971 MUTEX_EXIT(&nifq->ifq_lock);
5972 }
5973
5974
5975 /* ------------------------------------------------------------------------ */
5976 /* Function: ipf_updateipid */
5977 /* Returns: int - 0 == success, -1 == error (packet should be droppped) */
5978 /* Parameters: fin(I) - pointer to packet information */
5979 /* */
5980 /* When we are doing NAT, change the IP of every packet to represent a */
5981 /* single sequence of packets coming from the host, hiding any host */
5982 /* specific sequencing that might otherwise be revealed. If the packet is */
5983 /* a fragment, then store the 'new' IPid in the fragment cache and look up */
5984 /* the fragment cache for non-leading fragments. If a non-leading fragment */
5985 /* has no match in the cache, return an error. */
5986 /* ------------------------------------------------------------------------ */
5987 static int
ipf_updateipid(fr_info_t * fin)5988 ipf_updateipid(fr_info_t *fin)
5989 {
5990 u_short id, ido, sums;
5991 u_32_t sumd, sum;
5992 ip_t *ip;
5993
5994 ip = fin->fin_ip;
5995 ido = ntohs(ip->ip_id);
5996 if (fin->fin_off != 0) {
5997 sum = ipf_frag_ipidknown(fin);
5998 if (sum == 0xffffffff)
5999 return (-1);
6000 sum &= 0xffff;
6001 id = (u_short)sum;
6002 ip->ip_id = htons(id);
6003 } else {
6004 ip_fillid(ip, V_ip_random_id);
6005 id = ntohs(ip->ip_id);
6006 if ((fin->fin_flx & FI_FRAG) != 0)
6007 (void) ipf_frag_ipidnew(fin, (u_32_t)id);
6008 }
6009
6010 if (id == ido)
6011 return (0);
6012 CALC_SUMD(ido, id, sumd); /* DESTRUCTIVE MACRO! id,ido change */
6013 sum = (~ntohs(ip->ip_sum)) & 0xffff;
6014 sum += sumd;
6015 sum = (sum >> 16) + (sum & 0xffff);
6016 sum = (sum >> 16) + (sum & 0xffff);
6017 sums = ~(u_short)sum;
6018 ip->ip_sum = htons(sums);
6019 return (0);
6020 }
6021
6022
6023 #ifdef NEED_FRGETIFNAME
6024 /* ------------------------------------------------------------------------ */
6025 /* Function: ipf_getifname */
6026 /* Returns: char * - pointer to interface name */
6027 /* Parameters: ifp(I) - pointer to network interface */
6028 /* buffer(O) - pointer to where to store interface name */
6029 /* */
6030 /* Constructs an interface name in the buffer passed. The buffer passed is */
6031 /* expected to be at least LIFNAMSIZ in bytes big. If buffer is passed in */
6032 /* as a NULL pointer then return a pointer to a static array. */
6033 /* ------------------------------------------------------------------------ */
6034 char *
ipf_getifname(struct ifnet * ifp,char * buffer)6035 ipf_getifname(struct ifnet *ifp, char *buffer)
6036 {
6037 static char namebuf[LIFNAMSIZ];
6038 # if SOLARIS || defined(__FreeBSD__)
6039 int unit, space;
6040 char temp[20];
6041 char *s;
6042 # endif
6043
6044 if (buffer == NULL)
6045 buffer = namebuf;
6046 (void) strncpy(buffer, ifp->if_name, LIFNAMSIZ);
6047 buffer[LIFNAMSIZ - 1] = '\0';
6048 # if SOLARIS || defined(__FreeBSD__)
6049 for (s = buffer; *s; s++)
6050 ;
6051 unit = ifp->if_unit;
6052 space = LIFNAMSIZ - (s - buffer);
6053 if ((space > 0) && (unit >= 0)) {
6054 (void) snprintf(temp, sizeof(name), "%d", unit);
6055 (void) strncpy(s, temp, space);
6056 }
6057 # endif
6058 return (buffer);
6059 }
6060 #endif
6061
6062
6063 /* ------------------------------------------------------------------------ */
6064 /* Function: ipf_ioctlswitch */
6065 /* Returns: int - -1 continue processing, else ioctl return value */
6066 /* Parameters: unit(I) - device unit opened */
6067 /* data(I) - pointer to ioctl data */
6068 /* cmd(I) - ioctl command */
6069 /* mode(I) - mode value */
6070 /* uid(I) - uid making the ioctl call */
6071 /* ctx(I) - pointer to context data */
6072 /* */
6073 /* Based on the value of unit, call the appropriate ioctl handler or return */
6074 /* EIO if ipfilter is not running. Also checks if write perms are req'd */
6075 /* for the device in order to execute the ioctl. A special case is made */
6076 /* SIOCIPFINTERROR so that the same code isn't required in every handler. */
6077 /* The context data pointer is passed through as this is used as the key */
6078 /* for locating a matching token for continued access for walking lists, */
6079 /* etc. */
6080 /* ------------------------------------------------------------------------ */
6081 int
ipf_ioctlswitch(ipf_main_softc_t * softc,int unit,void * data,ioctlcmd_t cmd,int mode,int uid,void * ctx)6082 ipf_ioctlswitch(ipf_main_softc_t *softc, int unit, void *data, ioctlcmd_t cmd,
6083 int mode, int uid, void *ctx)
6084 {
6085 int error = 0;
6086
6087 switch (cmd)
6088 {
6089 case SIOCIPFINTERROR :
6090 error = BCOPYOUT(&softc->ipf_interror, data,
6091 sizeof(softc->ipf_interror));
6092 if (error != 0) {
6093 IPFERROR(40);
6094 error = EFAULT;
6095 }
6096 return (error);
6097 default :
6098 break;
6099 }
6100
6101 switch (unit)
6102 {
6103 case IPL_LOGIPF :
6104 error = ipf_ipf_ioctl(softc, data, cmd, mode, uid, ctx);
6105 break;
6106 case IPL_LOGNAT :
6107 if (softc->ipf_running > 0) {
6108 error = ipf_nat_ioctl(softc, data, cmd, mode,
6109 uid, ctx);
6110 } else {
6111 IPFERROR(42);
6112 error = EIO;
6113 }
6114 break;
6115 case IPL_LOGSTATE :
6116 if (softc->ipf_running > 0) {
6117 error = ipf_state_ioctl(softc, data, cmd, mode,
6118 uid, ctx);
6119 } else {
6120 IPFERROR(43);
6121 error = EIO;
6122 }
6123 break;
6124 case IPL_LOGAUTH :
6125 if (softc->ipf_running > 0) {
6126 error = ipf_auth_ioctl(softc, data, cmd, mode,
6127 uid, ctx);
6128 } else {
6129 IPFERROR(44);
6130 error = EIO;
6131 }
6132 break;
6133 case IPL_LOGSYNC :
6134 if (softc->ipf_running > 0) {
6135 error = ipf_sync_ioctl(softc, data, cmd, mode,
6136 uid, ctx);
6137 } else {
6138 error = EIO;
6139 IPFERROR(45);
6140 }
6141 break;
6142 case IPL_LOGSCAN :
6143 #ifdef IPFILTER_SCAN
6144 if (softc->ipf_running > 0)
6145 error = ipf_scan_ioctl(softc, data, cmd, mode,
6146 uid, ctx);
6147 else
6148 #endif
6149 {
6150 error = EIO;
6151 IPFERROR(46);
6152 }
6153 break;
6154 case IPL_LOGLOOKUP :
6155 if (softc->ipf_running > 0) {
6156 error = ipf_lookup_ioctl(softc, data, cmd, mode,
6157 uid, ctx);
6158 } else {
6159 error = EIO;
6160 IPFERROR(47);
6161 }
6162 break;
6163 default :
6164 IPFERROR(48);
6165 error = EIO;
6166 break;
6167 }
6168
6169 return (error);
6170 }
6171
6172
6173 /*
6174 * This array defines the expected size of objects coming into the kernel
6175 * for the various recognised object types. The first column is flags (see
6176 * below), 2nd column is current size, 3rd column is the version number of
6177 * when the current size became current.
6178 * Flags:
6179 * 1 = minimum size, not absolute size
6180 */
6181 static const int ipf_objbytes[IPFOBJ_COUNT][3] = {
6182 { 1, sizeof(struct frentry), 5010000 }, /* 0 */
6183 { 1, sizeof(struct friostat), 5010000 },
6184 { 0, sizeof(struct fr_info), 5010000 },
6185 { 0, sizeof(struct ipf_authstat), 4010100 },
6186 { 0, sizeof(struct ipfrstat), 5010000 },
6187 { 1, sizeof(struct ipnat), 5010000 }, /* 5 */
6188 { 0, sizeof(struct natstat), 5010000 },
6189 { 0, sizeof(struct ipstate_save), 5010000 },
6190 { 1, sizeof(struct nat_save), 5010000 },
6191 { 0, sizeof(struct natlookup), 5010000 },
6192 { 1, sizeof(struct ipstate), 5010000 }, /* 10 */
6193 { 0, sizeof(struct ips_stat), 5010000 },
6194 { 0, sizeof(struct frauth), 5010000 },
6195 { 0, sizeof(struct ipftune), 4010100 },
6196 { 0, sizeof(struct nat), 5010000 },
6197 { 0, sizeof(struct ipfruleiter), 4011400 }, /* 15 */
6198 { 0, sizeof(struct ipfgeniter), 4011400 },
6199 { 0, sizeof(struct ipftable), 4011400 },
6200 { 0, sizeof(struct ipflookupiter), 4011400 },
6201 { 0, sizeof(struct ipftq) * IPF_TCP_NSTATES },
6202 { 1, 0, 0 }, /* IPFEXPR */
6203 { 0, 0, 0 }, /* PROXYCTL */
6204 { 0, sizeof (struct fripf), 5010000 }
6205 };
6206
6207
6208 /* ------------------------------------------------------------------------ */
6209 /* Function: ipf_inobj */
6210 /* Returns: int - 0 = success, else failure */
6211 /* Parameters: softc(I) - soft context pointerto work with */
6212 /* data(I) - pointer to ioctl data */
6213 /* objp(O) - where to store ipfobj structure */
6214 /* ptr(I) - pointer to data to copy out */
6215 /* type(I) - type of structure being moved */
6216 /* */
6217 /* Copy in the contents of what the ipfobj_t points to. In future, we */
6218 /* add things to check for version numbers, sizes, etc, to make it backward */
6219 /* compatible at the ABI for user land. */
6220 /* If objp is not NULL then we assume that the caller wants to see what is */
6221 /* in the ipfobj_t structure being copied in. As an example, this can tell */
6222 /* the caller what version of ipfilter the ioctl program was written to. */
6223 /* ------------------------------------------------------------------------ */
6224 int
ipf_inobj(ipf_main_softc_t * softc,void * data,ipfobj_t * objp,void * ptr,int type)6225 ipf_inobj(ipf_main_softc_t *softc, void *data, ipfobj_t *objp, void *ptr,
6226 int type)
6227 {
6228 ipfobj_t obj;
6229 int error;
6230 int size;
6231
6232 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6233 IPFERROR(49);
6234 return (EINVAL);
6235 }
6236
6237 if (objp == NULL)
6238 objp = &obj;
6239 error = BCOPYIN(data, objp, sizeof(*objp));
6240 if (error != 0) {
6241 IPFERROR(124);
6242 return (EFAULT);
6243 }
6244
6245 if (objp->ipfo_type != type) {
6246 IPFERROR(50);
6247 return (EINVAL);
6248 }
6249
6250 if (objp->ipfo_rev >= ipf_objbytes[type][2]) {
6251 if ((ipf_objbytes[type][0] & 1) != 0) {
6252 if (objp->ipfo_size < ipf_objbytes[type][1]) {
6253 IPFERROR(51);
6254 return (EINVAL);
6255 }
6256 size = ipf_objbytes[type][1];
6257 } else if (objp->ipfo_size == ipf_objbytes[type][1]) {
6258 size = objp->ipfo_size;
6259 } else {
6260 IPFERROR(52);
6261 return (EINVAL);
6262 }
6263 error = COPYIN(objp->ipfo_ptr, ptr, size);
6264 if (error != 0) {
6265 IPFERROR(55);
6266 error = EFAULT;
6267 }
6268 } else {
6269 #ifdef IPFILTER_COMPAT
6270 error = ipf_in_compat(softc, objp, ptr, 0);
6271 #else
6272 IPFERROR(54);
6273 error = EINVAL;
6274 #endif
6275 }
6276 return (error);
6277 }
6278
6279
6280 /* ------------------------------------------------------------------------ */
6281 /* Function: ipf_inobjsz */
6282 /* Returns: int - 0 = success, else failure */
6283 /* Parameters: softc(I) - soft context pointerto work with */
6284 /* data(I) - pointer to ioctl data */
6285 /* ptr(I) - pointer to store real data in */
6286 /* type(I) - type of structure being moved */
6287 /* sz(I) - size of data to copy */
6288 /* */
6289 /* As per ipf_inobj, except the size of the object to copy in is passed in */
6290 /* but it must not be smaller than the size defined for the type and the */
6291 /* type must allow for varied sized objects. The extra requirement here is */
6292 /* that sz must match the size of the object being passed in - this is not */
6293 /* not possible nor required in ipf_inobj(). */
6294 /* ------------------------------------------------------------------------ */
6295 int
ipf_inobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6296 ipf_inobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6297 {
6298 ipfobj_t obj;
6299 int error;
6300
6301 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6302 IPFERROR(56);
6303 return (EINVAL);
6304 }
6305
6306 error = BCOPYIN(data, &obj, sizeof(obj));
6307 if (error != 0) {
6308 IPFERROR(125);
6309 return (EFAULT);
6310 }
6311
6312 if (obj.ipfo_type != type) {
6313 IPFERROR(58);
6314 return (EINVAL);
6315 }
6316
6317 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6318 if (((ipf_objbytes[type][0] & 1) == 0) ||
6319 (sz < ipf_objbytes[type][1])) {
6320 IPFERROR(57);
6321 return (EINVAL);
6322 }
6323 error = COPYIN(obj.ipfo_ptr, ptr, sz);
6324 if (error != 0) {
6325 IPFERROR(61);
6326 error = EFAULT;
6327 }
6328 } else {
6329 #ifdef IPFILTER_COMPAT
6330 error = ipf_in_compat(softc, &obj, ptr, sz);
6331 #else
6332 IPFERROR(60);
6333 error = EINVAL;
6334 #endif
6335 }
6336 return (error);
6337 }
6338
6339
6340 /* ------------------------------------------------------------------------ */
6341 /* Function: ipf_outobjsz */
6342 /* Returns: int - 0 = success, else failure */
6343 /* Parameters: data(I) - pointer to ioctl data */
6344 /* ptr(I) - pointer to store real data in */
6345 /* type(I) - type of structure being moved */
6346 /* sz(I) - size of data to copy */
6347 /* */
6348 /* As per ipf_outobj, except the size of the object to copy out is passed in*/
6349 /* but it must not be smaller than the size defined for the type and the */
6350 /* type must allow for varied sized objects. The extra requirement here is */
6351 /* that sz must match the size of the object being passed in - this is not */
6352 /* not possible nor required in ipf_outobj(). */
6353 /* ------------------------------------------------------------------------ */
6354 int
ipf_outobjsz(ipf_main_softc_t * softc,void * data,void * ptr,int type,int sz)6355 ipf_outobjsz(ipf_main_softc_t *softc, void *data, void *ptr, int type, int sz)
6356 {
6357 ipfobj_t obj;
6358 int error;
6359
6360 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6361 IPFERROR(62);
6362 return (EINVAL);
6363 }
6364
6365 error = BCOPYIN(data, &obj, sizeof(obj));
6366 if (error != 0) {
6367 IPFERROR(127);
6368 return (EFAULT);
6369 }
6370
6371 if (obj.ipfo_type != type) {
6372 IPFERROR(63);
6373 return (EINVAL);
6374 }
6375
6376 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6377 if (((ipf_objbytes[type][0] & 1) == 0) ||
6378 (sz < ipf_objbytes[type][1])) {
6379 IPFERROR(146);
6380 return (EINVAL);
6381 }
6382 error = COPYOUT(ptr, obj.ipfo_ptr, sz);
6383 if (error != 0) {
6384 IPFERROR(66);
6385 error = EFAULT;
6386 }
6387 } else {
6388 #ifdef IPFILTER_COMPAT
6389 error = ipf_out_compat(softc, &obj, ptr);
6390 #else
6391 IPFERROR(65);
6392 error = EINVAL;
6393 #endif
6394 }
6395 return (error);
6396 }
6397
6398
6399 /* ------------------------------------------------------------------------ */
6400 /* Function: ipf_outobj */
6401 /* Returns: int - 0 = success, else failure */
6402 /* Parameters: data(I) - pointer to ioctl data */
6403 /* ptr(I) - pointer to store real data in */
6404 /* type(I) - type of structure being moved */
6405 /* */
6406 /* Copy out the contents of what ptr is to where ipfobj points to. In */
6407 /* future, we add things to check for version numbers, sizes, etc, to make */
6408 /* it backward compatible at the ABI for user land. */
6409 /* ------------------------------------------------------------------------ */
6410 int
ipf_outobj(ipf_main_softc_t * softc,void * data,void * ptr,int type)6411 ipf_outobj(ipf_main_softc_t *softc, void *data, void *ptr, int type)
6412 {
6413 ipfobj_t obj;
6414 int error;
6415
6416 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6417 IPFERROR(67);
6418 return (EINVAL);
6419 }
6420
6421 error = BCOPYIN(data, &obj, sizeof(obj));
6422 if (error != 0) {
6423 IPFERROR(126);
6424 return (EFAULT);
6425 }
6426
6427 if (obj.ipfo_type != type) {
6428 IPFERROR(68);
6429 return (EINVAL);
6430 }
6431
6432 if (obj.ipfo_rev >= ipf_objbytes[type][2]) {
6433 if ((ipf_objbytes[type][0] & 1) != 0) {
6434 if (obj.ipfo_size < ipf_objbytes[type][1]) {
6435 IPFERROR(69);
6436 return (EINVAL);
6437 }
6438 } else if (obj.ipfo_size != ipf_objbytes[type][1]) {
6439 IPFERROR(70);
6440 return (EINVAL);
6441 }
6442
6443 error = COPYOUT(ptr, obj.ipfo_ptr, obj.ipfo_size);
6444 if (error != 0) {
6445 IPFERROR(73);
6446 error = EFAULT;
6447 }
6448 } else {
6449 #ifdef IPFILTER_COMPAT
6450 error = ipf_out_compat(softc, &obj, ptr);
6451 #else
6452 IPFERROR(72);
6453 error = EINVAL;
6454 #endif
6455 }
6456 return (error);
6457 }
6458
6459
6460 /* ------------------------------------------------------------------------ */
6461 /* Function: ipf_outobjk */
6462 /* Returns: int - 0 = success, else failure */
6463 /* Parameters: obj(I) - pointer to data description structure */
6464 /* ptr(I) - pointer to kernel data to copy out */
6465 /* */
6466 /* In the above functions, the ipfobj_t structure is copied into the kernel,*/
6467 /* telling ipfilter how to copy out data. In this instance, the ipfobj_t is */
6468 /* already populated with information and now we just need to use it. */
6469 /* There is no need for this function to have a "type" parameter as there */
6470 /* is no point in validating information that comes from the kernel with */
6471 /* itself. */
6472 /* ------------------------------------------------------------------------ */
6473 int
ipf_outobjk(ipf_main_softc_t * softc,ipfobj_t * obj,void * ptr)6474 ipf_outobjk(ipf_main_softc_t *softc, ipfobj_t *obj, void *ptr)
6475 {
6476 int type = obj->ipfo_type;
6477 int error;
6478
6479 if ((type < 0) || (type >= IPFOBJ_COUNT)) {
6480 IPFERROR(147);
6481 return (EINVAL);
6482 }
6483
6484 if (obj->ipfo_rev >= ipf_objbytes[type][2]) {
6485 if ((ipf_objbytes[type][0] & 1) != 0) {
6486 if (obj->ipfo_size < ipf_objbytes[type][1]) {
6487 IPFERROR(148);
6488 return (EINVAL);
6489 }
6490
6491 } else if (obj->ipfo_size != ipf_objbytes[type][1]) {
6492 IPFERROR(149);
6493 return (EINVAL);
6494 }
6495
6496 error = COPYOUT(ptr, obj->ipfo_ptr, obj->ipfo_size);
6497 if (error != 0) {
6498 IPFERROR(150);
6499 error = EFAULT;
6500 }
6501 } else {
6502 #ifdef IPFILTER_COMPAT
6503 error = ipf_out_compat(softc, obj, ptr);
6504 #else
6505 IPFERROR(151);
6506 error = EINVAL;
6507 #endif
6508 }
6509 return (error);
6510 }
6511
6512
6513 /* ------------------------------------------------------------------------ */
6514 /* Function: ipf_checkl4sum */
6515 /* Returns: int - 0 = good, -1 = bad, 1 = cannot check */
6516 /* Parameters: fin(I) - pointer to packet information */
6517 /* */
6518 /* If possible, calculate the layer 4 checksum for the packet. If this is */
6519 /* not possible, return without indicating a failure or success but in a */
6520 /* way that is ditinguishable. This function should only be called by the */
6521 /* ipf_checkv6sum() for each platform. */
6522 /* ------------------------------------------------------------------------ */
6523 inline int
ipf_checkl4sum(fr_info_t * fin)6524 ipf_checkl4sum(fr_info_t *fin)
6525 {
6526 u_short sum, hdrsum, *csump;
6527 udphdr_t *udp;
6528 int dosum;
6529
6530 /*
6531 * If the TCP packet isn't a fragment, isn't too short and otherwise
6532 * isn't already considered "bad", then validate the checksum. If
6533 * this check fails then considered the packet to be "bad".
6534 */
6535 if ((fin->fin_flx & (FI_FRAG|FI_SHORT|FI_BAD)) != 0)
6536 return (1);
6537
6538 DT2(l4sumo, int, fin->fin_out, int, (int)fin->fin_p);
6539 if (fin->fin_out == 1) {
6540 fin->fin_cksum = FI_CK_SUMOK;
6541 return (0);
6542 }
6543
6544 csump = NULL;
6545 hdrsum = 0;
6546 dosum = 0;
6547 sum = 0;
6548
6549 switch (fin->fin_p)
6550 {
6551 case IPPROTO_TCP :
6552 csump = &((tcphdr_t *)fin->fin_dp)->th_sum;
6553 dosum = 1;
6554 break;
6555
6556 case IPPROTO_UDP :
6557 udp = fin->fin_dp;
6558 if (udp->uh_sum != 0) {
6559 csump = &udp->uh_sum;
6560 dosum = 1;
6561 }
6562 break;
6563
6564 #ifdef USE_INET6
6565 case IPPROTO_ICMPV6 :
6566 csump = &((struct icmp6_hdr *)fin->fin_dp)->icmp6_cksum;
6567 dosum = 1;
6568 break;
6569 #endif
6570
6571 case IPPROTO_ICMP :
6572 csump = &((struct icmp *)fin->fin_dp)->icmp_cksum;
6573 dosum = 1;
6574 break;
6575
6576 default :
6577 return (1);
6578 /*NOTREACHED*/
6579 }
6580
6581 if (csump != NULL) {
6582 hdrsum = *csump;
6583 if (fin->fin_p == IPPROTO_UDP && hdrsum == 0xffff)
6584 hdrsum = 0x0000;
6585 }
6586
6587 if (dosum) {
6588 sum = fr_cksum(fin, fin->fin_ip, fin->fin_p, fin->fin_dp);
6589 }
6590 #if !defined(_KERNEL)
6591 if (sum == hdrsum) {
6592 FR_DEBUG(("checkl4sum: %hx == %hx\n", sum, hdrsum));
6593 } else {
6594 FR_DEBUG(("checkl4sum: %hx != %hx\n", sum, hdrsum));
6595 }
6596 #endif
6597 DT3(l4sums, u_short, hdrsum, u_short, sum, fr_info_t *, fin);
6598 #ifdef USE_INET6
6599 if (hdrsum == sum || (sum == 0 && IP_V(fin->fin_ip) == 6)) {
6600 #else
6601 if (hdrsum == sum) {
6602 #endif
6603 fin->fin_cksum = FI_CK_SUMOK;
6604 return (0);
6605 }
6606 fin->fin_cksum = FI_CK_BAD;
6607 return (-1);
6608 }
6609
6610
6611 /* ------------------------------------------------------------------------ */
6612 /* Function: ipf_ifpfillv4addr */
6613 /* Returns: int - 0 = address update, -1 = address not updated */
6614 /* Parameters: atype(I) - type of network address update to perform */
6615 /* sin(I) - pointer to source of address information */
6616 /* mask(I) - pointer to source of netmask information */
6617 /* inp(I) - pointer to destination address store */
6618 /* inpmask(I) - pointer to destination netmask store */
6619 /* */
6620 /* Given a type of network address update (atype) to perform, copy */
6621 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6622 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6623 /* which case the operation fails. For all values of atype other than */
6624 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6625 /* value. */
6626 /* ------------------------------------------------------------------------ */
6627 int
6628 ipf_ifpfillv4addr(int atype, struct sockaddr_in *sin, struct sockaddr_in *mask,
6629 struct in_addr *inp, struct in_addr *inpmask)
6630 {
6631 if (inpmask != NULL && atype != FRI_NETMASKED)
6632 inpmask->s_addr = 0xffffffff;
6633
6634 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6635 if (atype == FRI_NETMASKED) {
6636 if (inpmask == NULL)
6637 return (-1);
6638 inpmask->s_addr = mask->sin_addr.s_addr;
6639 }
6640 inp->s_addr = sin->sin_addr.s_addr & mask->sin_addr.s_addr;
6641 } else {
6642 inp->s_addr = sin->sin_addr.s_addr;
6643 }
6644 return (0);
6645 }
6646
6647
6648 #ifdef USE_INET6
6649 /* ------------------------------------------------------------------------ */
6650 /* Function: ipf_ifpfillv6addr */
6651 /* Returns: int - 0 = address update, -1 = address not updated */
6652 /* Parameters: atype(I) - type of network address update to perform */
6653 /* sin(I) - pointer to source of address information */
6654 /* mask(I) - pointer to source of netmask information */
6655 /* inp(I) - pointer to destination address store */
6656 /* inpmask(I) - pointer to destination netmask store */
6657 /* */
6658 /* Given a type of network address update (atype) to perform, copy */
6659 /* information from sin/mask into inp/inpmask. If ipnmask is NULL then no */
6660 /* netmask update is performed unless FRI_NETMASKED is passed as atype, in */
6661 /* which case the operation fails. For all values of atype other than */
6662 /* FRI_NETMASKED, if inpmask is non-NULL then the mask is set to an all 1s */
6663 /* value. */
6664 /* ------------------------------------------------------------------------ */
6665 int
6666 ipf_ifpfillv6addr(int atype, struct sockaddr_in6 *sin,
6667 struct sockaddr_in6 *mask, i6addr_t *inp, i6addr_t *inpmask)
6668 {
6669 i6addr_t *src, *and;
6670
6671 src = (i6addr_t *)&sin->sin6_addr;
6672 and = (i6addr_t *)&mask->sin6_addr;
6673
6674 if (inpmask != NULL && atype != FRI_NETMASKED) {
6675 inpmask->i6[0] = 0xffffffff;
6676 inpmask->i6[1] = 0xffffffff;
6677 inpmask->i6[2] = 0xffffffff;
6678 inpmask->i6[3] = 0xffffffff;
6679 }
6680
6681 if (atype == FRI_NETWORK || atype == FRI_NETMASKED) {
6682 if (atype == FRI_NETMASKED) {
6683 if (inpmask == NULL)
6684 return (-1);
6685 inpmask->i6[0] = and->i6[0];
6686 inpmask->i6[1] = and->i6[1];
6687 inpmask->i6[2] = and->i6[2];
6688 inpmask->i6[3] = and->i6[3];
6689 }
6690
6691 inp->i6[0] = src->i6[0] & and->i6[0];
6692 inp->i6[1] = src->i6[1] & and->i6[1];
6693 inp->i6[2] = src->i6[2] & and->i6[2];
6694 inp->i6[3] = src->i6[3] & and->i6[3];
6695 } else {
6696 inp->i6[0] = src->i6[0];
6697 inp->i6[1] = src->i6[1];
6698 inp->i6[2] = src->i6[2];
6699 inp->i6[3] = src->i6[3];
6700 }
6701 return (0);
6702 }
6703 #endif
6704
6705
6706 /* ------------------------------------------------------------------------ */
6707 /* Function: ipf_matchtag */
6708 /* Returns: 0 == mismatch, 1 == match. */
6709 /* Parameters: tag1(I) - pointer to first tag to compare */
6710 /* tag2(I) - pointer to second tag to compare */
6711 /* */
6712 /* Returns true (non-zero) or false(0) if the two tag structures can be */
6713 /* considered to be a match or not match, respectively. The tag is 16 */
6714 /* bytes long (16 characters) but that is overlayed with 4 32bit ints so */
6715 /* compare the ints instead, for speed. tag1 is the master of the */
6716 /* comparison. This function should only be called with both tag1 and tag2 */
6717 /* as non-NULL pointers. */
6718 /* ------------------------------------------------------------------------ */
6719 int
6720 ipf_matchtag(ipftag_t *tag1, ipftag_t *tag2)
6721 {
6722 if (tag1 == tag2)
6723 return (1);
6724
6725 if ((tag1->ipt_num[0] == 0) && (tag2->ipt_num[0] == 0))
6726 return (1);
6727
6728 if ((tag1->ipt_num[0] == tag2->ipt_num[0]) &&
6729 (tag1->ipt_num[1] == tag2->ipt_num[1]) &&
6730 (tag1->ipt_num[2] == tag2->ipt_num[2]) &&
6731 (tag1->ipt_num[3] == tag2->ipt_num[3]))
6732 return (1);
6733 return (0);
6734 }
6735
6736
6737 /* ------------------------------------------------------------------------ */
6738 /* Function: ipf_coalesce */
6739 /* Returns: 1 == success, -1 == failure, 0 == no change */
6740 /* Parameters: fin(I) - pointer to packet information */
6741 /* */
6742 /* Attempt to get all of the packet data into a single, contiguous buffer. */
6743 /* If this call returns a failure then the buffers have also been freed. */
6744 /* ------------------------------------------------------------------------ */
6745 int
6746 ipf_coalesce(fr_info_t *fin)
6747 {
6748
6749 if ((fin->fin_flx & FI_COALESCE) != 0)
6750 return (1);
6751
6752 /*
6753 * If the mbuf pointers indicate that there is no mbuf to work with,
6754 * return but do not indicate success or failure.
6755 */
6756 if (fin->fin_m == NULL || fin->fin_mp == NULL)
6757 return (0);
6758
6759 #if defined(_KERNEL)
6760 if (ipf_pullup(fin->fin_m, fin, fin->fin_plen) == NULL) {
6761 ipf_main_softc_t *softc = fin->fin_main_soft;
6762
6763 DT1(frb_coalesce, fr_info_t *, fin);
6764 LBUMP(ipf_stats[fin->fin_out].fr_badcoalesces);
6765 # if SOLARIS
6766 FREE_MB_T(*fin->fin_mp);
6767 # endif
6768 fin->fin_reason = FRB_COALESCE;
6769 *fin->fin_mp = NULL;
6770 fin->fin_m = NULL;
6771 return (-1);
6772 }
6773 #else
6774 fin = fin; /* LINT */
6775 #endif
6776 return (1);
6777 }
6778
6779
6780 /*
6781 * The following table lists all of the tunable variables that can be
6782 * accessed via SIOCIPFGET/SIOCIPFSET/SIOCIPFGETNEXt. The format of each row
6783 * in the table below is as follows:
6784 *
6785 * pointer to value, name of value, minimum, maximum, size of the value's
6786 * container, value attribute flags
6787 *
6788 * For convienience, IPFT_RDONLY means the value is read-only, IPFT_WRDISABLED
6789 * means the value can only be written to when IPFilter is loaded but disabled.
6790 * The obvious implication is if neither of these are set then the value can be
6791 * changed at any time without harm.
6792 */
6793
6794
6795 /* ------------------------------------------------------------------------ */
6796 /* Function: ipf_tune_findbycookie */
6797 /* Returns: NULL = search failed, else pointer to tune struct */
6798 /* Parameters: cookie(I) - cookie value to search for amongst tuneables */
6799 /* next(O) - pointer to place to store the cookie for the */
6800 /* "next" tuneable, if it is desired. */
6801 /* */
6802 /* This function is used to walk through all of the existing tunables with */
6803 /* successive calls. It searches the known tunables for the one which has */
6804 /* a matching value for "cookie" - ie its address. When returning a match, */
6805 /* the next one to be found may be returned inside next. */
6806 /* ------------------------------------------------------------------------ */
6807 static ipftuneable_t *
6808 ipf_tune_findbycookie(ipftuneable_t **ptop, void *cookie, void **next)
6809 {
6810 ipftuneable_t *ta, **tap;
6811
6812 for (ta = *ptop; ta->ipft_name != NULL; ta++)
6813 if (ta == cookie) {
6814 if (next != NULL) {
6815 /*
6816 * If the next entry in the array has a name
6817 * present, then return a pointer to it for
6818 * where to go next, else return a pointer to
6819 * the dynaminc list as a key to search there
6820 * next. This facilitates a weak linking of
6821 * the two "lists" together.
6822 */
6823 if ((ta + 1)->ipft_name != NULL)
6824 *next = ta + 1;
6825 else
6826 *next = ptop;
6827 }
6828 return (ta);
6829 }
6830
6831 for (tap = ptop; (ta = *tap) != NULL; tap = &ta->ipft_next)
6832 if (tap == cookie) {
6833 if (next != NULL)
6834 *next = &ta->ipft_next;
6835 return (ta);
6836 }
6837
6838 if (next != NULL)
6839 *next = NULL;
6840 return (NULL);
6841 }
6842
6843
6844 /* ------------------------------------------------------------------------ */
6845 /* Function: ipf_tune_findbyname */
6846 /* Returns: NULL = search failed, else pointer to tune struct */
6847 /* Parameters: name(I) - name of the tuneable entry to find. */
6848 /* */
6849 /* Search the static array of tuneables and the list of dynamic tuneables */
6850 /* for an entry with a matching name. If we can find one, return a pointer */
6851 /* to the matching structure. */
6852 /* ------------------------------------------------------------------------ */
6853 static ipftuneable_t *
6854 ipf_tune_findbyname(ipftuneable_t *top, const char *name)
6855 {
6856 ipftuneable_t *ta;
6857
6858 for (ta = top; ta != NULL; ta = ta->ipft_next)
6859 if (!strcmp(ta->ipft_name, name)) {
6860 return (ta);
6861 }
6862
6863 return (NULL);
6864 }
6865
6866
6867 /* ------------------------------------------------------------------------ */
6868 /* Function: ipf_tune_add_array */
6869 /* Returns: int - 0 == success, else failure */
6870 /* Parameters: newtune - pointer to new tune array to add to tuneables */
6871 /* */
6872 /* Appends tune structures from the array passed in (newtune) to the end of */
6873 /* the current list of "dynamic" tuneable parameters. */
6874 /* If any entry to be added is already present (by name) then the operation */
6875 /* is aborted - entries that have been added are removed before returning. */
6876 /* An entry with no name (NULL) is used as the indication that the end of */
6877 /* the array has been reached. */
6878 /* ------------------------------------------------------------------------ */
6879 int
6880 ipf_tune_add_array(ipf_main_softc_t *softc, ipftuneable_t *newtune)
6881 {
6882 ipftuneable_t *nt, *dt;
6883 int error = 0;
6884
6885 for (nt = newtune; nt->ipft_name != NULL; nt++) {
6886 error = ipf_tune_add(softc, nt);
6887 if (error != 0) {
6888 for (dt = newtune; dt != nt; dt++) {
6889 (void) ipf_tune_del(softc, dt);
6890 }
6891 }
6892 }
6893
6894 return (error);
6895 }
6896
6897
6898 /* ------------------------------------------------------------------------ */
6899 /* Function: ipf_tune_array_link */
6900 /* Returns: 0 == success, -1 == failure */
6901 /* Parameters: softc(I) - soft context pointerto work with */
6902 /* array(I) - pointer to an array of tuneables */
6903 /* */
6904 /* Given an array of tunables (array), append them to the current list of */
6905 /* tuneables for this context (softc->ipf_tuners.) To properly prepare the */
6906 /* the array for being appended to the list, initialise all of the next */
6907 /* pointers so we don't need to walk parts of it with ++ and others with */
6908 /* next. The array is expected to have an entry with a NULL name as the */
6909 /* terminator. Trying to add an array with no non-NULL names will return as */
6910 /* a failure. */
6911 /* ------------------------------------------------------------------------ */
6912 int
6913 ipf_tune_array_link(ipf_main_softc_t *softc, ipftuneable_t *array)
6914 {
6915 ipftuneable_t *t, **p;
6916
6917 t = array;
6918 if (t->ipft_name == NULL)
6919 return (-1);
6920
6921 for (; t[1].ipft_name != NULL; t++)
6922 t[0].ipft_next = &t[1];
6923 t->ipft_next = NULL;
6924
6925 /*
6926 * Since a pointer to the last entry isn't kept, we need to find it
6927 * each time we want to add new variables to the list.
6928 */
6929 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6930 if (t->ipft_name == NULL)
6931 break;
6932 *p = array;
6933
6934 return (0);
6935 }
6936
6937
6938 /* ------------------------------------------------------------------------ */
6939 /* Function: ipf_tune_array_unlink */
6940 /* Returns: 0 == success, -1 == failure */
6941 /* Parameters: softc(I) - soft context pointerto work with */
6942 /* array(I) - pointer to an array of tuneables */
6943 /* */
6944 /* ------------------------------------------------------------------------ */
6945 int
6946 ipf_tune_array_unlink(ipf_main_softc_t *softc, ipftuneable_t *array)
6947 {
6948 ipftuneable_t *t, **p;
6949
6950 for (p = &softc->ipf_tuners; (t = *p) != NULL; p = &t->ipft_next)
6951 if (t == array)
6952 break;
6953 if (t == NULL)
6954 return (-1);
6955
6956 for (; t[1].ipft_name != NULL; t++)
6957 ;
6958
6959 *p = t->ipft_next;
6960
6961 return (0);
6962 }
6963
6964
6965 /* ------------------------------------------------------------------------ */
6966 /* Function: ipf_tune_array_copy */
6967 /* Returns: NULL = failure, else pointer to new array */
6968 /* Parameters: base(I) - pointer to structure base */
6969 /* size(I) - size of the array at template */
6970 /* template(I) - original array to copy */
6971 /* */
6972 /* Allocate memory for a new set of tuneable values and copy everything */
6973 /* from template into the new region of memory. The new region is full of */
6974 /* uninitialised pointers (ipft_next) so set them up. Now, ipftp_offset... */
6975 /* */
6976 /* NOTE: the following assumes that sizeof(long) == sizeof(void *) */
6977 /* In the array template, ipftp_offset is the offset (in bytes) of the */
6978 /* location of the tuneable value inside the structure pointed to by base. */
6979 /* As ipftp_offset is a union over the pointers to the tuneable values, if */
6980 /* we add base to the copy's ipftp_offset, copy ends up with a pointer in */
6981 /* ipftp_void that points to the stored value. */
6982 /* ------------------------------------------------------------------------ */
6983 ipftuneable_t *
6984 ipf_tune_array_copy(void *base, size_t size, ipftuneable_t *template)
6985 {
6986 ipftuneable_t *copy;
6987 int i;
6988
6989
6990 KMALLOCS(copy, ipftuneable_t *, size);
6991 if (copy == NULL) {
6992 return (NULL);
6993 }
6994 bcopy(template, copy, size);
6995
6996 for (i = 0; copy[i].ipft_name; i++) {
6997 copy[i].ipft_una.ipftp_offset += (u_long)base;
6998 copy[i].ipft_next = copy + i + 1;
6999 }
7000
7001 return (copy);
7002 }
7003
7004
7005 /* ------------------------------------------------------------------------ */
7006 /* Function: ipf_tune_add */
7007 /* Returns: int - 0 == success, else failure */
7008 /* Parameters: newtune - pointer to new tune entry to add to tuneables */
7009 /* */
7010 /* Appends tune structures from the array passed in (newtune) to the end of */
7011 /* the current list of "dynamic" tuneable parameters. Once added, the */
7012 /* owner of the object is not expected to ever change "ipft_next". */
7013 /* ------------------------------------------------------------------------ */
7014 int
7015 ipf_tune_add(ipf_main_softc_t *softc, ipftuneable_t *newtune)
7016 {
7017 ipftuneable_t *ta, **tap;
7018
7019 ta = ipf_tune_findbyname(softc->ipf_tuners, newtune->ipft_name);
7020 if (ta != NULL) {
7021 IPFERROR(74);
7022 return (EEXIST);
7023 }
7024
7025 for (tap = &softc->ipf_tuners; *tap != NULL; tap = &(*tap)->ipft_next)
7026 ;
7027
7028 newtune->ipft_next = NULL;
7029 *tap = newtune;
7030 return (0);
7031 }
7032
7033
7034 /* ------------------------------------------------------------------------ */
7035 /* Function: ipf_tune_del */
7036 /* Returns: int - 0 == success, else failure */
7037 /* Parameters: oldtune - pointer to tune entry to remove from the list of */
7038 /* current dynamic tuneables */
7039 /* */
7040 /* Search for the tune structure, by pointer, in the list of those that are */
7041 /* dynamically added at run time. If found, adjust the list so that this */
7042 /* structure is no longer part of it. */
7043 /* ------------------------------------------------------------------------ */
7044 int
7045 ipf_tune_del(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7046 {
7047 ipftuneable_t *ta, **tap;
7048 int error = 0;
7049
7050 for (tap = &softc->ipf_tuners; (ta = *tap) != NULL;
7051 tap = &ta->ipft_next) {
7052 if (ta == oldtune) {
7053 *tap = oldtune->ipft_next;
7054 oldtune->ipft_next = NULL;
7055 break;
7056 }
7057 }
7058
7059 if (ta == NULL) {
7060 error = ESRCH;
7061 IPFERROR(75);
7062 }
7063 return (error);
7064 }
7065
7066
7067 /* ------------------------------------------------------------------------ */
7068 /* Function: ipf_tune_del_array */
7069 /* Returns: int - 0 == success, else failure */
7070 /* Parameters: oldtune - pointer to tuneables array */
7071 /* */
7072 /* Remove each tuneable entry in the array from the list of "dynamic" */
7073 /* tunables. If one entry should fail to be found, an error will be */
7074 /* returned and no further ones removed. */
7075 /* An entry with a NULL name is used as the indicator of the last entry in */
7076 /* the array. */
7077 /* ------------------------------------------------------------------------ */
7078 int
7079 ipf_tune_del_array(ipf_main_softc_t *softc, ipftuneable_t *oldtune)
7080 {
7081 ipftuneable_t *ot;
7082 int error = 0;
7083
7084 for (ot = oldtune; ot->ipft_name != NULL; ot++) {
7085 error = ipf_tune_del(softc, ot);
7086 if (error != 0)
7087 break;
7088 }
7089
7090 return (error);
7091
7092 }
7093
7094
7095 /* ------------------------------------------------------------------------ */
7096 /* Function: ipf_tune */
7097 /* Returns: int - 0 == success, else failure */
7098 /* Parameters: cmd(I) - ioctl command number */
7099 /* data(I) - pointer to ioctl data structure */
7100 /* */
7101 /* Implement handling of SIOCIPFGETNEXT, SIOCIPFGET and SIOCIPFSET. These */
7102 /* three ioctls provide the means to access and control global variables */
7103 /* within IPFilter, allowing (for example) timeouts and table sizes to be */
7104 /* changed without rebooting, reloading or recompiling. The initialisation */
7105 /* and 'destruction' routines of the various components of ipfilter are all */
7106 /* each responsible for handling their own values being too big. */
7107 /* ------------------------------------------------------------------------ */
7108 int
7109 ipf_ipftune(ipf_main_softc_t *softc, ioctlcmd_t cmd, void *data)
7110 {
7111 ipftuneable_t *ta;
7112 ipftune_t tu;
7113 void *cookie;
7114 int error;
7115
7116 error = ipf_inobj(softc, data, NULL, &tu, IPFOBJ_TUNEABLE);
7117 if (error != 0)
7118 return (error);
7119
7120 tu.ipft_name[sizeof(tu.ipft_name) - 1] = '\0';
7121 cookie = tu.ipft_cookie;
7122 ta = NULL;
7123
7124 switch (cmd)
7125 {
7126 case SIOCIPFGETNEXT :
7127 /*
7128 * If cookie is non-NULL, assume it to be a pointer to the last
7129 * entry we looked at, so find it (if possible) and return a
7130 * pointer to the next one after it. The last entry in the
7131 * the table is a NULL entry, so when we get to it, set cookie
7132 * to NULL and return that, indicating end of list, erstwhile
7133 * if we come in with cookie set to NULL, we are starting anew
7134 * at the front of the list.
7135 */
7136 if (cookie != NULL) {
7137 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7138 cookie, &tu.ipft_cookie);
7139 } else {
7140 ta = softc->ipf_tuners;
7141 tu.ipft_cookie = ta + 1;
7142 }
7143 if (ta != NULL) {
7144 /*
7145 * Entry found, but does the data pointed to by that
7146 * row fit in what we can return?
7147 */
7148 if (ta->ipft_sz > sizeof(tu.ipft_un)) {
7149 IPFERROR(76);
7150 return (EINVAL);
7151 }
7152
7153 tu.ipft_vlong = 0;
7154 if (ta->ipft_sz == sizeof(u_long))
7155 tu.ipft_vlong = *ta->ipft_plong;
7156 else if (ta->ipft_sz == sizeof(u_int))
7157 tu.ipft_vint = *ta->ipft_pint;
7158 else if (ta->ipft_sz == sizeof(u_short))
7159 tu.ipft_vshort = *ta->ipft_pshort;
7160 else if (ta->ipft_sz == sizeof(u_char))
7161 tu.ipft_vchar = *ta->ipft_pchar;
7162
7163 tu.ipft_sz = ta->ipft_sz;
7164 tu.ipft_min = ta->ipft_min;
7165 tu.ipft_max = ta->ipft_max;
7166 tu.ipft_flags = ta->ipft_flags;
7167 bcopy(ta->ipft_name, tu.ipft_name,
7168 MIN(sizeof(tu.ipft_name),
7169 strlen(ta->ipft_name) + 1));
7170 }
7171 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7172 break;
7173
7174 case SIOCIPFGET :
7175 case SIOCIPFSET :
7176 /*
7177 * Search by name or by cookie value for a particular entry
7178 * in the tuning parameter table.
7179 */
7180 IPFERROR(77);
7181 error = ESRCH;
7182 if (cookie != NULL) {
7183 ta = ipf_tune_findbycookie(&softc->ipf_tuners,
7184 cookie, NULL);
7185 if (ta != NULL)
7186 error = 0;
7187 } else if (tu.ipft_name[0] != '\0') {
7188 ta = ipf_tune_findbyname(softc->ipf_tuners,
7189 tu.ipft_name);
7190 if (ta != NULL)
7191 error = 0;
7192 }
7193 if (error != 0)
7194 break;
7195
7196 if (cmd == (ioctlcmd_t)SIOCIPFGET) {
7197 /*
7198 * Fetch the tuning parameters for a particular value
7199 */
7200 tu.ipft_vlong = 0;
7201 if (ta->ipft_sz == sizeof(u_long))
7202 tu.ipft_vlong = *ta->ipft_plong;
7203 else if (ta->ipft_sz == sizeof(u_int))
7204 tu.ipft_vint = *ta->ipft_pint;
7205 else if (ta->ipft_sz == sizeof(u_short))
7206 tu.ipft_vshort = *ta->ipft_pshort;
7207 else if (ta->ipft_sz == sizeof(u_char))
7208 tu.ipft_vchar = *ta->ipft_pchar;
7209 tu.ipft_cookie = ta;
7210 tu.ipft_sz = ta->ipft_sz;
7211 tu.ipft_min = ta->ipft_min;
7212 tu.ipft_max = ta->ipft_max;
7213 tu.ipft_flags = ta->ipft_flags;
7214 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7215
7216 } else if (cmd == (ioctlcmd_t)SIOCIPFSET) {
7217 /*
7218 * Set an internal parameter. The hard part here is
7219 * getting the new value safely and correctly out of
7220 * the kernel (given we only know its size, not type.)
7221 */
7222 u_long in;
7223
7224 if (((ta->ipft_flags & IPFT_WRDISABLED) != 0) &&
7225 (softc->ipf_running > 0)) {
7226 IPFERROR(78);
7227 error = EBUSY;
7228 break;
7229 }
7230
7231 in = tu.ipft_vlong;
7232 if (in < ta->ipft_min || in > ta->ipft_max) {
7233 IPFERROR(79);
7234 error = EINVAL;
7235 break;
7236 }
7237
7238 if (ta->ipft_func != NULL) {
7239 SPL_INT(s);
7240
7241 SPL_NET(s);
7242 error = (*ta->ipft_func)(softc, ta,
7243 &tu.ipft_un);
7244 SPL_X(s);
7245
7246 } else if (ta->ipft_sz == sizeof(u_long)) {
7247 tu.ipft_vlong = *ta->ipft_plong;
7248 *ta->ipft_plong = in;
7249
7250 } else if (ta->ipft_sz == sizeof(u_int)) {
7251 tu.ipft_vint = *ta->ipft_pint;
7252 *ta->ipft_pint = (u_int)(in & 0xffffffff);
7253
7254 } else if (ta->ipft_sz == sizeof(u_short)) {
7255 tu.ipft_vshort = *ta->ipft_pshort;
7256 *ta->ipft_pshort = (u_short)(in & 0xffff);
7257
7258 } else if (ta->ipft_sz == sizeof(u_char)) {
7259 tu.ipft_vchar = *ta->ipft_pchar;
7260 *ta->ipft_pchar = (u_char)(in & 0xff);
7261 }
7262 error = ipf_outobj(softc, data, &tu, IPFOBJ_TUNEABLE);
7263 }
7264 break;
7265
7266 default :
7267 IPFERROR(80);
7268 error = EINVAL;
7269 break;
7270 }
7271
7272 return (error);
7273 }
7274
7275
7276 /* ------------------------------------------------------------------------ */
7277 /* Function: ipf_zerostats */
7278 /* Returns: int - 0 = success, else failure */
7279 /* Parameters: data(O) - pointer to pointer for copying data back to */
7280 /* */
7281 /* Copies the current statistics out to userspace and then zero's the */
7282 /* current ones in the kernel. The lock is only held across the bzero() as */
7283 /* the copyout may result in paging (ie network activity.) */
7284 /* ------------------------------------------------------------------------ */
7285 int
7286 ipf_zerostats(ipf_main_softc_t *softc, caddr_t data)
7287 {
7288 friostat_t fio;
7289 ipfobj_t obj;
7290 int error;
7291
7292 error = ipf_inobj(softc, data, &obj, &fio, IPFOBJ_IPFSTAT);
7293 if (error != 0)
7294 return (error);
7295 ipf_getstat(softc, &fio, obj.ipfo_rev);
7296 error = ipf_outobj(softc, data, &fio, IPFOBJ_IPFSTAT);
7297 if (error != 0)
7298 return (error);
7299
7300 WRITE_ENTER(&softc->ipf_mutex);
7301 bzero(&softc->ipf_stats, sizeof(softc->ipf_stats));
7302 RWLOCK_EXIT(&softc->ipf_mutex);
7303
7304 return (0);
7305 }
7306
7307
7308 /* ------------------------------------------------------------------------ */
7309 /* Function: ipf_resolvedest */
7310 /* Returns: Nil */
7311 /* Parameters: softc(I) - pointer to soft context main structure */
7312 /* base(I) - where strings are stored */
7313 /* fdp(IO) - pointer to destination information to resolve */
7314 /* v(I) - IP protocol version to match */
7315 /* */
7316 /* Looks up an interface name in the frdest structure pointed to by fdp and */
7317 /* if a matching name can be found for the particular IP protocol version */
7318 /* then store the interface pointer in the frdest struct. If no match is */
7319 /* found, then set the interface pointer to be -1 as NULL is considered to */
7320 /* indicate there is no information at all in the structure. */
7321 /* ------------------------------------------------------------------------ */
7322 int
7323 ipf_resolvedest(ipf_main_softc_t *softc, char *base, frdest_t *fdp, int v)
7324 {
7325 int errval = 0;
7326 void *ifp;
7327
7328 ifp = NULL;
7329
7330 if (fdp->fd_name != -1) {
7331 if (fdp->fd_type == FRD_DSTLIST) {
7332 ifp = ipf_lookup_res_name(softc, IPL_LOGIPF,
7333 IPLT_DSTLIST,
7334 base + fdp->fd_name,
7335 NULL);
7336 if (ifp == NULL) {
7337 IPFERROR(144);
7338 errval = ESRCH;
7339 }
7340 } else {
7341 ifp = GETIFP(base + fdp->fd_name, v);
7342 if (ifp == NULL)
7343 ifp = (void *)-1;
7344 }
7345 }
7346 fdp->fd_ptr = ifp;
7347
7348 return (errval);
7349 }
7350
7351
7352 /* ------------------------------------------------------------------------ */
7353 /* Function: ipf_resolvenic */
7354 /* Returns: void* - NULL = wildcard name, -1 = failed to find NIC, else */
7355 /* pointer to interface structure for NIC */
7356 /* Parameters: softc(I)- pointer to soft context main structure */
7357 /* name(I) - complete interface name */
7358 /* v(I) - IP protocol version */
7359 /* */
7360 /* Look for a network interface structure that firstly has a matching name */
7361 /* to that passed in and that is also being used for that IP protocol */
7362 /* version (necessary on some platforms where there are separate listings */
7363 /* for both IPv4 and IPv6 on the same physical NIC. */
7364 /* ------------------------------------------------------------------------ */
7365 void *
7366 ipf_resolvenic(ipf_main_softc_t *softc __unused, char *name, int v)
7367 {
7368 void *nic;
7369
7370 if (name[0] == '\0')
7371 return (NULL);
7372
7373 if ((name[1] == '\0') && ((name[0] == '-') || (name[0] == '*'))) {
7374 return (NULL);
7375 }
7376
7377 nic = GETIFP(name, v);
7378 if (nic == NULL)
7379 nic = (void *)-1;
7380 return (nic);
7381 }
7382
7383
7384 /* ------------------------------------------------------------------------ */
7385 /* Function: ipf_token_expire */
7386 /* Returns: None. */
7387 /* Parameters: softc(I) - pointer to soft context main structure */
7388 /* */
7389 /* This function is run every ipf tick to see if there are any tokens that */
7390 /* have been held for too long and need to be freed up. */
7391 /* ------------------------------------------------------------------------ */
7392 void
7393 ipf_token_expire(ipf_main_softc_t *softc)
7394 {
7395 ipftoken_t *it;
7396
7397 WRITE_ENTER(&softc->ipf_tokens);
7398 while ((it = softc->ipf_token_head) != NULL) {
7399 if (it->ipt_die > softc->ipf_ticks)
7400 break;
7401
7402 ipf_token_deref(softc, it);
7403 }
7404 RWLOCK_EXIT(&softc->ipf_tokens);
7405 }
7406
7407
7408 /* ------------------------------------------------------------------------ */
7409 /* Function: ipf_token_flush */
7410 /* Returns: None. */
7411 /* Parameters: softc(I) - pointer to soft context main structure */
7412 /* */
7413 /* Loop through all of the existing tokens and call deref to see if they */
7414 /* can be freed. Normally a function like this might just loop on */
7415 /* ipf_token_head but there is a chance that a token might have a ref count */
7416 /* of greater than one and in that case the reference would drop twice */
7417 /* by code that is only entitled to drop it once. */
7418 /* ------------------------------------------------------------------------ */
7419 static void
7420 ipf_token_flush(ipf_main_softc_t *softc)
7421 {
7422 ipftoken_t *it, *next;
7423
7424 WRITE_ENTER(&softc->ipf_tokens);
7425 for (it = softc->ipf_token_head; it != NULL; it = next) {
7426 next = it->ipt_next;
7427 (void) ipf_token_deref(softc, it);
7428 }
7429 RWLOCK_EXIT(&softc->ipf_tokens);
7430 }
7431
7432
7433 /* ------------------------------------------------------------------------ */
7434 /* Function: ipf_token_del */
7435 /* Returns: int - 0 = success, else error */
7436 /* Parameters: softc(I)- pointer to soft context main structure */
7437 /* type(I) - the token type to match */
7438 /* uid(I) - uid owning the token */
7439 /* ptr(I) - context pointer for the token */
7440 /* */
7441 /* This function looks for a token in the current list that matches up */
7442 /* the fields (type, uid, ptr). If none is found, ESRCH is returned, else */
7443 /* call ipf_token_dewref() to remove it from the list. In the event that */
7444 /* the token has a reference held elsewhere, setting ipt_complete to 2 */
7445 /* enables debugging to distinguish between the two paths that ultimately */
7446 /* lead to a token to be deleted. */
7447 /* ------------------------------------------------------------------------ */
7448 int
7449 ipf_token_del(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7450 {
7451 ipftoken_t *it;
7452 int error;
7453
7454 IPFERROR(82);
7455 error = ESRCH;
7456
7457 WRITE_ENTER(&softc->ipf_tokens);
7458 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7459 if (ptr == it->ipt_ctx && type == it->ipt_type &&
7460 uid == it->ipt_uid) {
7461 it->ipt_complete = 2;
7462 ipf_token_deref(softc, it);
7463 error = 0;
7464 break;
7465 }
7466 }
7467 RWLOCK_EXIT(&softc->ipf_tokens);
7468
7469 return (error);
7470 }
7471
7472
7473 /* ------------------------------------------------------------------------ */
7474 /* Function: ipf_token_mark_complete */
7475 /* Returns: None. */
7476 /* Parameters: token(I) - pointer to token structure */
7477 /* */
7478 /* Mark a token as being ineligable for being found with ipf_token_find. */
7479 /* ------------------------------------------------------------------------ */
7480 void
7481 ipf_token_mark_complete(ipftoken_t *token)
7482 {
7483 if (token->ipt_complete == 0)
7484 token->ipt_complete = 1;
7485 }
7486
7487
7488 /* ------------------------------------------------------------------------ */
7489 /* Function: ipf_token_find */
7490 /* Returns: ipftoken_t * - NULL if no memory, else pointer to token */
7491 /* Parameters: softc(I)- pointer to soft context main structure */
7492 /* type(I) - the token type to match */
7493 /* uid(I) - uid owning the token */
7494 /* ptr(I) - context pointer for the token */
7495 /* */
7496 /* This function looks for a live token in the list of current tokens that */
7497 /* matches the tuple (type, uid, ptr). If one cannot be found then one is */
7498 /* allocated. If one is found then it is moved to the top of the list of */
7499 /* currently active tokens. */
7500 /* ------------------------------------------------------------------------ */
7501 ipftoken_t *
7502 ipf_token_find(ipf_main_softc_t *softc, int type, int uid, void *ptr)
7503 {
7504 ipftoken_t *it, *new;
7505
7506 KMALLOC(new, ipftoken_t *);
7507 if (new != NULL)
7508 bzero((char *)new, sizeof(*new));
7509
7510 WRITE_ENTER(&softc->ipf_tokens);
7511 for (it = softc->ipf_token_head; it != NULL; it = it->ipt_next) {
7512 if ((ptr == it->ipt_ctx) && (type == it->ipt_type) &&
7513 (uid == it->ipt_uid) && (it->ipt_complete < 2))
7514 break;
7515 }
7516
7517 if (it == NULL) {
7518 it = new;
7519 new = NULL;
7520 if (it == NULL) {
7521 RWLOCK_EXIT(&softc->ipf_tokens);
7522 return (NULL);
7523 }
7524 it->ipt_ctx = ptr;
7525 it->ipt_uid = uid;
7526 it->ipt_type = type;
7527 it->ipt_ref = 1;
7528 } else {
7529 if (new != NULL) {
7530 KFREE(new);
7531 new = NULL;
7532 }
7533
7534 if (it->ipt_complete > 0)
7535 it = NULL;
7536 else
7537 ipf_token_unlink(softc, it);
7538 }
7539
7540 if (it != NULL) {
7541 it->ipt_pnext = softc->ipf_token_tail;
7542 *softc->ipf_token_tail = it;
7543 softc->ipf_token_tail = &it->ipt_next;
7544 it->ipt_next = NULL;
7545 it->ipt_ref++;
7546
7547 it->ipt_die = softc->ipf_ticks + 20;
7548 }
7549
7550 RWLOCK_EXIT(&softc->ipf_tokens);
7551
7552 return (it);
7553 }
7554
7555
7556 /* ------------------------------------------------------------------------ */
7557 /* Function: ipf_token_unlink */
7558 /* Returns: None. */
7559 /* Parameters: softc(I) - pointer to soft context main structure */
7560 /* token(I) - pointer to token structure */
7561 /* Write Locks: ipf_tokens */
7562 /* */
7563 /* This function unlinks a token structure from the linked list of tokens */
7564 /* that "own" it. The head pointer never needs to be explicitly adjusted */
7565 /* but the tail does due to the linked list implementation. */
7566 /* ------------------------------------------------------------------------ */
7567 static void
7568 ipf_token_unlink(ipf_main_softc_t *softc, ipftoken_t *token)
7569 {
7570
7571 if (softc->ipf_token_tail == &token->ipt_next)
7572 softc->ipf_token_tail = token->ipt_pnext;
7573
7574 *token->ipt_pnext = token->ipt_next;
7575 if (token->ipt_next != NULL)
7576 token->ipt_next->ipt_pnext = token->ipt_pnext;
7577 token->ipt_next = NULL;
7578 token->ipt_pnext = NULL;
7579 }
7580
7581
7582 /* ------------------------------------------------------------------------ */
7583 /* Function: ipf_token_deref */
7584 /* Returns: int - 0 == token freed, else reference count */
7585 /* Parameters: softc(I) - pointer to soft context main structure */
7586 /* token(I) - pointer to token structure */
7587 /* Write Locks: ipf_tokens */
7588 /* */
7589 /* Drop the reference count on the token structure and if it drops to zero, */
7590 /* call the dereference function for the token type because it is then */
7591 /* possible to free the token data structure. */
7592 /* ------------------------------------------------------------------------ */
7593 int
7594 ipf_token_deref(ipf_main_softc_t *softc, ipftoken_t *token)
7595 {
7596 void *data, **datap;
7597
7598 ASSERT(token->ipt_ref > 0);
7599 token->ipt_ref--;
7600 if (token->ipt_ref > 0)
7601 return (token->ipt_ref);
7602
7603 data = token->ipt_data;
7604 datap = &data;
7605
7606 if ((data != NULL) && (data != (void *)-1)) {
7607 switch (token->ipt_type)
7608 {
7609 case IPFGENITER_IPF :
7610 (void) ipf_derefrule(softc, (frentry_t **)datap);
7611 break;
7612 case IPFGENITER_IPNAT :
7613 WRITE_ENTER(&softc->ipf_nat);
7614 ipf_nat_rule_deref(softc, (ipnat_t **)datap);
7615 RWLOCK_EXIT(&softc->ipf_nat);
7616 break;
7617 case IPFGENITER_NAT :
7618 ipf_nat_deref(softc, (nat_t **)datap);
7619 break;
7620 case IPFGENITER_STATE :
7621 ipf_state_deref(softc, (ipstate_t **)datap);
7622 break;
7623 case IPFGENITER_FRAG :
7624 ipf_frag_pkt_deref(softc, (ipfr_t **)datap);
7625 break;
7626 case IPFGENITER_NATFRAG :
7627 ipf_frag_nat_deref(softc, (ipfr_t **)datap);
7628 break;
7629 case IPFGENITER_HOSTMAP :
7630 WRITE_ENTER(&softc->ipf_nat);
7631 ipf_nat_hostmapdel(softc, (hostmap_t **)datap);
7632 RWLOCK_EXIT(&softc->ipf_nat);
7633 break;
7634 default :
7635 ipf_lookup_iterderef(softc, token->ipt_type, data);
7636 break;
7637 }
7638 }
7639
7640 ipf_token_unlink(softc, token);
7641 KFREE(token);
7642 return (0);
7643 }
7644
7645
7646 /* ------------------------------------------------------------------------ */
7647 /* Function: ipf_nextrule */
7648 /* Returns: frentry_t * - NULL == no more rules, else pointer to next */
7649 /* Parameters: softc(I) - pointer to soft context main structure */
7650 /* fr(I) - pointer to filter rule */
7651 /* out(I) - 1 == out rules, 0 == input rules */
7652 /* */
7653 /* Starting with "fr", find the next rule to visit. This includes visiting */
7654 /* the list of rule groups if either fr is NULL (empty list) or it is the */
7655 /* last rule in the list. When walking rule lists, it is either input or */
7656 /* output rules that are returned, never both. */
7657 /* ------------------------------------------------------------------------ */
7658 static frentry_t *
7659 ipf_nextrule(ipf_main_softc_t *softc, int active, int unit, frentry_t *fr,
7660 int out)
7661 {
7662 frentry_t *next;
7663 frgroup_t *fg;
7664
7665 if (fr != NULL && fr->fr_group != -1) {
7666 fg = ipf_findgroup(softc, fr->fr_names + fr->fr_group,
7667 unit, active, NULL);
7668 if (fg != NULL)
7669 fg = fg->fg_next;
7670 } else {
7671 fg = softc->ipf_groups[unit][active];
7672 }
7673
7674 while (fg != NULL) {
7675 next = fg->fg_start;
7676 while (next != NULL) {
7677 if (out) {
7678 if (next->fr_flags & FR_OUTQUE)
7679 return (next);
7680 } else if (next->fr_flags & FR_INQUE) {
7681 return (next);
7682 }
7683 next = next->fr_next;
7684 }
7685 if (next == NULL)
7686 fg = fg->fg_next;
7687 }
7688
7689 return (NULL);
7690 }
7691
7692 /* ------------------------------------------------------------------------ */
7693 /* Function: ipf_getnextrule */
7694 /* Returns: int - 0 = success, else error */
7695 /* Parameters: softc(I)- pointer to soft context main structure */
7696 /* t(I) - pointer to destination information to resolve */
7697 /* ptr(I) - pointer to ipfobj_t to copyin from user space */
7698 /* */
7699 /* This function's first job is to bring in the ipfruleiter_t structure via */
7700 /* the ipfobj_t structure to determine what should be the next rule to */
7701 /* return. Once the ipfruleiter_t has been brought in, it then tries to */
7702 /* find the 'next rule'. This may include searching rule group lists or */
7703 /* just be as simple as looking at the 'next' field in the rule structure. */
7704 /* When we have found the rule to return, increase its reference count and */
7705 /* if we used an existing rule to get here, decrease its reference count. */
7706 /* ------------------------------------------------------------------------ */
7707 int
7708 ipf_getnextrule(ipf_main_softc_t *softc, ipftoken_t *t, void *ptr)
7709 {
7710 frentry_t *fr, *next, zero;
7711 ipfruleiter_t it;
7712 int error, out;
7713 frgroup_t *fg;
7714 ipfobj_t obj;
7715 int predict;
7716 char *dst;
7717 int unit;
7718
7719 if (t == NULL || ptr == NULL) {
7720 IPFERROR(84);
7721 return (EFAULT);
7722 }
7723
7724 error = ipf_inobj(softc, ptr, &obj, &it, IPFOBJ_IPFITER);
7725 if (error != 0)
7726 return (error);
7727
7728 if ((it.iri_inout < 0) || (it.iri_inout > 3)) {
7729 IPFERROR(85);
7730 return (EINVAL);
7731 }
7732 if ((it.iri_active != 0) && (it.iri_active != 1)) {
7733 IPFERROR(86);
7734 return (EINVAL);
7735 }
7736 if (it.iri_nrules == 0) {
7737 IPFERROR(87);
7738 return (ENOSPC);
7739 }
7740 if (it.iri_rule == NULL) {
7741 IPFERROR(88);
7742 return (EFAULT);
7743 }
7744
7745 fg = NULL;
7746 fr = t->ipt_data;
7747 if ((it.iri_inout & F_OUT) != 0)
7748 out = 1;
7749 else
7750 out = 0;
7751 if ((it.iri_inout & F_ACIN) != 0)
7752 unit = IPL_LOGCOUNT;
7753 else
7754 unit = IPL_LOGIPF;
7755
7756 READ_ENTER(&softc->ipf_mutex);
7757 if (fr == NULL) {
7758 if (*it.iri_group == '\0') {
7759 if (unit == IPL_LOGCOUNT) {
7760 next = softc->ipf_acct[out][it.iri_active];
7761 } else {
7762 next = softc->ipf_rules[out][it.iri_active];
7763 }
7764 if (next == NULL)
7765 next = ipf_nextrule(softc, it.iri_active,
7766 unit, NULL, out);
7767 } else {
7768 fg = ipf_findgroup(softc, it.iri_group, unit,
7769 it.iri_active, NULL);
7770 if (fg != NULL)
7771 next = fg->fg_start;
7772 else
7773 next = NULL;
7774 }
7775 } else {
7776 next = fr->fr_next;
7777 if (next == NULL)
7778 next = ipf_nextrule(softc, it.iri_active, unit,
7779 fr, out);
7780 }
7781
7782 if (next != NULL && next->fr_next != NULL)
7783 predict = 1;
7784 else if (ipf_nextrule(softc, it.iri_active, unit, next, out) != NULL)
7785 predict = 1;
7786 else
7787 predict = 0;
7788
7789 if (fr != NULL)
7790 (void) ipf_derefrule(softc, &fr);
7791
7792 obj.ipfo_type = IPFOBJ_FRENTRY;
7793 dst = (char *)it.iri_rule;
7794
7795 if (next != NULL) {
7796 obj.ipfo_size = next->fr_size;
7797 MUTEX_ENTER(&next->fr_lock);
7798 next->fr_ref++;
7799 MUTEX_EXIT(&next->fr_lock);
7800 t->ipt_data = next;
7801 } else {
7802 obj.ipfo_size = sizeof(frentry_t);
7803 bzero(&zero, sizeof(zero));
7804 next = &zero;
7805 t->ipt_data = NULL;
7806 }
7807 it.iri_rule = predict ? next : NULL;
7808 if (predict == 0)
7809 ipf_token_mark_complete(t);
7810
7811 RWLOCK_EXIT(&softc->ipf_mutex);
7812
7813 obj.ipfo_ptr = dst;
7814 error = ipf_outobjk(softc, &obj, next);
7815 if (error == 0 && t->ipt_data != NULL) {
7816 dst += obj.ipfo_size;
7817 if (next->fr_data != NULL) {
7818 ipfobj_t dobj;
7819
7820 if (next->fr_type == FR_T_IPFEXPR)
7821 dobj.ipfo_type = IPFOBJ_IPFEXPR;
7822 else
7823 dobj.ipfo_type = IPFOBJ_FRIPF;
7824 dobj.ipfo_size = next->fr_dsize;
7825 dobj.ipfo_rev = obj.ipfo_rev;
7826 dobj.ipfo_ptr = dst;
7827 error = ipf_outobjk(softc, &dobj, next->fr_data);
7828 }
7829 }
7830
7831 if ((fr != NULL) && (next == &zero))
7832 (void) ipf_derefrule(softc, &fr);
7833
7834 return (error);
7835 }
7836
7837
7838 /* ------------------------------------------------------------------------ */
7839 /* Function: ipf_frruleiter */
7840 /* Returns: int - 0 = success, else error */
7841 /* Parameters: softc(I)- pointer to soft context main structure */
7842 /* data(I) - the token type to match */
7843 /* uid(I) - uid owning the token */
7844 /* ptr(I) - context pointer for the token */
7845 /* */
7846 /* This function serves as a stepping stone between ipf_ipf_ioctl and */
7847 /* ipf_getnextrule. It's role is to find the right token in the kernel for */
7848 /* the process doing the ioctl and use that to ask for the next rule. */
7849 /* ------------------------------------------------------------------------ */
7850 static int
7851 ipf_frruleiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7852 {
7853 ipftoken_t *token;
7854 ipfruleiter_t it;
7855 ipfobj_t obj;
7856 int error;
7857
7858 token = ipf_token_find(softc, IPFGENITER_IPF, uid, ctx);
7859 if (token != NULL) {
7860 error = ipf_getnextrule(softc, token, data);
7861 WRITE_ENTER(&softc->ipf_tokens);
7862 ipf_token_deref(softc, token);
7863 RWLOCK_EXIT(&softc->ipf_tokens);
7864 } else {
7865 error = ipf_inobj(softc, data, &obj, &it, IPFOBJ_IPFITER);
7866 if (error != 0)
7867 return (error);
7868 it.iri_rule = NULL;
7869 error = ipf_outobj(softc, data, &it, IPFOBJ_IPFITER);
7870 }
7871
7872 return (error);
7873 }
7874
7875
7876 /* ------------------------------------------------------------------------ */
7877 /* Function: ipf_geniter */
7878 /* Returns: int - 0 = success, else error */
7879 /* Parameters: softc(I) - pointer to soft context main structure */
7880 /* token(I) - pointer to ipftoken_t structure */
7881 /* itp(I) - pointer to iterator data */
7882 /* */
7883 /* Decide which iterator function to call using information passed through */
7884 /* the ipfgeniter_t structure at itp. */
7885 /* ------------------------------------------------------------------------ */
7886 static int
7887 ipf_geniter(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp)
7888 {
7889 int error;
7890
7891 switch (itp->igi_type)
7892 {
7893 case IPFGENITER_FRAG :
7894 error = ipf_frag_pkt_next(softc, token, itp);
7895 break;
7896 default :
7897 IPFERROR(92);
7898 error = EINVAL;
7899 break;
7900 }
7901
7902 return (error);
7903 }
7904
7905
7906 /* ------------------------------------------------------------------------ */
7907 /* Function: ipf_genericiter */
7908 /* Returns: int - 0 = success, else error */
7909 /* Parameters: softc(I)- pointer to soft context main structure */
7910 /* data(I) - the token type to match */
7911 /* uid(I) - uid owning the token */
7912 /* ptr(I) - context pointer for the token */
7913 /* */
7914 /* Handle the SIOCGENITER ioctl for the ipfilter device. The primary role */
7915 /* ------------------------------------------------------------------------ */
7916 int
7917 ipf_genericiter(ipf_main_softc_t *softc, void *data, int uid, void *ctx)
7918 {
7919 ipftoken_t *token;
7920 ipfgeniter_t iter;
7921 int error;
7922
7923 error = ipf_inobj(softc, data, NULL, &iter, IPFOBJ_GENITER);
7924 if (error != 0)
7925 return (error);
7926
7927 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
7928 if (token != NULL) {
7929 token->ipt_subtype = iter.igi_type;
7930 error = ipf_geniter(softc, token, &iter);
7931 WRITE_ENTER(&softc->ipf_tokens);
7932 ipf_token_deref(softc, token);
7933 RWLOCK_EXIT(&softc->ipf_tokens);
7934 } else {
7935 IPFERROR(93);
7936 error = 0;
7937 }
7938
7939 return (error);
7940 }
7941
7942
7943 /* ------------------------------------------------------------------------ */
7944 /* Function: ipf_ipf_ioctl */
7945 /* Returns: int - 0 = success, else error */
7946 /* Parameters: softc(I)- pointer to soft context main structure */
7947 /* data(I) - the token type to match */
7948 /* cmd(I) - the ioctl command number */
7949 /* mode(I) - mode flags for the ioctl */
7950 /* uid(I) - uid owning the token */
7951 /* ptr(I) - context pointer for the token */
7952 /* */
7953 /* This function handles all of the ioctl command that are actually issued */
7954 /* to the /dev/ipl device. */
7955 /* ------------------------------------------------------------------------ */
7956 int
7957 ipf_ipf_ioctl(ipf_main_softc_t *softc, caddr_t data, ioctlcmd_t cmd, int mode,
7958 int uid, void *ctx)
7959 {
7960 friostat_t fio;
7961 int error, tmp;
7962 ipfobj_t obj;
7963 SPL_INT(s);
7964
7965 switch (cmd)
7966 {
7967 case SIOCFRENB :
7968 if (!(mode & FWRITE)) {
7969 IPFERROR(94);
7970 error = EPERM;
7971 } else {
7972 error = BCOPYIN(data, &tmp, sizeof(tmp));
7973 if (error != 0) {
7974 IPFERROR(95);
7975 error = EFAULT;
7976 break;
7977 }
7978
7979 WRITE_ENTER(&softc->ipf_global);
7980 if (tmp) {
7981 if (softc->ipf_running > 0)
7982 error = 0;
7983 else
7984 error = ipfattach(softc);
7985 if (error == 0)
7986 softc->ipf_running = 1;
7987 else
7988 (void) ipfdetach(softc);
7989 } else {
7990 if (softc->ipf_running == 1)
7991 error = ipfdetach(softc);
7992 else
7993 error = 0;
7994 if (error == 0)
7995 softc->ipf_running = -1;
7996 }
7997 RWLOCK_EXIT(&softc->ipf_global);
7998 }
7999 break;
8000
8001 case SIOCIPFSET :
8002 if (!(mode & FWRITE)) {
8003 IPFERROR(96);
8004 error = EPERM;
8005 break;
8006 }
8007 /* FALLTHRU */
8008 case SIOCIPFGETNEXT :
8009 case SIOCIPFGET :
8010 error = ipf_ipftune(softc, cmd, (void *)data);
8011 break;
8012
8013 case SIOCSETFF :
8014 if (!(mode & FWRITE)) {
8015 IPFERROR(97);
8016 error = EPERM;
8017 } else {
8018 error = BCOPYIN(data, &softc->ipf_flags,
8019 sizeof(softc->ipf_flags));
8020 if (error != 0) {
8021 IPFERROR(98);
8022 error = EFAULT;
8023 }
8024 }
8025 break;
8026
8027 case SIOCGETFF :
8028 error = BCOPYOUT(&softc->ipf_flags, data,
8029 sizeof(softc->ipf_flags));
8030 if (error != 0) {
8031 IPFERROR(99);
8032 error = EFAULT;
8033 }
8034 break;
8035
8036 case SIOCFUNCL :
8037 error = ipf_resolvefunc(softc, (void *)data);
8038 break;
8039
8040 case SIOCINAFR :
8041 case SIOCRMAFR :
8042 case SIOCADAFR :
8043 case SIOCZRLST :
8044 if (!(mode & FWRITE)) {
8045 IPFERROR(100);
8046 error = EPERM;
8047 } else {
8048 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8049 softc->ipf_active, 1);
8050 }
8051 break;
8052
8053 case SIOCINIFR :
8054 case SIOCRMIFR :
8055 case SIOCADIFR :
8056 if (!(mode & FWRITE)) {
8057 IPFERROR(101);
8058 error = EPERM;
8059 } else {
8060 error = frrequest(softc, IPL_LOGIPF, cmd, (caddr_t)data,
8061 1 - softc->ipf_active, 1);
8062 }
8063 break;
8064
8065 case SIOCSWAPA :
8066 if (!(mode & FWRITE)) {
8067 IPFERROR(102);
8068 error = EPERM;
8069 } else {
8070 WRITE_ENTER(&softc->ipf_mutex);
8071 error = BCOPYOUT(&softc->ipf_active, data,
8072 sizeof(softc->ipf_active));
8073 if (error != 0) {
8074 IPFERROR(103);
8075 error = EFAULT;
8076 } else {
8077 softc->ipf_active = 1 - softc->ipf_active;
8078 }
8079 RWLOCK_EXIT(&softc->ipf_mutex);
8080 }
8081 break;
8082
8083 case SIOCGETFS :
8084 error = ipf_inobj(softc, (void *)data, &obj, &fio,
8085 IPFOBJ_IPFSTAT);
8086 if (error != 0)
8087 break;
8088 ipf_getstat(softc, &fio, obj.ipfo_rev);
8089 error = ipf_outobj(softc, (void *)data, &fio, IPFOBJ_IPFSTAT);
8090 break;
8091
8092 case SIOCFRZST :
8093 if (!(mode & FWRITE)) {
8094 IPFERROR(104);
8095 error = EPERM;
8096 } else
8097 error = ipf_zerostats(softc, (caddr_t)data);
8098 break;
8099
8100 case SIOCIPFFL :
8101 if (!(mode & FWRITE)) {
8102 IPFERROR(105);
8103 error = EPERM;
8104 } else {
8105 error = BCOPYIN(data, &tmp, sizeof(tmp));
8106 if (!error) {
8107 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8108 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8109 if (error != 0) {
8110 IPFERROR(106);
8111 error = EFAULT;
8112 }
8113 } else {
8114 IPFERROR(107);
8115 error = EFAULT;
8116 }
8117 }
8118 break;
8119
8120 #ifdef USE_INET6
8121 case SIOCIPFL6 :
8122 if (!(mode & FWRITE)) {
8123 IPFERROR(108);
8124 error = EPERM;
8125 } else {
8126 error = BCOPYIN(data, &tmp, sizeof(tmp));
8127 if (!error) {
8128 tmp = ipf_flush(softc, IPL_LOGIPF, tmp);
8129 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8130 if (error != 0) {
8131 IPFERROR(109);
8132 error = EFAULT;
8133 }
8134 } else {
8135 IPFERROR(110);
8136 error = EFAULT;
8137 }
8138 }
8139 break;
8140 #endif
8141
8142 case SIOCSTLCK :
8143 if (!(mode & FWRITE)) {
8144 IPFERROR(122);
8145 error = EPERM;
8146 } else {
8147 error = BCOPYIN(data, &tmp, sizeof(tmp));
8148 if (error == 0) {
8149 ipf_state_setlock(softc->ipf_state_soft, tmp);
8150 ipf_nat_setlock(softc->ipf_nat_soft, tmp);
8151 ipf_frag_setlock(softc->ipf_frag_soft, tmp);
8152 ipf_auth_setlock(softc->ipf_auth_soft, tmp);
8153 } else {
8154 IPFERROR(111);
8155 error = EFAULT;
8156 }
8157 }
8158 break;
8159
8160 #ifdef IPFILTER_LOG
8161 case SIOCIPFFB :
8162 if (!(mode & FWRITE)) {
8163 IPFERROR(112);
8164 error = EPERM;
8165 } else {
8166 tmp = ipf_log_clear(softc, IPL_LOGIPF);
8167 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8168 if (error) {
8169 IPFERROR(113);
8170 error = EFAULT;
8171 }
8172 }
8173 break;
8174 #endif /* IPFILTER_LOG */
8175
8176 case SIOCFRSYN :
8177 if (!(mode & FWRITE)) {
8178 IPFERROR(114);
8179 error = EPERM;
8180 } else {
8181 WRITE_ENTER(&softc->ipf_global);
8182 #if (SOLARIS && defined(_KERNEL)) && !defined(INSTANCES)
8183 error = ipfsync();
8184 #else
8185 ipf_sync(softc, NULL);
8186 error = 0;
8187 #endif
8188 RWLOCK_EXIT(&softc->ipf_global);
8189
8190 }
8191 break;
8192
8193 case SIOCGFRST :
8194 error = ipf_outobj(softc, (void *)data,
8195 ipf_frag_stats(softc->ipf_frag_soft),
8196 IPFOBJ_FRAGSTAT);
8197 break;
8198
8199 #ifdef IPFILTER_LOG
8200 case FIONREAD :
8201 tmp = ipf_log_bytesused(softc, IPL_LOGIPF);
8202 error = BCOPYOUT(&tmp, data, sizeof(tmp));
8203 break;
8204 #endif
8205
8206 case SIOCIPFITER :
8207 SPL_SCHED(s);
8208 error = ipf_frruleiter(softc, data, uid, ctx);
8209 SPL_X(s);
8210 break;
8211
8212 case SIOCGENITER :
8213 SPL_SCHED(s);
8214 error = ipf_genericiter(softc, data, uid, ctx);
8215 SPL_X(s);
8216 break;
8217
8218 case SIOCIPFDELTOK :
8219 error = BCOPYIN(data, &tmp, sizeof(tmp));
8220 if (error == 0) {
8221 SPL_SCHED(s);
8222 error = ipf_token_del(softc, tmp, uid, ctx);
8223 SPL_X(s);
8224 }
8225 break;
8226
8227 default :
8228 IPFERROR(115);
8229 error = EINVAL;
8230 break;
8231 }
8232
8233 return (error);
8234 }
8235
8236
8237 /* ------------------------------------------------------------------------ */
8238 /* Function: ipf_decaps */
8239 /* Returns: int - -1 == decapsulation failed, else bit mask of */
8240 /* flags indicating packet filtering decision. */
8241 /* Parameters: fin(I) - pointer to packet information */
8242 /* pass(I) - IP protocol version to match */
8243 /* l5proto(I) - layer 5 protocol to decode UDP data as. */
8244 /* */
8245 /* This function is called for packets that are wrapt up in other packets, */
8246 /* for example, an IP packet that is the entire data segment for another IP */
8247 /* packet. If the basic constraints for this are satisfied, change the */
8248 /* buffer to point to the start of the inner packet and start processing */
8249 /* rules belonging to the head group this rule specifies. */
8250 /* ------------------------------------------------------------------------ */
8251 u_32_t
8252 ipf_decaps(fr_info_t *fin, u_32_t pass, int l5proto)
8253 {
8254 fr_info_t fin2, *fino = NULL;
8255 int elen, hlen, nh;
8256 grehdr_t gre;
8257 ip_t *ip;
8258 mb_t *m;
8259
8260 if ((fin->fin_flx & FI_COALESCE) == 0)
8261 if (ipf_coalesce(fin) == -1)
8262 goto cantdecaps;
8263
8264 m = fin->fin_m;
8265 hlen = fin->fin_hlen;
8266
8267 switch (fin->fin_p)
8268 {
8269 case IPPROTO_UDP :
8270 /*
8271 * In this case, the specific protocol being decapsulated
8272 * inside UDP frames comes from the rule.
8273 */
8274 nh = fin->fin_fr->fr_icode;
8275 break;
8276
8277 case IPPROTO_GRE : /* 47 */
8278 bcopy(fin->fin_dp, (char *)&gre, sizeof(gre));
8279 hlen += sizeof(grehdr_t);
8280 if (gre.gr_R|gre.gr_s)
8281 goto cantdecaps;
8282 if (gre.gr_C)
8283 hlen += 4;
8284 if (gre.gr_K)
8285 hlen += 4;
8286 if (gre.gr_S)
8287 hlen += 4;
8288
8289 nh = IPPROTO_IP;
8290
8291 /*
8292 * If the routing options flag is set, validate that it is
8293 * there and bounce over it.
8294 */
8295 #if 0
8296 /* This is really heavy weight and lots of room for error, */
8297 /* so for now, put it off and get the simple stuff right. */
8298 if (gre.gr_R) {
8299 u_char off, len, *s;
8300 u_short af;
8301 int end;
8302
8303 end = 0;
8304 s = fin->fin_dp;
8305 s += hlen;
8306 aplen = fin->fin_plen - hlen;
8307 while (aplen > 3) {
8308 af = (s[0] << 8) | s[1];
8309 off = s[2];
8310 len = s[3];
8311 aplen -= 4;
8312 s += 4;
8313 if (af == 0 && len == 0) {
8314 end = 1;
8315 break;
8316 }
8317 if (aplen < len)
8318 break;
8319 s += len;
8320 aplen -= len;
8321 }
8322 if (end != 1)
8323 goto cantdecaps;
8324 hlen = s - (u_char *)fin->fin_dp;
8325 }
8326 #endif
8327 break;
8328
8329 #ifdef IPPROTO_IPIP
8330 case IPPROTO_IPIP : /* 4 */
8331 #endif
8332 nh = IPPROTO_IP;
8333 break;
8334
8335 default : /* Includes ESP, AH is special for IPv4 */
8336 goto cantdecaps;
8337 }
8338
8339 switch (nh)
8340 {
8341 case IPPROTO_IP :
8342 case IPPROTO_IPV6 :
8343 break;
8344 default :
8345 goto cantdecaps;
8346 }
8347
8348 bcopy((char *)fin, (char *)&fin2, sizeof(fin2));
8349 fino = fin;
8350 fin = &fin2;
8351 elen = hlen;
8352 #if SOLARIS && defined(_KERNEL)
8353 m->b_rptr += elen;
8354 #else
8355 m->m_data += elen;
8356 m->m_len -= elen;
8357 #endif
8358 fin->fin_plen -= elen;
8359
8360 ip = (ip_t *)((char *)fin->fin_ip + elen);
8361
8362 /*
8363 * Make sure we have at least enough data for the network layer
8364 * header.
8365 */
8366 if (IP_V(ip) == 4)
8367 hlen = IP_HL(ip) << 2;
8368 #ifdef USE_INET6
8369 else if (IP_V(ip) == 6)
8370 hlen = sizeof(ip6_t);
8371 #endif
8372 else
8373 goto cantdecaps2;
8374
8375 if (fin->fin_plen < hlen)
8376 goto cantdecaps2;
8377
8378 fin->fin_dp = (char *)ip + hlen;
8379
8380 if (IP_V(ip) == 4) {
8381 /*
8382 * Perform IPv4 header checksum validation.
8383 */
8384 if (ipf_cksum((u_short *)ip, hlen))
8385 goto cantdecaps2;
8386 }
8387
8388 if (ipf_makefrip(hlen, ip, fin) == -1) {
8389 cantdecaps2:
8390 if (m != NULL) {
8391 #if SOLARIS && defined(_KERNEL)
8392 m->b_rptr -= elen;
8393 #else
8394 m->m_data -= elen;
8395 m->m_len += elen;
8396 #endif
8397 }
8398 cantdecaps:
8399 DT1(frb_decapfrip, fr_info_t *, fin);
8400 pass &= ~FR_CMDMASK;
8401 pass |= FR_BLOCK|FR_QUICK;
8402 fin->fin_reason = FRB_DECAPFRIP;
8403 return (-1);
8404 }
8405
8406 pass = ipf_scanlist(fin, pass);
8407
8408 /*
8409 * Copy the packet filter "result" fields out of the fr_info_t struct
8410 * that is local to the decapsulation processing and back into the
8411 * one we were called with.
8412 */
8413 fino->fin_flx = fin->fin_flx;
8414 fino->fin_rev = fin->fin_rev;
8415 fino->fin_icode = fin->fin_icode;
8416 fino->fin_rule = fin->fin_rule;
8417 (void) strncpy(fino->fin_group, fin->fin_group, FR_GROUPLEN);
8418 fino->fin_fr = fin->fin_fr;
8419 fino->fin_error = fin->fin_error;
8420 fino->fin_mp = fin->fin_mp;
8421 fino->fin_m = fin->fin_m;
8422 m = fin->fin_m;
8423 if (m != NULL) {
8424 #if SOLARIS && defined(_KERNEL)
8425 m->b_rptr -= elen;
8426 #else
8427 m->m_data -= elen;
8428 m->m_len += elen;
8429 #endif
8430 }
8431 return (pass);
8432 }
8433
8434
8435 /* ------------------------------------------------------------------------ */
8436 /* Function: ipf_matcharray_load */
8437 /* Returns: int - 0 = success, else error */
8438 /* Parameters: softc(I) - pointer to soft context main structure */
8439 /* data(I) - pointer to ioctl data */
8440 /* objp(I) - ipfobj_t structure to load data into */
8441 /* arrayptr(I) - pointer to location to store array pointer */
8442 /* */
8443 /* This function loads in a mathing array through the ipfobj_t struct that */
8444 /* describes it. Sanity checking and array size limitations are enforced */
8445 /* in this function to prevent userspace from trying to load in something */
8446 /* that is insanely big. Once the size of the array is known, the memory */
8447 /* required is malloc'd and returned through changing *arrayptr. The */
8448 /* contents of the array are verified before returning. Only in the event */
8449 /* of a successful call is the caller required to free up the malloc area. */
8450 /* ------------------------------------------------------------------------ */
8451 int
8452 ipf_matcharray_load(ipf_main_softc_t *softc, caddr_t data, ipfobj_t *objp,
8453 int **arrayptr)
8454 {
8455 int arraysize, *array, error;
8456
8457 *arrayptr = NULL;
8458
8459 error = BCOPYIN(data, objp, sizeof(*objp));
8460 if (error != 0) {
8461 IPFERROR(116);
8462 return (EFAULT);
8463 }
8464
8465 if (objp->ipfo_type != IPFOBJ_IPFEXPR) {
8466 IPFERROR(117);
8467 return (EINVAL);
8468 }
8469
8470 if (((objp->ipfo_size & 3) != 0) || (objp->ipfo_size == 0) ||
8471 (objp->ipfo_size > 1024)) {
8472 IPFERROR(118);
8473 return (EINVAL);
8474 }
8475
8476 arraysize = objp->ipfo_size * sizeof(*array);
8477 KMALLOCS(array, int *, arraysize);
8478 if (array == NULL) {
8479 IPFERROR(119);
8480 return (ENOMEM);
8481 }
8482
8483 error = COPYIN(objp->ipfo_ptr, array, arraysize);
8484 if (error != 0) {
8485 KFREES(array, arraysize);
8486 IPFERROR(120);
8487 return (EFAULT);
8488 }
8489
8490 if (ipf_matcharray_verify(array, arraysize) != 0) {
8491 KFREES(array, arraysize);
8492 IPFERROR(121);
8493 return (EINVAL);
8494 }
8495
8496 *arrayptr = array;
8497 return (0);
8498 }
8499
8500
8501 /* ------------------------------------------------------------------------ */
8502 /* Function: ipf_matcharray_verify */
8503 /* Returns: Nil */
8504 /* Parameters: array(I) - pointer to matching array */
8505 /* arraysize(I) - number of elements in the array */
8506 /* */
8507 /* Verify the contents of a matching array by stepping through each element */
8508 /* in it. The actual commands in the array are not verified for */
8509 /* correctness, only that all of the sizes are correctly within limits. */
8510 /* ------------------------------------------------------------------------ */
8511 int
8512 ipf_matcharray_verify(int *array, int arraysize)
8513 {
8514 int i, nelem, maxidx;
8515 ipfexp_t *e;
8516
8517 nelem = arraysize / sizeof(*array);
8518
8519 /*
8520 * Currently, it makes no sense to have an array less than 6
8521 * elements long - the initial size at the from, a single operation
8522 * (minimum 4 in length) and a trailer, for a total of 6.
8523 */
8524 if ((array[0] < 6) || (arraysize < 24) || (arraysize > 4096)) {
8525 return (-1);
8526 }
8527
8528 /*
8529 * Verify the size of data pointed to by array with how long
8530 * the array claims to be itself.
8531 */
8532 if (array[0] * sizeof(*array) != arraysize) {
8533 return (-1);
8534 }
8535
8536 maxidx = nelem - 1;
8537 /*
8538 * The last opcode in this array should be an IPF_EXP_END.
8539 */
8540 if (array[maxidx] != IPF_EXP_END) {
8541 return (-1);
8542 }
8543
8544 for (i = 1; i < maxidx; ) {
8545 e = (ipfexp_t *)(array + i);
8546
8547 /*
8548 * The length of the bits to check must be at least 1
8549 * (or else there is nothing to comapre with!) and it
8550 * cannot exceed the length of the data present.
8551 */
8552 if ((e->ipfe_size < 1 ) ||
8553 (e->ipfe_size + i > maxidx)) {
8554 return (-1);
8555 }
8556 i += e->ipfe_size;
8557 }
8558 return (0);
8559 }
8560
8561
8562 /* ------------------------------------------------------------------------ */
8563 /* Function: ipf_fr_matcharray */
8564 /* Returns: int - 0 = match failed, else positive match */
8565 /* Parameters: fin(I) - pointer to packet information */
8566 /* array(I) - pointer to matching array */
8567 /* */
8568 /* This function is used to apply a matching array against a packet and */
8569 /* return an indication of whether or not the packet successfully matches */
8570 /* all of the commands in it. */
8571 /* ------------------------------------------------------------------------ */
8572 static int
8573 ipf_fr_matcharray(fr_info_t *fin, int *array)
8574 {
8575 int i, n, *x, rv, p;
8576 ipfexp_t *e;
8577
8578 rv = 0;
8579 n = array[0];
8580 x = array + 1;
8581
8582 for (; n > 0; x += 3 + x[3], rv = 0) {
8583 e = (ipfexp_t *)x;
8584 if (e->ipfe_cmd == IPF_EXP_END)
8585 break;
8586 n -= e->ipfe_size;
8587
8588 /*
8589 * The upper 16 bits currently store the protocol value.
8590 * This is currently used with TCP and UDP port compares and
8591 * allows "tcp.port = 80" without requiring an explicit
8592 " "ip.pr = tcp" first.
8593 */
8594 p = e->ipfe_cmd >> 16;
8595 if ((p != 0) && (p != fin->fin_p))
8596 break;
8597
8598 switch (e->ipfe_cmd)
8599 {
8600 case IPF_EXP_IP_PR :
8601 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8602 rv |= (fin->fin_p == e->ipfe_arg0[i]);
8603 }
8604 break;
8605
8606 case IPF_EXP_IP_SRCADDR :
8607 if (fin->fin_v != 4)
8608 break;
8609 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8610 rv |= ((fin->fin_saddr &
8611 e->ipfe_arg0[i * 2 + 1]) ==
8612 e->ipfe_arg0[i * 2]);
8613 }
8614 break;
8615
8616 case IPF_EXP_IP_DSTADDR :
8617 if (fin->fin_v != 4)
8618 break;
8619 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8620 rv |= ((fin->fin_daddr &
8621 e->ipfe_arg0[i * 2 + 1]) ==
8622 e->ipfe_arg0[i * 2]);
8623 }
8624 break;
8625
8626 case IPF_EXP_IP_ADDR :
8627 if (fin->fin_v != 4)
8628 break;
8629 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8630 rv |= ((fin->fin_saddr &
8631 e->ipfe_arg0[i * 2 + 1]) ==
8632 e->ipfe_arg0[i * 2]) ||
8633 ((fin->fin_daddr &
8634 e->ipfe_arg0[i * 2 + 1]) ==
8635 e->ipfe_arg0[i * 2]);
8636 }
8637 break;
8638
8639 #ifdef USE_INET6
8640 case IPF_EXP_IP6_SRCADDR :
8641 if (fin->fin_v != 6)
8642 break;
8643 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8644 rv |= IP6_MASKEQ(&fin->fin_src6,
8645 &e->ipfe_arg0[i * 8 + 4],
8646 &e->ipfe_arg0[i * 8]);
8647 }
8648 break;
8649
8650 case IPF_EXP_IP6_DSTADDR :
8651 if (fin->fin_v != 6)
8652 break;
8653 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8654 rv |= IP6_MASKEQ(&fin->fin_dst6,
8655 &e->ipfe_arg0[i * 8 + 4],
8656 &e->ipfe_arg0[i * 8]);
8657 }
8658 break;
8659
8660 case IPF_EXP_IP6_ADDR :
8661 if (fin->fin_v != 6)
8662 break;
8663 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8664 rv |= IP6_MASKEQ(&fin->fin_src6,
8665 &e->ipfe_arg0[i * 8 + 4],
8666 &e->ipfe_arg0[i * 8]) ||
8667 IP6_MASKEQ(&fin->fin_dst6,
8668 &e->ipfe_arg0[i * 8 + 4],
8669 &e->ipfe_arg0[i * 8]);
8670 }
8671 break;
8672 #endif
8673
8674 case IPF_EXP_UDP_PORT :
8675 case IPF_EXP_TCP_PORT :
8676 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8677 rv |= (fin->fin_sport == e->ipfe_arg0[i]) ||
8678 (fin->fin_dport == e->ipfe_arg0[i]);
8679 }
8680 break;
8681
8682 case IPF_EXP_UDP_SPORT :
8683 case IPF_EXP_TCP_SPORT :
8684 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8685 rv |= (fin->fin_sport == e->ipfe_arg0[i]);
8686 }
8687 break;
8688
8689 case IPF_EXP_UDP_DPORT :
8690 case IPF_EXP_TCP_DPORT :
8691 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8692 rv |= (fin->fin_dport == e->ipfe_arg0[i]);
8693 }
8694 break;
8695
8696 case IPF_EXP_TCP_FLAGS :
8697 for (i = 0; !rv && i < e->ipfe_narg; i++) {
8698 rv |= ((fin->fin_tcpf &
8699 e->ipfe_arg0[i * 2 + 1]) ==
8700 e->ipfe_arg0[i * 2]);
8701 }
8702 break;
8703 }
8704 rv ^= e->ipfe_not;
8705
8706 if (rv == 0)
8707 break;
8708 }
8709
8710 return (rv);
8711 }
8712
8713
8714 /* ------------------------------------------------------------------------ */
8715 /* Function: ipf_queueflush */
8716 /* Returns: int - number of entries flushed (0 = none) */
8717 /* Parameters: softc(I) - pointer to soft context main structure */
8718 /* deletefn(I) - function to call to delete entry */
8719 /* ipfqs(I) - top of the list of ipf internal queues */
8720 /* userqs(I) - top of the list of user defined timeouts */
8721 /* */
8722 /* This fucntion gets called when the state/NAT hash tables fill up and we */
8723 /* need to try a bit harder to free up some space. The algorithm used here */
8724 /* split into two parts but both halves have the same goal: to reduce the */
8725 /* number of connections considered to be "active" to the low watermark. */
8726 /* There are two steps in doing this: */
8727 /* 1) Remove any TCP connections that are already considered to be "closed" */
8728 /* but have not yet been removed from the state table. The two states */
8729 /* TCPS_TIME_WAIT and TCPS_CLOSED are considered to be the perfect */
8730 /* candidates for this style of removal. If freeing up entries in */
8731 /* CLOSED or both CLOSED and TIME_WAIT brings us to the low watermark, */
8732 /* we do not go on to step 2. */
8733 /* */
8734 /* 2) Look for the oldest entries on each timeout queue and free them if */
8735 /* they are within the given window we are considering. Where the */
8736 /* window starts and the steps taken to increase its size depend upon */
8737 /* how long ipf has been running (ipf_ticks.) Anything modified in the */
8738 /* last 30 seconds is not touched. */
8739 /* touched */
8740 /* die ipf_ticks 30*1.5 1800*1.5 | 43200*1.5 */
8741 /* | | | | | | */
8742 /* future <--+----------+--------+-----------+-----+-----+-----------> past */
8743 /* now \_int=30s_/ \_int=1hr_/ \_int=12hr */
8744 /* */
8745 /* Points to note: */
8746 /* - tqe_die is the time, in the future, when entries die. */
8747 /* - tqe_die - ipf_ticks is how long left the connection has to live in ipf */
8748 /* ticks. */
8749 /* - tqe_touched is when the entry was last used by NAT/state */
8750 /* - the closer tqe_touched is to ipf_ticks, the further tqe_die will be */
8751 /* ipf_ticks any given timeout queue and vice versa. */
8752 /* - both tqe_die and tqe_touched increase over time */
8753 /* - timeout queues are sorted with the highest value of tqe_die at the */
8754 /* bottom and therefore the smallest values of each are at the top */
8755 /* - the pointer passed in as ipfqs should point to an array of timeout */
8756 /* queues representing each of the TCP states */
8757 /* */
8758 /* We start by setting up a maximum range to scan for things to move of */
8759 /* iend (newest) to istart (oldest) in chunks of "interval". If nothing is */
8760 /* found in that range, "interval" is adjusted (so long as it isn't 30) and */
8761 /* we start again with a new value for "iend" and "istart". This is */
8762 /* continued until we either finish the scan of 30 second intervals or the */
8763 /* low water mark is reached. */
8764 /* ------------------------------------------------------------------------ */
8765 int
8766 ipf_queueflush(ipf_main_softc_t *softc, ipftq_delete_fn_t deletefn,
8767 ipftq_t *ipfqs, ipftq_t *userqs, u_int *activep, int size, int low)
8768 {
8769 u_long interval, istart, iend;
8770 ipftq_t *ifq, *ifqnext;
8771 ipftqent_t *tqe, *tqn;
8772 int removed = 0;
8773
8774 for (tqn = ipfqs[IPF_TCPS_CLOSED].ifq_head; ((tqe = tqn) != NULL); ) {
8775 tqn = tqe->tqe_next;
8776 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8777 removed++;
8778 }
8779 if ((*activep * 100 / size) > low) {
8780 for (tqn = ipfqs[IPF_TCPS_TIME_WAIT].ifq_head;
8781 ((tqe = tqn) != NULL); ) {
8782 tqn = tqe->tqe_next;
8783 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8784 removed++;
8785 }
8786 }
8787
8788 if ((*activep * 100 / size) <= low) {
8789 return (removed);
8790 }
8791
8792 /*
8793 * NOTE: Use of "* 15 / 10" is required here because if "* 1.5" is
8794 * used then the operations are upgraded to floating point
8795 * and kernels don't like floating point...
8796 */
8797 if (softc->ipf_ticks > IPF_TTLVAL(43200 * 15 / 10)) {
8798 istart = IPF_TTLVAL(86400 * 4);
8799 interval = IPF_TTLVAL(43200);
8800 } else if (softc->ipf_ticks > IPF_TTLVAL(1800 * 15 / 10)) {
8801 istart = IPF_TTLVAL(43200);
8802 interval = IPF_TTLVAL(1800);
8803 } else if (softc->ipf_ticks > IPF_TTLVAL(30 * 15 / 10)) {
8804 istart = IPF_TTLVAL(1800);
8805 interval = IPF_TTLVAL(30);
8806 } else {
8807 return (0);
8808 }
8809 if (istart > softc->ipf_ticks) {
8810 if (softc->ipf_ticks - interval < interval)
8811 istart = interval;
8812 else
8813 istart = (softc->ipf_ticks / interval) * interval;
8814 }
8815
8816 iend = softc->ipf_ticks - interval;
8817
8818 while ((*activep * 100 / size) > low) {
8819 u_long try;
8820
8821 try = softc->ipf_ticks - istart;
8822
8823 for (ifq = ipfqs; ifq != NULL; ifq = ifq->ifq_next) {
8824 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8825 if (try < tqe->tqe_touched)
8826 break;
8827 tqn = tqe->tqe_next;
8828 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8829 removed++;
8830 }
8831 }
8832
8833 for (ifq = userqs; ifq != NULL; ifq = ifqnext) {
8834 ifqnext = ifq->ifq_next;
8835
8836 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
8837 if (try < tqe->tqe_touched)
8838 break;
8839 tqn = tqe->tqe_next;
8840 if ((*deletefn)(softc, tqe->tqe_parent) == 0)
8841 removed++;
8842 }
8843 }
8844
8845 if (try >= iend) {
8846 if (interval == IPF_TTLVAL(43200)) {
8847 interval = IPF_TTLVAL(1800);
8848 } else if (interval == IPF_TTLVAL(1800)) {
8849 interval = IPF_TTLVAL(30);
8850 } else {
8851 break;
8852 }
8853 if (interval >= softc->ipf_ticks)
8854 break;
8855
8856 iend = softc->ipf_ticks - interval;
8857 }
8858 istart -= interval;
8859 }
8860
8861 return (removed);
8862 }
8863
8864
8865 /* ------------------------------------------------------------------------ */
8866 /* Function: ipf_deliverlocal */
8867 /* Returns: int - 1 = local address, 0 = non-local address */
8868 /* Parameters: softc(I) - pointer to soft context main structure */
8869 /* ipversion(I) - IP protocol version (4 or 6) */
8870 /* ifp(I) - network interface pointer */
8871 /* ipaddr(I) - IPv4/6 destination address */
8872 /* */
8873 /* This fucntion is used to determine in the address "ipaddr" belongs to */
8874 /* the network interface represented by ifp. */
8875 /* ------------------------------------------------------------------------ */
8876 int
8877 ipf_deliverlocal(ipf_main_softc_t *softc, int ipversion, void *ifp,
8878 i6addr_t *ipaddr)
8879 {
8880 i6addr_t addr;
8881 int islocal = 0;
8882
8883 if (ipversion == 4) {
8884 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8885 if (addr.in4.s_addr == ipaddr->in4.s_addr)
8886 islocal = 1;
8887 }
8888
8889 #ifdef USE_INET6
8890 } else if (ipversion == 6) {
8891 if (ipf_ifpaddr(softc, 6, FRI_NORMAL, ifp, &addr, NULL) == 0) {
8892 if (IP6_EQ(&addr, ipaddr))
8893 islocal = 1;
8894 }
8895 #endif
8896 }
8897
8898 return (islocal);
8899 }
8900
8901
8902 /* ------------------------------------------------------------------------ */
8903 /* Function: ipf_settimeout */
8904 /* Returns: int - 0 = success, -1 = failure */
8905 /* Parameters: softc(I) - pointer to soft context main structure */
8906 /* t(I) - pointer to tuneable array entry */
8907 /* p(I) - pointer to values passed in to apply */
8908 /* */
8909 /* This function is called to set the timeout values for each distinct */
8910 /* queue timeout that is available. When called, it calls into both the */
8911 /* state and NAT code, telling them to update their timeout queues. */
8912 /* ------------------------------------------------------------------------ */
8913 static int
8914 ipf_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
8915 ipftuneval_t *p)
8916 {
8917
8918 /*
8919 * ipf_interror should be set by the functions called here, not
8920 * by this function - it's just a middle man.
8921 */
8922 if (ipf_state_settimeout(softc, t, p) == -1)
8923 return (-1);
8924 if (ipf_nat_settimeout(softc, t, p) == -1)
8925 return (-1);
8926 return (0);
8927 }
8928
8929
8930 /* ------------------------------------------------------------------------ */
8931 /* Function: ipf_apply_timeout */
8932 /* Returns: int - 0 = success, -1 = failure */
8933 /* Parameters: head(I) - pointer to tuneable array entry */
8934 /* seconds(I) - pointer to values passed in to apply */
8935 /* */
8936 /* This function applies a timeout of "seconds" to the timeout queue that */
8937 /* is pointed to by "head". All entries on this list have an expiration */
8938 /* set to be the current tick value of ipf plus the ttl. Given that this */
8939 /* function should only be called when the delta is non-zero, the task is */
8940 /* to walk the entire list and apply the change. The sort order will not */
8941 /* change. The only catch is that this is O(n) across the list, so if the */
8942 /* queue has lots of entries (10s of thousands or 100s of thousands), it */
8943 /* could take a relatively long time to work through them all. */
8944 /* ------------------------------------------------------------------------ */
8945 void
8946 ipf_apply_timeout(ipftq_t *head, u_int seconds)
8947 {
8948 u_int oldtimeout, newtimeout;
8949 ipftqent_t *tqe;
8950 int delta;
8951
8952 MUTEX_ENTER(&head->ifq_lock);
8953 oldtimeout = head->ifq_ttl;
8954 newtimeout = IPF_TTLVAL(seconds);
8955 delta = oldtimeout - newtimeout;
8956
8957 head->ifq_ttl = newtimeout;
8958
8959 for (tqe = head->ifq_head; tqe != NULL; tqe = tqe->tqe_next) {
8960 tqe->tqe_die += delta;
8961 }
8962 MUTEX_EXIT(&head->ifq_lock);
8963 }
8964
8965
8966 /* ------------------------------------------------------------------------ */
8967 /* Function: ipf_settimeout_tcp */
8968 /* Returns: int - 0 = successfully applied, -1 = failed */
8969 /* Parameters: t(I) - pointer to tuneable to change */
8970 /* p(I) - pointer to new timeout information */
8971 /* tab(I) - pointer to table of TCP queues */
8972 /* */
8973 /* This function applies the new timeout (p) to the TCP tunable (t) and */
8974 /* updates all of the entries on the relevant timeout queue by calling */
8975 /* ipf_apply_timeout(). */
8976 /* ------------------------------------------------------------------------ */
8977 int
8978 ipf_settimeout_tcp(ipftuneable_t *t, ipftuneval_t *p, ipftq_t *tab)
8979 {
8980 if (!strcmp(t->ipft_name, "tcp_idle_timeout") ||
8981 !strcmp(t->ipft_name, "tcp_established")) {
8982 ipf_apply_timeout(&tab[IPF_TCPS_ESTABLISHED], p->ipftu_int);
8983 } else if (!strcmp(t->ipft_name, "tcp_close_wait")) {
8984 ipf_apply_timeout(&tab[IPF_TCPS_CLOSE_WAIT], p->ipftu_int);
8985 } else if (!strcmp(t->ipft_name, "tcp_last_ack")) {
8986 ipf_apply_timeout(&tab[IPF_TCPS_LAST_ACK], p->ipftu_int);
8987 } else if (!strcmp(t->ipft_name, "tcp_timeout")) {
8988 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8989 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8990 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8991 } else if (!strcmp(t->ipft_name, "tcp_listen")) {
8992 ipf_apply_timeout(&tab[IPF_TCPS_LISTEN], p->ipftu_int);
8993 } else if (!strcmp(t->ipft_name, "tcp_half_established")) {
8994 ipf_apply_timeout(&tab[IPF_TCPS_HALF_ESTAB], p->ipftu_int);
8995 } else if (!strcmp(t->ipft_name, "tcp_closing")) {
8996 ipf_apply_timeout(&tab[IPF_TCPS_CLOSING], p->ipftu_int);
8997 } else if (!strcmp(t->ipft_name, "tcp_syn_received")) {
8998 ipf_apply_timeout(&tab[IPF_TCPS_SYN_RECEIVED], p->ipftu_int);
8999 } else if (!strcmp(t->ipft_name, "tcp_syn_sent")) {
9000 ipf_apply_timeout(&tab[IPF_TCPS_SYN_SENT], p->ipftu_int);
9001 } else if (!strcmp(t->ipft_name, "tcp_closed")) {
9002 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9003 } else if (!strcmp(t->ipft_name, "tcp_half_closed")) {
9004 ipf_apply_timeout(&tab[IPF_TCPS_CLOSED], p->ipftu_int);
9005 } else if (!strcmp(t->ipft_name, "tcp_time_wait")) {
9006 ipf_apply_timeout(&tab[IPF_TCPS_TIME_WAIT], p->ipftu_int);
9007 } else {
9008 /*
9009 * ipf_interror isn't set here because it should be set
9010 * by whatever called this function.
9011 */
9012 return (-1);
9013 }
9014 return (0);
9015 }
9016
9017
9018 /* ------------------------------------------------------------------------ */
9019 /* Function: ipf_main_soft_create */
9020 /* Returns: NULL = failure, else success */
9021 /* Parameters: arg(I) - pointer to soft context structure if already allocd */
9022 /* */
9023 /* Create the foundation soft context structure. In circumstances where it */
9024 /* is not required to dynamically allocate the context, a pointer can be */
9025 /* passed in (rather than NULL) to a structure to be initialised. */
9026 /* The main thing of interest is that a number of locks are initialised */
9027 /* here instead of in the where might be expected - in the relevant create */
9028 /* function elsewhere. This is done because the current locking design has */
9029 /* some areas where these locks are used outside of their module. */
9030 /* Possibly the most important exercise that is done here is setting of all */
9031 /* the timeout values, allowing them to be changed before init(). */
9032 /* ------------------------------------------------------------------------ */
9033 void *
9034 ipf_main_soft_create(void *arg)
9035 {
9036 ipf_main_softc_t *softc;
9037
9038 if (arg == NULL) {
9039 KMALLOC(softc, ipf_main_softc_t *);
9040 if (softc == NULL)
9041 return (NULL);
9042 } else {
9043 softc = arg;
9044 }
9045
9046 bzero((char *)softc, sizeof(*softc));
9047
9048 /*
9049 * This serves as a flag as to whether or not the softc should be
9050 * free'd when _destroy is called.
9051 */
9052 softc->ipf_dynamic_softc = (arg == NULL) ? 1 : 0;
9053
9054 softc->ipf_tuners = ipf_tune_array_copy(softc,
9055 sizeof(ipf_main_tuneables),
9056 ipf_main_tuneables);
9057 if (softc->ipf_tuners == NULL) {
9058 ipf_main_soft_destroy(softc);
9059 return (NULL);
9060 }
9061
9062 MUTEX_INIT(&softc->ipf_rw, "ipf rw mutex");
9063 MUTEX_INIT(&softc->ipf_timeoutlock, "ipf timeout lock");
9064 RWLOCK_INIT(&softc->ipf_global, "ipf filter load/unload mutex");
9065 RWLOCK_INIT(&softc->ipf_mutex, "ipf filter rwlock");
9066 RWLOCK_INIT(&softc->ipf_tokens, "ipf token rwlock");
9067 RWLOCK_INIT(&softc->ipf_state, "ipf state rwlock");
9068 RWLOCK_INIT(&softc->ipf_nat, "ipf IP NAT rwlock");
9069 RWLOCK_INIT(&softc->ipf_poolrw, "ipf pool rwlock");
9070 RWLOCK_INIT(&softc->ipf_frag, "ipf frag rwlock");
9071
9072 softc->ipf_token_head = NULL;
9073 softc->ipf_token_tail = &softc->ipf_token_head;
9074
9075 softc->ipf_tcpidletimeout = FIVE_DAYS;
9076 softc->ipf_tcpclosewait = IPF_TTLVAL(2 * TCP_MSL);
9077 softc->ipf_tcplastack = IPF_TTLVAL(30);
9078 softc->ipf_tcptimewait = IPF_TTLVAL(2 * TCP_MSL);
9079 softc->ipf_tcptimeout = IPF_TTLVAL(2 * TCP_MSL);
9080 softc->ipf_tcpsynsent = IPF_TTLVAL(2 * TCP_MSL);
9081 softc->ipf_tcpsynrecv = IPF_TTLVAL(2 * TCP_MSL);
9082 softc->ipf_tcpclosed = IPF_TTLVAL(30);
9083 softc->ipf_tcphalfclosed = IPF_TTLVAL(2 * 3600);
9084 softc->ipf_udptimeout = IPF_TTLVAL(120);
9085 softc->ipf_udpacktimeout = IPF_TTLVAL(12);
9086 softc->ipf_icmptimeout = IPF_TTLVAL(60);
9087 softc->ipf_icmpacktimeout = IPF_TTLVAL(6);
9088 softc->ipf_iptimeout = IPF_TTLVAL(60);
9089
9090 #if defined(IPFILTER_DEFAULT_BLOCK)
9091 softc->ipf_pass = FR_BLOCK|FR_NOMATCH;
9092 #else
9093 softc->ipf_pass = (IPF_DEFAULT_PASS)|FR_NOMATCH;
9094 #endif
9095 softc->ipf_minttl = 4;
9096 softc->ipf_icmpminfragmtu = 68;
9097 softc->ipf_max_namelen = 128;
9098 softc->ipf_flags = IPF_LOGGING;
9099
9100 #ifdef LARGE_NAT
9101 softc->ipf_large_nat = 1;
9102 #endif
9103 ipf_fbsd_kenv_get(softc);
9104
9105 return (softc);
9106 }
9107
9108 /* ------------------------------------------------------------------------ */
9109 /* Function: ipf_main_soft_init */
9110 /* Returns: 0 = success, -1 = failure */
9111 /* Parameters: softc(I) - pointer to soft context main structure */
9112 /* */
9113 /* A null-op function that exists as a placeholder so that the flow in */
9114 /* other functions is obvious. */
9115 /* ------------------------------------------------------------------------ */
9116 /*ARGSUSED*/
9117 int
9118 ipf_main_soft_init(ipf_main_softc_t *softc)
9119 {
9120 return (0);
9121 }
9122
9123
9124 /* ------------------------------------------------------------------------ */
9125 /* Function: ipf_main_soft_destroy */
9126 /* Returns: void */
9127 /* Parameters: softc(I) - pointer to soft context main structure */
9128 /* */
9129 /* Undo everything that we did in ipf_main_soft_create. */
9130 /* */
9131 /* The most important check that needs to be made here is whether or not */
9132 /* the structure was allocated by ipf_main_soft_create() by checking what */
9133 /* value is stored in ipf_dynamic_main. */
9134 /* ------------------------------------------------------------------------ */
9135 /*ARGSUSED*/
9136 void
9137 ipf_main_soft_destroy(ipf_main_softc_t *softc)
9138 {
9139
9140 RW_DESTROY(&softc->ipf_frag);
9141 RW_DESTROY(&softc->ipf_poolrw);
9142 RW_DESTROY(&softc->ipf_nat);
9143 RW_DESTROY(&softc->ipf_state);
9144 RW_DESTROY(&softc->ipf_tokens);
9145 RW_DESTROY(&softc->ipf_mutex);
9146 RW_DESTROY(&softc->ipf_global);
9147 MUTEX_DESTROY(&softc->ipf_timeoutlock);
9148 MUTEX_DESTROY(&softc->ipf_rw);
9149
9150 if (softc->ipf_tuners != NULL) {
9151 KFREES(softc->ipf_tuners, sizeof(ipf_main_tuneables));
9152 }
9153 if (softc->ipf_dynamic_softc == 1) {
9154 KFREE(softc);
9155 }
9156 }
9157
9158
9159 /* ------------------------------------------------------------------------ */
9160 /* Function: ipf_main_soft_fini */
9161 /* Returns: 0 = success, -1 = failure */
9162 /* Parameters: softc(I) - pointer to soft context main structure */
9163 /* */
9164 /* Clean out the rules which have been added since _init was last called, */
9165 /* the only dynamic part of the mainline. */
9166 /* ------------------------------------------------------------------------ */
9167 int
9168 ipf_main_soft_fini(ipf_main_softc_t *softc)
9169 {
9170 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9171 (void) ipf_flush(softc, IPL_LOGIPF, FR_INQUE|FR_OUTQUE);
9172 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE|FR_INACTIVE);
9173 (void) ipf_flush(softc, IPL_LOGCOUNT, FR_INQUE|FR_OUTQUE);
9174
9175 return (0);
9176 }
9177
9178
9179 /* ------------------------------------------------------------------------ */
9180 /* Function: ipf_main_load */
9181 /* Returns: 0 = success, -1 = failure */
9182 /* Parameters: none */
9183 /* */
9184 /* Handle global initialisation that needs to be done for the base part of */
9185 /* IPFilter. At present this just amounts to initialising some ICMP lookup */
9186 /* arrays that get used by the state/NAT code. */
9187 /* ------------------------------------------------------------------------ */
9188 int
9189 ipf_main_load(void)
9190 {
9191 int i;
9192
9193 /* fill icmp reply type table */
9194 for (i = 0; i <= ICMP_MAXTYPE; i++)
9195 icmpreplytype4[i] = -1;
9196 icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
9197 icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
9198 icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
9199 icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
9200
9201 #ifdef USE_INET6
9202 /* fill icmp reply type table */
9203 for (i = 0; i <= ICMP6_MAXTYPE; i++)
9204 icmpreplytype6[i] = -1;
9205 icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
9206 icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
9207 icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
9208 icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
9209 icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
9210 #endif
9211
9212 return (0);
9213 }
9214
9215
9216 /* ------------------------------------------------------------------------ */
9217 /* Function: ipf_main_unload */
9218 /* Returns: 0 = success, -1 = failure */
9219 /* Parameters: none */
9220 /* */
9221 /* A null-op function that exists as a placeholder so that the flow in */
9222 /* other functions is obvious. */
9223 /* ------------------------------------------------------------------------ */
9224 int
9225 ipf_main_unload(void)
9226 {
9227 return (0);
9228 }
9229
9230
9231 /* ------------------------------------------------------------------------ */
9232 /* Function: ipf_load_all */
9233 /* Returns: 0 = success, -1 = failure */
9234 /* Parameters: none */
9235 /* */
9236 /* Work through all of the subsystems inside IPFilter and call the load */
9237 /* function for each in an order that won't lead to a crash :) */
9238 /* ------------------------------------------------------------------------ */
9239 int
9240 ipf_load_all(void)
9241 {
9242 if (ipf_main_load() == -1)
9243 return (-1);
9244
9245 if (ipf_state_main_load() == -1)
9246 return (-1);
9247
9248 if (ipf_nat_main_load() == -1)
9249 return (-1);
9250
9251 if (ipf_frag_main_load() == -1)
9252 return (-1);
9253
9254 if (ipf_auth_main_load() == -1)
9255 return (-1);
9256
9257 if (ipf_proxy_main_load() == -1)
9258 return (-1);
9259
9260 return (0);
9261 }
9262
9263
9264 /* ------------------------------------------------------------------------ */
9265 /* Function: ipf_unload_all */
9266 /* Returns: 0 = success, -1 = failure */
9267 /* Parameters: none */
9268 /* */
9269 /* Work through all of the subsystems inside IPFilter and call the unload */
9270 /* function for each in an order that won't lead to a crash :) */
9271 /* ------------------------------------------------------------------------ */
9272 int
9273 ipf_unload_all(void)
9274 {
9275 if (ipf_proxy_main_unload() == -1)
9276 return (-1);
9277
9278 if (ipf_auth_main_unload() == -1)
9279 return (-1);
9280
9281 if (ipf_frag_main_unload() == -1)
9282 return (-1);
9283
9284 if (ipf_nat_main_unload() == -1)
9285 return (-1);
9286
9287 if (ipf_state_main_unload() == -1)
9288 return (-1);
9289
9290 if (ipf_main_unload() == -1)
9291 return (-1);
9292
9293 return (0);
9294 }
9295
9296
9297 /* ------------------------------------------------------------------------ */
9298 /* Function: ipf_create_all */
9299 /* Returns: NULL = failure, else success */
9300 /* Parameters: arg(I) - pointer to soft context main structure */
9301 /* */
9302 /* Work through all of the subsystems inside IPFilter and call the create */
9303 /* function for each in an order that won't lead to a crash :) */
9304 /* ------------------------------------------------------------------------ */
9305 ipf_main_softc_t *
9306 ipf_create_all(void *arg)
9307 {
9308 ipf_main_softc_t *softc;
9309
9310 softc = ipf_main_soft_create(arg);
9311 if (softc == NULL)
9312 return (NULL);
9313
9314 #ifdef IPFILTER_LOG
9315 softc->ipf_log_soft = ipf_log_soft_create(softc);
9316 if (softc->ipf_log_soft == NULL) {
9317 ipf_destroy_all(softc);
9318 return (NULL);
9319 }
9320 #endif
9321
9322 softc->ipf_lookup_soft = ipf_lookup_soft_create(softc);
9323 if (softc->ipf_lookup_soft == NULL) {
9324 ipf_destroy_all(softc);
9325 return (NULL);
9326 }
9327
9328 softc->ipf_sync_soft = ipf_sync_soft_create(softc);
9329 if (softc->ipf_sync_soft == NULL) {
9330 ipf_destroy_all(softc);
9331 return (NULL);
9332 }
9333
9334 softc->ipf_state_soft = ipf_state_soft_create(softc);
9335 if (softc->ipf_state_soft == NULL) {
9336 ipf_destroy_all(softc);
9337 return (NULL);
9338 }
9339
9340 softc->ipf_nat_soft = ipf_nat_soft_create(softc);
9341 if (softc->ipf_nat_soft == NULL) {
9342 ipf_destroy_all(softc);
9343 return (NULL);
9344 }
9345
9346 softc->ipf_frag_soft = ipf_frag_soft_create(softc);
9347 if (softc->ipf_frag_soft == NULL) {
9348 ipf_destroy_all(softc);
9349 return (NULL);
9350 }
9351
9352 softc->ipf_auth_soft = ipf_auth_soft_create(softc);
9353 if (softc->ipf_auth_soft == NULL) {
9354 ipf_destroy_all(softc);
9355 return (NULL);
9356 }
9357
9358 softc->ipf_proxy_soft = ipf_proxy_soft_create(softc);
9359 if (softc->ipf_proxy_soft == NULL) {
9360 ipf_destroy_all(softc);
9361 return (NULL);
9362 }
9363
9364 return (softc);
9365 }
9366
9367
9368 /* ------------------------------------------------------------------------ */
9369 /* Function: ipf_destroy_all */
9370 /* Returns: void */
9371 /* Parameters: softc(I) - pointer to soft context main structure */
9372 /* */
9373 /* Work through all of the subsystems inside IPFilter and call the destroy */
9374 /* function for each in an order that won't lead to a crash :) */
9375 /* */
9376 /* Every one of these functions is expected to succeed, so there is no */
9377 /* checking of return values. */
9378 /* ------------------------------------------------------------------------ */
9379 void
9380 ipf_destroy_all(ipf_main_softc_t *softc)
9381 {
9382
9383 if (softc->ipf_state_soft != NULL) {
9384 ipf_state_soft_destroy(softc, softc->ipf_state_soft);
9385 softc->ipf_state_soft = NULL;
9386 }
9387
9388 if (softc->ipf_nat_soft != NULL) {
9389 ipf_nat_soft_destroy(softc, softc->ipf_nat_soft);
9390 softc->ipf_nat_soft = NULL;
9391 }
9392
9393 if (softc->ipf_frag_soft != NULL) {
9394 ipf_frag_soft_destroy(softc, softc->ipf_frag_soft);
9395 softc->ipf_frag_soft = NULL;
9396 }
9397
9398 if (softc->ipf_auth_soft != NULL) {
9399 ipf_auth_soft_destroy(softc, softc->ipf_auth_soft);
9400 softc->ipf_auth_soft = NULL;
9401 }
9402
9403 if (softc->ipf_proxy_soft != NULL) {
9404 ipf_proxy_soft_destroy(softc, softc->ipf_proxy_soft);
9405 softc->ipf_proxy_soft = NULL;
9406 }
9407
9408 if (softc->ipf_sync_soft != NULL) {
9409 ipf_sync_soft_destroy(softc, softc->ipf_sync_soft);
9410 softc->ipf_sync_soft = NULL;
9411 }
9412
9413 if (softc->ipf_lookup_soft != NULL) {
9414 ipf_lookup_soft_destroy(softc, softc->ipf_lookup_soft);
9415 softc->ipf_lookup_soft = NULL;
9416 }
9417
9418 #ifdef IPFILTER_LOG
9419 if (softc->ipf_log_soft != NULL) {
9420 ipf_log_soft_destroy(softc, softc->ipf_log_soft);
9421 softc->ipf_log_soft = NULL;
9422 }
9423 #endif
9424
9425 ipf_main_soft_destroy(softc);
9426 }
9427
9428
9429 /* ------------------------------------------------------------------------ */
9430 /* Function: ipf_init_all */
9431 /* Returns: 0 = success, -1 = failure */
9432 /* Parameters: softc(I) - pointer to soft context main structure */
9433 /* */
9434 /* Work through all of the subsystems inside IPFilter and call the init */
9435 /* function for each in an order that won't lead to a crash :) */
9436 /* ------------------------------------------------------------------------ */
9437 int
9438 ipf_init_all(ipf_main_softc_t *softc)
9439 {
9440
9441 if (ipf_main_soft_init(softc) == -1)
9442 return (-1);
9443
9444 #ifdef IPFILTER_LOG
9445 if (ipf_log_soft_init(softc, softc->ipf_log_soft) == -1)
9446 return (-1);
9447 #endif
9448
9449 if (ipf_lookup_soft_init(softc, softc->ipf_lookup_soft) == -1)
9450 return (-1);
9451
9452 if (ipf_sync_soft_init(softc, softc->ipf_sync_soft) == -1)
9453 return (-1);
9454
9455 if (ipf_state_soft_init(softc, softc->ipf_state_soft) == -1)
9456 return (-1);
9457
9458 if (ipf_nat_soft_init(softc, softc->ipf_nat_soft) == -1)
9459 return (-1);
9460
9461 if (ipf_frag_soft_init(softc, softc->ipf_frag_soft) == -1)
9462 return (-1);
9463
9464 if (ipf_auth_soft_init(softc, softc->ipf_auth_soft) == -1)
9465 return (-1);
9466
9467 if (ipf_proxy_soft_init(softc, softc->ipf_proxy_soft) == -1)
9468 return (-1);
9469
9470 return (0);
9471 }
9472
9473
9474 /* ------------------------------------------------------------------------ */
9475 /* Function: ipf_fini_all */
9476 /* Returns: 0 = success, -1 = failure */
9477 /* Parameters: softc(I) - pointer to soft context main structure */
9478 /* */
9479 /* Work through all of the subsystems inside IPFilter and call the fini */
9480 /* function for each in an order that won't lead to a crash :) */
9481 /* ------------------------------------------------------------------------ */
9482 int
9483 ipf_fini_all(ipf_main_softc_t *softc)
9484 {
9485
9486 ipf_token_flush(softc);
9487
9488 if (ipf_proxy_soft_fini(softc, softc->ipf_proxy_soft) == -1)
9489 return (-1);
9490
9491 if (ipf_auth_soft_fini(softc, softc->ipf_auth_soft) == -1)
9492 return (-1);
9493
9494 if (ipf_frag_soft_fini(softc, softc->ipf_frag_soft) == -1)
9495 return (-1);
9496
9497 if (ipf_nat_soft_fini(softc, softc->ipf_nat_soft) == -1)
9498 return (-1);
9499
9500 if (ipf_state_soft_fini(softc, softc->ipf_state_soft) == -1)
9501 return (-1);
9502
9503 if (ipf_sync_soft_fini(softc, softc->ipf_sync_soft) == -1)
9504 return (-1);
9505
9506 if (ipf_lookup_soft_fini(softc, softc->ipf_lookup_soft) == -1)
9507 return (-1);
9508
9509 #ifdef IPFILTER_LOG
9510 if (ipf_log_soft_fini(softc, softc->ipf_log_soft) == -1)
9511 return (-1);
9512 #endif
9513
9514 if (ipf_main_soft_fini(softc) == -1)
9515 return (-1);
9516
9517 return (0);
9518 }
9519
9520
9521 /* ------------------------------------------------------------------------ */
9522 /* Function: ipf_rule_expire */
9523 /* Returns: Nil */
9524 /* Parameters: softc(I) - pointer to soft context main structure */
9525 /* */
9526 /* At present this function exists just to support temporary addition of */
9527 /* firewall rules. Both inactive and active lists are scanned for items to */
9528 /* purge, as by rights, the expiration is computed as soon as the rule is */
9529 /* loaded in. */
9530 /* ------------------------------------------------------------------------ */
9531 void
9532 ipf_rule_expire(ipf_main_softc_t *softc)
9533 {
9534 frentry_t *fr;
9535
9536 if ((softc->ipf_rule_explist[0] == NULL) &&
9537 (softc->ipf_rule_explist[1] == NULL))
9538 return;
9539
9540 WRITE_ENTER(&softc->ipf_mutex);
9541
9542 while ((fr = softc->ipf_rule_explist[0]) != NULL) {
9543 /*
9544 * Because the list is kept sorted on insertion, the fist
9545 * one that dies in the future means no more work to do.
9546 */
9547 if (fr->fr_die > softc->ipf_ticks)
9548 break;
9549 ipf_rule_delete(softc, fr, IPL_LOGIPF, 0);
9550 }
9551
9552 while ((fr = softc->ipf_rule_explist[1]) != NULL) {
9553 /*
9554 * Because the list is kept sorted on insertion, the fist
9555 * one that dies in the future means no more work to do.
9556 */
9557 if (fr->fr_die > softc->ipf_ticks)
9558 break;
9559 ipf_rule_delete(softc, fr, IPL_LOGIPF, 1);
9560 }
9561
9562 RWLOCK_EXIT(&softc->ipf_mutex);
9563 }
9564
9565
9566 static int ipf_ht_node_cmp(struct host_node_s *, struct host_node_s *);
9567 static void ipf_ht_node_make_key(host_track_t *, host_node_t *, int,
9568 i6addr_t *);
9569
9570 host_node_t RBI_ZERO(ipf_rb);
9571 RBI_CODE(ipf_rb, host_node_t, hn_entry, ipf_ht_node_cmp)
9572
9573
9574 /* ------------------------------------------------------------------------ */
9575 /* Function: ipf_ht_node_cmp */
9576 /* Returns: int - 0 == nodes are the same, .. */
9577 /* Parameters: k1(I) - pointer to first key to compare */
9578 /* k2(I) - pointer to second key to compare */
9579 /* */
9580 /* The "key" for the node is a combination of two fields: the address */
9581 /* family and the address itself. */
9582 /* */
9583 /* Because we're not actually interpreting the address data, it isn't */
9584 /* necessary to convert them to/from network/host byte order. The mask is */
9585 /* just used to remove bits that aren't significant - it doesn't matter */
9586 /* where they are, as long as they're always in the same place. */
9587 /* */
9588 /* As with IP6_EQ, comparing IPv6 addresses starts at the bottom because */
9589 /* this is where individual ones will differ the most - but not true for */
9590 /* for /48's, etc. */
9591 /* ------------------------------------------------------------------------ */
9592 static int
9593 ipf_ht_node_cmp(struct host_node_s *k1, struct host_node_s *k2)
9594 {
9595 int i;
9596
9597 i = (k2->hn_addr.adf_family - k1->hn_addr.adf_family);
9598 if (i != 0)
9599 return (i);
9600
9601 if (k1->hn_addr.adf_family == AF_INET)
9602 return (k2->hn_addr.adf_addr.in4.s_addr -
9603 k1->hn_addr.adf_addr.in4.s_addr);
9604
9605 i = k2->hn_addr.adf_addr.i6[3] - k1->hn_addr.adf_addr.i6[3];
9606 if (i != 0)
9607 return (i);
9608 i = k2->hn_addr.adf_addr.i6[2] - k1->hn_addr.adf_addr.i6[2];
9609 if (i != 0)
9610 return (i);
9611 i = k2->hn_addr.adf_addr.i6[1] - k1->hn_addr.adf_addr.i6[1];
9612 if (i != 0)
9613 return (i);
9614 i = k2->hn_addr.adf_addr.i6[0] - k1->hn_addr.adf_addr.i6[0];
9615 return (i);
9616 }
9617
9618
9619 /* ------------------------------------------------------------------------ */
9620 /* Function: ipf_ht_node_make_key */
9621 /* Returns: Nil */
9622 /* parameters: htp(I) - pointer to address tracking structure */
9623 /* key(I) - where to store masked address for lookup */
9624 /* family(I) - protocol family of address */
9625 /* addr(I) - pointer to network address */
9626 /* */
9627 /* Using the "netmask" (number of bits) stored parent host tracking struct, */
9628 /* copy the address passed in into the key structure whilst masking out the */
9629 /* bits that we don't want. */
9630 /* */
9631 /* Because the parser will set ht_netmask to 128 if there is no protocol */
9632 /* specified (the parser doesn't know if it should be a v4 or v6 rule), we */
9633 /* have to be wary of that and not allow 32-128 to happen. */
9634 /* ------------------------------------------------------------------------ */
9635 static void
9636 ipf_ht_node_make_key(host_track_t *htp, host_node_t *key, int family,
9637 i6addr_t *addr)
9638 {
9639 key->hn_addr.adf_family = family;
9640 if (family == AF_INET) {
9641 u_32_t mask;
9642 int bits;
9643
9644 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in4);
9645 bits = htp->ht_netmask;
9646 if (bits >= 32) {
9647 mask = 0xffffffff;
9648 } else {
9649 mask = htonl(0xffffffff << (32 - bits));
9650 }
9651 key->hn_addr.adf_addr.in4.s_addr = addr->in4.s_addr & mask;
9652 #ifdef USE_INET6
9653 } else {
9654 int bits = htp->ht_netmask;
9655
9656 key->hn_addr.adf_len = sizeof(key->hn_addr.adf_addr.in6);
9657 if (bits > 96) {
9658 key->hn_addr.adf_addr.i6[3] = addr->i6[3] &
9659 htonl(0xffffffff << (128 - bits));
9660 key->hn_addr.adf_addr.i6[2] = addr->i6[2];
9661 key->hn_addr.adf_addr.i6[1] = addr->i6[2];
9662 key->hn_addr.adf_addr.i6[0] = addr->i6[2];
9663 } else if (bits > 64) {
9664 key->hn_addr.adf_addr.i6[3] = 0;
9665 key->hn_addr.adf_addr.i6[2] = addr->i6[2] &
9666 htonl(0xffffffff << (96 - bits));
9667 key->hn_addr.adf_addr.i6[1] = addr->i6[1];
9668 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9669 } else if (bits > 32) {
9670 key->hn_addr.adf_addr.i6[3] = 0;
9671 key->hn_addr.adf_addr.i6[2] = 0;
9672 key->hn_addr.adf_addr.i6[1] = addr->i6[1] &
9673 htonl(0xffffffff << (64 - bits));
9674 key->hn_addr.adf_addr.i6[0] = addr->i6[0];
9675 } else {
9676 key->hn_addr.adf_addr.i6[3] = 0;
9677 key->hn_addr.adf_addr.i6[2] = 0;
9678 key->hn_addr.adf_addr.i6[1] = 0;
9679 key->hn_addr.adf_addr.i6[0] = addr->i6[0] &
9680 htonl(0xffffffff << (32 - bits));
9681 }
9682 #endif
9683 }
9684 }
9685
9686
9687 /* ------------------------------------------------------------------------ */
9688 /* Function: ipf_ht_node_add */
9689 /* Returns: int - 0 == success, -1 == failure */
9690 /* Parameters: softc(I) - pointer to soft context main structure */
9691 /* htp(I) - pointer to address tracking structure */
9692 /* family(I) - protocol family of address */
9693 /* addr(I) - pointer to network address */
9694 /* */
9695 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9696 /* ipf_ht_node_del FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9697 /* */
9698 /* After preparing the key with the address information to find, look in */
9699 /* the red-black tree to see if the address is known. A successful call to */
9700 /* this function can mean one of two things: a new node was added to the */
9701 /* tree or a matching node exists and we're able to bump up its activity. */
9702 /* ------------------------------------------------------------------------ */
9703 int
9704 ipf_ht_node_add(ipf_main_softc_t *softc, host_track_t *htp, int family,
9705 i6addr_t *addr)
9706 {
9707 host_node_t *h;
9708 host_node_t k;
9709
9710 ipf_ht_node_make_key(htp, &k, family, addr);
9711
9712 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9713 if (h == NULL) {
9714 if (htp->ht_cur_nodes >= htp->ht_max_nodes)
9715 return (-1);
9716 KMALLOC(h, host_node_t *);
9717 if (h == NULL) {
9718 DT(ipf_rb_no_mem);
9719 LBUMP(ipf_rb_no_mem);
9720 return (-1);
9721 }
9722
9723 /*
9724 * If there was a macro to initialise the RB node then that
9725 * would get used here, but there isn't...
9726 */
9727 bzero((char *)h, sizeof(*h));
9728 h->hn_addr = k.hn_addr;
9729 h->hn_addr.adf_family = k.hn_addr.adf_family;
9730 RBI_INSERT(ipf_rb, &htp->ht_root, h);
9731 htp->ht_cur_nodes++;
9732 } else {
9733 if ((htp->ht_max_per_node != 0) &&
9734 (h->hn_active >= htp->ht_max_per_node)) {
9735 DT(ipf_rb_node_max);
9736 LBUMP(ipf_rb_node_max);
9737 return (-1);
9738 }
9739 }
9740
9741 h->hn_active++;
9742
9743 return (0);
9744 }
9745
9746
9747 /* ------------------------------------------------------------------------ */
9748 /* Function: ipf_ht_node_del */
9749 /* Returns: int - 0 == success, -1 == failure */
9750 /* parameters: htp(I) - pointer to address tracking structure */
9751 /* family(I) - protocol family of address */
9752 /* addr(I) - pointer to network address */
9753 /* */
9754 /* NOTE: THIS FUNCTION MUST BE CALLED WITH AN EXCLUSIVE LOCK THAT PREVENTS */
9755 /* ipf_ht_node_add FROM RUNNING CONCURRENTLY ON THE SAME htp. */
9756 /* */
9757 /* Try and find the address passed in amongst the leavese on this tree to */
9758 /* be friend. If found then drop the active account for that node drops by */
9759 /* one. If that count reaches 0, it is time to free it all up. */
9760 /* ------------------------------------------------------------------------ */
9761 int
9762 ipf_ht_node_del(host_track_t *htp, int family, i6addr_t *addr)
9763 {
9764 host_node_t *h;
9765 host_node_t k;
9766
9767 ipf_ht_node_make_key(htp, &k, family, addr);
9768
9769 h = RBI_SEARCH(ipf_rb, &htp->ht_root, &k);
9770 if (h == NULL) {
9771 return (-1);
9772 } else {
9773 h->hn_active--;
9774 if (h->hn_active == 0) {
9775 (void) RBI_DELETE(ipf_rb, &htp->ht_root, h);
9776 htp->ht_cur_nodes--;
9777 KFREE(h);
9778 }
9779 }
9780
9781 return (0);
9782 }
9783
9784
9785 /* ------------------------------------------------------------------------ */
9786 /* Function: ipf_rb_ht_init */
9787 /* Returns: Nil */
9788 /* Parameters: head(I) - pointer to host tracking structure */
9789 /* */
9790 /* Initialise the host tracking structure to be ready for use above. */
9791 /* ------------------------------------------------------------------------ */
9792 void
9793 ipf_rb_ht_init(host_track_t *head)
9794 {
9795 RBI_INIT(ipf_rb, &head->ht_root);
9796 }
9797
9798
9799 /* ------------------------------------------------------------------------ */
9800 /* Function: ipf_rb_ht_freenode */
9801 /* Returns: Nil */
9802 /* Parameters: head(I) - pointer to host tracking structure */
9803 /* arg(I) - additional argument from walk caller */
9804 /* */
9805 /* Free an actual host_node_t structure. */
9806 /* ------------------------------------------------------------------------ */
9807 void
9808 ipf_rb_ht_freenode(host_node_t *node, void *arg)
9809 {
9810 KFREE(node);
9811 }
9812
9813
9814 /* ------------------------------------------------------------------------ */
9815 /* Function: ipf_rb_ht_flush */
9816 /* Returns: Nil */
9817 /* Parameters: head(I) - pointer to host tracking structure */
9818 /* */
9819 /* Remove all of the nodes in the tree tracking hosts by calling a walker */
9820 /* and free'ing each one. */
9821 /* ------------------------------------------------------------------------ */
9822 void
9823 ipf_rb_ht_flush(host_track_t *head)
9824 {
9825 RBI_WALK(ipf_rb, &head->ht_root, ipf_rb_ht_freenode, NULL);
9826 }
9827
9828
9829 /* ------------------------------------------------------------------------ */
9830 /* Function: ipf_slowtimer */
9831 /* Returns: Nil */
9832 /* Parameters: ptr(I) - pointer to main ipf soft context structure */
9833 /* */
9834 /* Slowly expire held state for fragments. Timeouts are set * in */
9835 /* expectation of this being called twice per second. */
9836 /* ------------------------------------------------------------------------ */
9837 void
9838 ipf_slowtimer(ipf_main_softc_t *softc)
9839 {
9840
9841 ipf_token_expire(softc);
9842 ipf_frag_expire(softc);
9843 ipf_state_expire(softc);
9844 ipf_nat_expire(softc);
9845 ipf_auth_expire(softc);
9846 ipf_lookup_expire(softc);
9847 ipf_rule_expire(softc);
9848 ipf_sync_expire(softc);
9849 softc->ipf_ticks++;
9850 }
9851
9852
9853 /* ------------------------------------------------------------------------ */
9854 /* Function: ipf_inet_mask_add */
9855 /* Returns: Nil */
9856 /* Parameters: bits(I) - pointer to nat context information */
9857 /* mtab(I) - pointer to mask hash table structure */
9858 /* */
9859 /* When called, bits represents the mask of a new NAT rule that has just */
9860 /* been added. This function inserts a bitmask into the array of masks to */
9861 /* search when searching for a matching NAT rule for a packet. */
9862 /* Prevention of duplicate masks is achieved by checking the use count for */
9863 /* a given netmask. */
9864 /* ------------------------------------------------------------------------ */
9865 void
9866 ipf_inet_mask_add(int bits, ipf_v4_masktab_t *mtab)
9867 {
9868 u_32_t mask;
9869 int i, j;
9870
9871 mtab->imt4_masks[bits]++;
9872 if (mtab->imt4_masks[bits] > 1)
9873 return;
9874
9875 if (bits == 0)
9876 mask = 0;
9877 else
9878 mask = 0xffffffff << (32 - bits);
9879
9880 for (i = 0; i < 33; i++) {
9881 if (ntohl(mtab->imt4_active[i]) < mask) {
9882 for (j = 32; j > i; j--)
9883 mtab->imt4_active[j] = mtab->imt4_active[j - 1];
9884 mtab->imt4_active[i] = htonl(mask);
9885 break;
9886 }
9887 }
9888 mtab->imt4_max++;
9889 }
9890
9891
9892 /* ------------------------------------------------------------------------ */
9893 /* Function: ipf_inet_mask_del */
9894 /* Returns: Nil */
9895 /* Parameters: bits(I) - number of bits set in the netmask */
9896 /* mtab(I) - pointer to mask hash table structure */
9897 /* */
9898 /* Remove the 32bit bitmask represented by "bits" from the collection of */
9899 /* netmasks stored inside of mtab. */
9900 /* ------------------------------------------------------------------------ */
9901 void
9902 ipf_inet_mask_del(int bits, ipf_v4_masktab_t *mtab)
9903 {
9904 u_32_t mask;
9905 int i, j;
9906
9907 mtab->imt4_masks[bits]--;
9908 if (mtab->imt4_masks[bits] > 0)
9909 return;
9910
9911 mask = htonl(0xffffffff << (32 - bits));
9912 for (i = 0; i < 33; i++) {
9913 if (mtab->imt4_active[i] == mask) {
9914 for (j = i + 1; j < 33; j++)
9915 mtab->imt4_active[j - 1] = mtab->imt4_active[j];
9916 break;
9917 }
9918 }
9919 mtab->imt4_max--;
9920 ASSERT(mtab->imt4_max >= 0);
9921 }
9922
9923
9924 #ifdef USE_INET6
9925 /* ------------------------------------------------------------------------ */
9926 /* Function: ipf_inet6_mask_add */
9927 /* Returns: Nil */
9928 /* Parameters: bits(I) - number of bits set in mask */
9929 /* mask(I) - pointer to mask to add */
9930 /* mtab(I) - pointer to mask hash table structure */
9931 /* */
9932 /* When called, bitcount represents the mask of a IPv6 NAT map rule that */
9933 /* has just been added. This function inserts a bitmask into the array of */
9934 /* masks to search when searching for a matching NAT rule for a packet. */
9935 /* Prevention of duplicate masks is achieved by checking the use count for */
9936 /* a given netmask. */
9937 /* ------------------------------------------------------------------------ */
9938 void
9939 ipf_inet6_mask_add(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9940 {
9941 i6addr_t zero;
9942 int i, j;
9943
9944 mtab->imt6_masks[bits]++;
9945 if (mtab->imt6_masks[bits] > 1)
9946 return;
9947
9948 if (bits == 0) {
9949 mask = &zero;
9950 zero.i6[0] = 0;
9951 zero.i6[1] = 0;
9952 zero.i6[2] = 0;
9953 zero.i6[3] = 0;
9954 }
9955
9956 for (i = 0; i < 129; i++) {
9957 if (IP6_LT(&mtab->imt6_active[i], mask)) {
9958 for (j = 128; j > i; j--)
9959 mtab->imt6_active[j] = mtab->imt6_active[j - 1];
9960 mtab->imt6_active[i] = *mask;
9961 break;
9962 }
9963 }
9964 mtab->imt6_max++;
9965 }
9966
9967
9968 /* ------------------------------------------------------------------------ */
9969 /* Function: ipf_inet6_mask_del */
9970 /* Returns: Nil */
9971 /* Parameters: bits(I) - number of bits set in mask */
9972 /* mask(I) - pointer to mask to remove */
9973 /* mtab(I) - pointer to mask hash table structure */
9974 /* */
9975 /* Remove the 128bit bitmask represented by "bits" from the collection of */
9976 /* netmasks stored inside of mtab. */
9977 /* ------------------------------------------------------------------------ */
9978 void
9979 ipf_inet6_mask_del(int bits, i6addr_t *mask, ipf_v6_masktab_t *mtab)
9980 {
9981 i6addr_t zero;
9982 int i, j;
9983
9984 mtab->imt6_masks[bits]--;
9985 if (mtab->imt6_masks[bits] > 0)
9986 return;
9987
9988 if (bits == 0)
9989 mask = &zero;
9990 zero.i6[0] = 0;
9991 zero.i6[1] = 0;
9992 zero.i6[2] = 0;
9993 zero.i6[3] = 0;
9994
9995 for (i = 0; i < 129; i++) {
9996 if (IP6_EQ(&mtab->imt6_active[i], mask)) {
9997 for (j = i + 1; j < 129; j++) {
9998 mtab->imt6_active[j - 1] = mtab->imt6_active[j];
9999 if (IP6_EQ(&mtab->imt6_active[j - 1], &zero))
10000 break;
10001 }
10002 break;
10003 }
10004 }
10005 mtab->imt6_max--;
10006 ASSERT(mtab->imt6_max >= 0);
10007 }
10008 #endif
10009
10010 /* ------------------------------------------------------------------------ */
10011 /* Function: ipf_check_names_string */
10012 /* Returns: int - 0 == success */
10013 /* - 1 == negative offset */
10014 /* - 2 == offset exceds namelen */
10015 /* - 3 == string exceeds the names string */
10016 /* Parameters: names - pointer to names string */
10017 /* namelen - total length of names string */
10018 /* offset - offset into names string */
10019 /* */
10020 /* Validate the names string (fr_names for ipfilter, in_names for ipnat). */
10021 /* ------------------------------------------------------------------------ */
10022 int
10023 ipf_check_names_string(char *names, int namelen, int offset)
10024 {
10025 const char *name;
10026 size_t len;
10027
10028 if (offset == -1)
10029 return (0);
10030 if (offset < 0)
10031 return (1);
10032 if (offset > namelen)
10033 return (2);
10034 name = &names[offset];
10035 len = strnlen(name, namelen - offset);
10036 if (len == namelen - offset)
10037 return (3);
10038 return (0);
10039 }
10040