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