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