FreeBSD/Linux Kernel Cross Reference
sys/netinet/ip_fw2.c
1 /*-
2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #define DEB(x)
30 #define DDB(x) x
31
32 /*
33 * Implement IP packet firewall (new version)
34 */
35
36 #if !defined(KLD_MODULE)
37 #include "opt_ipfw.h"
38 #include "opt_ipdivert.h"
39 #include "opt_ipdn.h"
40 #include "opt_inet.h"
41 #ifndef INET
42 #error IPFIREWALL requires INET.
43 #endif /* INET */
44 #endif
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_mac.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/condvar.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
54 #include <sys/mbuf.h>
55 #include <sys/kernel.h>
56 #include <sys/lock.h>
57 #include <sys/jail.h>
58 #include <sys/module.h>
59 #include <sys/priv.h>
60 #include <sys/proc.h>
61 #include <sys/rwlock.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/ucred.h>
67 #include <net/if.h>
68 #include <net/radix.h>
69 #include <net/route.h>
70 #include <net/pf_mtag.h>
71
72 #define IPFW_INTERNAL /* Access to protected data structures in ip_fw.h. */
73
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/in_var.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_fw.h>
82 #include <netinet/ip_divert.h>
83 #include <netinet/ip_dummynet.h>
84 #include <netinet/ip_carp.h>
85 #include <netinet/pim.h>
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
89 #include <netinet/tcpip.h>
90 #include <netinet/udp.h>
91 #include <netinet/udp_var.h>
92 #include <netinet/sctp.h>
93 #include <netgraph/ng_ipfw.h>
94
95 #include <altq/if_altq.h>
96
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #ifdef INET6
100 #include <netinet6/scope6_var.h>
101 #endif
102
103 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
104
105 #include <machine/in_cksum.h> /* XXX for in_cksum */
106
107 #include <security/mac/mac_framework.h>
108
109 /*
110 * set_disable contains one bit per set value (0..31).
111 * If the bit is set, all rules with the corresponding set
112 * are disabled. Set RESVD_SET(31) is reserved for the default rule
113 * and rules that are not deleted by the flush command,
114 * and CANNOT be disabled.
115 * Rules in set RESVD_SET can only be deleted explicitly.
116 */
117 static u_int32_t set_disable;
118
119 static int fw_verbose;
120 static int verbose_limit;
121
122 static struct callout ipfw_timeout;
123 static uma_zone_t ipfw_dyn_rule_zone;
124
125 /*
126 * Data structure to cache our ucred related
127 * information. This structure only gets used if
128 * the user specified UID/GID based constraints in
129 * a firewall rule.
130 */
131 struct ip_fw_ugid {
132 gid_t fw_groups[NGROUPS];
133 int fw_ngroups;
134 uid_t fw_uid;
135 int fw_prid;
136 };
137
138 /*
139 * list of rules for layer 3
140 */
141 struct ip_fw_chain layer3_chain;
142
143 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
144 MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
145 #define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
146 ipfw_nat_t *ipfw_nat_ptr = NULL;
147 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
148 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
149 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
150 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
151
152 struct table_entry {
153 struct radix_node rn[2];
154 struct sockaddr_in addr, mask;
155 u_int32_t value;
156 };
157
158 static int fw_debug = 1;
159 static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
160
161 extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
162
163 #ifdef SYSCTL_NODE
164 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
165 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
166 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &fw_enable, 0,
167 ipfw_chg_hook, "I", "Enable ipfw");
168 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
169 &autoinc_step, 0, "Rule number autincrement step");
170 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
171 CTLFLAG_RW | CTLFLAG_SECURE3,
172 &fw_one_pass, 0,
173 "Only do a single pass through ipfw when using dummynet(4)");
174 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
175 &fw_debug, 0, "Enable printing of debug ip_fw statements");
176 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
177 CTLFLAG_RW | CTLFLAG_SECURE3,
178 &fw_verbose, 0, "Log matches to ipfw rules");
179 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
180 &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
181 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
182 NULL, IPFW_DEFAULT_RULE, "The default/max possible rule number.");
183
184 /*
185 * Description of dynamic rules.
186 *
187 * Dynamic rules are stored in lists accessed through a hash table
188 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
189 * be modified through the sysctl variable dyn_buckets which is
190 * updated when the table becomes empty.
191 *
192 * XXX currently there is only one list, ipfw_dyn.
193 *
194 * When a packet is received, its address fields are first masked
195 * with the mask defined for the rule, then hashed, then matched
196 * against the entries in the corresponding list.
197 * Dynamic rules can be used for different purposes:
198 * + stateful rules;
199 * + enforcing limits on the number of sessions;
200 * + in-kernel NAT (not implemented yet)
201 *
202 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
203 * measured in seconds and depending on the flags.
204 *
205 * The total number of dynamic rules is stored in dyn_count.
206 * The max number of dynamic rules is dyn_max. When we reach
207 * the maximum number of rules we do not create anymore. This is
208 * done to avoid consuming too much memory, but also too much
209 * time when searching on each packet (ideally, we should try instead
210 * to put a limit on the length of the list on each bucket...).
211 *
212 * Each dynamic rule holds a pointer to the parent ipfw rule so
213 * we know what action to perform. Dynamic rules are removed when
214 * the parent rule is deleted. XXX we should make them survive.
215 *
216 * There are some limitations with dynamic rules -- we do not
217 * obey the 'randomized match', and we do not do multiple
218 * passes through the firewall. XXX check the latter!!!
219 */
220 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
221 static u_int32_t dyn_buckets = 256; /* must be power of 2 */
222 static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
223
224 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
225 #define IPFW_DYN_LOCK_INIT() \
226 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
227 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
228 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
229 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
230 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
231
232 /*
233 * Timeouts for various events in handing dynamic rules.
234 */
235 static u_int32_t dyn_ack_lifetime = 300;
236 static u_int32_t dyn_syn_lifetime = 20;
237 static u_int32_t dyn_fin_lifetime = 1;
238 static u_int32_t dyn_rst_lifetime = 1;
239 static u_int32_t dyn_udp_lifetime = 10;
240 static u_int32_t dyn_short_lifetime = 5;
241
242 /*
243 * Keepalives are sent if dyn_keepalive is set. They are sent every
244 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
245 * seconds of lifetime of a rule.
246 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
247 * than dyn_keepalive_period.
248 */
249
250 static u_int32_t dyn_keepalive_interval = 20;
251 static u_int32_t dyn_keepalive_period = 5;
252 static u_int32_t dyn_keepalive = 1; /* do send keepalives */
253
254 static u_int32_t static_count; /* # of static rules */
255 static u_int32_t static_len; /* size in bytes of static rules */
256 static u_int32_t dyn_count; /* # of dynamic rules */
257 static u_int32_t dyn_max = 4096; /* max # of dynamic rules */
258
259 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
260 &dyn_buckets, 0, "Number of dyn. buckets");
261 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
262 &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
263 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
264 &dyn_count, 0, "Number of dyn. rules");
265 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
266 &dyn_max, 0, "Max number of dyn. rules");
267 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
268 &static_count, 0, "Number of static rules");
269 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
270 &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
271 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
272 &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
273 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
274 &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
275 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
276 &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
277 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
278 &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
279 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
280 &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
281 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
282 &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
283
284 #ifdef INET6
285 /*
286 * IPv6 specific variables
287 */
288 SYSCTL_DECL(_net_inet6_ip6);
289
290 static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
291 static struct sysctl_oid *ip6_fw_sysctl_tree;
292 #endif /* INET6 */
293 #endif /* SYSCTL_NODE */
294
295 static int fw_deny_unknown_exthdrs = 1;
296
297
298 /*
299 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
300 * Other macros just cast void * into the appropriate type
301 */
302 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
303 #define TCP(p) ((struct tcphdr *)(p))
304 #define SCTP(p) ((struct sctphdr *)(p))
305 #define UDP(p) ((struct udphdr *)(p))
306 #define ICMP(p) ((struct icmphdr *)(p))
307 #define ICMP6(p) ((struct icmp6_hdr *)(p))
308
309 static __inline int
310 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
311 {
312 int type = icmp->icmp_type;
313
314 return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
315 }
316
317 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
318 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
319
320 static int
321 is_icmp_query(struct icmphdr *icmp)
322 {
323 int type = icmp->icmp_type;
324
325 return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
326 }
327 #undef TT
328
329 /*
330 * The following checks use two arrays of 8 or 16 bits to store the
331 * bits that we want set or clear, respectively. They are in the
332 * low and high half of cmd->arg1 or cmd->d[0].
333 *
334 * We scan options and store the bits we find set. We succeed if
335 *
336 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
337 *
338 * The code is sometimes optimized not to store additional variables.
339 */
340
341 static int
342 flags_match(ipfw_insn *cmd, u_int8_t bits)
343 {
344 u_char want_clear;
345 bits = ~bits;
346
347 if ( ((cmd->arg1 & 0xff) & bits) != 0)
348 return 0; /* some bits we want set were clear */
349 want_clear = (cmd->arg1 >> 8) & 0xff;
350 if ( (want_clear & bits) != want_clear)
351 return 0; /* some bits we want clear were set */
352 return 1;
353 }
354
355 static int
356 ipopts_match(struct ip *ip, ipfw_insn *cmd)
357 {
358 int optlen, bits = 0;
359 u_char *cp = (u_char *)(ip + 1);
360 int x = (ip->ip_hl << 2) - sizeof (struct ip);
361
362 for (; x > 0; x -= optlen, cp += optlen) {
363 int opt = cp[IPOPT_OPTVAL];
364
365 if (opt == IPOPT_EOL)
366 break;
367 if (opt == IPOPT_NOP)
368 optlen = 1;
369 else {
370 optlen = cp[IPOPT_OLEN];
371 if (optlen <= 0 || optlen > x)
372 return 0; /* invalid or truncated */
373 }
374 switch (opt) {
375
376 default:
377 break;
378
379 case IPOPT_LSRR:
380 bits |= IP_FW_IPOPT_LSRR;
381 break;
382
383 case IPOPT_SSRR:
384 bits |= IP_FW_IPOPT_SSRR;
385 break;
386
387 case IPOPT_RR:
388 bits |= IP_FW_IPOPT_RR;
389 break;
390
391 case IPOPT_TS:
392 bits |= IP_FW_IPOPT_TS;
393 break;
394 }
395 }
396 return (flags_match(cmd, bits));
397 }
398
399 static int
400 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
401 {
402 int optlen, bits = 0;
403 u_char *cp = (u_char *)(tcp + 1);
404 int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
405
406 for (; x > 0; x -= optlen, cp += optlen) {
407 int opt = cp[0];
408 if (opt == TCPOPT_EOL)
409 break;
410 if (opt == TCPOPT_NOP)
411 optlen = 1;
412 else {
413 optlen = cp[1];
414 if (optlen <= 0)
415 break;
416 }
417
418 switch (opt) {
419
420 default:
421 break;
422
423 case TCPOPT_MAXSEG:
424 bits |= IP_FW_TCPOPT_MSS;
425 break;
426
427 case TCPOPT_WINDOW:
428 bits |= IP_FW_TCPOPT_WINDOW;
429 break;
430
431 case TCPOPT_SACK_PERMITTED:
432 case TCPOPT_SACK:
433 bits |= IP_FW_TCPOPT_SACK;
434 break;
435
436 case TCPOPT_TIMESTAMP:
437 bits |= IP_FW_TCPOPT_TS;
438 break;
439
440 }
441 }
442 return (flags_match(cmd, bits));
443 }
444
445 static int
446 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
447 {
448 if (ifp == NULL) /* no iface with this packet, match fails */
449 return 0;
450 /* Check by name or by IP address */
451 if (cmd->name[0] != '\0') { /* match by name */
452 /* Check name */
453 if (cmd->p.glob) {
454 if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
455 return(1);
456 } else {
457 if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
458 return(1);
459 }
460 } else {
461 struct ifaddr *ia;
462
463 /* XXX lock? */
464 TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
465 if (ia->ifa_addr->sa_family != AF_INET)
466 continue;
467 if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
468 (ia->ifa_addr))->sin_addr.s_addr)
469 return(1); /* match */
470 }
471 }
472 return(0); /* no match, fail ... */
473 }
474
475 /*
476 * The verify_path function checks if a route to the src exists and
477 * if it is reachable via ifp (when provided).
478 *
479 * The 'verrevpath' option checks that the interface that an IP packet
480 * arrives on is the same interface that traffic destined for the
481 * packet's source address would be routed out of. The 'versrcreach'
482 * option just checks that the source address is reachable via any route
483 * (except default) in the routing table. These two are a measure to block
484 * forged packets. This is also commonly known as "anti-spoofing" or Unicast
485 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
486 * is purposely reminiscent of the Cisco IOS command,
487 *
488 * ip verify unicast reverse-path
489 * ip verify unicast source reachable-via any
490 *
491 * which implements the same functionality. But note that syntax is
492 * misleading. The check may be performed on all IP packets whether unicast,
493 * multicast, or broadcast.
494 */
495 static int
496 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
497 {
498 struct route ro;
499 struct sockaddr_in *dst;
500
501 bzero(&ro, sizeof(ro));
502
503 dst = (struct sockaddr_in *)&(ro.ro_dst);
504 dst->sin_family = AF_INET;
505 dst->sin_len = sizeof(*dst);
506 dst->sin_addr = src;
507 in_rtalloc_ign(&ro, RTF_CLONING, fib);
508
509 if (ro.ro_rt == NULL)
510 return 0;
511
512 /*
513 * If ifp is provided, check for equality with rtentry.
514 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
515 * in order to pass packets injected back by if_simloop():
516 * if useloopback == 1 routing entry (via lo0) for our own address
517 * may exist, so we need to handle routing assymetry.
518 */
519 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
520 RTFREE(ro.ro_rt);
521 return 0;
522 }
523
524 /* if no ifp provided, check if rtentry is not default route */
525 if (ifp == NULL &&
526 satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
527 RTFREE(ro.ro_rt);
528 return 0;
529 }
530
531 /* or if this is a blackhole/reject route */
532 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
533 RTFREE(ro.ro_rt);
534 return 0;
535 }
536
537 /* found valid route */
538 RTFREE(ro.ro_rt);
539 return 1;
540 }
541
542 #ifdef INET6
543 /*
544 * ipv6 specific rules here...
545 */
546 static __inline int
547 icmp6type_match (int type, ipfw_insn_u32 *cmd)
548 {
549 return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
550 }
551
552 static int
553 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
554 {
555 int i;
556 for (i=0; i <= cmd->o.arg1; ++i )
557 if (curr_flow == cmd->d[i] )
558 return 1;
559 return 0;
560 }
561
562 /* support for IP6_*_ME opcodes */
563 static int
564 search_ip6_addr_net (struct in6_addr * ip6_addr)
565 {
566 struct ifnet *mdc;
567 struct ifaddr *mdc2;
568 struct in6_ifaddr *fdm;
569 struct in6_addr copia;
570
571 TAILQ_FOREACH(mdc, &ifnet, if_link)
572 TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
573 if (mdc2->ifa_addr->sa_family == AF_INET6) {
574 fdm = (struct in6_ifaddr *)mdc2;
575 copia = fdm->ia_addr.sin6_addr;
576 /* need for leaving scope_id in the sock_addr */
577 in6_clearscope(&copia);
578 if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
579 return 1;
580 }
581 }
582 return 0;
583 }
584
585 static int
586 verify_path6(struct in6_addr *src, struct ifnet *ifp)
587 {
588 struct route_in6 ro;
589 struct sockaddr_in6 *dst;
590
591 bzero(&ro, sizeof(ro));
592
593 dst = (struct sockaddr_in6 * )&(ro.ro_dst);
594 dst->sin6_family = AF_INET6;
595 dst->sin6_len = sizeof(*dst);
596 dst->sin6_addr = *src;
597 /* XXX MRT 0 for ipv6 at this time */
598 rtalloc_ign((struct route *)&ro, RTF_CLONING);
599
600 if (ro.ro_rt == NULL)
601 return 0;
602
603 /*
604 * if ifp is provided, check for equality with rtentry
605 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
606 * to support the case of sending packets to an address of our own.
607 * (where the former interface is the first argument of if_simloop()
608 * (=ifp), the latter is lo0)
609 */
610 if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
611 RTFREE(ro.ro_rt);
612 return 0;
613 }
614
615 /* if no ifp provided, check if rtentry is not default route */
616 if (ifp == NULL &&
617 IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
618 RTFREE(ro.ro_rt);
619 return 0;
620 }
621
622 /* or if this is a blackhole/reject route */
623 if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
624 RTFREE(ro.ro_rt);
625 return 0;
626 }
627
628 /* found valid route */
629 RTFREE(ro.ro_rt);
630 return 1;
631
632 }
633 static __inline int
634 hash_packet6(struct ipfw_flow_id *id)
635 {
636 u_int32_t i;
637 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
638 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
639 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
640 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
641 (id->dst_port) ^ (id->src_port);
642 return i;
643 }
644
645 static int
646 is_icmp6_query(int icmp6_type)
647 {
648 if ((icmp6_type <= ICMP6_MAXTYPE) &&
649 (icmp6_type == ICMP6_ECHO_REQUEST ||
650 icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
651 icmp6_type == ICMP6_WRUREQUEST ||
652 icmp6_type == ICMP6_FQDN_QUERY ||
653 icmp6_type == ICMP6_NI_QUERY))
654 return (1);
655
656 return (0);
657 }
658
659 static void
660 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
661 {
662 struct mbuf *m;
663
664 m = args->m;
665 if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
666 struct tcphdr *tcp;
667 tcp_seq ack, seq;
668 int flags;
669 struct {
670 struct ip6_hdr ip6;
671 struct tcphdr th;
672 } ti;
673 tcp = (struct tcphdr *)((char *)ip6 + hlen);
674
675 if ((tcp->th_flags & TH_RST) != 0) {
676 m_freem(m);
677 args->m = NULL;
678 return;
679 }
680
681 ti.ip6 = *ip6;
682 ti.th = *tcp;
683 ti.th.th_seq = ntohl(ti.th.th_seq);
684 ti.th.th_ack = ntohl(ti.th.th_ack);
685 ti.ip6.ip6_nxt = IPPROTO_TCP;
686
687 if (ti.th.th_flags & TH_ACK) {
688 ack = 0;
689 seq = ti.th.th_ack;
690 flags = TH_RST;
691 } else {
692 ack = ti.th.th_seq;
693 if ((m->m_flags & M_PKTHDR) != 0) {
694 /*
695 * total new data to ACK is:
696 * total packet length,
697 * minus the header length,
698 * minus the tcp header length.
699 */
700 ack += m->m_pkthdr.len - hlen
701 - (ti.th.th_off << 2);
702 } else if (ip6->ip6_plen) {
703 ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
704 hlen - (ti.th.th_off << 2);
705 } else {
706 m_freem(m);
707 return;
708 }
709 if (tcp->th_flags & TH_SYN)
710 ack++;
711 seq = 0;
712 flags = TH_RST|TH_ACK;
713 }
714 bcopy(&ti, ip6, sizeof(ti));
715 /*
716 * m is only used to recycle the mbuf
717 * The data in it is never read so we don't need
718 * to correct the offsets or anything
719 */
720 tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
721 } else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
722 #if 0
723 /*
724 * Unlike above, the mbufs need to line up with the ip6 hdr,
725 * as the contents are read. We need to m_adj() the
726 * needed amount.
727 * The mbuf will however be thrown away so we can adjust it.
728 * Remember we did an m_pullup on it already so we
729 * can make some assumptions about contiguousness.
730 */
731 if (args->L3offset)
732 m_adj(m, args->L3offset);
733 #endif
734 icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
735 } else
736 m_freem(m);
737
738 args->m = NULL;
739 }
740
741 #endif /* INET6 */
742
743 static u_int64_t norule_counter; /* counter for ipfw_log(NULL...) */
744
745 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
746 #define SNP(buf) buf, sizeof(buf)
747
748 /*
749 * We enter here when we have a rule with O_LOG.
750 * XXX this function alone takes about 2Kbytes of code!
751 */
752 static void
753 ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
754 struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
755 struct ip *ip)
756 {
757 struct ether_header *eh = args->eh;
758 char *action;
759 int limit_reached = 0;
760 char action2[40], proto[128], fragment[32];
761
762 fragment[0] = '\0';
763 proto[0] = '\0';
764
765 if (f == NULL) { /* bogus pkt */
766 if (verbose_limit != 0 && norule_counter >= verbose_limit)
767 return;
768 norule_counter++;
769 if (norule_counter == verbose_limit)
770 limit_reached = verbose_limit;
771 action = "Refuse";
772 } else { /* O_LOG is the first action, find the real one */
773 ipfw_insn *cmd = ACTION_PTR(f);
774 ipfw_insn_log *l = (ipfw_insn_log *)cmd;
775
776 if (l->max_log != 0 && l->log_left == 0)
777 return;
778 l->log_left--;
779 if (l->log_left == 0)
780 limit_reached = l->max_log;
781 cmd += F_LEN(cmd); /* point to first action */
782 if (cmd->opcode == O_ALTQ) {
783 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
784
785 snprintf(SNPARGS(action2, 0), "Altq %d",
786 altq->qid);
787 cmd += F_LEN(cmd);
788 }
789 if (cmd->opcode == O_PROB)
790 cmd += F_LEN(cmd);
791
792 if (cmd->opcode == O_TAG)
793 cmd += F_LEN(cmd);
794
795 action = action2;
796 switch (cmd->opcode) {
797 case O_DENY:
798 action = "Deny";
799 break;
800
801 case O_REJECT:
802 if (cmd->arg1==ICMP_REJECT_RST)
803 action = "Reset";
804 else if (cmd->arg1==ICMP_UNREACH_HOST)
805 action = "Reject";
806 else
807 snprintf(SNPARGS(action2, 0), "Unreach %d",
808 cmd->arg1);
809 break;
810
811 case O_UNREACH6:
812 if (cmd->arg1==ICMP6_UNREACH_RST)
813 action = "Reset";
814 else
815 snprintf(SNPARGS(action2, 0), "Unreach %d",
816 cmd->arg1);
817 break;
818
819 case O_ACCEPT:
820 action = "Accept";
821 break;
822 case O_COUNT:
823 action = "Count";
824 break;
825 case O_DIVERT:
826 snprintf(SNPARGS(action2, 0), "Divert %d",
827 cmd->arg1);
828 break;
829 case O_TEE:
830 snprintf(SNPARGS(action2, 0), "Tee %d",
831 cmd->arg1);
832 break;
833 case O_SETFIB:
834 snprintf(SNPARGS(action2, 0), "SetFib %d",
835 cmd->arg1);
836 break;
837 case O_SKIPTO:
838 snprintf(SNPARGS(action2, 0), "SkipTo %d",
839 cmd->arg1);
840 break;
841 case O_PIPE:
842 snprintf(SNPARGS(action2, 0), "Pipe %d",
843 cmd->arg1);
844 break;
845 case O_QUEUE:
846 snprintf(SNPARGS(action2, 0), "Queue %d",
847 cmd->arg1);
848 break;
849 case O_FORWARD_IP: {
850 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
851 int len;
852 struct in_addr dummyaddr;
853 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
854 dummyaddr.s_addr = htonl(tablearg);
855 else
856 dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
857
858 len = snprintf(SNPARGS(action2, 0), "Forward to %s",
859 inet_ntoa(dummyaddr));
860
861 if (sa->sa.sin_port)
862 snprintf(SNPARGS(action2, len), ":%d",
863 sa->sa.sin_port);
864 }
865 break;
866 case O_NETGRAPH:
867 snprintf(SNPARGS(action2, 0), "Netgraph %d",
868 cmd->arg1);
869 break;
870 case O_NGTEE:
871 snprintf(SNPARGS(action2, 0), "Ngtee %d",
872 cmd->arg1);
873 break;
874 case O_NAT:
875 action = "Nat";
876 break;
877 default:
878 action = "UNKNOWN";
879 break;
880 }
881 }
882
883 if (hlen == 0) { /* non-ip */
884 snprintf(SNPARGS(proto, 0), "MAC");
885
886 } else {
887 int len;
888 char src[48], dst[48];
889 struct icmphdr *icmp;
890 struct tcphdr *tcp;
891 struct udphdr *udp;
892 #ifdef INET6
893 struct ip6_hdr *ip6 = NULL;
894 struct icmp6_hdr *icmp6;
895 #endif
896 src[0] = '\0';
897 dst[0] = '\0';
898 #ifdef INET6
899 if (IS_IP6_FLOW_ID(&(args->f_id))) {
900 char ip6buf[INET6_ADDRSTRLEN];
901 snprintf(src, sizeof(src), "[%s]",
902 ip6_sprintf(ip6buf, &args->f_id.src_ip6));
903 snprintf(dst, sizeof(dst), "[%s]",
904 ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
905
906 ip6 = (struct ip6_hdr *)ip;
907 tcp = (struct tcphdr *)(((char *)ip) + hlen);
908 udp = (struct udphdr *)(((char *)ip) + hlen);
909 } else
910 #endif
911 {
912 tcp = L3HDR(struct tcphdr, ip);
913 udp = L3HDR(struct udphdr, ip);
914
915 inet_ntoa_r(ip->ip_src, src);
916 inet_ntoa_r(ip->ip_dst, dst);
917 }
918
919 switch (args->f_id.proto) {
920 case IPPROTO_TCP:
921 len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
922 if (offset == 0)
923 snprintf(SNPARGS(proto, len), ":%d %s:%d",
924 ntohs(tcp->th_sport),
925 dst,
926 ntohs(tcp->th_dport));
927 else
928 snprintf(SNPARGS(proto, len), " %s", dst);
929 break;
930
931 case IPPROTO_UDP:
932 len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
933 if (offset == 0)
934 snprintf(SNPARGS(proto, len), ":%d %s:%d",
935 ntohs(udp->uh_sport),
936 dst,
937 ntohs(udp->uh_dport));
938 else
939 snprintf(SNPARGS(proto, len), " %s", dst);
940 break;
941
942 case IPPROTO_ICMP:
943 icmp = L3HDR(struct icmphdr, ip);
944 if (offset == 0)
945 len = snprintf(SNPARGS(proto, 0),
946 "ICMP:%u.%u ",
947 icmp->icmp_type, icmp->icmp_code);
948 else
949 len = snprintf(SNPARGS(proto, 0), "ICMP ");
950 len += snprintf(SNPARGS(proto, len), "%s", src);
951 snprintf(SNPARGS(proto, len), " %s", dst);
952 break;
953 #ifdef INET6
954 case IPPROTO_ICMPV6:
955 icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
956 if (offset == 0)
957 len = snprintf(SNPARGS(proto, 0),
958 "ICMPv6:%u.%u ",
959 icmp6->icmp6_type, icmp6->icmp6_code);
960 else
961 len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
962 len += snprintf(SNPARGS(proto, len), "%s", src);
963 snprintf(SNPARGS(proto, len), " %s", dst);
964 break;
965 #endif
966 default:
967 len = snprintf(SNPARGS(proto, 0), "P:%d %s",
968 args->f_id.proto, src);
969 snprintf(SNPARGS(proto, len), " %s", dst);
970 break;
971 }
972
973 #ifdef INET6
974 if (IS_IP6_FLOW_ID(&(args->f_id))) {
975 if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
976 snprintf(SNPARGS(fragment, 0),
977 " (frag %08x:%d@%d%s)",
978 args->f_id.frag_id6,
979 ntohs(ip6->ip6_plen) - hlen,
980 ntohs(offset & IP6F_OFF_MASK) << 3,
981 (offset & IP6F_MORE_FRAG) ? "+" : "");
982 } else
983 #endif
984 {
985 int ip_off, ip_len;
986 if (eh != NULL) { /* layer 2 packets are as on the wire */
987 ip_off = ntohs(ip->ip_off);
988 ip_len = ntohs(ip->ip_len);
989 } else {
990 ip_off = ip->ip_off;
991 ip_len = ip->ip_len;
992 }
993 if (ip_off & (IP_MF | IP_OFFMASK))
994 snprintf(SNPARGS(fragment, 0),
995 " (frag %d:%d@%d%s)",
996 ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
997 offset << 3,
998 (ip_off & IP_MF) ? "+" : "");
999 }
1000 }
1001 if (oif || m->m_pkthdr.rcvif)
1002 log(LOG_SECURITY | LOG_INFO,
1003 "ipfw: %d %s %s %s via %s%s\n",
1004 f ? f->rulenum : -1,
1005 action, proto, oif ? "out" : "in",
1006 oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1007 fragment);
1008 else
1009 log(LOG_SECURITY | LOG_INFO,
1010 "ipfw: %d %s %s [no if info]%s\n",
1011 f ? f->rulenum : -1,
1012 action, proto, fragment);
1013 if (limit_reached)
1014 log(LOG_SECURITY | LOG_NOTICE,
1015 "ipfw: limit %d reached on entry %d\n",
1016 limit_reached, f ? f->rulenum : -1);
1017 }
1018
1019 /*
1020 * IMPORTANT: the hash function for dynamic rules must be commutative
1021 * in source and destination (ip,port), because rules are bidirectional
1022 * and we want to find both in the same bucket.
1023 */
1024 static __inline int
1025 hash_packet(struct ipfw_flow_id *id)
1026 {
1027 u_int32_t i;
1028
1029 #ifdef INET6
1030 if (IS_IP6_FLOW_ID(id))
1031 i = hash_packet6(id);
1032 else
1033 #endif /* INET6 */
1034 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1035 i &= (curr_dyn_buckets - 1);
1036 return i;
1037 }
1038
1039 /**
1040 * unlink a dynamic rule from a chain. prev is a pointer to
1041 * the previous one, q is a pointer to the rule to delete,
1042 * head is a pointer to the head of the queue.
1043 * Modifies q and potentially also head.
1044 */
1045 #define UNLINK_DYN_RULE(prev, head, q) { \
1046 ipfw_dyn_rule *old_q = q; \
1047 \
1048 /* remove a refcount to the parent */ \
1049 if (q->dyn_type == O_LIMIT) \
1050 q->parent->count--; \
1051 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1052 (q->id.src_ip), (q->id.src_port), \
1053 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1054 if (prev != NULL) \
1055 prev->next = q = q->next; \
1056 else \
1057 head = q = q->next; \
1058 dyn_count--; \
1059 uma_zfree(ipfw_dyn_rule_zone, old_q); }
1060
1061 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1062
1063 /**
1064 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1065 *
1066 * If keep_me == NULL, rules are deleted even if not expired,
1067 * otherwise only expired rules are removed.
1068 *
1069 * The value of the second parameter is also used to point to identify
1070 * a rule we absolutely do not want to remove (e.g. because we are
1071 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1072 * rules). The pointer is only used for comparison, so any non-null
1073 * value will do.
1074 */
1075 static void
1076 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1077 {
1078 static u_int32_t last_remove = 0;
1079
1080 #define FORCE (keep_me == NULL)
1081
1082 ipfw_dyn_rule *prev, *q;
1083 int i, pass = 0, max_pass = 0;
1084
1085 IPFW_DYN_LOCK_ASSERT();
1086
1087 if (ipfw_dyn_v == NULL || dyn_count == 0)
1088 return;
1089 /* do not expire more than once per second, it is useless */
1090 if (!FORCE && last_remove == time_uptime)
1091 return;
1092 last_remove = time_uptime;
1093
1094 /*
1095 * because O_LIMIT refer to parent rules, during the first pass only
1096 * remove child and mark any pending LIMIT_PARENT, and remove
1097 * them in a second pass.
1098 */
1099 next_pass:
1100 for (i = 0 ; i < curr_dyn_buckets ; i++) {
1101 for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1102 /*
1103 * Logic can become complex here, so we split tests.
1104 */
1105 if (q == keep_me)
1106 goto next;
1107 if (rule != NULL && rule != q->rule)
1108 goto next; /* not the one we are looking for */
1109 if (q->dyn_type == O_LIMIT_PARENT) {
1110 /*
1111 * handle parent in the second pass,
1112 * record we need one.
1113 */
1114 max_pass = 1;
1115 if (pass == 0)
1116 goto next;
1117 if (FORCE && q->count != 0 ) {
1118 /* XXX should not happen! */
1119 printf("ipfw: OUCH! cannot remove rule,"
1120 " count %d\n", q->count);
1121 }
1122 } else {
1123 if (!FORCE &&
1124 !TIME_LEQ( q->expire, time_uptime ))
1125 goto next;
1126 }
1127 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1128 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1129 continue;
1130 }
1131 next:
1132 prev=q;
1133 q=q->next;
1134 }
1135 }
1136 if (pass++ < max_pass)
1137 goto next_pass;
1138 }
1139
1140
1141 /**
1142 * lookup a dynamic rule.
1143 */
1144 static ipfw_dyn_rule *
1145 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1146 struct tcphdr *tcp)
1147 {
1148 /*
1149 * stateful ipfw extensions.
1150 * Lookup into dynamic session queue
1151 */
1152 #define MATCH_REVERSE 0
1153 #define MATCH_FORWARD 1
1154 #define MATCH_NONE 2
1155 #define MATCH_UNKNOWN 3
1156 int i, dir = MATCH_NONE;
1157 ipfw_dyn_rule *prev, *q=NULL;
1158
1159 IPFW_DYN_LOCK_ASSERT();
1160
1161 if (ipfw_dyn_v == NULL)
1162 goto done; /* not found */
1163 i = hash_packet( pkt );
1164 for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1165 if (q->dyn_type == O_LIMIT_PARENT && q->count)
1166 goto next;
1167 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1168 UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1169 continue;
1170 }
1171 if (pkt->proto == q->id.proto &&
1172 q->dyn_type != O_LIMIT_PARENT) {
1173 if (IS_IP6_FLOW_ID(pkt)) {
1174 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1175 &(q->id.src_ip6)) &&
1176 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1177 &(q->id.dst_ip6)) &&
1178 pkt->src_port == q->id.src_port &&
1179 pkt->dst_port == q->id.dst_port ) {
1180 dir = MATCH_FORWARD;
1181 break;
1182 }
1183 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1184 &(q->id.dst_ip6)) &&
1185 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1186 &(q->id.src_ip6)) &&
1187 pkt->src_port == q->id.dst_port &&
1188 pkt->dst_port == q->id.src_port ) {
1189 dir = MATCH_REVERSE;
1190 break;
1191 }
1192 } else {
1193 if (pkt->src_ip == q->id.src_ip &&
1194 pkt->dst_ip == q->id.dst_ip &&
1195 pkt->src_port == q->id.src_port &&
1196 pkt->dst_port == q->id.dst_port ) {
1197 dir = MATCH_FORWARD;
1198 break;
1199 }
1200 if (pkt->src_ip == q->id.dst_ip &&
1201 pkt->dst_ip == q->id.src_ip &&
1202 pkt->src_port == q->id.dst_port &&
1203 pkt->dst_port == q->id.src_port ) {
1204 dir = MATCH_REVERSE;
1205 break;
1206 }
1207 }
1208 }
1209 next:
1210 prev = q;
1211 q = q->next;
1212 }
1213 if (q == NULL)
1214 goto done; /* q = NULL, not found */
1215
1216 if ( prev != NULL) { /* found and not in front */
1217 prev->next = q->next;
1218 q->next = ipfw_dyn_v[i];
1219 ipfw_dyn_v[i] = q;
1220 }
1221 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1222 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1223
1224 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1225 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1226 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1227 switch (q->state) {
1228 case TH_SYN: /* opening */
1229 q->expire = time_uptime + dyn_syn_lifetime;
1230 break;
1231
1232 case BOTH_SYN: /* move to established */
1233 case BOTH_SYN | TH_FIN : /* one side tries to close */
1234 case BOTH_SYN | (TH_FIN << 8) :
1235 if (tcp) {
1236 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1237 u_int32_t ack = ntohl(tcp->th_ack);
1238 if (dir == MATCH_FORWARD) {
1239 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1240 q->ack_fwd = ack;
1241 else { /* ignore out-of-sequence */
1242 break;
1243 }
1244 } else {
1245 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1246 q->ack_rev = ack;
1247 else { /* ignore out-of-sequence */
1248 break;
1249 }
1250 }
1251 }
1252 q->expire = time_uptime + dyn_ack_lifetime;
1253 break;
1254
1255 case BOTH_SYN | BOTH_FIN: /* both sides closed */
1256 if (dyn_fin_lifetime >= dyn_keepalive_period)
1257 dyn_fin_lifetime = dyn_keepalive_period - 1;
1258 q->expire = time_uptime + dyn_fin_lifetime;
1259 break;
1260
1261 default:
1262 #if 0
1263 /*
1264 * reset or some invalid combination, but can also
1265 * occur if we use keep-state the wrong way.
1266 */
1267 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1268 printf("invalid state: 0x%x\n", q->state);
1269 #endif
1270 if (dyn_rst_lifetime >= dyn_keepalive_period)
1271 dyn_rst_lifetime = dyn_keepalive_period - 1;
1272 q->expire = time_uptime + dyn_rst_lifetime;
1273 break;
1274 }
1275 } else if (pkt->proto == IPPROTO_UDP) {
1276 q->expire = time_uptime + dyn_udp_lifetime;
1277 } else {
1278 /* other protocols */
1279 q->expire = time_uptime + dyn_short_lifetime;
1280 }
1281 done:
1282 if (match_direction)
1283 *match_direction = dir;
1284 return q;
1285 }
1286
1287 static ipfw_dyn_rule *
1288 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1289 struct tcphdr *tcp)
1290 {
1291 ipfw_dyn_rule *q;
1292
1293 IPFW_DYN_LOCK();
1294 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1295 if (q == NULL)
1296 IPFW_DYN_UNLOCK();
1297 /* NB: return table locked when q is not NULL */
1298 return q;
1299 }
1300
1301 static void
1302 realloc_dynamic_table(void)
1303 {
1304 IPFW_DYN_LOCK_ASSERT();
1305
1306 /*
1307 * Try reallocation, make sure we have a power of 2 and do
1308 * not allow more than 64k entries. In case of overflow,
1309 * default to 1024.
1310 */
1311
1312 if (dyn_buckets > 65536)
1313 dyn_buckets = 1024;
1314 if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1315 dyn_buckets = curr_dyn_buckets; /* reset */
1316 return;
1317 }
1318 curr_dyn_buckets = dyn_buckets;
1319 if (ipfw_dyn_v != NULL)
1320 free(ipfw_dyn_v, M_IPFW);
1321 for (;;) {
1322 ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1323 M_IPFW, M_NOWAIT | M_ZERO);
1324 if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1325 break;
1326 curr_dyn_buckets /= 2;
1327 }
1328 }
1329
1330 /**
1331 * Install state of type 'type' for a dynamic session.
1332 * The hash table contains two type of rules:
1333 * - regular rules (O_KEEP_STATE)
1334 * - rules for sessions with limited number of sess per user
1335 * (O_LIMIT). When they are created, the parent is
1336 * increased by 1, and decreased on delete. In this case,
1337 * the third parameter is the parent rule and not the chain.
1338 * - "parent" rules for the above (O_LIMIT_PARENT).
1339 */
1340 static ipfw_dyn_rule *
1341 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1342 {
1343 ipfw_dyn_rule *r;
1344 int i;
1345
1346 IPFW_DYN_LOCK_ASSERT();
1347
1348 if (ipfw_dyn_v == NULL ||
1349 (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1350 realloc_dynamic_table();
1351 if (ipfw_dyn_v == NULL)
1352 return NULL; /* failed ! */
1353 }
1354 i = hash_packet(id);
1355
1356 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1357 if (r == NULL) {
1358 printf ("ipfw: sorry cannot allocate state\n");
1359 return NULL;
1360 }
1361
1362 /* increase refcount on parent, and set pointer */
1363 if (dyn_type == O_LIMIT) {
1364 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1365 if ( parent->dyn_type != O_LIMIT_PARENT)
1366 panic("invalid parent");
1367 parent->count++;
1368 r->parent = parent;
1369 rule = parent->rule;
1370 }
1371
1372 r->id = *id;
1373 r->expire = time_uptime + dyn_syn_lifetime;
1374 r->rule = rule;
1375 r->dyn_type = dyn_type;
1376 r->pcnt = r->bcnt = 0;
1377 r->count = 0;
1378
1379 r->bucket = i;
1380 r->next = ipfw_dyn_v[i];
1381 ipfw_dyn_v[i] = r;
1382 dyn_count++;
1383 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1384 dyn_type,
1385 (r->id.src_ip), (r->id.src_port),
1386 (r->id.dst_ip), (r->id.dst_port),
1387 dyn_count ); )
1388 return r;
1389 }
1390
1391 /**
1392 * lookup dynamic parent rule using pkt and rule as search keys.
1393 * If the lookup fails, then install one.
1394 */
1395 static ipfw_dyn_rule *
1396 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1397 {
1398 ipfw_dyn_rule *q;
1399 int i;
1400
1401 IPFW_DYN_LOCK_ASSERT();
1402
1403 if (ipfw_dyn_v) {
1404 int is_v6 = IS_IP6_FLOW_ID(pkt);
1405 i = hash_packet( pkt );
1406 for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1407 if (q->dyn_type == O_LIMIT_PARENT &&
1408 rule== q->rule &&
1409 pkt->proto == q->id.proto &&
1410 pkt->src_port == q->id.src_port &&
1411 pkt->dst_port == q->id.dst_port &&
1412 (
1413 (is_v6 &&
1414 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1415 &(q->id.src_ip6)) &&
1416 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1417 &(q->id.dst_ip6))) ||
1418 (!is_v6 &&
1419 pkt->src_ip == q->id.src_ip &&
1420 pkt->dst_ip == q->id.dst_ip)
1421 )
1422 ) {
1423 q->expire = time_uptime + dyn_short_lifetime;
1424 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1425 return q;
1426 }
1427 }
1428 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1429 }
1430
1431 /**
1432 * Install dynamic state for rule type cmd->o.opcode
1433 *
1434 * Returns 1 (failure) if state is not installed because of errors or because
1435 * session limitations are enforced.
1436 */
1437 static int
1438 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1439 struct ip_fw_args *args, uint32_t tablearg)
1440 {
1441 static int last_log;
1442 ipfw_dyn_rule *q;
1443 struct in_addr da;
1444 char src[48], dst[48];
1445
1446 src[0] = '\0';
1447 dst[0] = '\0';
1448
1449 DEB(
1450 printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1451 __func__, cmd->o.opcode,
1452 (args->f_id.src_ip), (args->f_id.src_port),
1453 (args->f_id.dst_ip), (args->f_id.dst_port));
1454 )
1455
1456 IPFW_DYN_LOCK();
1457
1458 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1459
1460 if (q != NULL) { /* should never occur */
1461 if (last_log != time_uptime) {
1462 last_log = time_uptime;
1463 printf("ipfw: %s: entry already present, done\n",
1464 __func__);
1465 }
1466 IPFW_DYN_UNLOCK();
1467 return (0);
1468 }
1469
1470 if (dyn_count >= dyn_max)
1471 /* Run out of slots, try to remove any expired rule. */
1472 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1473
1474 if (dyn_count >= dyn_max) {
1475 if (last_log != time_uptime) {
1476 last_log = time_uptime;
1477 printf("ipfw: %s: Too many dynamic rules\n", __func__);
1478 }
1479 IPFW_DYN_UNLOCK();
1480 return (1); /* cannot install, notify caller */
1481 }
1482
1483 switch (cmd->o.opcode) {
1484 case O_KEEP_STATE: /* bidir rule */
1485 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1486 break;
1487
1488 case O_LIMIT: { /* limit number of sessions */
1489 struct ipfw_flow_id id;
1490 ipfw_dyn_rule *parent;
1491 uint32_t conn_limit;
1492 uint16_t limit_mask = cmd->limit_mask;
1493
1494 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1495 tablearg : cmd->conn_limit;
1496
1497 DEB(
1498 if (cmd->conn_limit == IP_FW_TABLEARG)
1499 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1500 "(tablearg)\n", __func__, conn_limit);
1501 else
1502 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1503 __func__, conn_limit);
1504 )
1505
1506 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1507 id.proto = args->f_id.proto;
1508 id.addr_type = args->f_id.addr_type;
1509 id.fib = M_GETFIB(args->m);
1510
1511 if (IS_IP6_FLOW_ID (&(args->f_id))) {
1512 if (limit_mask & DYN_SRC_ADDR)
1513 id.src_ip6 = args->f_id.src_ip6;
1514 if (limit_mask & DYN_DST_ADDR)
1515 id.dst_ip6 = args->f_id.dst_ip6;
1516 } else {
1517 if (limit_mask & DYN_SRC_ADDR)
1518 id.src_ip = args->f_id.src_ip;
1519 if (limit_mask & DYN_DST_ADDR)
1520 id.dst_ip = args->f_id.dst_ip;
1521 }
1522 if (limit_mask & DYN_SRC_PORT)
1523 id.src_port = args->f_id.src_port;
1524 if (limit_mask & DYN_DST_PORT)
1525 id.dst_port = args->f_id.dst_port;
1526 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1527 printf("ipfw: %s: add parent failed\n", __func__);
1528 IPFW_DYN_UNLOCK();
1529 return (1);
1530 }
1531
1532 if (parent->count >= conn_limit) {
1533 /* See if we can remove some expired rule. */
1534 remove_dyn_rule(rule, parent);
1535 if (parent->count >= conn_limit) {
1536 if (fw_verbose && last_log != time_uptime) {
1537 last_log = time_uptime;
1538 #ifdef INET6
1539 /*
1540 * XXX IPv6 flows are not
1541 * supported yet.
1542 */
1543 if (IS_IP6_FLOW_ID(&(args->f_id))) {
1544 char ip6buf[INET6_ADDRSTRLEN];
1545 snprintf(src, sizeof(src),
1546 "[%s]", ip6_sprintf(ip6buf,
1547 &args->f_id.src_ip6));
1548 snprintf(dst, sizeof(dst),
1549 "[%s]", ip6_sprintf(ip6buf,
1550 &args->f_id.dst_ip6));
1551 } else
1552 #endif
1553 {
1554 da.s_addr =
1555 htonl(args->f_id.src_ip);
1556 inet_ntoa_r(da, src);
1557 da.s_addr =
1558 htonl(args->f_id.dst_ip);
1559 inet_ntoa_r(da, dst);
1560 }
1561 log(LOG_SECURITY | LOG_DEBUG,
1562 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1563 parent->rule->rulenum,
1564 "drop session",
1565 src, (args->f_id.src_port),
1566 dst, (args->f_id.dst_port),
1567 "too many entries");
1568 }
1569 IPFW_DYN_UNLOCK();
1570 return (1);
1571 }
1572 }
1573 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1574 break;
1575 }
1576 default:
1577 printf("ipfw: %s: unknown dynamic rule type %u\n",
1578 __func__, cmd->o.opcode);
1579 IPFW_DYN_UNLOCK();
1580 return (1);
1581 }
1582
1583 /* XXX just set lifetime */
1584 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1585
1586 IPFW_DYN_UNLOCK();
1587 return (0);
1588 }
1589
1590 /*
1591 * Generate a TCP packet, containing either a RST or a keepalive.
1592 * When flags & TH_RST, we are sending a RST packet, because of a
1593 * "reset" action matched the packet.
1594 * Otherwise we are sending a keepalive, and flags & TH_
1595 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1596 * so that MAC can label the reply appropriately.
1597 */
1598 static struct mbuf *
1599 send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1600 u_int32_t ack, int flags)
1601 {
1602 struct mbuf *m;
1603 struct ip *ip;
1604 struct tcphdr *tcp;
1605
1606 MGETHDR(m, M_DONTWAIT, MT_DATA);
1607 if (m == 0)
1608 return (NULL);
1609 m->m_pkthdr.rcvif = (struct ifnet *)0;
1610
1611 M_SETFIB(m, id->fib);
1612 #ifdef MAC
1613 if (replyto != NULL)
1614 mac_create_mbuf_netlayer(replyto, m);
1615 else
1616 mac_create_mbuf_from_firewall(m);
1617 #else
1618 (void)replyto; /* don't warn about unused arg */
1619 #endif
1620
1621 m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1622 m->m_data += max_linkhdr;
1623
1624 ip = mtod(m, struct ip *);
1625 bzero(ip, m->m_len);
1626 tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1627 ip->ip_p = IPPROTO_TCP;
1628 tcp->th_off = 5;
1629 /*
1630 * Assume we are sending a RST (or a keepalive in the reverse
1631 * direction), swap src and destination addresses and ports.
1632 */
1633 ip->ip_src.s_addr = htonl(id->dst_ip);
1634 ip->ip_dst.s_addr = htonl(id->src_ip);
1635 tcp->th_sport = htons(id->dst_port);
1636 tcp->th_dport = htons(id->src_port);
1637 if (flags & TH_RST) { /* we are sending a RST */
1638 if (flags & TH_ACK) {
1639 tcp->th_seq = htonl(ack);
1640 tcp->th_ack = htonl(0);
1641 tcp->th_flags = TH_RST;
1642 } else {
1643 if (flags & TH_SYN)
1644 seq++;
1645 tcp->th_seq = htonl(0);
1646 tcp->th_ack = htonl(seq);
1647 tcp->th_flags = TH_RST | TH_ACK;
1648 }
1649 } else {
1650 /*
1651 * We are sending a keepalive. flags & TH_SYN determines
1652 * the direction, forward if set, reverse if clear.
1653 * NOTE: seq and ack are always assumed to be correct
1654 * as set by the caller. This may be confusing...
1655 */
1656 if (flags & TH_SYN) {
1657 /*
1658 * we have to rewrite the correct addresses!
1659 */
1660 ip->ip_dst.s_addr = htonl(id->dst_ip);
1661 ip->ip_src.s_addr = htonl(id->src_ip);
1662 tcp->th_dport = htons(id->dst_port);
1663 tcp->th_sport = htons(id->src_port);
1664 }
1665 tcp->th_seq = htonl(seq);
1666 tcp->th_ack = htonl(ack);
1667 tcp->th_flags = TH_ACK;
1668 }
1669 /*
1670 * set ip_len to the payload size so we can compute
1671 * the tcp checksum on the pseudoheader
1672 * XXX check this, could save a couple of words ?
1673 */
1674 ip->ip_len = htons(sizeof(struct tcphdr));
1675 tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1676 /*
1677 * now fill fields left out earlier
1678 */
1679 ip->ip_ttl = ip_defttl;
1680 ip->ip_len = m->m_pkthdr.len;
1681 m->m_flags |= M_SKIP_FIREWALL;
1682 return (m);
1683 }
1684
1685 /*
1686 * sends a reject message, consuming the mbuf passed as an argument.
1687 */
1688 static void
1689 send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1690 {
1691
1692 #if 0
1693 /* XXX When ip is not guaranteed to be at mtod() we will
1694 * need to account for this */
1695 * The mbuf will however be thrown away so we can adjust it.
1696 * Remember we did an m_pullup on it already so we
1697 * can make some assumptions about contiguousness.
1698 */
1699 if (args->L3offset)
1700 m_adj(m, args->L3offset);
1701 #endif
1702 if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1703 /* We need the IP header in host order for icmp_error(). */
1704 if (args->eh != NULL) {
1705 ip->ip_len = ntohs(ip->ip_len);
1706 ip->ip_off = ntohs(ip->ip_off);
1707 }
1708 icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1709 } else if (args->f_id.proto == IPPROTO_TCP) {
1710 struct tcphdr *const tcp =
1711 L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1712 if ( (tcp->th_flags & TH_RST) == 0) {
1713 struct mbuf *m;
1714 m = send_pkt(args->m, &(args->f_id),
1715 ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1716 tcp->th_flags | TH_RST);
1717 if (m != NULL)
1718 ip_output(m, NULL, NULL, 0, NULL, NULL);
1719 }
1720 m_freem(args->m);
1721 } else
1722 m_freem(args->m);
1723 args->m = NULL;
1724 }
1725
1726 /**
1727 *
1728 * Given an ip_fw *, lookup_next_rule will return a pointer
1729 * to the next rule, which can be either the jump
1730 * target (for skipto instructions) or the next one in the list (in
1731 * all other cases including a missing jump target).
1732 * The result is also written in the "next_rule" field of the rule.
1733 * Backward jumps are not allowed, so start looking from the next
1734 * rule...
1735 *
1736 * This never returns NULL -- in case we do not have an exact match,
1737 * the next rule is returned. When the ruleset is changed,
1738 * pointers are flushed so we are always correct.
1739 */
1740
1741 static struct ip_fw *
1742 lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1743 {
1744 struct ip_fw *rule = NULL;
1745 ipfw_insn *cmd;
1746 u_int16_t rulenum;
1747
1748 /* look for action, in case it is a skipto */
1749 cmd = ACTION_PTR(me);
1750 if (cmd->opcode == O_LOG)
1751 cmd += F_LEN(cmd);
1752 if (cmd->opcode == O_ALTQ)
1753 cmd += F_LEN(cmd);
1754 if (cmd->opcode == O_TAG)
1755 cmd += F_LEN(cmd);
1756 if (cmd->opcode == O_SKIPTO ) {
1757 if (tablearg != 0) {
1758 rulenum = (u_int16_t)tablearg;
1759 } else {
1760 rulenum = cmd->arg1;
1761 }
1762 for (rule = me->next; rule ; rule = rule->next) {
1763 if (rule->rulenum >= rulenum) {
1764 break;
1765 }
1766 }
1767 }
1768 if (rule == NULL) /* failure or not a skipto */
1769 rule = me->next;
1770 me->next_rule = rule;
1771 return rule;
1772 }
1773
1774 static int
1775 add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1776 uint8_t mlen, uint32_t value)
1777 {
1778 struct radix_node_head *rnh;
1779 struct table_entry *ent;
1780
1781 if (tbl >= IPFW_TABLES_MAX)
1782 return (EINVAL);
1783 rnh = ch->tables[tbl];
1784 ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1785 if (ent == NULL)
1786 return (ENOMEM);
1787 ent->value = value;
1788 ent->addr.sin_len = ent->mask.sin_len = 8;
1789 ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1790 ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1791 IPFW_WLOCK(&layer3_chain);
1792 if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1793 NULL) {
1794 IPFW_WUNLOCK(&layer3_chain);
1795 free(ent, M_IPFW_TBL);
1796 return (EEXIST);
1797 }
1798 IPFW_WUNLOCK(&layer3_chain);
1799 return (0);
1800 }
1801
1802 static int
1803 del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1804 uint8_t mlen)
1805 {
1806 struct radix_node_head *rnh;
1807 struct table_entry *ent;
1808 struct sockaddr_in sa, mask;
1809
1810 if (tbl >= IPFW_TABLES_MAX)
1811 return (EINVAL);
1812 rnh = ch->tables[tbl];
1813 sa.sin_len = mask.sin_len = 8;
1814 mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1815 sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1816 IPFW_WLOCK(ch);
1817 ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1818 if (ent == NULL) {
1819 IPFW_WUNLOCK(ch);
1820 return (ESRCH);
1821 }
1822 IPFW_WUNLOCK(ch);
1823 free(ent, M_IPFW_TBL);
1824 return (0);
1825 }
1826
1827 static int
1828 flush_table_entry(struct radix_node *rn, void *arg)
1829 {
1830 struct radix_node_head * const rnh = arg;
1831 struct table_entry *ent;
1832
1833 ent = (struct table_entry *)
1834 rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1835 if (ent != NULL)
1836 free(ent, M_IPFW_TBL);
1837 return (0);
1838 }
1839
1840 static int
1841 flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1842 {
1843 struct radix_node_head *rnh;
1844
1845 IPFW_WLOCK_ASSERT(ch);
1846
1847 if (tbl >= IPFW_TABLES_MAX)
1848 return (EINVAL);
1849 rnh = ch->tables[tbl];
1850 KASSERT(rnh != NULL, ("NULL IPFW table"));
1851 rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1852 return (0);
1853 }
1854
1855 static void
1856 flush_tables(struct ip_fw_chain *ch)
1857 {
1858 uint16_t tbl;
1859
1860 IPFW_WLOCK_ASSERT(ch);
1861
1862 for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1863 flush_table(ch, tbl);
1864 }
1865
1866 static int
1867 init_tables(struct ip_fw_chain *ch)
1868 {
1869 int i;
1870 uint16_t j;
1871
1872 for (i = 0; i < IPFW_TABLES_MAX; i++) {
1873 if (!rn_inithead((void **)&ch->tables[i], 32)) {
1874 for (j = 0; j < i; j++) {
1875 (void) flush_table(ch, j);
1876 }
1877 return (ENOMEM);
1878 }
1879 }
1880 return (0);
1881 }
1882
1883 static int
1884 lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1885 uint32_t *val)
1886 {
1887 struct radix_node_head *rnh;
1888 struct table_entry *ent;
1889 struct sockaddr_in sa;
1890
1891 if (tbl >= IPFW_TABLES_MAX)
1892 return (0);
1893 rnh = ch->tables[tbl];
1894 sa.sin_len = 8;
1895 sa.sin_addr.s_addr = addr;
1896 ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1897 if (ent != NULL) {
1898 *val = ent->value;
1899 return (1);
1900 }
1901 return (0);
1902 }
1903
1904 static int
1905 count_table_entry(struct radix_node *rn, void *arg)
1906 {
1907 u_int32_t * const cnt = arg;
1908
1909 (*cnt)++;
1910 return (0);
1911 }
1912
1913 static int
1914 count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1915 {
1916 struct radix_node_head *rnh;
1917
1918 if (tbl >= IPFW_TABLES_MAX)
1919 return (EINVAL);
1920 rnh = ch->tables[tbl];
1921 *cnt = 0;
1922 rnh->rnh_walktree(rnh, count_table_entry, cnt);
1923 return (0);
1924 }
1925
1926 static int
1927 dump_table_entry(struct radix_node *rn, void *arg)
1928 {
1929 struct table_entry * const n = (struct table_entry *)rn;
1930 ipfw_table * const tbl = arg;
1931 ipfw_table_entry *ent;
1932
1933 if (tbl->cnt == tbl->size)
1934 return (1);
1935 ent = &tbl->ent[tbl->cnt];
1936 ent->tbl = tbl->tbl;
1937 if (in_nullhost(n->mask.sin_addr))
1938 ent->masklen = 0;
1939 else
1940 ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1941 ent->addr = n->addr.sin_addr.s_addr;
1942 ent->value = n->value;
1943 tbl->cnt++;
1944 return (0);
1945 }
1946
1947 static int
1948 dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1949 {
1950 struct radix_node_head *rnh;
1951
1952 if (tbl->tbl >= IPFW_TABLES_MAX)
1953 return (EINVAL);
1954 rnh = ch->tables[tbl->tbl];
1955 tbl->cnt = 0;
1956 rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1957 return (0);
1958 }
1959
1960 static void
1961 fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1962 {
1963 struct ucred *cr;
1964
1965 cr = inp->inp_cred;
1966 ugp->fw_prid = jailed(cr) ? cr->cr_prison->pr_id : -1;
1967 ugp->fw_uid = cr->cr_uid;
1968 ugp->fw_ngroups = cr->cr_ngroups;
1969 bcopy(cr->cr_groups, ugp->fw_groups, sizeof(ugp->fw_groups));
1970 }
1971
1972 static int
1973 check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1974 struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1975 u_int16_t src_port, struct ip_fw_ugid *ugp, int *ugid_lookupp,
1976 struct inpcb *inp)
1977 {
1978 struct inpcbinfo *pi;
1979 int wildcard;
1980 struct inpcb *pcb;
1981 int match;
1982 gid_t *gp;
1983
1984 /*
1985 * Check to see if the UDP or TCP stack supplied us with
1986 * the PCB. If so, rather then holding a lock and looking
1987 * up the PCB, we can use the one that was supplied.
1988 */
1989 if (inp && *ugid_lookupp == 0) {
1990 INP_LOCK_ASSERT(inp);
1991 if (inp->inp_socket != NULL) {
1992 fill_ugid_cache(inp, ugp);
1993 *ugid_lookupp = 1;
1994 } else
1995 *ugid_lookupp = -1;
1996 }
1997 /*
1998 * If we have already been here and the packet has no
1999 * PCB entry associated with it, then we can safely
2000 * assume that this is a no match.
2001 */
2002 if (*ugid_lookupp == -1)
2003 return (0);
2004 if (proto == IPPROTO_TCP) {
2005 wildcard = 0;
2006 pi = &tcbinfo;
2007 } else if (proto == IPPROTO_UDP) {
2008 wildcard = INPLOOKUP_WILDCARD;
2009 pi = &udbinfo;
2010 } else
2011 return 0;
2012 match = 0;
2013 if (*ugid_lookupp == 0) {
2014 INP_INFO_RLOCK(pi);
2015 pcb = (oif) ?
2016 in_pcblookup_hash(pi,
2017 dst_ip, htons(dst_port),
2018 src_ip, htons(src_port),
2019 wildcard, oif) :
2020 in_pcblookup_hash(pi,
2021 src_ip, htons(src_port),
2022 dst_ip, htons(dst_port),
2023 wildcard, NULL);
2024 if (pcb != NULL) {
2025 fill_ugid_cache(pcb, ugp);
2026 *ugid_lookupp = 1;
2027 }
2028 INP_INFO_RUNLOCK(pi);
2029 if (*ugid_lookupp == 0) {
2030 /*
2031 * If the lookup did not yield any results, there
2032 * is no sense in coming back and trying again. So
2033 * we can set lookup to -1 and ensure that we wont
2034 * bother the pcb system again.
2035 */
2036 *ugid_lookupp = -1;
2037 return (0);
2038 }
2039 }
2040 if (insn->o.opcode == O_UID)
2041 match = (ugp->fw_uid == (uid_t)insn->d[0]);
2042 else if (insn->o.opcode == O_GID) {
2043 for (gp = ugp->fw_groups;
2044 gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2045 if (*gp == (gid_t)insn->d[0]) {
2046 match = 1;
2047 break;
2048 }
2049 } else if (insn->o.opcode == O_JAIL)
2050 match = (ugp->fw_prid == (int)insn->d[0]);
2051 return match;
2052 }
2053
2054 /*
2055 * The main check routine for the firewall.
2056 *
2057 * All arguments are in args so we can modify them and return them
2058 * back to the caller.
2059 *
2060 * Parameters:
2061 *
2062 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
2063 * Starts with the IP header.
2064 * args->eh (in) Mac header if present, or NULL for layer3 packet.
2065 * args->L3offset Number of bytes bypassed if we came from L2.
2066 * e.g. often sizeof(eh) ** NOTYET **
2067 * args->oif Outgoing interface, or NULL if packet is incoming.
2068 * The incoming interface is in the mbuf. (in)
2069 * args->divert_rule (in/out)
2070 * Skip up to the first rule past this rule number;
2071 * upon return, non-zero port number for divert or tee.
2072 *
2073 * args->rule Pointer to the last matching rule (in/out)
2074 * args->next_hop Socket we are forwarding to (out).
2075 * args->f_id Addresses grabbed from the packet (out)
2076 * args->cookie a cookie depending on rule action
2077 *
2078 * Return value:
2079 *
2080 * IP_FW_PASS the packet must be accepted
2081 * IP_FW_DENY the packet must be dropped
2082 * IP_FW_DIVERT divert packet, port in m_tag
2083 * IP_FW_TEE tee packet, port in m_tag
2084 * IP_FW_DUMMYNET to dummynet, pipe in args->cookie
2085 * IP_FW_NETGRAPH into netgraph, cookie args->cookie
2086 *
2087 */
2088 int
2089 ipfw_chk(struct ip_fw_args *args)
2090 {
2091 /*
2092 * Local variables holding state during the processing of a packet:
2093 *
2094 * IMPORTANT NOTE: to speed up the processing of rules, there
2095 * are some assumption on the values of the variables, which
2096 * are documented here. Should you change them, please check
2097 * the implementation of the various instructions to make sure
2098 * that they still work.
2099 *
2100 * args->eh The MAC header. It is non-null for a layer2
2101 * packet, it is NULL for a layer-3 packet.
2102 * **notyet**
2103 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2104 *
2105 * m | args->m Pointer to the mbuf, as received from the caller.
2106 * It may change if ipfw_chk() does an m_pullup, or if it
2107 * consumes the packet because it calls send_reject().
2108 * XXX This has to change, so that ipfw_chk() never modifies
2109 * or consumes the buffer.
2110 * ip is the beginning of the ip(4 or 6) header.
2111 * Calculated by adding the L3offset to the start of data.
2112 * (Until we start using L3offset, the packet is
2113 * supposed to start with the ip header).
2114 */
2115 struct mbuf *m = args->m;
2116 struct ip *ip = mtod(m, struct ip *);
2117
2118 /*
2119 * For rules which contain uid/gid or jail constraints, cache
2120 * a copy of the users credentials after the pcb lookup has been
2121 * executed. This will speed up the processing of rules with
2122 * these types of constraints, as well as decrease contention
2123 * on pcb related locks.
2124 */
2125 struct ip_fw_ugid fw_ugid_cache;
2126 int ugid_lookup = 0;
2127
2128 /*
2129 * divinput_flags If non-zero, set to the IP_FW_DIVERT_*_FLAG
2130 * associated with a packet input on a divert socket. This
2131 * will allow to distinguish traffic and its direction when
2132 * it originates from a divert socket.
2133 */
2134 u_int divinput_flags = 0;
2135
2136 /*
2137 * oif | args->oif If NULL, ipfw_chk has been called on the
2138 * inbound path (ether_input, ip_input).
2139 * If non-NULL, ipfw_chk has been called on the outbound path
2140 * (ether_output, ip_output).
2141 */
2142 struct ifnet *oif = args->oif;
2143
2144 struct ip_fw *f = NULL; /* matching rule */
2145 int retval = 0;
2146
2147 /*
2148 * hlen The length of the IP header.
2149 */
2150 u_int hlen = 0; /* hlen >0 means we have an IP pkt */
2151
2152 /*
2153 * offset The offset of a fragment. offset != 0 means that
2154 * we have a fragment at this offset of an IPv4 packet.
2155 * offset == 0 means that (if this is an IPv4 packet)
2156 * this is the first or only fragment.
2157 * For IPv6 offset == 0 means there is no Fragment Header.
2158 * If offset != 0 for IPv6 always use correct mask to
2159 * get the correct offset because we add IP6F_MORE_FRAG
2160 * to be able to dectect the first fragment which would
2161 * otherwise have offset = 0.
2162 */
2163 u_short offset = 0;
2164
2165 /*
2166 * Local copies of addresses. They are only valid if we have
2167 * an IP packet.
2168 *
2169 * proto The protocol. Set to 0 for non-ip packets,
2170 * or to the protocol read from the packet otherwise.
2171 * proto != 0 means that we have an IPv4 packet.
2172 *
2173 * src_port, dst_port port numbers, in HOST format. Only
2174 * valid for TCP and UDP packets.
2175 *
2176 * src_ip, dst_ip ip addresses, in NETWORK format.
2177 * Only valid for IPv4 packets.
2178 */
2179 u_int8_t proto;
2180 u_int16_t src_port = 0, dst_port = 0; /* NOTE: host format */
2181 struct in_addr src_ip, dst_ip; /* NOTE: network format */
2182 u_int16_t ip_len=0;
2183 int pktlen;
2184 u_int16_t etype = 0; /* Host order stored ether type */
2185
2186 /*
2187 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2188 * MATCH_NONE when checked and not matched (q = NULL),
2189 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2190 */
2191 int dyn_dir = MATCH_UNKNOWN;
2192 ipfw_dyn_rule *q = NULL;
2193 struct ip_fw_chain *chain = &layer3_chain;
2194 struct m_tag *mtag;
2195
2196 /*
2197 * We store in ulp a pointer to the upper layer protocol header.
2198 * In the ipv4 case this is easy to determine from the header,
2199 * but for ipv6 we might have some additional headers in the middle.
2200 * ulp is NULL if not found.
2201 */
2202 void *ulp = NULL; /* upper layer protocol pointer. */
2203 /* XXX ipv6 variables */
2204 int is_ipv6 = 0;
2205 u_int16_t ext_hd = 0; /* bits vector for extension header filtering */
2206 /* end of ipv6 variables */
2207 int is_ipv4 = 0;
2208
2209 if (m->m_flags & M_SKIP_FIREWALL)
2210 return (IP_FW_PASS); /* accept */
2211
2212 pktlen = m->m_pkthdr.len;
2213 args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2214 proto = args->f_id.proto = 0; /* mark f_id invalid */
2215 /* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2216
2217 /*
2218 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2219 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2220 * pointer might become stale after other pullups (but we never use it
2221 * this way).
2222 */
2223 #define PULLUP_TO(len, p, T) \
2224 do { \
2225 int x = (len) + sizeof(T); \
2226 if ((m)->m_len < x) { \
2227 args->m = m = m_pullup(m, x); \
2228 if (m == NULL) \
2229 goto pullup_failed; \
2230 } \
2231 p = (mtod(m, char *) + (len)); \
2232 } while (0)
2233
2234 /*
2235 * if we have an ether header,
2236 */
2237 if (args->eh)
2238 etype = ntohs(args->eh->ether_type);
2239
2240 /* Identify IP packets and fill up variables. */
2241 if (pktlen >= sizeof(struct ip6_hdr) &&
2242 (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2243 struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2244 is_ipv6 = 1;
2245 args->f_id.addr_type = 6;
2246 hlen = sizeof(struct ip6_hdr);
2247 proto = ip6->ip6_nxt;
2248
2249 /* Search extension headers to find upper layer protocols */
2250 while (ulp == NULL) {
2251 switch (proto) {
2252 case IPPROTO_ICMPV6:
2253 PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2254 args->f_id.flags = ICMP6(ulp)->icmp6_type;
2255 break;
2256
2257 case IPPROTO_TCP:
2258 PULLUP_TO(hlen, ulp, struct tcphdr);
2259 dst_port = TCP(ulp)->th_dport;
2260 src_port = TCP(ulp)->th_sport;
2261 args->f_id.flags = TCP(ulp)->th_flags;
2262 break;
2263
2264 case IPPROTO_SCTP:
2265 PULLUP_TO(hlen, ulp, struct sctphdr);
2266 src_port = SCTP(ulp)->src_port;
2267 dst_port = SCTP(ulp)->dest_port;
2268 break;
2269
2270 case IPPROTO_UDP:
2271 PULLUP_TO(hlen, ulp, struct udphdr);
2272 dst_port = UDP(ulp)->uh_dport;
2273 src_port = UDP(ulp)->uh_sport;
2274 break;
2275
2276 case IPPROTO_HOPOPTS: /* RFC 2460 */
2277 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2278 ext_hd |= EXT_HOPOPTS;
2279 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2280 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2281 ulp = NULL;
2282 break;
2283
2284 case IPPROTO_ROUTING: /* RFC 2460 */
2285 PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2286 switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2287 case 0:
2288 ext_hd |= EXT_RTHDR0;
2289 break;
2290 case 2:
2291 ext_hd |= EXT_RTHDR2;
2292 break;
2293 default:
2294 printf("IPFW2: IPV6 - Unknown Routing "
2295 "Header type(%d)\n",
2296 ((struct ip6_rthdr *)ulp)->ip6r_type);
2297 if (fw_deny_unknown_exthdrs)
2298 return (IP_FW_DENY);
2299 break;
2300 }
2301 ext_hd |= EXT_ROUTING;
2302 hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2303 proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2304 ulp = NULL;
2305 break;
2306
2307 case IPPROTO_FRAGMENT: /* RFC 2460 */
2308 PULLUP_TO(hlen, ulp, struct ip6_frag);
2309 ext_hd |= EXT_FRAGMENT;
2310 hlen += sizeof (struct ip6_frag);
2311 proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2312 offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2313 IP6F_OFF_MASK;
2314 /* Add IP6F_MORE_FRAG for offset of first
2315 * fragment to be != 0. */
2316 offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2317 IP6F_MORE_FRAG;
2318 if (offset == 0) {
2319 printf("IPFW2: IPV6 - Invalid Fragment "
2320 "Header\n");
2321 if (fw_deny_unknown_exthdrs)
2322 return (IP_FW_DENY);
2323 break;
2324 }
2325 args->f_id.frag_id6 =
2326 ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2327 ulp = NULL;
2328 break;
2329
2330 case IPPROTO_DSTOPTS: /* RFC 2460 */
2331 PULLUP_TO(hlen, ulp, struct ip6_hbh);
2332 ext_hd |= EXT_DSTOPTS;
2333 hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2334 proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2335 ulp = NULL;
2336 break;
2337
2338 case IPPROTO_AH: /* RFC 2402 */
2339 PULLUP_TO(hlen, ulp, struct ip6_ext);
2340 ext_hd |= EXT_AH;
2341 hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2342 proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2343 ulp = NULL;
2344 break;
2345
2346 case IPPROTO_ESP: /* RFC 2406 */
2347 PULLUP_TO(hlen, ulp, uint32_t); /* SPI, Seq# */
2348 /* Anything past Seq# is variable length and
2349 * data past this ext. header is encrypted. */
2350 ext_hd |= EXT_ESP;
2351 break;
2352
2353 case IPPROTO_NONE: /* RFC 2460 */
2354 /*
2355 * Packet ends here, and IPv6 header has
2356 * already been pulled up. If ip6e_len!=0
2357 * then octets must be ignored.
2358 */
2359 ulp = ip; /* non-NULL to get out of loop. */
2360 break;
2361
2362 case IPPROTO_OSPFIGP:
2363 /* XXX OSPF header check? */
2364 PULLUP_TO(hlen, ulp, struct ip6_ext);
2365 break;
2366
2367 case IPPROTO_PIM:
2368 /* XXX PIM header check? */
2369 PULLUP_TO(hlen, ulp, struct pim);
2370 break;
2371
2372 case IPPROTO_CARP:
2373 PULLUP_TO(hlen, ulp, struct carp_header);
2374 if (((struct carp_header *)ulp)->carp_version !=
2375 CARP_VERSION)
2376 return (IP_FW_DENY);
2377 if (((struct carp_header *)ulp)->carp_type !=
2378 CARP_ADVERTISEMENT)
2379 return (IP_FW_DENY);
2380 break;
2381
2382 case IPPROTO_IPV6: /* RFC 2893 */
2383 PULLUP_TO(hlen, ulp, struct ip6_hdr);
2384 break;
2385
2386 case IPPROTO_IPV4: /* RFC 2893 */
2387 PULLUP_TO(hlen, ulp, struct ip);
2388 break;
2389
2390 default:
2391 printf("IPFW2: IPV6 - Unknown Extension "
2392 "Header(%d), ext_hd=%x\n", proto, ext_hd);
2393 if (fw_deny_unknown_exthdrs)
2394 return (IP_FW_DENY);
2395 PULLUP_TO(hlen, ulp, struct ip6_ext);
2396 break;
2397 } /*switch */
2398 }
2399 ip = mtod(m, struct ip *);
2400 ip6 = (struct ip6_hdr *)ip;
2401 args->f_id.src_ip6 = ip6->ip6_src;
2402 args->f_id.dst_ip6 = ip6->ip6_dst;
2403 args->f_id.src_ip = 0;
2404 args->f_id.dst_ip = 0;
2405 args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2406 } else if (pktlen >= sizeof(struct ip) &&
2407 (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2408 is_ipv4 = 1;
2409 hlen = ip->ip_hl << 2;
2410 args->f_id.addr_type = 4;
2411
2412 /*
2413 * Collect parameters into local variables for faster matching.
2414 */
2415 proto = ip->ip_p;
2416 src_ip = ip->ip_src;
2417 dst_ip = ip->ip_dst;
2418 if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2419 offset = ntohs(ip->ip_off) & IP_OFFMASK;
2420 ip_len = ntohs(ip->ip_len);
2421 } else {
2422 offset = ip->ip_off & IP_OFFMASK;
2423 ip_len = ip->ip_len;
2424 }
2425 pktlen = ip_len < pktlen ? ip_len : pktlen;
2426
2427 if (offset == 0) {
2428 switch (proto) {
2429 case IPPROTO_TCP:
2430 PULLUP_TO(hlen, ulp, struct tcphdr);
2431 dst_port = TCP(ulp)->th_dport;
2432 src_port = TCP(ulp)->th_sport;
2433 args->f_id.flags = TCP(ulp)->th_flags;
2434 break;
2435
2436 case IPPROTO_UDP:
2437 PULLUP_TO(hlen, ulp, struct udphdr);
2438 dst_port = UDP(ulp)->uh_dport;
2439 src_port = UDP(ulp)->uh_sport;
2440 break;
2441
2442 case IPPROTO_ICMP:
2443 PULLUP_TO(hlen, ulp, struct icmphdr);
2444 args->f_id.flags = ICMP(ulp)->icmp_type;
2445 break;
2446
2447 default:
2448 break;
2449 }
2450 }
2451
2452 ip = mtod(m, struct ip *);
2453 args->f_id.src_ip = ntohl(src_ip.s_addr);
2454 args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2455 }
2456 #undef PULLUP_TO
2457 if (proto) { /* we may have port numbers, store them */
2458 args->f_id.proto = proto;
2459 args->f_id.src_port = src_port = ntohs(src_port);
2460 args->f_id.dst_port = dst_port = ntohs(dst_port);
2461 }
2462
2463 IPFW_RLOCK(chain);
2464 mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2465 if (args->rule) {
2466 /*
2467 * Packet has already been tagged. Look for the next rule
2468 * to restart processing.
2469 *
2470 * If fw_one_pass != 0 then just accept it.
2471 * XXX should not happen here, but optimized out in
2472 * the caller.
2473 */
2474 if (fw_one_pass) {
2475 IPFW_RUNLOCK(chain);
2476 return (IP_FW_PASS);
2477 }
2478
2479 f = args->rule->next_rule;
2480 if (f == NULL)
2481 f = lookup_next_rule(args->rule, 0);
2482 } else {
2483 /*
2484 * Find the starting rule. It can be either the first
2485 * one, or the one after divert_rule if asked so.
2486 */
2487 int skipto = mtag ? divert_cookie(mtag) : 0;
2488
2489 f = chain->rules;
2490 if (args->eh == NULL && skipto != 0) {
2491 if (skipto >= IPFW_DEFAULT_RULE) {
2492 IPFW_RUNLOCK(chain);
2493 return (IP_FW_DENY); /* invalid */
2494 }
2495 while (f && f->rulenum <= skipto)
2496 f = f->next;
2497 if (f == NULL) { /* drop packet */
2498 IPFW_RUNLOCK(chain);
2499 return (IP_FW_DENY);
2500 }
2501 }
2502 }
2503 /* reset divert rule to avoid confusion later */
2504 if (mtag) {
2505 divinput_flags = divert_info(mtag) &
2506 (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2507 m_tag_delete(m, mtag);
2508 }
2509
2510 /*
2511 * Now scan the rules, and parse microinstructions for each rule.
2512 */
2513 for (; f; f = f->next) {
2514 ipfw_insn *cmd;
2515 uint32_t tablearg = 0;
2516 int l, cmdlen, skip_or; /* skip rest of OR block */
2517
2518 again:
2519 if (set_disable & (1 << f->set) )
2520 continue;
2521
2522 skip_or = 0;
2523 for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2524 l -= cmdlen, cmd += cmdlen) {
2525 int match;
2526
2527 /*
2528 * check_body is a jump target used when we find a
2529 * CHECK_STATE, and need to jump to the body of
2530 * the target rule.
2531 */
2532
2533 check_body:
2534 cmdlen = F_LEN(cmd);
2535 /*
2536 * An OR block (insn_1 || .. || insn_n) has the
2537 * F_OR bit set in all but the last instruction.
2538 * The first match will set "skip_or", and cause
2539 * the following instructions to be skipped until
2540 * past the one with the F_OR bit clear.
2541 */
2542 if (skip_or) { /* skip this instruction */
2543 if ((cmd->len & F_OR) == 0)
2544 skip_or = 0; /* next one is good */
2545 continue;
2546 }
2547 match = 0; /* set to 1 if we succeed */
2548
2549 switch (cmd->opcode) {
2550 /*
2551 * The first set of opcodes compares the packet's
2552 * fields with some pattern, setting 'match' if a
2553 * match is found. At the end of the loop there is
2554 * logic to deal with F_NOT and F_OR flags associated
2555 * with the opcode.
2556 */
2557 case O_NOP:
2558 match = 1;
2559 break;
2560
2561 case O_FORWARD_MAC:
2562 printf("ipfw: opcode %d unimplemented\n",
2563 cmd->opcode);
2564 break;
2565
2566 case O_GID:
2567 case O_UID:
2568 case O_JAIL:
2569 /*
2570 * We only check offset == 0 && proto != 0,
2571 * as this ensures that we have a
2572 * packet with the ports info.
2573 */
2574 if (offset!=0)
2575 break;
2576 if (is_ipv6) /* XXX to be fixed later */
2577 break;
2578 if (proto == IPPROTO_TCP ||
2579 proto == IPPROTO_UDP)
2580 match = check_uidgid(
2581 (ipfw_insn_u32 *)cmd,
2582 proto, oif,
2583 dst_ip, dst_port,
2584 src_ip, src_port, &fw_ugid_cache,
2585 &ugid_lookup, args->inp);
2586 break;
2587
2588 case O_RECV:
2589 match = iface_match(m->m_pkthdr.rcvif,
2590 (ipfw_insn_if *)cmd);
2591 break;
2592
2593 case O_XMIT:
2594 match = iface_match(oif, (ipfw_insn_if *)cmd);
2595 break;
2596
2597 case O_VIA:
2598 match = iface_match(oif ? oif :
2599 m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2600 break;
2601
2602 case O_MACADDR2:
2603 if (args->eh != NULL) { /* have MAC header */
2604 u_int32_t *want = (u_int32_t *)
2605 ((ipfw_insn_mac *)cmd)->addr;
2606 u_int32_t *mask = (u_int32_t *)
2607 ((ipfw_insn_mac *)cmd)->mask;
2608 u_int32_t *hdr = (u_int32_t *)args->eh;
2609
2610 match =
2611 ( want[0] == (hdr[0] & mask[0]) &&
2612 want[1] == (hdr[1] & mask[1]) &&
2613 want[2] == (hdr[2] & mask[2]) );
2614 }
2615 break;
2616
2617 case O_MAC_TYPE:
2618 if (args->eh != NULL) {
2619 u_int16_t *p =
2620 ((ipfw_insn_u16 *)cmd)->ports;
2621 int i;
2622
2623 for (i = cmdlen - 1; !match && i>0;
2624 i--, p += 2)
2625 match = (etype >= p[0] &&
2626 etype <= p[1]);
2627 }
2628 break;
2629
2630 case O_FRAG:
2631 match = (offset != 0);
2632 break;
2633
2634 case O_IN: /* "out" is "not in" */
2635 match = (oif == NULL);
2636 break;
2637
2638 case O_LAYER2:
2639 match = (args->eh != NULL);
2640 break;
2641
2642 case O_DIVERTED:
2643 match = (cmd->arg1 & 1 && divinput_flags &
2644 IP_FW_DIVERT_LOOPBACK_FLAG) ||
2645 (cmd->arg1 & 2 && divinput_flags &
2646 IP_FW_DIVERT_OUTPUT_FLAG);
2647 break;
2648
2649 case O_PROTO:
2650 /*
2651 * We do not allow an arg of 0 so the
2652 * check of "proto" only suffices.
2653 */
2654 match = (proto == cmd->arg1);
2655 break;
2656
2657 case O_IP_SRC:
2658 match = is_ipv4 &&
2659 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2660 src_ip.s_addr);
2661 break;
2662
2663 case O_IP_SRC_LOOKUP:
2664 case O_IP_DST_LOOKUP:
2665 if (is_ipv4) {
2666 uint32_t a =
2667 (cmd->opcode == O_IP_DST_LOOKUP) ?
2668 dst_ip.s_addr : src_ip.s_addr;
2669 uint32_t v;
2670
2671 match = lookup_table(chain, cmd->arg1, a,
2672 &v);
2673 if (!match)
2674 break;
2675 if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2676 match =
2677 ((ipfw_insn_u32 *)cmd)->d[0] == v;
2678 else
2679 tablearg = v;
2680 }
2681 break;
2682
2683 case O_IP_SRC_MASK:
2684 case O_IP_DST_MASK:
2685 if (is_ipv4) {
2686 uint32_t a =
2687 (cmd->opcode == O_IP_DST_MASK) ?
2688 dst_ip.s_addr : src_ip.s_addr;
2689 uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2690 int i = cmdlen-1;
2691
2692 for (; !match && i>0; i-= 2, p+= 2)
2693 match = (p[0] == (a & p[1]));
2694 }
2695 break;
2696
2697 case O_IP_SRC_ME:
2698 if (is_ipv4) {
2699 struct ifnet *tif;
2700
2701 INADDR_TO_IFP(src_ip, tif);
2702 match = (tif != NULL);
2703 }
2704 break;
2705
2706 case O_IP_DST_SET:
2707 case O_IP_SRC_SET:
2708 if (is_ipv4) {
2709 u_int32_t *d = (u_int32_t *)(cmd+1);
2710 u_int32_t addr =
2711 cmd->opcode == O_IP_DST_SET ?
2712 args->f_id.dst_ip :
2713 args->f_id.src_ip;
2714
2715 if (addr < d[0])
2716 break;
2717 addr -= d[0]; /* subtract base */
2718 match = (addr < cmd->arg1) &&
2719 ( d[ 1 + (addr>>5)] &
2720 (1<<(addr & 0x1f)) );
2721 }
2722 break;
2723
2724 case O_IP_DST:
2725 match = is_ipv4 &&
2726 (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2727 dst_ip.s_addr);
2728 break;
2729
2730 case O_IP_DST_ME:
2731 if (is_ipv4) {
2732 struct ifnet *tif;
2733
2734 INADDR_TO_IFP(dst_ip, tif);
2735 match = (tif != NULL);
2736 }
2737 break;
2738
2739 case O_IP_SRCPORT:
2740 case O_IP_DSTPORT:
2741 /*
2742 * offset == 0 && proto != 0 is enough
2743 * to guarantee that we have a
2744 * packet with port info.
2745 */
2746 if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2747 && offset == 0) {
2748 u_int16_t x =
2749 (cmd->opcode == O_IP_SRCPORT) ?
2750 src_port : dst_port ;
2751 u_int16_t *p =
2752 ((ipfw_insn_u16 *)cmd)->ports;
2753 int i;
2754
2755 for (i = cmdlen - 1; !match && i>0;
2756 i--, p += 2)
2757 match = (x>=p[0] && x<=p[1]);
2758 }
2759 break;
2760
2761 case O_ICMPTYPE:
2762 match = (offset == 0 && proto==IPPROTO_ICMP &&
2763 icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2764 break;
2765
2766 #ifdef INET6
2767 case O_ICMP6TYPE:
2768 match = is_ipv6 && offset == 0 &&
2769 proto==IPPROTO_ICMPV6 &&
2770 icmp6type_match(
2771 ICMP6(ulp)->icmp6_type,
2772 (ipfw_insn_u32 *)cmd);
2773 break;
2774 #endif /* INET6 */
2775
2776 case O_IPOPT:
2777 match = (is_ipv4 &&
2778 ipopts_match(ip, cmd) );
2779 break;
2780
2781 case O_IPVER:
2782 match = (is_ipv4 &&
2783 cmd->arg1 == ip->ip_v);
2784 break;
2785
2786 case O_IPID:
2787 case O_IPLEN:
2788 case O_IPTTL:
2789 if (is_ipv4) { /* only for IP packets */
2790 uint16_t x;
2791 uint16_t *p;
2792 int i;
2793
2794 if (cmd->opcode == O_IPLEN)
2795 x = ip_len;
2796 else if (cmd->opcode == O_IPTTL)
2797 x = ip->ip_ttl;
2798 else /* must be IPID */
2799 x = ntohs(ip->ip_id);
2800 if (cmdlen == 1) {
2801 match = (cmd->arg1 == x);
2802 break;
2803 }
2804 /* otherwise we have ranges */
2805 p = ((ipfw_insn_u16 *)cmd)->ports;
2806 i = cmdlen - 1;
2807 for (; !match && i>0; i--, p += 2)
2808 match = (x >= p[0] && x <= p[1]);
2809 }
2810 break;
2811
2812 case O_IPPRECEDENCE:
2813 match = (is_ipv4 &&
2814 (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2815 break;
2816
2817 case O_IPTOS:
2818 match = (is_ipv4 &&
2819 flags_match(cmd, ip->ip_tos));
2820 break;
2821
2822 case O_TCPDATALEN:
2823 if (proto == IPPROTO_TCP && offset == 0) {
2824 struct tcphdr *tcp;
2825 uint16_t x;
2826 uint16_t *p;
2827 int i;
2828
2829 tcp = TCP(ulp);
2830 x = ip_len -
2831 ((ip->ip_hl + tcp->th_off) << 2);
2832 if (cmdlen == 1) {
2833 match = (cmd->arg1 == x);
2834 break;
2835 }
2836 /* otherwise we have ranges */
2837 p = ((ipfw_insn_u16 *)cmd)->ports;
2838 i = cmdlen - 1;
2839 for (; !match && i>0; i--, p += 2)
2840 match = (x >= p[0] && x <= p[1]);
2841 }
2842 break;
2843
2844 case O_TCPFLAGS:
2845 match = (proto == IPPROTO_TCP && offset == 0 &&
2846 flags_match(cmd, TCP(ulp)->th_flags));
2847 break;
2848
2849 case O_TCPOPTS:
2850 match = (proto == IPPROTO_TCP && offset == 0 &&
2851 tcpopts_match(TCP(ulp), cmd));
2852 break;
2853
2854 case O_TCPSEQ:
2855 match = (proto == IPPROTO_TCP && offset == 0 &&
2856 ((ipfw_insn_u32 *)cmd)->d[0] ==
2857 TCP(ulp)->th_seq);
2858 break;
2859
2860 case O_TCPACK:
2861 match = (proto == IPPROTO_TCP && offset == 0 &&
2862 ((ipfw_insn_u32 *)cmd)->d[0] ==
2863 TCP(ulp)->th_ack);
2864 break;
2865
2866 case O_TCPWIN:
2867 match = (proto == IPPROTO_TCP && offset == 0 &&
2868 cmd->arg1 == TCP(ulp)->th_win);
2869 break;
2870
2871 case O_ESTAB:
2872 /* reject packets which have SYN only */
2873 /* XXX should i also check for TH_ACK ? */
2874 match = (proto == IPPROTO_TCP && offset == 0 &&
2875 (TCP(ulp)->th_flags &
2876 (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2877 break;
2878
2879 case O_ALTQ: {
2880 struct pf_mtag *at;
2881 ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2882
2883 match = 1;
2884 at = pf_find_mtag(m);
2885 if (at != NULL && at->qid != 0)
2886 break;
2887 at = pf_get_mtag(m);
2888 if (at == NULL) {
2889 /*
2890 * Let the packet fall back to the
2891 * default ALTQ.
2892 */
2893 break;
2894 }
2895 at->qid = altq->qid;
2896 if (is_ipv4)
2897 at->af = AF_INET;
2898 else
2899 at->af = AF_LINK;
2900 at->hdr = ip;
2901 break;
2902 }
2903
2904 case O_LOG:
2905 if (fw_verbose)
2906 ipfw_log(f, hlen, args, m,
2907 oif, offset, tablearg, ip);
2908 match = 1;
2909 break;
2910
2911 case O_PROB:
2912 match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2913 break;
2914
2915 case O_VERREVPATH:
2916 /* Outgoing packets automatically pass/match */
2917 match = ((oif != NULL) ||
2918 (m->m_pkthdr.rcvif == NULL) ||
2919 (
2920 #ifdef INET6
2921 is_ipv6 ?
2922 verify_path6(&(args->f_id.src_ip6),
2923 m->m_pkthdr.rcvif) :
2924 #endif
2925 verify_path(src_ip, m->m_pkthdr.rcvif,
2926 args->f_id.fib)));
2927 break;
2928
2929 case O_VERSRCREACH:
2930 /* Outgoing packets automatically pass/match */
2931 match = (hlen > 0 && ((oif != NULL) ||
2932 #ifdef INET6
2933 is_ipv6 ?
2934 verify_path6(&(args->f_id.src_ip6),
2935 NULL) :
2936 #endif
2937 verify_path(src_ip, NULL, args->f_id.fib)));
2938 break;
2939
2940 case O_ANTISPOOF:
2941 /* Outgoing packets automatically pass/match */
2942 if (oif == NULL && hlen > 0 &&
2943 ( (is_ipv4 && in_localaddr(src_ip))
2944 #ifdef INET6
2945 || (is_ipv6 &&
2946 in6_localaddr(&(args->f_id.src_ip6)))
2947 #endif
2948 ))
2949 match =
2950 #ifdef INET6
2951 is_ipv6 ? verify_path6(
2952 &(args->f_id.src_ip6),
2953 m->m_pkthdr.rcvif) :
2954 #endif
2955 verify_path(src_ip,
2956 m->m_pkthdr.rcvif,
2957 args->f_id.fib);
2958 else
2959 match = 1;
2960 break;
2961
2962 case O_IPSEC:
2963 #ifdef IPSEC
2964 match = (m_tag_find(m,
2965 PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2966 #endif
2967 /* otherwise no match */
2968 break;
2969
2970 #ifdef INET6
2971 case O_IP6_SRC:
2972 match = is_ipv6 &&
2973 IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2974 &((ipfw_insn_ip6 *)cmd)->addr6);
2975 break;
2976
2977 case O_IP6_DST:
2978 match = is_ipv6 &&
2979 IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2980 &((ipfw_insn_ip6 *)cmd)->addr6);
2981 break;
2982 case O_IP6_SRC_MASK:
2983 case O_IP6_DST_MASK:
2984 if (is_ipv6) {
2985 int i = cmdlen - 1;
2986 struct in6_addr p;
2987 struct in6_addr *d =
2988 &((ipfw_insn_ip6 *)cmd)->addr6;
2989
2990 for (; !match && i > 0; d += 2,
2991 i -= F_INSN_SIZE(struct in6_addr)
2992 * 2) {
2993 p = (cmd->opcode ==
2994 O_IP6_SRC_MASK) ?
2995 args->f_id.src_ip6:
2996 args->f_id.dst_ip6;
2997 APPLY_MASK(&p, &d[1]);
2998 match =
2999 IN6_ARE_ADDR_EQUAL(&d[0],
3000 &p);
3001 }
3002 }
3003 break;
3004
3005 case O_IP6_SRC_ME:
3006 match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3007 break;
3008
3009 case O_IP6_DST_ME:
3010 match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3011 break;
3012
3013 case O_FLOW6ID:
3014 match = is_ipv6 &&
3015 flow6id_match(args->f_id.flow_id6,
3016 (ipfw_insn_u32 *) cmd);
3017 break;
3018
3019 case O_EXT_HDR:
3020 match = is_ipv6 &&
3021 (ext_hd & ((ipfw_insn *) cmd)->arg1);
3022 break;
3023
3024 case O_IP6:
3025 match = is_ipv6;
3026 break;
3027 #endif
3028
3029 case O_IP4:
3030 match = is_ipv4;
3031 break;
3032
3033 case O_TAG: {
3034 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3035 tablearg : cmd->arg1;
3036
3037 /* Packet is already tagged with this tag? */
3038 mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3039
3040 /* We have `untag' action when F_NOT flag is
3041 * present. And we must remove this mtag from
3042 * mbuf and reset `match' to zero (`match' will
3043 * be inversed later).
3044 * Otherwise we should allocate new mtag and
3045 * push it into mbuf.
3046 */
3047 if (cmd->len & F_NOT) { /* `untag' action */
3048 if (mtag != NULL)
3049 m_tag_delete(m, mtag);
3050 } else if (mtag == NULL) {
3051 if ((mtag = m_tag_alloc(MTAG_IPFW,
3052 tag, 0, M_NOWAIT)) != NULL)
3053 m_tag_prepend(m, mtag);
3054 }
3055 match = (cmd->len & F_NOT) ? 0: 1;
3056 break;
3057 }
3058
3059 case O_FIB: /* try match the specified fib */
3060 if (args->f_id.fib == cmd->arg1)
3061 match = 1;
3062 break;
3063
3064 case O_TAGGED: {
3065 uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3066 tablearg : cmd->arg1;
3067
3068 if (cmdlen == 1) {
3069 match = m_tag_locate(m, MTAG_IPFW,
3070 tag, NULL) != NULL;
3071 break;
3072 }
3073
3074 /* we have ranges */
3075 for (mtag = m_tag_first(m);
3076 mtag != NULL && !match;
3077 mtag = m_tag_next(m, mtag)) {
3078 uint16_t *p;
3079 int i;
3080
3081 if (mtag->m_tag_cookie != MTAG_IPFW)
3082 continue;
3083
3084 p = ((ipfw_insn_u16 *)cmd)->ports;
3085 i = cmdlen - 1;
3086 for(; !match && i > 0; i--, p += 2)
3087 match =
3088 mtag->m_tag_id >= p[0] &&
3089 mtag->m_tag_id <= p[1];
3090 }
3091 break;
3092 }
3093
3094 /*
3095 * The second set of opcodes represents 'actions',
3096 * i.e. the terminal part of a rule once the packet
3097 * matches all previous patterns.
3098 * Typically there is only one action for each rule,
3099 * and the opcode is stored at the end of the rule
3100 * (but there are exceptions -- see below).
3101 *
3102 * In general, here we set retval and terminate the
3103 * outer loop (would be a 'break 3' in some language,
3104 * but we need to do a 'goto done').
3105 *
3106 * Exceptions:
3107 * O_COUNT and O_SKIPTO actions:
3108 * instead of terminating, we jump to the next rule
3109 * ('goto next_rule', equivalent to a 'break 2'),
3110 * or to the SKIPTO target ('goto again' after
3111 * having set f, cmd and l), respectively.
3112 *
3113 * O_TAG, O_LOG and O_ALTQ action parameters:
3114 * perform some action and set match = 1;
3115 *
3116 * O_LIMIT and O_KEEP_STATE: these opcodes are
3117 * not real 'actions', and are stored right
3118 * before the 'action' part of the rule.
3119 * These opcodes try to install an entry in the
3120 * state tables; if successful, we continue with
3121 * the next opcode (match=1; break;), otherwise
3122 * the packet * must be dropped
3123 * ('goto done' after setting retval);
3124 *
3125 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3126 * cause a lookup of the state table, and a jump
3127 * to the 'action' part of the parent rule
3128 * ('goto check_body') if an entry is found, or
3129 * (CHECK_STATE only) a jump to the next rule if
3130 * the entry is not found ('goto next_rule').
3131 * The result of the lookup is cached to make
3132 * further instances of these opcodes are
3133 * effectively NOPs.
3134 */
3135 case O_LIMIT:
3136 case O_KEEP_STATE:
3137 if (install_state(f,
3138 (ipfw_insn_limit *)cmd, args, tablearg)) {
3139 retval = IP_FW_DENY;
3140 goto done; /* error/limit violation */
3141 }
3142 match = 1;
3143 break;
3144
3145 case O_PROBE_STATE:
3146 case O_CHECK_STATE:
3147 /*
3148 * dynamic rules are checked at the first
3149 * keep-state or check-state occurrence,
3150 * with the result being stored in dyn_dir.
3151 * The compiler introduces a PROBE_STATE
3152 * instruction for us when we have a
3153 * KEEP_STATE (because PROBE_STATE needs
3154 * to be run first).
3155 */
3156 if (dyn_dir == MATCH_UNKNOWN &&
3157 (q = lookup_dyn_rule(&args->f_id,
3158 &dyn_dir, proto == IPPROTO_TCP ?
3159 TCP(ulp) : NULL))
3160 != NULL) {
3161 /*
3162 * Found dynamic entry, update stats
3163 * and jump to the 'action' part of
3164 * the parent rule.
3165 */
3166 q->pcnt++;
3167 q->bcnt += pktlen;
3168 f = q->rule;
3169 cmd = ACTION_PTR(f);
3170 l = f->cmd_len - f->act_ofs;
3171 IPFW_DYN_UNLOCK();
3172 goto check_body;
3173 }
3174 /*
3175 * Dynamic entry not found. If CHECK_STATE,
3176 * skip to next rule, if PROBE_STATE just
3177 * ignore and continue with next opcode.
3178 */
3179 if (cmd->opcode == O_CHECK_STATE)
3180 goto next_rule;
3181 match = 1;
3182 break;
3183
3184 case O_ACCEPT:
3185 retval = 0; /* accept */
3186 goto done;
3187
3188 case O_PIPE:
3189 case O_QUEUE:
3190 args->rule = f; /* report matching rule */
3191 if (cmd->arg1 == IP_FW_TABLEARG)
3192 args->cookie = tablearg;
3193 else
3194 args->cookie = cmd->arg1;
3195 retval = IP_FW_DUMMYNET;
3196 goto done;
3197
3198 case O_DIVERT:
3199 case O_TEE: {
3200 struct divert_tag *dt;
3201
3202 if (args->eh) /* not on layer 2 */
3203 break;
3204 mtag = m_tag_get(PACKET_TAG_DIVERT,
3205 sizeof(struct divert_tag),
3206 M_NOWAIT);
3207 if (mtag == NULL) {
3208 /* XXX statistic */
3209 /* drop packet */
3210 IPFW_RUNLOCK(chain);
3211 return (IP_FW_DENY);
3212 }
3213 dt = (struct divert_tag *)(mtag+1);
3214 dt->cookie = f->rulenum;
3215 if (cmd->arg1 == IP_FW_TABLEARG)
3216 dt->info = tablearg;
3217 else
3218 dt->info = cmd->arg1;
3219 m_tag_prepend(m, mtag);
3220 retval = (cmd->opcode == O_DIVERT) ?
3221 IP_FW_DIVERT : IP_FW_TEE;
3222 goto done;
3223 }
3224
3225 case O_COUNT:
3226 case O_SKIPTO:
3227 f->pcnt++; /* update stats */
3228 f->bcnt += pktlen;
3229 f->timestamp = time_uptime;
3230 if (cmd->opcode == O_COUNT)
3231 goto next_rule;
3232 /* handle skipto */
3233 if (cmd->arg1 == IP_FW_TABLEARG) {
3234 f = lookup_next_rule(f, tablearg);
3235 } else {
3236 if (f->next_rule == NULL)
3237 lookup_next_rule(f, 0);
3238 f = f->next_rule;
3239 }
3240 goto again;
3241
3242 case O_REJECT:
3243 /*
3244 * Drop the packet and send a reject notice
3245 * if the packet is not ICMP (or is an ICMP
3246 * query), and it is not multicast/broadcast.
3247 */
3248 if (hlen > 0 && is_ipv4 && offset == 0 &&
3249 (proto != IPPROTO_ICMP ||
3250 is_icmp_query(ICMP(ulp))) &&
3251 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3252 !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3253 send_reject(args, cmd->arg1, ip_len, ip);
3254 m = args->m;
3255 }
3256 /* FALLTHROUGH */
3257 #ifdef INET6
3258 case O_UNREACH6:
3259 if (hlen > 0 && is_ipv6 &&
3260 ((offset & IP6F_OFF_MASK) == 0) &&
3261 (proto != IPPROTO_ICMPV6 ||
3262 (is_icmp6_query(args->f_id.flags) == 1)) &&
3263 !(m->m_flags & (M_BCAST|M_MCAST)) &&
3264 !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3265 send_reject6(
3266 args, cmd->arg1, hlen,
3267 (struct ip6_hdr *)ip);
3268 m = args->m;
3269 }
3270 /* FALLTHROUGH */
3271 #endif
3272 case O_DENY:
3273 retval = IP_FW_DENY;
3274 goto done;
3275
3276 case O_FORWARD_IP: {
3277 struct sockaddr_in *sa;
3278 sa = &(((ipfw_insn_sa *)cmd)->sa);
3279 if (args->eh) /* not valid on layer2 pkts */
3280 break;
3281 if (!q || dyn_dir == MATCH_FORWARD) {
3282 if (sa->sin_addr.s_addr == INADDR_ANY) {
3283 bcopy(sa, &args->hopstore,
3284 sizeof(*sa));
3285 args->hopstore.sin_addr.s_addr =
3286 htonl(tablearg);
3287 args->next_hop =
3288 &args->hopstore;
3289 } else {
3290 args->next_hop = sa;
3291 }
3292 }
3293 retval = IP_FW_PASS;
3294 }
3295 goto done;
3296
3297 case O_NETGRAPH:
3298 case O_NGTEE:
3299 args->rule = f; /* report matching rule */
3300 if (cmd->arg1 == IP_FW_TABLEARG)
3301 args->cookie = tablearg;
3302 else
3303 args->cookie = cmd->arg1;
3304 retval = (cmd->opcode == O_NETGRAPH) ?
3305 IP_FW_NETGRAPH : IP_FW_NGTEE;
3306 goto done;
3307
3308 case O_SETFIB:
3309 f->pcnt++; /* update stats */
3310 f->bcnt += pktlen;
3311 f->timestamp = time_uptime;
3312 M_SETFIB(m, cmd->arg1);
3313 args->f_id.fib = cmd->arg1;
3314 goto next_rule;
3315
3316 case O_NAT: {
3317 struct cfg_nat *t;
3318 int nat_id;
3319
3320 if (IPFW_NAT_LOADED) {
3321 args->rule = f; /* Report matching rule. */
3322 t = ((ipfw_insn_nat *)cmd)->nat;
3323 if (t == NULL) {
3324 nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3325 tablearg : cmd->arg1;
3326 LOOKUP_NAT(layer3_chain, nat_id, t);
3327 if (t == NULL) {
3328 retval = IP_FW_DENY;
3329 goto done;
3330 }
3331 if (cmd->arg1 != IP_FW_TABLEARG)
3332 ((ipfw_insn_nat *)cmd)->nat = t;
3333 }
3334 retval = ipfw_nat_ptr(args, t, m);
3335 } else
3336 retval = IP_FW_DENY;
3337 goto done;
3338 }
3339
3340 default:
3341 panic("-- unknown opcode %d\n", cmd->opcode);
3342 } /* end of switch() on opcodes */
3343
3344 if (cmd->len & F_NOT)
3345 match = !match;
3346
3347 if (match) {
3348 if (cmd->len & F_OR)
3349 skip_or = 1;
3350 } else {
3351 if (!(cmd->len & F_OR)) /* not an OR block, */
3352 break; /* try next rule */
3353 }
3354
3355 } /* end of inner for, scan opcodes */
3356
3357 next_rule:; /* try next rule */
3358
3359 } /* end of outer for, scan rules */
3360 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3361 IPFW_RUNLOCK(chain);
3362 return (IP_FW_DENY);
3363
3364 done:
3365 /* Update statistics */
3366 f->pcnt++;
3367 f->bcnt += pktlen;
3368 f->timestamp = time_uptime;
3369 IPFW_RUNLOCK(chain);
3370 return (retval);
3371
3372 pullup_failed:
3373 if (fw_verbose)
3374 printf("ipfw: pullup failed\n");
3375 return (IP_FW_DENY);
3376 }
3377
3378 /*
3379 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3380 * These will be reconstructed on the fly as packets are matched.
3381 */
3382 static void
3383 flush_rule_ptrs(struct ip_fw_chain *chain)
3384 {
3385 struct ip_fw *rule;
3386
3387 IPFW_WLOCK_ASSERT(chain);
3388
3389 for (rule = chain->rules; rule; rule = rule->next)
3390 rule->next_rule = NULL;
3391 }
3392
3393 /*
3394 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3395 * possibly create a rule number and add the rule to the list.
3396 * Update the rule_number in the input struct so the caller knows it as well.
3397 */
3398 static int
3399 add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3400 {
3401 struct ip_fw *rule, *f, *prev;
3402 int l = RULESIZE(input_rule);
3403
3404 if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3405 return (EINVAL);
3406
3407 rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3408 if (rule == NULL)
3409 return (ENOSPC);
3410
3411 bcopy(input_rule, rule, l);
3412
3413 rule->next = NULL;
3414 rule->next_rule = NULL;
3415
3416 rule->pcnt = 0;
3417 rule->bcnt = 0;
3418 rule->timestamp = 0;
3419
3420 IPFW_WLOCK(chain);
3421
3422 if (chain->rules == NULL) { /* default rule */
3423 chain->rules = rule;
3424 goto done;
3425 }
3426
3427 /*
3428 * If rulenum is 0, find highest numbered rule before the
3429 * default rule, and add autoinc_step
3430 */
3431 if (autoinc_step < 1)
3432 autoinc_step = 1;
3433 else if (autoinc_step > 1000)
3434 autoinc_step = 1000;
3435 if (rule->rulenum == 0) {
3436 /*
3437 * locate the highest numbered rule before default
3438 */
3439 for (f = chain->rules; f; f = f->next) {
3440 if (f->rulenum == IPFW_DEFAULT_RULE)
3441 break;
3442 rule->rulenum = f->rulenum;
3443 }
3444 if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
3445 rule->rulenum += autoinc_step;
3446 input_rule->rulenum = rule->rulenum;
3447 }
3448
3449 /*
3450 * Now insert the new rule in the right place in the sorted list.
3451 */
3452 for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3453 if (f->rulenum > rule->rulenum) { /* found the location */
3454 if (prev) {
3455 rule->next = f;
3456 prev->next = rule;
3457 } else { /* head insert */
3458 rule->next = chain->rules;
3459 chain->rules = rule;
3460 }
3461 break;
3462 }
3463 }
3464 flush_rule_ptrs(chain);
3465 done:
3466 static_count++;
3467 static_len += l;
3468 IPFW_WUNLOCK(chain);
3469 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3470 rule->rulenum, static_count);)
3471 return (0);
3472 }
3473
3474 /**
3475 * Remove a static rule (including derived * dynamic rules)
3476 * and place it on the ``reap list'' for later reclamation.
3477 * The caller is in charge of clearing rule pointers to avoid
3478 * dangling pointers.
3479 * @return a pointer to the next entry.
3480 * Arguments are not checked, so they better be correct.
3481 */
3482 static struct ip_fw *
3483 remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3484 struct ip_fw *prev)
3485 {
3486 struct ip_fw *n;
3487 int l = RULESIZE(rule);
3488
3489 IPFW_WLOCK_ASSERT(chain);
3490
3491 n = rule->next;
3492 IPFW_DYN_LOCK();
3493 remove_dyn_rule(rule, NULL /* force removal */);
3494 IPFW_DYN_UNLOCK();
3495 if (prev == NULL)
3496 chain->rules = n;
3497 else
3498 prev->next = n;
3499 static_count--;
3500 static_len -= l;
3501
3502 rule->next = chain->reap;
3503 chain->reap = rule;
3504
3505 return n;
3506 }
3507
3508 /**
3509 * Reclaim storage associated with a list of rules. This is
3510 * typically the list created using remove_rule.
3511 */
3512 static void
3513 reap_rules(struct ip_fw *head)
3514 {
3515 struct ip_fw *rule;
3516
3517 while ((rule = head) != NULL) {
3518 head = head->next;
3519 if (DUMMYNET_LOADED)
3520 ip_dn_ruledel_ptr(rule);
3521 free(rule, M_IPFW);
3522 }
3523 }
3524
3525 /*
3526 * Remove all rules from a chain (except rules in set RESVD_SET
3527 * unless kill_default = 1). The caller is responsible for
3528 * reclaiming storage for the rules left in chain->reap.
3529 */
3530 static void
3531 free_chain(struct ip_fw_chain *chain, int kill_default)
3532 {
3533 struct ip_fw *prev, *rule;
3534
3535 IPFW_WLOCK_ASSERT(chain);
3536
3537 flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3538 for (prev = NULL, rule = chain->rules; rule ; )
3539 if (kill_default || rule->set != RESVD_SET)
3540 rule = remove_rule(chain, rule, prev);
3541 else {
3542 prev = rule;
3543 rule = rule->next;
3544 }
3545 }
3546
3547 /**
3548 * Remove all rules with given number, and also do set manipulation.
3549 * Assumes chain != NULL && *chain != NULL.
3550 *
3551 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3552 * the next 8 bits are the new set, the top 8 bits are the command:
3553 *
3554 * 0 delete rules with given number
3555 * 1 delete rules with given set number
3556 * 2 move rules with given number to new set
3557 * 3 move rules with given set number to new set
3558 * 4 swap sets with given numbers
3559 * 5 delete rules with given number and with given set number
3560 */
3561 static int
3562 del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3563 {
3564 struct ip_fw *prev = NULL, *rule;
3565 u_int16_t rulenum; /* rule or old_set */
3566 u_int8_t cmd, new_set;
3567
3568 rulenum = arg & 0xffff;
3569 cmd = (arg >> 24) & 0xff;
3570 new_set = (arg >> 16) & 0xff;
3571
3572 if (cmd > 5 || new_set > RESVD_SET)
3573 return EINVAL;
3574 if (cmd == 0 || cmd == 2 || cmd == 5) {
3575 if (rulenum >= IPFW_DEFAULT_RULE)
3576 return EINVAL;
3577 } else {
3578 if (rulenum > RESVD_SET) /* old_set */
3579 return EINVAL;
3580 }
3581
3582 IPFW_WLOCK(chain);
3583 rule = chain->rules;
3584 chain->reap = NULL;
3585 switch (cmd) {
3586 case 0: /* delete rules with given number */
3587 /*
3588 * locate first rule to delete
3589 */
3590 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3591 ;
3592 if (rule->rulenum != rulenum) {
3593 IPFW_WUNLOCK(chain);
3594 return EINVAL;
3595 }
3596
3597 /*
3598 * flush pointers outside the loop, then delete all matching
3599 * rules. prev remains the same throughout the cycle.
3600 */
3601 flush_rule_ptrs(chain);
3602 while (rule->rulenum == rulenum)
3603 rule = remove_rule(chain, rule, prev);
3604 break;
3605
3606 case 1: /* delete all rules with given set number */
3607 flush_rule_ptrs(chain);
3608 rule = chain->rules;
3609 while (rule->rulenum < IPFW_DEFAULT_RULE)
3610 if (rule->set == rulenum)
3611 rule = remove_rule(chain, rule, prev);
3612 else {
3613 prev = rule;
3614 rule = rule->next;
3615 }
3616 break;
3617
3618 case 2: /* move rules with given number to new set */
3619 rule = chain->rules;
3620 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3621 if (rule->rulenum == rulenum)
3622 rule->set = new_set;
3623 break;
3624
3625 case 3: /* move rules with given set number to new set */
3626 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3627 if (rule->set == rulenum)
3628 rule->set = new_set;
3629 break;
3630
3631 case 4: /* swap two sets */
3632 for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3633 if (rule->set == rulenum)
3634 rule->set = new_set;
3635 else if (rule->set == new_set)
3636 rule->set = rulenum;
3637 break;
3638 case 5: /* delete rules with given number and with given set number.
3639 * rulenum - given rule number;
3640 * new_set - given set number.
3641 */
3642 for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3643 ;
3644 if (rule->rulenum != rulenum) {
3645 IPFW_WUNLOCK(chain);
3646 return (EINVAL);
3647 }
3648 flush_rule_ptrs(chain);
3649 while (rule->rulenum == rulenum) {
3650 if (rule->set == new_set)
3651 rule = remove_rule(chain, rule, prev);
3652 else {
3653 prev = rule;
3654 rule = rule->next;
3655 }
3656 }
3657 }
3658 /*
3659 * Look for rules to reclaim. We grab the list before
3660 * releasing the lock then reclaim them w/o the lock to
3661 * avoid a LOR with dummynet.
3662 */
3663 rule = chain->reap;
3664 chain->reap = NULL;
3665 IPFW_WUNLOCK(chain);
3666 if (rule)
3667 reap_rules(rule);
3668 return 0;
3669 }
3670
3671 /*
3672 * Clear counters for a specific rule.
3673 * The enclosing "table" is assumed locked.
3674 */
3675 static void
3676 clear_counters(struct ip_fw *rule, int log_only)
3677 {
3678 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3679
3680 if (log_only == 0) {
3681 rule->bcnt = rule->pcnt = 0;
3682 rule->timestamp = 0;
3683 }
3684 if (l->o.opcode == O_LOG)
3685 l->log_left = l->max_log;
3686 }
3687
3688 /**
3689 * Reset some or all counters on firewall rules.
3690 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3691 * the next 8 bits are the set number, the top 8 bits are the command:
3692 * 0 work with rules from all set's;
3693 * 1 work with rules only from specified set.
3694 * Specified rule number is zero if we want to clear all entries.
3695 * log_only is 1 if we only want to reset logs, zero otherwise.
3696 */
3697 static int
3698 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3699 {
3700 struct ip_fw *rule;
3701 char *msg;
3702
3703 uint16_t rulenum = arg & 0xffff;
3704 uint8_t set = (arg >> 16) & 0xff;
3705 uint8_t cmd = (arg >> 24) & 0xff;
3706
3707 if (cmd > 1)
3708 return (EINVAL);
3709 if (cmd == 1 && set > RESVD_SET)
3710 return (EINVAL);
3711
3712 IPFW_WLOCK(chain);
3713 if (rulenum == 0) {
3714 norule_counter = 0;
3715 for (rule = chain->rules; rule; rule = rule->next) {
3716 /* Skip rules from another set. */
3717 if (cmd == 1 && rule->set != set)
3718 continue;
3719 clear_counters(rule, log_only);
3720 }
3721 msg = log_only ? "ipfw: All logging counts reset.\n" :
3722 "ipfw: Accounting cleared.\n";
3723 } else {
3724 int cleared = 0;
3725 /*
3726 * We can have multiple rules with the same number, so we
3727 * need to clear them all.
3728 */
3729 for (rule = chain->rules; rule; rule = rule->next)
3730 if (rule->rulenum == rulenum) {
3731 while (rule && rule->rulenum == rulenum) {
3732 if (cmd == 0 || rule->set == set)
3733 clear_counters(rule, log_only);
3734 rule = rule->next;
3735 }
3736 cleared = 1;
3737 break;
3738 }
3739 if (!cleared) { /* we did not find any matching rules */
3740 IPFW_WUNLOCK(chain);
3741 return (EINVAL);
3742 }
3743 msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3744 "ipfw: Entry %d cleared.\n";
3745 }
3746 IPFW_WUNLOCK(chain);
3747
3748 if (fw_verbose)
3749 log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3750 return (0);
3751 }
3752
3753 /*
3754 * Check validity of the structure before insert.
3755 * Fortunately rules are simple, so this mostly need to check rule sizes.
3756 */
3757 static int
3758 check_ipfw_struct(struct ip_fw *rule, int size)
3759 {
3760 int l, cmdlen = 0;
3761 int have_action=0;
3762 ipfw_insn *cmd;
3763
3764 if (size < sizeof(*rule)) {
3765 printf("ipfw: rule too short\n");
3766 return (EINVAL);
3767 }
3768 /* first, check for valid size */
3769 l = RULESIZE(rule);
3770 if (l != size) {
3771 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3772 return (EINVAL);
3773 }
3774 if (rule->act_ofs >= rule->cmd_len) {
3775 printf("ipfw: bogus action offset (%u > %u)\n",
3776 rule->act_ofs, rule->cmd_len - 1);
3777 return (EINVAL);
3778 }
3779 /*
3780 * Now go for the individual checks. Very simple ones, basically only
3781 * instruction sizes.
3782 */
3783 for (l = rule->cmd_len, cmd = rule->cmd ;
3784 l > 0 ; l -= cmdlen, cmd += cmdlen) {
3785 cmdlen = F_LEN(cmd);
3786 if (cmdlen > l) {
3787 printf("ipfw: opcode %d size truncated\n",
3788 cmd->opcode);
3789 return EINVAL;
3790 }
3791 DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3792 switch (cmd->opcode) {
3793 case O_PROBE_STATE:
3794 case O_KEEP_STATE:
3795 case O_PROTO:
3796 case O_IP_SRC_ME:
3797 case O_IP_DST_ME:
3798 case O_LAYER2:
3799 case O_IN:
3800 case O_FRAG:
3801 case O_DIVERTED:
3802 case O_IPOPT:
3803 case O_IPTOS:
3804 case O_IPPRECEDENCE:
3805 case O_IPVER:
3806 case O_TCPWIN:
3807 case O_TCPFLAGS:
3808 case O_TCPOPTS:
3809 case O_ESTAB:
3810 case O_VERREVPATH:
3811 case O_VERSRCREACH:
3812 case O_ANTISPOOF:
3813 case O_IPSEC:
3814 #ifdef INET6
3815 case O_IP6_SRC_ME:
3816 case O_IP6_DST_ME:
3817 case O_EXT_HDR:
3818 case O_IP6:
3819 #endif
3820 case O_IP4:
3821 case O_TAG:
3822 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3823 goto bad_size;
3824 break;
3825
3826 case O_FIB:
3827 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3828 goto bad_size;
3829 if (cmd->arg1 >= rt_numfibs) {
3830 printf("ipfw: invalid fib number %d\n",
3831 cmd->arg1);
3832 return EINVAL;
3833 }
3834 break;
3835
3836 case O_SETFIB:
3837 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3838 goto bad_size;
3839 if (cmd->arg1 >= rt_numfibs) {
3840 printf("ipfw: invalid fib number %d\n",
3841 cmd->arg1);
3842 return EINVAL;
3843 }
3844 goto check_action;
3845
3846 case O_UID:
3847 case O_GID:
3848 case O_JAIL:
3849 case O_IP_SRC:
3850 case O_IP_DST:
3851 case O_TCPSEQ:
3852 case O_TCPACK:
3853 case O_PROB:
3854 case O_ICMPTYPE:
3855 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3856 goto bad_size;
3857 break;
3858
3859 case O_LIMIT:
3860 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3861 goto bad_size;
3862 break;
3863
3864 case O_LOG:
3865 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3866 goto bad_size;
3867
3868 ((ipfw_insn_log *)cmd)->log_left =
3869 ((ipfw_insn_log *)cmd)->max_log;
3870
3871 break;
3872
3873 case O_IP_SRC_MASK:
3874 case O_IP_DST_MASK:
3875 /* only odd command lengths */
3876 if ( !(cmdlen & 1) || cmdlen > 31)
3877 goto bad_size;
3878 break;
3879
3880 case O_IP_SRC_SET:
3881 case O_IP_DST_SET:
3882 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3883 printf("ipfw: invalid set size %d\n",
3884 cmd->arg1);
3885 return EINVAL;
3886 }
3887 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3888 (cmd->arg1+31)/32 )
3889 goto bad_size;
3890 break;
3891
3892 case O_IP_SRC_LOOKUP:
3893 case O_IP_DST_LOOKUP:
3894 if (cmd->arg1 >= IPFW_TABLES_MAX) {
3895 printf("ipfw: invalid table number %d\n",
3896 cmd->arg1);
3897 return (EINVAL);
3898 }
3899 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3900 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3901 goto bad_size;
3902 break;
3903
3904 case O_MACADDR2:
3905 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3906 goto bad_size;
3907 break;
3908
3909 case O_NOP:
3910 case O_IPID:
3911 case O_IPTTL:
3912 case O_IPLEN:
3913 case O_TCPDATALEN:
3914 case O_TAGGED:
3915 if (cmdlen < 1 || cmdlen > 31)
3916 goto bad_size;
3917 break;
3918
3919 case O_MAC_TYPE:
3920 case O_IP_SRCPORT:
3921 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3922 if (cmdlen < 2 || cmdlen > 31)
3923 goto bad_size;
3924 break;
3925
3926 case O_RECV:
3927 case O_XMIT:
3928 case O_VIA:
3929 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3930 goto bad_size;
3931 break;
3932
3933 case O_ALTQ:
3934 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3935 goto bad_size;
3936 break;
3937
3938 case O_PIPE:
3939 case O_QUEUE:
3940 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3941 goto bad_size;
3942 goto check_action;
3943
3944 case O_FORWARD_IP:
3945 #ifdef IPFIREWALL_FORWARD
3946 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3947 goto bad_size;
3948 goto check_action;
3949 #else
3950 return EINVAL;
3951 #endif
3952
3953 case O_DIVERT:
3954 case O_TEE:
3955 if (ip_divert_ptr == NULL)
3956 return EINVAL;
3957 else
3958 goto check_size;
3959 case O_NETGRAPH:
3960 case O_NGTEE:
3961 if (!NG_IPFW_LOADED)
3962 return EINVAL;
3963 else
3964 goto check_size;
3965 case O_NAT:
3966 if (!IPFW_NAT_LOADED)
3967 return EINVAL;
3968 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
3969 goto bad_size;
3970 goto check_action;
3971 case O_FORWARD_MAC: /* XXX not implemented yet */
3972 case O_CHECK_STATE:
3973 case O_COUNT:
3974 case O_ACCEPT:
3975 case O_DENY:
3976 case O_REJECT:
3977 #ifdef INET6
3978 case O_UNREACH6:
3979 #endif
3980 case O_SKIPTO:
3981 check_size:
3982 if (cmdlen != F_INSN_SIZE(ipfw_insn))
3983 goto bad_size;
3984 check_action:
3985 if (have_action) {
3986 printf("ipfw: opcode %d, multiple actions"
3987 " not allowed\n",
3988 cmd->opcode);
3989 return EINVAL;
3990 }
3991 have_action = 1;
3992 if (l != cmdlen) {
3993 printf("ipfw: opcode %d, action must be"
3994 " last opcode\n",
3995 cmd->opcode);
3996 return EINVAL;
3997 }
3998 break;
3999 #ifdef INET6
4000 case O_IP6_SRC:
4001 case O_IP6_DST:
4002 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4003 F_INSN_SIZE(ipfw_insn))
4004 goto bad_size;
4005 break;
4006
4007 case O_FLOW6ID:
4008 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4009 ((ipfw_insn_u32 *)cmd)->o.arg1)
4010 goto bad_size;
4011 break;
4012
4013 case O_IP6_SRC_MASK:
4014 case O_IP6_DST_MASK:
4015 if ( !(cmdlen & 1) || cmdlen > 127)
4016 goto bad_size;
4017 break;
4018 case O_ICMP6TYPE:
4019 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4020 goto bad_size;
4021 break;
4022 #endif
4023
4024 default:
4025 switch (cmd->opcode) {
4026 #ifndef INET6
4027 case O_IP6_SRC_ME:
4028 case O_IP6_DST_ME:
4029 case O_EXT_HDR:
4030 case O_IP6:
4031 case O_UNREACH6:
4032 case O_IP6_SRC:
4033 case O_IP6_DST:
4034 case O_FLOW6ID:
4035 case O_IP6_SRC_MASK:
4036 case O_IP6_DST_MASK:
4037 case O_ICMP6TYPE:
4038 printf("ipfw: no IPv6 support in kernel\n");
4039 return EPROTONOSUPPORT;
4040 #endif
4041 default:
4042 printf("ipfw: opcode %d, unknown opcode\n",
4043 cmd->opcode);
4044 return EINVAL;
4045 }
4046 }
4047 }
4048 if (have_action == 0) {
4049 printf("ipfw: missing action\n");
4050 return EINVAL;
4051 }
4052 return 0;
4053
4054 bad_size:
4055 printf("ipfw: opcode %d size %d wrong\n",
4056 cmd->opcode, cmdlen);
4057 return EINVAL;
4058 }
4059
4060 /*
4061 * Copy the static and dynamic rules to the supplied buffer
4062 * and return the amount of space actually used.
4063 */
4064 static size_t
4065 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4066 {
4067 char *bp = buf;
4068 char *ep = bp + space;
4069 struct ip_fw *rule;
4070 int i;
4071 time_t boot_seconds;
4072
4073 boot_seconds = boottime.tv_sec;
4074 /* XXX this can take a long time and locking will block packet flow */
4075 IPFW_RLOCK(chain);
4076 for (rule = chain->rules; rule ; rule = rule->next) {
4077 /*
4078 * Verify the entry fits in the buffer in case the
4079 * rules changed between calculating buffer space and
4080 * now. This would be better done using a generation
4081 * number but should suffice for now.
4082 */
4083 i = RULESIZE(rule);
4084 if (bp + i <= ep) {
4085 bcopy(rule, bp, i);
4086 /*
4087 * XXX HACK. Store the disable mask in the "next" pointer
4088 * in a wild attempt to keep the ABI the same.
4089 * Why do we do this on EVERY rule?
4090 */
4091 bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
4092 sizeof(set_disable));
4093 if (((struct ip_fw *)bp)->timestamp)
4094 ((struct ip_fw *)bp)->timestamp += boot_seconds;
4095 bp += i;
4096 }
4097 }
4098 IPFW_RUNLOCK(chain);
4099 if (ipfw_dyn_v) {
4100 ipfw_dyn_rule *p, *last = NULL;
4101
4102 IPFW_DYN_LOCK();
4103 for (i = 0 ; i < curr_dyn_buckets; i++)
4104 for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4105 if (bp + sizeof *p <= ep) {
4106 ipfw_dyn_rule *dst =
4107 (ipfw_dyn_rule *)bp;
4108 bcopy(p, dst, sizeof *p);
4109 bcopy(&(p->rule->rulenum), &(dst->rule),
4110 sizeof(p->rule->rulenum));
4111 /*
4112 * store set number into high word of
4113 * dst->rule pointer.
4114 */
4115 bcopy(&(p->rule->set),
4116 (char *)&dst->rule +
4117 sizeof(p->rule->rulenum),
4118 sizeof(p->rule->set));
4119 /*
4120 * store a non-null value in "next".
4121 * The userland code will interpret a
4122 * NULL here as a marker
4123 * for the last dynamic rule.
4124 */
4125 bcopy(&dst, &dst->next, sizeof(dst));
4126 last = dst;
4127 dst->expire =
4128 TIME_LEQ(dst->expire, time_uptime) ?
4129 0 : dst->expire - time_uptime ;
4130 bp += sizeof(ipfw_dyn_rule);
4131 }
4132 }
4133 IPFW_DYN_UNLOCK();
4134 if (last != NULL) /* mark last dynamic rule */
4135 bzero(&last->next, sizeof(last));
4136 }
4137 return (bp - (char *)buf);
4138 }
4139
4140
4141 /**
4142 * {set|get}sockopt parser.
4143 */
4144 static int
4145 ipfw_ctl(struct sockopt *sopt)
4146 {
4147 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4148 int error;
4149 size_t size;
4150 struct ip_fw *buf, *rule;
4151 u_int32_t rulenum[2];
4152
4153 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4154 if (error)
4155 return (error);
4156
4157 /*
4158 * Disallow modifications in really-really secure mode, but still allow
4159 * the logging counters to be reset.
4160 */
4161 if (sopt->sopt_name == IP_FW_ADD ||
4162 (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4163 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4164 if (error)
4165 return (error);
4166 }
4167
4168 error = 0;
4169
4170 switch (sopt->sopt_name) {
4171 case IP_FW_GET:
4172 /*
4173 * pass up a copy of the current rules. Static rules
4174 * come first (the last of which has number IPFW_DEFAULT_RULE),
4175 * followed by a possibly empty list of dynamic rule.
4176 * The last dynamic rule has NULL in the "next" field.
4177 *
4178 * Note that the calculated size is used to bound the
4179 * amount of data returned to the user. The rule set may
4180 * change between calculating the size and returning the
4181 * data in which case we'll just return what fits.
4182 */
4183 size = static_len; /* size of static rules */
4184 if (ipfw_dyn_v) /* add size of dyn.rules */
4185 size += (dyn_count * sizeof(ipfw_dyn_rule));
4186
4187 /*
4188 * XXX todo: if the user passes a short length just to know
4189 * how much room is needed, do not bother filling up the
4190 * buffer, just jump to the sooptcopyout.
4191 */
4192 buf = malloc(size, M_TEMP, M_WAITOK);
4193 error = sooptcopyout(sopt, buf,
4194 ipfw_getrules(&layer3_chain, buf, size));
4195 free(buf, M_TEMP);
4196 break;
4197
4198 case IP_FW_FLUSH:
4199 /*
4200 * Normally we cannot release the lock on each iteration.
4201 * We could do it here only because we start from the head all
4202 * the times so there is no risk of missing some entries.
4203 * On the other hand, the risk is that we end up with
4204 * a very inconsistent ruleset, so better keep the lock
4205 * around the whole cycle.
4206 *
4207 * XXX this code can be improved by resetting the head of
4208 * the list to point to the default rule, and then freeing
4209 * the old list without the need for a lock.
4210 */
4211
4212 IPFW_WLOCK(&layer3_chain);
4213 layer3_chain.reap = NULL;
4214 free_chain(&layer3_chain, 0 /* keep default rule */);
4215 rule = layer3_chain.reap;
4216 layer3_chain.reap = NULL;
4217 IPFW_WUNLOCK(&layer3_chain);
4218 if (rule != NULL)
4219 reap_rules(rule);
4220 break;
4221
4222 case IP_FW_ADD:
4223 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4224 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4225 sizeof(struct ip_fw) );
4226 if (error == 0)
4227 error = check_ipfw_struct(rule, sopt->sopt_valsize);
4228 if (error == 0) {
4229 error = add_rule(&layer3_chain, rule);
4230 size = RULESIZE(rule);
4231 if (!error && sopt->sopt_dir == SOPT_GET)
4232 error = sooptcopyout(sopt, rule, size);
4233 }
4234 free(rule, M_TEMP);
4235 break;
4236
4237 case IP_FW_DEL:
4238 /*
4239 * IP_FW_DEL is used for deleting single rules or sets,
4240 * and (ab)used to atomically manipulate sets. Argument size
4241 * is used to distinguish between the two:
4242 * sizeof(u_int32_t)
4243 * delete single rule or set of rules,
4244 * or reassign rules (or sets) to a different set.
4245 * 2*sizeof(u_int32_t)
4246 * atomic disable/enable sets.
4247 * first u_int32_t contains sets to be disabled,
4248 * second u_int32_t contains sets to be enabled.
4249 */
4250 error = sooptcopyin(sopt, rulenum,
4251 2*sizeof(u_int32_t), sizeof(u_int32_t));
4252 if (error)
4253 break;
4254 size = sopt->sopt_valsize;
4255 if (size == sizeof(u_int32_t)) /* delete or reassign */
4256 error = del_entry(&layer3_chain, rulenum[0]);
4257 else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4258 set_disable =
4259 (set_disable | rulenum[0]) & ~rulenum[1] &
4260 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4261 else
4262 error = EINVAL;
4263 break;
4264
4265 case IP_FW_ZERO:
4266 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4267 rulenum[0] = 0;
4268 if (sopt->sopt_val != 0) {
4269 error = sooptcopyin(sopt, rulenum,
4270 sizeof(u_int32_t), sizeof(u_int32_t));
4271 if (error)
4272 break;
4273 }
4274 error = zero_entry(&layer3_chain, rulenum[0],
4275 sopt->sopt_name == IP_FW_RESETLOG);
4276 break;
4277
4278 case IP_FW_TABLE_ADD:
4279 {
4280 ipfw_table_entry ent;
4281
4282 error = sooptcopyin(sopt, &ent,
4283 sizeof(ent), sizeof(ent));
4284 if (error)
4285 break;
4286 error = add_table_entry(&layer3_chain, ent.tbl,
4287 ent.addr, ent.masklen, ent.value);
4288 }
4289 break;
4290
4291 case IP_FW_TABLE_DEL:
4292 {
4293 ipfw_table_entry ent;
4294
4295 error = sooptcopyin(sopt, &ent,
4296 sizeof(ent), sizeof(ent));
4297 if (error)
4298 break;
4299 error = del_table_entry(&layer3_chain, ent.tbl,
4300 ent.addr, ent.masklen);
4301 }
4302 break;
4303
4304 case IP_FW_TABLE_FLUSH:
4305 {
4306 u_int16_t tbl;
4307
4308 error = sooptcopyin(sopt, &tbl,
4309 sizeof(tbl), sizeof(tbl));
4310 if (error)
4311 break;
4312 IPFW_WLOCK(&layer3_chain);
4313 error = flush_table(&layer3_chain, tbl);
4314 IPFW_WUNLOCK(&layer3_chain);
4315 }
4316 break;
4317
4318 case IP_FW_TABLE_GETSIZE:
4319 {
4320 u_int32_t tbl, cnt;
4321
4322 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4323 sizeof(tbl))))
4324 break;
4325 IPFW_RLOCK(&layer3_chain);
4326 error = count_table(&layer3_chain, tbl, &cnt);
4327 IPFW_RUNLOCK(&layer3_chain);
4328 if (error)
4329 break;
4330 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4331 }
4332 break;
4333
4334 case IP_FW_TABLE_LIST:
4335 {
4336 ipfw_table *tbl;
4337
4338 if (sopt->sopt_valsize < sizeof(*tbl)) {
4339 error = EINVAL;
4340 break;
4341 }
4342 size = sopt->sopt_valsize;
4343 tbl = malloc(size, M_TEMP, M_WAITOK);
4344 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4345 if (error) {
4346 free(tbl, M_TEMP);
4347 break;
4348 }
4349 tbl->size = (size - sizeof(*tbl)) /
4350 sizeof(ipfw_table_entry);
4351 IPFW_RLOCK(&layer3_chain);
4352 error = dump_table(&layer3_chain, tbl);
4353 IPFW_RUNLOCK(&layer3_chain);
4354 if (error) {
4355 free(tbl, M_TEMP);
4356 break;
4357 }
4358 error = sooptcopyout(sopt, tbl, size);
4359 free(tbl, M_TEMP);
4360 }
4361 break;
4362
4363 case IP_FW_NAT_CFG:
4364 {
4365 if (IPFW_NAT_LOADED)
4366 error = ipfw_nat_cfg_ptr(sopt);
4367 else {
4368 printf("IP_FW_NAT_CFG: ipfw_nat not present, please load it.\n");
4369 error = EINVAL;
4370 }
4371 }
4372 break;
4373
4374 case IP_FW_NAT_DEL:
4375 {
4376 if (IPFW_NAT_LOADED)
4377 error = ipfw_nat_del_ptr(sopt);
4378 else {
4379 printf("IP_FW_NAT_DEL: ipfw_nat not present, please load it.\n");
4380 printf("ipfw_nat not loaded: %d\n", sopt->sopt_name);
4381 error = EINVAL;
4382 }
4383 }
4384 break;
4385
4386 case IP_FW_NAT_GET_CONFIG:
4387 {
4388 if (IPFW_NAT_LOADED)
4389 error = ipfw_nat_get_cfg_ptr(sopt);
4390 else {
4391 printf("IP_FW_NAT_GET_CFG: ipfw_nat not present, please load it.\n");
4392 error = EINVAL;
4393 }
4394 }
4395 break;
4396
4397 case IP_FW_NAT_GET_LOG:
4398 {
4399 if (IPFW_NAT_LOADED)
4400 error = ipfw_nat_get_log_ptr(sopt);
4401 else {
4402 printf("IP_FW_NAT_GET_LOG: ipfw_nat not present, please load it.\n");
4403 error = EINVAL;
4404 }
4405 }
4406 break;
4407
4408 default:
4409 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4410 error = EINVAL;
4411 }
4412
4413 return (error);
4414 #undef RULE_MAXSIZE
4415 }
4416
4417 /**
4418 * dummynet needs a reference to the default rule, because rules can be
4419 * deleted while packets hold a reference to them. When this happens,
4420 * dummynet changes the reference to the default rule (it could well be a
4421 * NULL pointer, but this way we do not need to check for the special
4422 * case, plus here he have info on the default behaviour).
4423 */
4424 struct ip_fw *ip_fw_default_rule;
4425
4426 /*
4427 * This procedure is only used to handle keepalives. It is invoked
4428 * every dyn_keepalive_period
4429 */
4430 static void
4431 ipfw_tick(void * __unused unused)
4432 {
4433 struct mbuf *m0, *m, *mnext, **mtailp;
4434 int i;
4435 ipfw_dyn_rule *q;
4436
4437 if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
4438 goto done;
4439
4440 /*
4441 * We make a chain of packets to go out here -- not deferring
4442 * until after we drop the IPFW dynamic rule lock would result
4443 * in a lock order reversal with the normal packet input -> ipfw
4444 * call stack.
4445 */
4446 m0 = NULL;
4447 mtailp = &m0;
4448 IPFW_DYN_LOCK();
4449 for (i = 0 ; i < curr_dyn_buckets ; i++) {
4450 for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
4451 if (q->dyn_type == O_LIMIT_PARENT)
4452 continue;
4453 if (q->id.proto != IPPROTO_TCP)
4454 continue;
4455 if ( (q->state & BOTH_SYN) != BOTH_SYN)
4456 continue;
4457 if (TIME_LEQ( time_uptime+dyn_keepalive_interval,
4458 q->expire))
4459 continue; /* too early */
4460 if (TIME_LEQ(q->expire, time_uptime))
4461 continue; /* too late, rule expired */
4462
4463 *mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4464 q->ack_fwd, TH_SYN);
4465 if (*mtailp != NULL)
4466 mtailp = &(*mtailp)->m_nextpkt;
4467 *mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4468 q->ack_rev, 0);
4469 if (*mtailp != NULL)
4470 mtailp = &(*mtailp)->m_nextpkt;
4471 }
4472 }
4473 IPFW_DYN_UNLOCK();
4474 for (m = mnext = m0; m != NULL; m = mnext) {
4475 mnext = m->m_nextpkt;
4476 m->m_nextpkt = NULL;
4477 ip_output(m, NULL, NULL, 0, NULL, NULL);
4478 }
4479 done:
4480 callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
4481 }
4482
4483 int
4484 ipfw_init(void)
4485 {
4486 struct ip_fw default_rule;
4487 int error;
4488
4489 #ifdef INET6
4490 /* Setup IPv6 fw sysctl tree. */
4491 sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4492 ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4493 SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4494 CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4495 SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4496 OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4497 &fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4498 SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4499 OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4500 &fw_deny_unknown_exthdrs, 0,
4501 "Deny packets with unknown IPv6 Extension Headers");
4502 #endif
4503
4504 layer3_chain.rules = NULL;
4505 IPFW_LOCK_INIT(&layer3_chain);
4506 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4507 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4508 UMA_ALIGN_PTR, 0);
4509 IPFW_DYN_LOCK_INIT();
4510 callout_init(&ipfw_timeout, CALLOUT_MPSAFE);
4511
4512 bzero(&default_rule, sizeof default_rule);
4513
4514 default_rule.act_ofs = 0;
4515 default_rule.rulenum = IPFW_DEFAULT_RULE;
4516 default_rule.cmd_len = 1;
4517 default_rule.set = RESVD_SET;
4518
4519 default_rule.cmd[0].len = 1;
4520 default_rule.cmd[0].opcode =
4521 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4522 1 ? O_ACCEPT :
4523 #endif
4524 O_DENY;
4525
4526 error = add_rule(&layer3_chain, &default_rule);
4527 if (error != 0) {
4528 printf("ipfw2: error %u initializing default rule "
4529 "(support disabled)\n", error);
4530 IPFW_DYN_LOCK_DESTROY();
4531 IPFW_LOCK_DESTROY(&layer3_chain);
4532 uma_zdestroy(ipfw_dyn_rule_zone);
4533 return (error);
4534 }
4535
4536 ip_fw_default_rule = layer3_chain.rules;
4537 printf("ipfw2 "
4538 #ifdef INET6
4539 "(+ipv6) "
4540 #endif
4541 "initialized, divert %s, nat %s, "
4542 "rule-based forwarding "
4543 #ifdef IPFIREWALL_FORWARD
4544 "enabled, "
4545 #else
4546 "disabled, "
4547 #endif
4548 "default to %s, logging ",
4549 #ifdef IPDIVERT
4550 "enabled",
4551 #else
4552 "loadable",
4553 #endif
4554 #ifdef IPFIREWALL_NAT
4555 "enabled",
4556 #else
4557 "loadable",
4558 #endif
4559
4560 default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4561
4562 #ifdef IPFIREWALL_VERBOSE
4563 fw_verbose = 1;
4564 #endif
4565 #ifdef IPFIREWALL_VERBOSE_LIMIT
4566 verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4567 #endif
4568 if (fw_verbose == 0)
4569 printf("disabled\n");
4570 else if (verbose_limit == 0)
4571 printf("unlimited\n");
4572 else
4573 printf("limited to %d packets/entry by default\n",
4574 verbose_limit);
4575
4576 error = init_tables(&layer3_chain);
4577 if (error) {
4578 IPFW_DYN_LOCK_DESTROY();
4579 IPFW_LOCK_DESTROY(&layer3_chain);
4580 uma_zdestroy(ipfw_dyn_rule_zone);
4581 return (error);
4582 }
4583 ip_fw_ctl_ptr = ipfw_ctl;
4584 ip_fw_chk_ptr = ipfw_chk;
4585 callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
4586 LIST_INIT(&layer3_chain.nat);
4587 return (0);
4588 }
4589
4590 void
4591 ipfw_destroy(void)
4592 {
4593 struct ip_fw *reap;
4594
4595 ip_fw_chk_ptr = NULL;
4596 ip_fw_ctl_ptr = NULL;
4597 callout_drain(&ipfw_timeout);
4598 IPFW_WLOCK(&layer3_chain);
4599 flush_tables(&layer3_chain);
4600 layer3_chain.reap = NULL;
4601 free_chain(&layer3_chain, 1 /* kill default rule */);
4602 reap = layer3_chain.reap, layer3_chain.reap = NULL;
4603 IPFW_WUNLOCK(&layer3_chain);
4604 if (reap != NULL)
4605 reap_rules(reap);
4606 IPFW_DYN_LOCK_DESTROY();
4607 uma_zdestroy(ipfw_dyn_rule_zone);
4608 if (ipfw_dyn_v != NULL)
4609 free(ipfw_dyn_v, M_IPFW);
4610 IPFW_LOCK_DESTROY(&layer3_chain);
4611
4612 #ifdef INET6
4613 /* Free IPv6 fw sysctl tree. */
4614 sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4615 #endif
4616
4617 printf("IP firewall unloaded\n");
4618 }
Cache object: dc363d8681d6042584910dc222ce6fb5
|