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