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