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