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