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