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