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