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