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