2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 * Copyright (c) 2014 Yandex LLC
4 * Copyright (c) 2014 Alexander V. Chernikov
6 * Supported by: Valeria Paoli
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
34 * Control socket and rule management routines for ipfw.
35 * Control is currently implemented via IP_FW3 setsockopt() code.
41 #error IPFIREWALL requires INET.
43 #include "opt_inet6.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h> /* struct m_tag used by nested headers */
49 #include <sys/kernel.h>
53 #include <sys/rwlock.h>
54 #include <sys/rmlock.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/fnv_hash.h>
61 #include <net/route.h>
64 #include <vm/vm_extern.h>
66 #include <netinet/in.h>
67 #include <netinet/ip_var.h> /* hooks */
68 #include <netinet/ip_fw.h>
70 #include <netpfil/ipfw/ip_fw_private.h>
71 #include <netpfil/ipfw/ip_fw_table.h>
74 #include <security/mac/mac_framework.h>
77 static int ipfw_ctl(struct sockopt *sopt);
78 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
79 struct rule_check_info *ci);
80 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
81 struct rule_check_info *ci);
82 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
83 struct rule_check_info *ci);
84 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
85 struct rule_check_info *ci);
87 #define NAMEDOBJ_HASH_SIZE 32
89 struct namedobj_instance {
90 struct namedobjects_head *names;
91 struct namedobjects_head *values;
92 uint32_t nn_size; /* names hash size */
93 uint32_t nv_size; /* number hash size */
94 u_long *idx_mask; /* used items bitmask */
95 uint32_t max_blocks; /* number of "long" blocks in bitmask */
96 uint32_t count; /* number of items */
97 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
98 objhash_hash_f *hash_f;
101 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
103 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
104 const void *key, uint32_t kopt);
105 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
106 static int objhash_cmp_name(struct named_object *no, const void *name,
109 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
111 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
112 struct sockopt_data *sd);
113 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
114 struct sockopt_data *sd);
115 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
116 struct sockopt_data *sd);
117 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
118 struct sockopt_data *sd);
119 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
120 struct sockopt_data *sd);
121 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
122 struct sockopt_data *sd);
123 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
124 struct sockopt_data *sd);
125 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
126 struct sockopt_data *sd);
128 /* ctl3 handler data */
129 struct mtx ctl3_lock;
130 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
131 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
132 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
133 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
135 static struct ipfw_sopt_handler *ctl3_handlers;
136 static size_t ctl3_hsize;
137 static uint64_t ctl3_refct, ctl3_gencnt;
138 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
139 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
141 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
143 static struct ipfw_sopt_handler scodes[] = {
144 { IP_FW_XGET, 0, HDIR_GET, dump_config },
145 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
146 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
147 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
148 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
149 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
150 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
151 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
152 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
153 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
154 { IP_FW_DUMP_SRVOBJECTS,0, HDIR_GET, dump_srvobjects },
158 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
159 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
160 uint16_t *puidx, uint8_t *ptype);
161 static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
163 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
164 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
165 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
166 struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
167 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
168 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
169 struct obj_idx *oib, struct obj_idx *end);
170 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
171 struct sockopt_data *sd);
174 * Opcode object rewriter variables
176 struct opcode_obj_rewrite *ctl3_rewriters;
177 static size_t ctl3_rsize;
180 * static variables followed by global ones
183 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
184 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
190 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
191 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
192 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
196 ipfw_destroy_counters()
199 uma_zdestroy(V_ipfw_cntr_zone);
203 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
207 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
208 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
214 free_rule(struct ip_fw *rule)
217 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
223 * Find the smallest rule >= key, id.
224 * We could use bsearch but it is so simple that we code it directly
227 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
232 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
235 if (r->rulenum < key)
236 lo = i + 1; /* continue from the next one */
237 else if (r->rulenum > key)
238 hi = i; /* this might be good */
240 lo = i + 1; /* continue from the next one */
241 else /* r->id >= id */
242 hi = i; /* this might be good */
248 * Builds skipto cache on rule set @map.
251 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
256 IPFW_UH_WLOCK_ASSERT(chain);
259 rulenum = map[mi]->rulenum;
260 smap = chain->idxmap_back;
265 for (i = 0; i < 65536; i++) {
267 /* Use the same rule index until i < rulenum */
268 if (i != rulenum || i == 65535)
270 /* Find next rule with num > i */
271 rulenum = map[++mi]->rulenum;
273 rulenum = map[++mi]->rulenum;
278 * Swaps prepared (backup) index with current one.
281 swap_skipto_cache(struct ip_fw_chain *chain)
285 IPFW_UH_WLOCK_ASSERT(chain);
286 IPFW_WLOCK_ASSERT(chain);
289 chain->idxmap = chain->idxmap_back;
290 chain->idxmap_back = map;
294 * Allocate and initialize skipto cache.
297 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
299 int *idxmap, *idxmap_back;
301 idxmap = malloc(65536 * sizeof(uint32_t *), M_IPFW,
303 idxmap_back = malloc(65536 * sizeof(uint32_t *), M_IPFW,
307 * Note we may be called at any time after initialization,
308 * for example, on first skipto rule, so we need to
309 * provide valid chain->idxmap on return
312 IPFW_UH_WLOCK(chain);
313 if (chain->idxmap != NULL) {
314 IPFW_UH_WUNLOCK(chain);
315 free(idxmap, M_IPFW);
316 free(idxmap_back, M_IPFW);
320 /* Set backup pointer first to permit building cache */
321 chain->idxmap_back = idxmap_back;
322 update_skipto_cache(chain, chain->map);
324 /* It is now safe to set chain->idxmap ptr */
325 chain->idxmap = idxmap;
326 swap_skipto_cache(chain);
328 IPFW_UH_WUNLOCK(chain);
332 * Destroys skipto cache.
335 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
338 if (chain->idxmap != NULL)
339 free(chain->idxmap, M_IPFW);
340 if (chain->idxmap != NULL)
341 free(chain->idxmap_back, M_IPFW);
346 * allocate a new map, returns the chain locked. extra is the number
347 * of entries to add or delete.
349 static struct ip_fw **
350 get_map(struct ip_fw_chain *chain, int extra, int locked)
357 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
359 i = chain->n_rules + extra;
360 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
362 printf("%s: cannot allocate map\n", __FUNCTION__);
366 IPFW_UH_WLOCK(chain);
367 if (i >= chain->n_rules + extra) /* good */
369 /* otherwise we lost the race, free and retry */
371 IPFW_UH_WUNLOCK(chain);
377 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
379 static struct ip_fw **
380 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
382 struct ip_fw **old_map;
386 chain->n_rules = new_len;
387 old_map = chain->map;
388 chain->map = new_map;
389 swap_skipto_cache(chain);
396 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
398 struct timeval boottime;
400 cntr->size = sizeof(*cntr);
402 if (krule->cntr != NULL) {
403 cntr->pcnt = counter_u64_fetch(krule->cntr);
404 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
405 cntr->timestamp = krule->timestamp;
407 if (cntr->timestamp > 0) {
408 getboottime(&boottime);
409 cntr->timestamp += boottime.tv_sec;
414 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
416 struct timeval boottime;
418 if (krule->cntr != NULL) {
419 cntr->pcnt = counter_u64_fetch(krule->cntr);
420 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
421 cntr->timestamp = krule->timestamp;
423 if (cntr->timestamp > 0) {
424 getboottime(&boottime);
425 cntr->timestamp += boottime.tv_sec;
430 * Copies rule @urule from v1 userland format (current).
432 * Assume @krule is zeroed.
435 import_rule1(struct rule_check_info *ci)
437 struct ip_fw_rule *urule;
440 urule = (struct ip_fw_rule *)ci->urule;
441 krule = (struct ip_fw *)ci->krule;
444 krule->act_ofs = urule->act_ofs;
445 krule->cmd_len = urule->cmd_len;
446 krule->rulenum = urule->rulenum;
447 krule->set = urule->set;
448 krule->flags = urule->flags;
450 /* Save rulenum offset */
451 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
454 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
458 * Export rule into v1 format (Current).
460 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
462 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
464 * Assume @data is zeroed.
467 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
469 struct ip_fw_bcounter *cntr;
470 struct ip_fw_rule *urule;
473 /* Fill in TLV header */
474 tlv = (ipfw_obj_tlv *)data;
475 tlv->type = IPFW_TLV_RULE_ENT;
480 cntr = (struct ip_fw_bcounter *)(tlv + 1);
481 urule = (struct ip_fw_rule *)(cntr + 1);
482 export_cntr1_base(krule, cntr);
484 urule = (struct ip_fw_rule *)(tlv + 1);
487 urule->act_ofs = krule->act_ofs;
488 urule->cmd_len = krule->cmd_len;
489 urule->rulenum = krule->rulenum;
490 urule->set = krule->set;
491 urule->flags = krule->flags;
492 urule->id = krule->id;
495 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
500 * Copies rule @urule from FreeBSD8 userland format (v0)
502 * Assume @krule is zeroed.
505 import_rule0(struct rule_check_info *ci)
507 struct ip_fw_rule0 *urule;
511 ipfw_insn_limit *lcmd;
514 urule = (struct ip_fw_rule0 *)ci->urule;
515 krule = (struct ip_fw *)ci->krule;
518 krule->act_ofs = urule->act_ofs;
519 krule->cmd_len = urule->cmd_len;
520 krule->rulenum = urule->rulenum;
521 krule->set = urule->set;
522 if ((urule->_pad & 1) != 0)
523 krule->flags |= IPFW_RULE_NOOPT;
525 /* Save rulenum offset */
526 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
529 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
533 * 1) convert tablearg value from 65535 to 0
534 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
536 * 3) convert table number in iface opcodes to u16
537 * 4) convert old `nat global` into new 65535
543 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
546 switch (cmd->opcode) {
547 /* Opcodes supporting tablearg */
559 if (cmd->arg1 == IP_FW_TABLEARG)
560 cmd->arg1 = IP_FW_TARG;
561 else if (cmd->arg1 == 0)
562 cmd->arg1 = IP_FW_NAT44_GLOBAL;
566 if (cmd->arg1 == IP_FW_TABLEARG)
567 cmd->arg1 = IP_FW_TARG;
572 lcmd = (ipfw_insn_limit *)cmd;
573 if (lcmd->conn_limit == IP_FW_TABLEARG)
574 lcmd->conn_limit = IP_FW_TARG;
576 /* Interface tables */
580 /* Interface table, possibly */
581 cmdif = (ipfw_insn_if *)cmd;
582 if (cmdif->name[0] != '\1')
585 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
592 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
595 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
599 ipfw_insn_limit *lcmd;
603 memset(urule, 0, len);
604 urule->act_ofs = krule->act_ofs;
605 urule->cmd_len = krule->cmd_len;
606 urule->rulenum = krule->rulenum;
607 urule->set = krule->set;
608 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
612 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
614 /* Export counters */
615 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
619 * 1) convert tablearg value from 0 to 65535
620 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
621 * 3) convert table number in iface opcodes to int
627 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
630 switch (cmd->opcode) {
631 /* Opcodes supporting tablearg */
643 if (cmd->arg1 == IP_FW_TARG)
644 cmd->arg1 = IP_FW_TABLEARG;
645 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
650 if (cmd->arg1 == IP_FW_TARG)
651 cmd->arg1 = IP_FW_TABLEARG;
653 cmd->arg1 &= ~0x8000;
656 lcmd = (ipfw_insn_limit *)cmd;
657 if (lcmd->conn_limit == IP_FW_TARG)
658 lcmd->conn_limit = IP_FW_TABLEARG;
660 /* Interface tables */
664 /* Interface table, possibly */
665 cmdif = (ipfw_insn_if *)cmd;
666 if (cmdif->name[0] != '\1')
669 cmdif->p.glob = cmdif->p.kidx;
676 * Add new rule(s) to the list possibly creating rule number for each.
677 * Update the rule_number in the input struct so the caller knows it as well.
678 * Must be called without IPFW_UH held
681 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
683 int error, i, insert_before, tcount;
684 uint16_t rulenum, *pnum;
685 struct rule_check_info *ci;
687 struct ip_fw **map; /* the new array of pointers */
689 /* Check if we need to do table/obj index remap */
691 for (ci = rci, i = 0; i < count; ci++, i++) {
692 if (ci->object_opcodes == 0)
696 * Rule has some object opcodes.
697 * We need to find (and create non-existing)
698 * kernel objects, and reference existing ones.
700 error = rewrite_rule_uidx(chain, ci);
704 * rewrite failed, state for current rule
705 * has been reverted. Check if we need to
711 * We have some more table rules
712 * we need to rollback.
715 IPFW_UH_WLOCK(chain);
718 if (ci->object_opcodes == 0)
720 unref_rule_objects(chain,ci->krule);
723 IPFW_UH_WUNLOCK(chain);
733 /* get_map returns with IPFW_UH_WLOCK if successful */
734 map = get_map(chain, count, 0 /* not locked */);
738 IPFW_UH_WLOCK(chain);
739 for (ci = rci, i = 0; i < count; ci++, i++) {
740 if (ci->object_opcodes == 0)
743 unref_rule_objects(chain, ci->krule);
745 IPFW_UH_WUNLOCK(chain);
751 if (V_autoinc_step < 1)
753 else if (V_autoinc_step > 1000)
754 V_autoinc_step = 1000;
756 /* FIXME: Handle count > 1 */
759 rulenum = krule->rulenum;
761 /* find the insertion point, we will insert before */
762 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
763 i = ipfw_find_rule(chain, insert_before, 0);
764 /* duplicate first part */
766 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
768 /* duplicate remaining part, we always have the default rule */
769 bcopy(chain->map + i, map + i + 1,
770 sizeof(struct ip_fw *) *(chain->n_rules - i));
772 /* Compute rule number and write it back */
773 rulenum = i > 0 ? map[i-1]->rulenum : 0;
774 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
775 rulenum += V_autoinc_step;
776 krule->rulenum = rulenum;
777 /* Save number to userland rule */
778 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
782 krule->id = chain->id + 1;
783 update_skipto_cache(chain, map);
784 map = swap_map(chain, map, chain->n_rules + 1);
785 chain->static_len += RULEUSIZE0(krule);
786 IPFW_UH_WUNLOCK(chain);
793 * Adds @rule to the list of rules to reap
796 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
800 IPFW_UH_WLOCK_ASSERT(chain);
802 /* Unlink rule from everywhere */
803 unref_rule_objects(chain, rule);
805 *((struct ip_fw **)rule) = *head;
810 * Reclaim storage associated with a list of rules. This is
811 * typically the list created using remove_rule.
812 * A NULL pointer on input is handled correctly.
815 ipfw_reap_rules(struct ip_fw *head)
819 while ((rule = head) != NULL) {
820 head = *((struct ip_fw **)head);
827 * (default || reserved || !match_set || !match_number)
829 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
830 * // the default rule is always protected
832 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
833 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
835 * match_set ::= (cmd == 0 || rule->set == set)
836 * // set number is ignored for cmd == 0
838 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
839 * // number is ignored for cmd == 1 or n == 0
843 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
846 /* Don't match default rule for modification queries */
847 if (rule->rulenum == IPFW_DEFAULT_RULE &&
848 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
851 /* Don't match rules in reserved set for flush requests */
852 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
855 /* If we're filtering by set, don't match other sets */
856 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
859 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
860 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
866 struct manage_sets_args {
872 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
875 struct manage_sets_args *args;
877 args = (struct manage_sets_args *)arg;
878 if (no->set == (uint8_t)args->set)
879 no->set = args->new_set;
880 else if (no->set == args->new_set)
881 no->set = (uint8_t)args->set;
886 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
889 struct manage_sets_args *args;
891 args = (struct manage_sets_args *)arg;
892 if (no->set == (uint8_t)args->set)
893 no->set = args->new_set;
898 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
901 struct manage_sets_args *args;
903 args = (struct manage_sets_args *)arg;
904 if (no->set != (uint8_t)args->set)
906 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
907 no->etlv, no->name) != NULL)
913 * Generic function to handler moving and swapping sets.
916 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
917 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
919 struct manage_sets_args args;
920 struct named_object *no;
923 args.new_set = new_set;
926 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
929 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
932 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
936 * @set used to pass kidx.
937 * When @new_set is zero - reset object counter,
938 * otherwise increment it.
940 no = ipfw_objhash_lookup_kidx(ni, set);
947 /* @set used to pass kidx */
948 no = ipfw_objhash_lookup_kidx(ni, set);
950 * First check number of references:
951 * when it differs, this mean other rules are holding
952 * reference to given object, so it is not possible to
953 * change its set. Note that refcnt may account references
954 * to some going-to-be-added rules. Since we don't know
955 * their numbers (and even if they will be added) it is
956 * perfectly OK to return error here.
958 if (no->ocnt != no->refcnt)
960 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
965 /* @set used to pass kidx */
966 no = ipfw_objhash_lookup_kidx(ni, set);
974 * Delete rules matching range @rt.
975 * Saves number of deleted rules in @ndel.
977 * Returns 0 on success.
980 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
982 struct ip_fw *reap, *rule, **map;
987 IPFW_UH_WLOCK(chain); /* arbitrate writers */
990 * Stage 1: Determine range to inspect.
991 * Range is half-inclusive, e.g [start, end).
994 end = chain->n_rules - 1;
996 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
997 start = ipfw_find_rule(chain, rt->start_rule, 0);
999 end = ipfw_find_rule(chain, rt->end_rule, 0);
1000 if (rt->end_rule != IPFW_DEFAULT_RULE)
1001 while (chain->map[end]->rulenum == rt->end_rule)
1005 /* Allocate new map of the same size */
1006 map = get_map(chain, 0, 1 /* locked */);
1008 IPFW_UH_WUNLOCK(chain);
1015 /* 1. bcopy the initial part of the map */
1017 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1018 /* 2. copy active rules between start and end */
1019 for (i = start; i < end; i++) {
1020 rule = chain->map[i];
1021 if (ipfw_match_range(rule, rt) == 0) {
1027 if (ipfw_is_dyn_rule(rule) != 0)
1030 /* 3. copy the final part of the map */
1031 bcopy(chain->map + end, map + ofs,
1032 (chain->n_rules - end) * sizeof(struct ip_fw *));
1033 /* 4. recalculate skipto cache */
1034 update_skipto_cache(chain, map);
1035 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1036 map = swap_map(chain, map, chain->n_rules - n);
1037 /* 6. Remove all dynamic states originated by deleted rules */
1039 ipfw_expire_dyn_rules(chain, rt);
1040 /* 7. now remove the rules deleted from the old map */
1041 for (i = start; i < end; i++) {
1043 if (ipfw_match_range(rule, rt) == 0)
1045 chain->static_len -= RULEUSIZE0(rule);
1046 ipfw_reap_add(chain, &reap, rule);
1048 IPFW_UH_WUNLOCK(chain);
1050 ipfw_reap_rules(reap);
1058 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1060 struct opcode_obj_rewrite *rw;
1063 int cmdlen, i, l, c;
1066 IPFW_UH_WLOCK_ASSERT(ch);
1068 /* Stage 1: count number of references by given rules */
1069 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1071 if (ipfw_match_range(rule, rt) == 0)
1073 if (rule->set == rt->new_set) /* nothing to do */
1075 /* Search opcodes with named objects */
1076 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1077 l > 0; l -= cmdlen, cmd += cmdlen) {
1078 cmdlen = F_LEN(cmd);
1079 rw = find_op_rw(cmd, &kidx, NULL);
1080 if (rw == NULL || rw->manage_sets == NULL)
1083 * When manage_sets() returns non-zero value to
1084 * COUNT_ONE command, consider this as an object
1085 * doesn't support sets (e.g. disabled with sysctl).
1086 * So, skip checks for this object.
1088 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1093 if (c == 0) /* No objects found */
1095 /* Stage 2: verify "ownership" */
1096 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1098 if (ipfw_match_range(rule, rt) == 0)
1100 if (rule->set == rt->new_set) /* nothing to do */
1102 /* Search opcodes with named objects */
1103 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1104 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1105 cmdlen = F_LEN(cmd);
1106 rw = find_op_rw(cmd, &kidx, NULL);
1107 if (rw == NULL || rw->manage_sets == NULL)
1109 /* Test for ownership and conflicting names */
1110 c = rw->manage_sets(ch, kidx,
1111 (uint8_t)rt->new_set, TEST_ONE);
1114 /* Stage 3: change set and cleanup */
1115 for (i = 0; i < ch->n_rules - 1; i++) {
1117 if (ipfw_match_range(rule, rt) == 0)
1119 if (rule->set == rt->new_set) /* nothing to do */
1121 /* Search opcodes with named objects */
1122 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1123 l > 0; l -= cmdlen, cmd += cmdlen) {
1124 cmdlen = F_LEN(cmd);
1125 rw = find_op_rw(cmd, &kidx, NULL);
1126 if (rw == NULL || rw->manage_sets == NULL)
1128 /* cleanup object counter */
1129 rw->manage_sets(ch, kidx,
1130 0 /* reset counter */, COUNT_ONE);
1134 rw->manage_sets(ch, kidx,
1135 (uint8_t)rt->new_set, MOVE_ONE);
1140 * Changes set of given rule rannge @rt
1143 * Returns 0 on success.
1146 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1151 IPFW_UH_WLOCK(chain);
1154 * Move rules with matching paramenerts to a new set.
1155 * This one is much more complex. We have to ensure
1156 * that all referenced tables (if any) are referenced
1157 * by given rule subset only. Otherwise, we can't move
1158 * them to new set and have to return error.
1160 if ((i = move_objects(chain, rt)) != 0) {
1161 IPFW_UH_WUNLOCK(chain);
1165 /* XXX: We have to do swap holding WLOCK */
1166 for (i = 0; i < chain->n_rules; i++) {
1167 rule = chain->map[i];
1168 if (ipfw_match_range(rule, rt) == 0)
1170 rule->set = rt->new_set;
1173 IPFW_UH_WUNLOCK(chain);
1179 * Clear counters for a specific rule.
1180 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1181 * so we only care that rules do not disappear.
1184 clear_counters(struct ip_fw *rule, int log_only)
1186 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1189 IPFW_ZERO_RULE_COUNTER(rule);
1190 if (l->o.opcode == O_LOG)
1191 l->log_left = l->max_log;
1195 * Flushes rules counters and/or log values on matching range.
1197 * Returns number of items cleared.
1200 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1207 rt->flags |= IPFW_RCFLAG_DEFAULT;
1209 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1210 for (i = 0; i < chain->n_rules; i++) {
1211 rule = chain->map[i];
1212 if (ipfw_match_range(rule, rt) == 0)
1214 clear_counters(rule, log_only);
1217 IPFW_UH_WUNLOCK(chain);
1223 check_range_tlv(ipfw_range_tlv *rt)
1226 if (rt->head.length != sizeof(*rt))
1228 if (rt->start_rule > rt->end_rule)
1230 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1233 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1240 * Delete rules matching specified parameters
1241 * Data layout (v0)(current):
1242 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1243 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1245 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1247 * Returns 0 on success.
1250 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1251 struct sockopt_data *sd)
1253 ipfw_range_header *rh;
1256 if (sd->valsize != sizeof(*rh))
1259 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1261 if (check_range_tlv(&rh->range) != 0)
1265 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1268 /* Save number of rules deleted */
1269 rh->range.new_set = ndel;
1274 * Move rules/sets matching specified parameters
1275 * Data layout (v0)(current):
1276 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1278 * Returns 0 on success.
1281 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1282 struct sockopt_data *sd)
1284 ipfw_range_header *rh;
1286 if (sd->valsize != sizeof(*rh))
1289 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1291 if (check_range_tlv(&rh->range) != 0)
1294 return (move_range(chain, &rh->range));
1298 * Clear rule accounting data matching specified parameters
1299 * Data layout (v0)(current):
1300 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1301 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1303 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1305 * Returns 0 on success.
1308 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1309 struct sockopt_data *sd)
1311 ipfw_range_header *rh;
1315 if (sd->valsize != sizeof(*rh))
1318 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1320 if (check_range_tlv(&rh->range) != 0)
1323 log_only = (op3->opcode == IP_FW_XRESETLOG);
1325 num = clear_range(chain, &rh->range, log_only);
1327 if (rh->range.flags & IPFW_RCFLAG_ALL)
1328 msg = log_only ? "All logging counts reset" :
1329 "Accounting cleared";
1331 msg = log_only ? "logging count reset" : "cleared";
1334 int lev = LOG_SECURITY | LOG_NOTICE;
1335 log(lev, "ipfw: %s.\n", msg);
1338 /* Save number of rules cleared */
1339 rh->range.new_set = num;
1344 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1348 IPFW_UH_WLOCK_ASSERT(chain);
1350 /* Change enabled/disabled sets mask */
1351 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1352 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1354 V_set_disable = v_set;
1355 IPFW_WUNLOCK(chain);
1359 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1361 struct opcode_obj_rewrite *rw;
1365 IPFW_UH_WLOCK_ASSERT(chain);
1367 if (rt->set == rt->new_set) /* nothing to do */
1372 * Berfore moving the rules we need to check that
1373 * there aren't any conflicting named objects.
1375 for (rw = ctl3_rewriters;
1376 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1377 if (rw->manage_sets == NULL)
1379 i = rw->manage_sets(chain, (uint8_t)rt->set,
1380 (uint8_t)rt->new_set, TEST_ALL);
1385 /* Swap or move two sets */
1386 for (i = 0; i < chain->n_rules - 1; i++) {
1387 rule = chain->map[i];
1388 if (rule->set == (uint8_t)rt->set)
1389 rule->set = (uint8_t)rt->new_set;
1390 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1391 rule->set = (uint8_t)rt->set;
1393 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1394 if (rw->manage_sets == NULL)
1396 rw->manage_sets(chain, (uint8_t)rt->set,
1397 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1403 * Swaps or moves set
1404 * Data layout (v0)(current):
1405 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1407 * Returns 0 on success.
1410 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1411 struct sockopt_data *sd)
1413 ipfw_range_header *rh;
1416 if (sd->valsize != sizeof(*rh))
1419 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1421 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1423 /* enable_sets() expects bitmasks. */
1424 if (op3->opcode != IP_FW_SET_ENABLE &&
1425 (rh->range.set >= IPFW_MAX_SETS ||
1426 rh->range.new_set >= IPFW_MAX_SETS))
1430 IPFW_UH_WLOCK(chain);
1431 switch (op3->opcode) {
1432 case IP_FW_SET_SWAP:
1433 case IP_FW_SET_MOVE:
1434 ret = swap_sets(chain, &rh->range,
1435 op3->opcode == IP_FW_SET_MOVE);
1437 case IP_FW_SET_ENABLE:
1438 enable_sets(chain, &rh->range);
1441 IPFW_UH_WUNLOCK(chain);
1447 * Remove all rules with given number, or do set manipulation.
1448 * Assumes chain != NULL && *chain != NULL.
1450 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1451 * the next 8 bits are the new set; the top 8 bits indicate the command:
1453 * 0 delete rules numbered "rulenum"
1454 * 1 delete rules in set "rulenum"
1455 * 2 move rules "rulenum" to set "new_set"
1456 * 3 move rules from set "rulenum" to set "new_set"
1457 * 4 swap sets "rulenum" and "new_set"
1458 * 5 delete rules "rulenum" and set "new_set"
1461 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1463 uint32_t num; /* rule number or old_set */
1464 uint8_t cmd, new_set;
1470 cmd = (arg >> 24) & 0xff;
1471 new_set = (arg >> 16) & 0xff;
1473 if (cmd > 5 || new_set > RESVD_SET)
1475 if (cmd == 0 || cmd == 2 || cmd == 5) {
1476 if (num >= IPFW_DEFAULT_RULE)
1479 if (num > RESVD_SET) /* old_set */
1483 /* Convert old requests into new representation */
1484 memset(&rt, 0, sizeof(rt));
1485 rt.start_rule = num;
1488 rt.new_set = new_set;
1492 case 0: /* delete rules numbered "rulenum" */
1494 rt.flags |= IPFW_RCFLAG_ALL;
1496 rt.flags |= IPFW_RCFLAG_RANGE;
1499 case 1: /* delete rules in set "rulenum" */
1500 rt.flags |= IPFW_RCFLAG_SET;
1503 case 5: /* delete rules "rulenum" and set "new_set" */
1504 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1509 case 2: /* move rules "rulenum" to set "new_set" */
1510 rt.flags |= IPFW_RCFLAG_RANGE;
1512 case 3: /* move rules from set "rulenum" to set "new_set" */
1513 IPFW_UH_WLOCK(chain);
1514 error = swap_sets(chain, &rt, 1);
1515 IPFW_UH_WUNLOCK(chain);
1517 case 4: /* swap sets "rulenum" and "new_set" */
1518 IPFW_UH_WLOCK(chain);
1519 error = swap_sets(chain, &rt, 0);
1520 IPFW_UH_WUNLOCK(chain);
1527 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1530 if (ndel == 0 && (cmd != 1 && num != 0))
1536 return (move_range(chain, &rt));
1540 * Reset some or all counters on firewall rules.
1541 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1542 * the next 8 bits are the set number, the top 8 bits are the command:
1543 * 0 work with rules from all set's;
1544 * 1 work with rules only from specified set.
1545 * Specified rule number is zero if we want to clear all entries.
1546 * log_only is 1 if we only want to reset logs, zero otherwise.
1549 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1555 uint16_t rulenum = arg & 0xffff;
1556 uint8_t set = (arg >> 16) & 0xff;
1557 uint8_t cmd = (arg >> 24) & 0xff;
1561 if (cmd == 1 && set > RESVD_SET)
1564 IPFW_UH_RLOCK(chain);
1566 V_norule_counter = 0;
1567 for (i = 0; i < chain->n_rules; i++) {
1568 rule = chain->map[i];
1569 /* Skip rules not in our set. */
1570 if (cmd == 1 && rule->set != set)
1572 clear_counters(rule, log_only);
1574 msg = log_only ? "All logging counts reset" :
1575 "Accounting cleared";
1578 for (i = 0; i < chain->n_rules; i++) {
1579 rule = chain->map[i];
1580 if (rule->rulenum == rulenum) {
1581 if (cmd == 0 || rule->set == set)
1582 clear_counters(rule, log_only);
1585 if (rule->rulenum > rulenum)
1588 if (!cleared) { /* we did not find any matching rules */
1589 IPFW_UH_RUNLOCK(chain);
1592 msg = log_only ? "logging count reset" : "cleared";
1594 IPFW_UH_RUNLOCK(chain);
1597 int lev = LOG_SECURITY | LOG_NOTICE;
1600 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1602 log(lev, "ipfw: %s.\n", msg);
1609 * Check rule head in FreeBSD11 format
1613 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1614 struct rule_check_info *ci)
1618 if (size < sizeof(*rule)) {
1619 printf("ipfw: rule too short\n");
1623 /* Check for valid cmd_len */
1624 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1626 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1629 if (rule->act_ofs >= rule->cmd_len) {
1630 printf("ipfw: bogus action offset (%u > %u)\n",
1631 rule->act_ofs, rule->cmd_len - 1);
1635 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1638 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1642 * Check rule head in FreeBSD8 format
1646 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1647 struct rule_check_info *ci)
1651 if (size < sizeof(*rule)) {
1652 printf("ipfw: rule too short\n");
1656 /* Check for valid cmd_len */
1657 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1659 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1662 if (rule->act_ofs >= rule->cmd_len) {
1663 printf("ipfw: bogus action offset (%u > %u)\n",
1664 rule->act_ofs, rule->cmd_len - 1);
1668 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1671 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1675 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1683 * Now go for the individual checks. Very simple ones, basically only
1684 * instruction sizes.
1686 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1687 cmdlen = F_LEN(cmd);
1689 printf("ipfw: opcode %d size truncated\n",
1693 switch (cmd->opcode) {
1696 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1698 ci->object_opcodes++;
1709 case O_IPPRECEDENCE:
1727 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1731 case O_EXTERNAL_ACTION:
1732 if (cmd->arg1 == 0 ||
1733 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1734 printf("ipfw: invalid external "
1738 ci->object_opcodes++;
1739 /* Do we have O_EXTERNAL_INSTANCE opcode? */
1743 cmdlen = F_LEN(cmd);
1744 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1745 printf("ipfw: invalid opcode "
1746 "next to external action %u\n",
1750 if (cmd->arg1 == 0 ||
1751 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1752 printf("ipfw: invalid external "
1753 "action instance opcode\n");
1756 ci->object_opcodes++;
1761 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1763 if (cmd->arg1 >= rt_numfibs) {
1764 printf("ipfw: invalid fib number %d\n",
1771 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1773 if ((cmd->arg1 != IP_FW_TARG) &&
1774 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1775 printf("ipfw: invalid fib number %d\n",
1776 cmd->arg1 & 0x7FFF);
1790 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1795 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1797 ci->object_opcodes++;
1801 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1804 ((ipfw_insn_log *)cmd)->log_left =
1805 ((ipfw_insn_log *)cmd)->max_log;
1811 /* only odd command lengths */
1812 if ((cmdlen & 1) == 0)
1818 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1819 printf("ipfw: invalid set size %d\n",
1823 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1828 case O_IP_SRC_LOOKUP:
1829 case O_IP_DST_LOOKUP:
1830 if (cmd->arg1 >= V_fw_tables_max) {
1831 printf("ipfw: invalid table number %d\n",
1835 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1836 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1837 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1839 ci->object_opcodes++;
1841 case O_IP_FLOW_LOOKUP:
1842 if (cmd->arg1 >= V_fw_tables_max) {
1843 printf("ipfw: invalid table number %d\n",
1847 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1848 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1850 ci->object_opcodes++;
1853 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1864 if (cmdlen < 1 || cmdlen > 31)
1869 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1875 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1876 if (cmdlen < 2 || cmdlen > 31)
1883 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1885 ci->object_opcodes++;
1889 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1895 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1900 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1905 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1912 if (ip_divert_ptr == NULL)
1918 if (ng_ipfw_input_p == NULL)
1923 if (!IPFW_NAT_LOADED)
1925 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1929 ci->object_opcodes++;
1931 case O_FORWARD_MAC: /* XXX not implemented yet */
1944 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1948 printf("ipfw: opcode %d, multiple actions"
1955 printf("ipfw: opcode %d, action must be"
1964 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1965 F_INSN_SIZE(ipfw_insn))
1970 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1971 ((ipfw_insn_u32 *)cmd)->o.arg1)
1975 case O_IP6_SRC_MASK:
1976 case O_IP6_DST_MASK:
1977 if ( !(cmdlen & 1) || cmdlen > 127)
1981 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
1987 switch (cmd->opcode) {
1997 case O_IP6_SRC_MASK:
1998 case O_IP6_DST_MASK:
2000 printf("ipfw: no IPv6 support in kernel\n");
2001 return (EPROTONOSUPPORT);
2004 printf("ipfw: opcode %d, unknown opcode\n",
2010 if (have_action == 0) {
2011 printf("ipfw: missing action\n");
2017 printf("ipfw: opcode %d size %d wrong\n",
2018 cmd->opcode, cmdlen);
2024 * Translation of requests for compatibility with FreeBSD 7.2/8.
2025 * a static variable tells us if we have an old client from userland,
2026 * and if necessary we translate requests and responses between the
2032 struct ip_fw7 *next; /* linked list of rules */
2033 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2034 /* 'next_rule' is used to pass up 'set_disable' status */
2036 uint16_t act_ofs; /* offset of action in 32-bit units */
2037 uint16_t cmd_len; /* # of 32-bit words in cmd */
2038 uint16_t rulenum; /* rule number */
2039 uint8_t set; /* rule set (0..31) */
2040 // #define RESVD_SET 31 /* set for default and persistent rules */
2041 uint8_t _pad; /* padding */
2042 // uint32_t id; /* rule id, only in v.8 */
2043 /* These fields are present in all rules. */
2044 uint64_t pcnt; /* Packet counter */
2045 uint64_t bcnt; /* Byte counter */
2046 uint32_t timestamp; /* tv_sec of last match */
2048 ipfw_insn cmd[1]; /* storage for commands */
2051 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2052 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2055 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2056 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2061 * Copy the static and dynamic rules to the supplied buffer
2062 * and return the amount of space actually used.
2063 * Must be run under IPFW_UH_RLOCK
2066 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2069 char *ep = bp + space;
2071 struct ip_fw_rule0 *dst;
2072 struct timeval boottime;
2073 int error, i, l, warnflag;
2074 time_t boot_seconds;
2078 getboottime(&boottime);
2079 boot_seconds = boottime.tv_sec;
2080 for (i = 0; i < chain->n_rules; i++) {
2081 rule = chain->map[i];
2084 /* Convert rule to FreeBSd 7.2 format */
2085 l = RULESIZE7(rule);
2086 if (bp + l + sizeof(uint32_t) <= ep) {
2087 bcopy(rule, bp, l + sizeof(uint32_t));
2088 error = set_legacy_obj_kidx(chain,
2089 (struct ip_fw_rule0 *)bp);
2092 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2094 return 0; /*XXX correct? */
2096 * XXX HACK. Store the disable mask in the "next"
2097 * pointer in a wild attempt to keep the ABI the same.
2098 * Why do we do this on EVERY rule?
2100 bcopy(&V_set_disable,
2101 &(((struct ip_fw7 *)bp)->next_rule),
2102 sizeof(V_set_disable));
2103 if (((struct ip_fw7 *)bp)->timestamp)
2104 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2107 continue; /* go to next rule */
2110 l = RULEUSIZE0(rule);
2111 if (bp + l > ep) { /* should not happen */
2112 printf("overflow dumping static rules\n");
2115 dst = (struct ip_fw_rule0 *)bp;
2116 export_rule0(rule, dst, l);
2117 error = set_legacy_obj_kidx(chain, dst);
2120 * XXX HACK. Store the disable mask in the "next"
2121 * pointer in a wild attempt to keep the ABI the same.
2122 * Why do we do this on EVERY rule?
2124 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2125 * so we need to fail _after_ saving at least one mask.
2127 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2129 dst->timestamp += boot_seconds;
2134 /* Non-fatal table rewrite error. */
2138 printf("Stop on rule %d. Fail to convert table\n",
2144 printf("ipfw: process %s is using legacy interfaces,"
2145 " consider rebuilding\n", "");
2146 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2147 return (bp - (char *)buf);
2152 uint32_t b; /* start rule */
2153 uint32_t e; /* end rule */
2154 uint32_t rcount; /* number of rules */
2155 uint32_t rsize; /* rules size */
2156 uint32_t tcount; /* number of tables */
2157 int rcounters; /* counters */
2161 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2164 ntlv->head.type = no->etlv;
2165 ntlv->head.length = sizeof(*ntlv);
2166 ntlv->idx = no->kidx;
2167 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2171 * Export named object info in instance @ni, identified by @kidx
2172 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2174 * Returns 0 on success.
2177 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2178 struct sockopt_data *sd)
2180 struct named_object *no;
2181 ipfw_obj_ntlv *ntlv;
2183 no = ipfw_objhash_lookup_kidx(ni, kidx);
2184 KASSERT(no != NULL, ("invalid object kernel index passed"));
2186 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2190 ipfw_export_obj_ntlv(no, ntlv);
2195 * Dumps static rules with table TLVs in buffer @sd.
2197 * Returns 0 on success.
2200 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2201 uint32_t *bmask, struct sockopt_data *sd)
2206 ipfw_obj_ctlv *ctlv;
2207 struct ip_fw *krule;
2208 struct namedobj_instance *ni;
2211 /* Dump table names first (if any) */
2212 if (da->tcount > 0) {
2214 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2217 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2218 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2220 ctlv->count = da->tcount;
2221 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2225 tcount = da->tcount;
2226 ni = ipfw_get_table_objhash(chain);
2227 while (tcount > 0) {
2228 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
2233 /* Jump to shared named object bitmask */
2234 if (i >= IPFW_TABLES_MAX) {
2235 ni = CHAIN_TO_SRV(chain);
2236 i -= IPFW_TABLES_MAX;
2237 bmask += IPFW_TABLES_MAX / 32;
2240 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2248 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2251 ctlv->head.type = IPFW_TLV_RULE_LIST;
2252 ctlv->head.length = da->rsize + sizeof(*ctlv);
2253 ctlv->count = da->rcount;
2255 for (i = da->b; i < da->e; i++) {
2256 krule = chain->map[i];
2258 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2259 if (da->rcounters != 0)
2260 l += sizeof(struct ip_fw_bcounter);
2261 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2265 export_rule1(krule, dst, l, da->rcounters);
2272 * Marks every object index used in @rule with bit in @bmask.
2273 * Used to generate bitmask of referenced tables/objects for given ruleset
2276 * Returns number of newly-referenced objects.
2279 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
2282 struct opcode_obj_rewrite *rw;
2284 int bidx, cmdlen, l, count;
2292 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2293 cmdlen = F_LEN(cmd);
2295 rw = find_op_rw(cmd, &kidx, &subtype);
2301 * Maintain separate bitmasks for table and
2302 * non-table objects.
2304 if (rw->etlv != IPFW_TLV_TBL_NAME)
2305 bidx += IPFW_TABLES_MAX / 32;
2307 if ((bmask[bidx] & (1 << (kidx % 32))) == 0)
2310 bmask[bidx] |= 1 << (kidx % 32);
2317 * Dumps requested objects data
2318 * Data layout (version 0)(current):
2319 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2320 * size = ipfw_cfg_lheader.size
2321 * Reply: [ ipfw_cfg_lheader
2322 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2323 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2324 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2326 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2328 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2329 * The rest (size, count) are set to zero and needs to be ignored.
2331 * Returns 0 on success.
2334 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2335 struct sockopt_data *sd)
2337 ipfw_cfg_lheader *hdr;
2342 struct dump_args da;
2345 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2351 /* Allocate needed state. Note we allocate 2xspace mask, for table&srv */
2352 if (hdr->flags & IPFW_CFG_GET_STATIC)
2353 bmask = malloc(IPFW_TABLES_MAX / 4, M_TEMP, M_WAITOK | M_ZERO);
2355 IPFW_UH_RLOCK(chain);
2358 * STAGE 1: Determine size/count for objects in range.
2359 * Prepare used tables bitmask.
2361 sz = sizeof(ipfw_cfg_lheader);
2362 memset(&da, 0, sizeof(da));
2365 da.e = chain->n_rules;
2367 if (hdr->end_rule != 0) {
2368 /* Handle custom range */
2369 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2370 rnum = IPFW_DEFAULT_RULE;
2371 da.b = ipfw_find_rule(chain, rnum, 0);
2372 rnum = hdr->end_rule;
2373 rnum = (rnum < IPFW_DEFAULT_RULE) ? rnum+1 : IPFW_DEFAULT_RULE;
2374 da.e = ipfw_find_rule(chain, rnum, 0) + 1;
2377 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2378 for (i = da.b; i < da.e; i++) {
2379 rule = chain->map[i];
2380 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2382 /* Update bitmask of used objects for given range */
2383 da.tcount += mark_object_kidx(chain, rule, bmask);
2385 /* Add counters if requested */
2386 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2387 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2392 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2393 sizeof(ipfw_obj_ctlv);
2394 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2397 if (hdr->flags & IPFW_CFG_GET_STATES)
2398 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2399 sizeof(ipfw_obj_ctlv);
2403 * Fill header anyway.
2404 * Note we have to save header fields to stable storage
2405 * buffer inside @sd can be flushed after dumping rules
2408 hdr->set_mask = ~V_set_disable;
2409 hdr_flags = hdr->flags;
2412 if (sd->valsize < sz) {
2417 /* STAGE2: Store actual data */
2418 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2419 error = dump_static_rules(chain, &da, bmask, sd);
2424 if (hdr_flags & IPFW_CFG_GET_STATES)
2425 error = ipfw_dump_states(chain, sd);
2428 IPFW_UH_RUNLOCK(chain);
2431 free(bmask, M_TEMP);
2437 ipfw_check_object_name_generic(const char *name)
2441 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2442 if (strnlen(name, nsize) == nsize)
2444 if (name[0] == '\0')
2450 * Creates non-existent objects referenced by rule.
2452 * Return 0 on success.
2455 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2456 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2458 struct opcode_obj_rewrite *rw;
2464 * Compatibility stuff: do actual creation for non-existing,
2465 * but referenced objects.
2467 for (p = oib; p < pidx; p++) {
2475 rw = find_op_rw(cmd + p->off, NULL, NULL);
2476 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2477 (cmd + p->off)->opcode));
2479 if (rw->create_object == NULL)
2482 error = rw->create_object(ch, ti, &kidx);
2489 * Error happened. We have to rollback everything.
2490 * Drop all already acquired references.
2493 unref_oib_objects(ch, cmd, oib, pidx);
2494 IPFW_UH_WUNLOCK(ch);
2503 * Compatibility function for old ipfw(8) binaries.
2504 * Rewrites table/nat kernel indices with userland ones.
2505 * Convert tables matching '/^\d+$/' to their atoi() value.
2506 * Use number 65535 for other tables.
2508 * Returns 0 on success.
2511 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2513 struct opcode_obj_rewrite *rw;
2514 struct named_object *no;
2518 int cmdlen, error, l;
2519 uint16_t kidx, uidx;
2527 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2528 cmdlen = F_LEN(cmd);
2530 /* Check if is index in given opcode */
2531 rw = find_op_rw(cmd, &kidx, &subtype);
2535 /* Try to find referenced kernel object */
2536 no = rw->find_bykidx(ch, kidx);
2540 val = strtol(no->name, &end, 10);
2541 if (*end == '\0' && val < 65535) {
2546 * We are called via legacy opcode.
2547 * Save error and show table as fake number
2548 * not to make ipfw(8) hang.
2554 rw->update(cmd, uidx);
2562 * Unreferences all already-referenced objects in given @cmd rule,
2563 * using information in @oib.
2565 * Used to rollback partially converted rule on error.
2568 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2569 struct obj_idx *end)
2571 struct opcode_obj_rewrite *rw;
2572 struct named_object *no;
2575 IPFW_UH_WLOCK_ASSERT(ch);
2577 for (p = oib; p < end; p++) {
2581 rw = find_op_rw(cmd + p->off, NULL, NULL);
2582 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2583 (cmd + p->off)->opcode));
2585 /* Find & unref by existing idx */
2586 no = rw->find_bykidx(ch, p->kidx);
2587 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2593 * Remove references from every object used in @rule.
2594 * Used at rule removal code.
2597 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2599 struct opcode_obj_rewrite *rw;
2600 struct named_object *no;
2606 IPFW_UH_WLOCK_ASSERT(ch);
2611 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2612 cmdlen = F_LEN(cmd);
2614 rw = find_op_rw(cmd, &kidx, &subtype);
2617 no = rw->find_bykidx(ch, kidx);
2619 KASSERT(no != NULL, ("table id %d not found", kidx));
2620 KASSERT(no->subtype == subtype,
2621 ("wrong type %d (%d) for table id %d",
2622 no->subtype, subtype, kidx));
2623 KASSERT(no->refcnt > 0, ("refcount for table %d is %d",
2626 if (no->refcnt == 1 && rw->destroy_object != NULL)
2627 rw->destroy_object(ch, no);
2635 * Find and reference object (if any) stored in instruction @cmd.
2637 * Saves object info in @pidx, sets
2638 * - @unresolved to 1 if object should exists but not found
2640 * Returns non-zero value in case of error.
2643 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2644 struct obj_idx *pidx, int *unresolved)
2646 struct named_object *no;
2647 struct opcode_obj_rewrite *rw;
2650 /* Check if this opcode is candidate for rewrite */
2651 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2655 /* Need to rewrite. Save necessary fields */
2656 pidx->uidx = ti->uidx;
2657 pidx->type = ti->type;
2659 /* Try to find referenced kernel object */
2660 error = rw->find_byname(ch, ti, &no);
2665 * Report about unresolved object for automaic
2672 /* Found. Bump refcount and update kidx. */
2674 rw->update(cmd, no->kidx);
2679 * Finds and bumps refcount for objects referenced by given @rule.
2680 * Auto-creates non-existing tables.
2681 * Fills in @oib array with userland/kernel indexes.
2683 * Returns 0 on success.
2686 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2687 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2689 struct obj_idx *pidx;
2691 int cmdlen, error, l, unresolved;
2701 /* Increase refcount on each existing referenced table. */
2702 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2703 cmdlen = F_LEN(cmd);
2706 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2710 * Compatibility stuff for old clients:
2711 * prepare to automaitcally create non-existing objects.
2713 if (unresolved != 0) {
2714 pidx->off = rule->cmd_len - l;
2720 /* Unref everything we have already done */
2721 unref_oib_objects(ch, rule->cmd, oib, pidx);
2722 IPFW_UH_WUNLOCK(ch);
2725 IPFW_UH_WUNLOCK(ch);
2727 /* Perform auto-creation for non-existing objects */
2729 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2731 /* Calculate real number of dynamic objects */
2732 ci->object_opcodes = (uint16_t)(pidx - oib);
2738 * Checks is opcode is referencing table of appropriate type.
2739 * Adds reference count for found table if true.
2740 * Rewrites user-supplied opcode values with kernel ones.
2742 * Returns 0 on success and appropriate error code otherwise.
2745 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2750 struct obj_idx *p, *pidx_first, *pidx_last;
2754 * Prepare an array for storing opcode indices.
2755 * Use stack allocation by default.
2757 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2759 pidx_first = ci->obuf;
2761 pidx_first = malloc(
2762 ci->object_opcodes * sizeof(struct obj_idx),
2763 M_IPFW, M_WAITOK | M_ZERO);
2767 memset(&ti, 0, sizeof(ti));
2769 /* Use set rule is assigned to. */
2770 ti.set = ci->krule->set;
2771 if (ci->ctlv != NULL) {
2772 ti.tlvs = (void *)(ci->ctlv + 1);
2773 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2776 /* Reference all used tables and other objects */
2777 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2781 * Note that ref_rule_objects() might have updated ci->object_opcodes
2782 * to reflect actual number of object opcodes.
2785 /* Perform rewrite of remaining opcodes */
2787 pidx_last = pidx_first + ci->object_opcodes;
2788 for (p = pidx_first; p < pidx_last; p++) {
2789 cmd = ci->krule->cmd + p->off;
2790 update_opcode_kidx(cmd, p->kidx);
2794 if (pidx_first != ci->obuf)
2795 free(pidx_first, M_IPFW);
2801 * Adds one or more rules to ipfw @chain.
2802 * Data layout (version 0)(current):
2806 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2807 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2812 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2813 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2816 * Rules in reply are modified to store their actual ruleset number.
2818 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2819 * according to their idx field and there has to be no duplicates.
2820 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2821 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2823 * Returns 0 on success.
2826 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2827 struct sockopt_data *sd)
2829 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2830 ipfw_obj_ntlv *ntlv;
2831 int clen, error, idx;
2832 uint32_t count, read;
2833 struct ip_fw_rule *r;
2834 struct rule_check_info rci, *ci, *cbuf;
2837 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2838 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2840 read = sizeof(ip_fw3_opheader);
2844 memset(&rci, 0, sizeof(struct rule_check_info));
2846 if (read + sizeof(*ctlv) > sd->valsize)
2849 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2850 clen = ctlv->head.length;
2851 /* Check size and alignment */
2852 if (clen > sd->valsize || clen < sizeof(*ctlv))
2854 if ((clen % sizeof(uint64_t)) != 0)
2858 * Some table names or other named objects.
2859 * Check for validness.
2861 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2862 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2867 * Ensure TLVs are sorted ascending and
2868 * there are no duplicates.
2871 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2873 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2876 error = ipfw_check_object_name_generic(ntlv->name);
2880 if (ntlv->idx <= idx)
2889 read += ctlv->head.length;
2890 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2893 if (read + sizeof(*ctlv) > sd->valsize)
2896 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2897 clen = ctlv->head.length;
2898 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2900 if ((clen % sizeof(uint64_t)) != 0)
2904 * TODO: Permit adding multiple rules at once
2906 if (ctlv->count != 1)
2909 clen -= sizeof(*ctlv);
2911 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2914 /* Allocate state for each rule or use stack */
2915 if (ctlv->count == 1) {
2916 memset(&rci, 0, sizeof(struct rule_check_info));
2919 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2924 * Check each rule for validness.
2925 * Ensure numbered rules are sorted ascending
2926 * and properly aligned
2929 r = (struct ip_fw_rule *)(ctlv + 1);
2933 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2934 if (rsize > clen || ctlv->count <= count) {
2940 error = check_ipfw_rule1(r, rsize, ci);
2945 if (r->rulenum != 0 && r->rulenum < idx) {
2946 printf("rulenum %d idx %d\n", r->rulenum, idx);
2952 ci->urule = (caddr_t)r;
2954 rsize = roundup2(rsize, sizeof(uint64_t));
2956 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2961 if (ctlv->count != count || error != 0) {
2968 read += ctlv->head.length;
2969 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2972 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
2973 if (cbuf != NULL && cbuf != &rci)
2979 * Passed rules seems to be valid.
2980 * Allocate storage and try to add them to chain.
2982 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
2983 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
2984 ci->krule = ipfw_alloc_rule(chain, clen);
2988 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
2989 /* Free allocate krules */
2990 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
2991 free_rule(ci->krule);
2994 if (cbuf != NULL && cbuf != &rci)
3001 * Lists all sopts currently registered.
3002 * Data layout (v0)(current):
3003 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3004 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3006 * Returns 0 on success
3009 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3010 struct sockopt_data *sd)
3012 struct _ipfw_obj_lheader *olh;
3014 struct ipfw_sopt_handler *sh;
3015 uint32_t count, n, size;
3017 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3020 if (sd->valsize < olh->size)
3025 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3027 /* Fill in header regadless of buffer size */
3029 olh->objsize = sizeof(ipfw_sopt_info);
3031 if (size > olh->size) {
3038 for (n = 1; n <= count; n++) {
3039 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3040 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3041 sh = &ctl3_handlers[n];
3042 i->opcode = sh->opcode;
3043 i->version = sh->version;
3044 i->refcnt = sh->refcnt;
3052 * Compares two opcodes.
3053 * Used both in qsort() and bsearch().
3055 * Returns 0 if match is found.
3058 compare_opcodes(const void *_a, const void *_b)
3060 const struct opcode_obj_rewrite *a, *b;
3062 a = (const struct opcode_obj_rewrite *)_a;
3063 b = (const struct opcode_obj_rewrite *)_b;
3065 if (a->opcode < b->opcode)
3067 else if (a->opcode > b->opcode)
3074 * XXX: Rewrite bsearch()
3077 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3078 struct opcode_obj_rewrite **phi)
3080 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3082 memset(&h, 0, sizeof(h));
3085 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3086 ctl3_rsize, sizeof(h), compare_opcodes);
3090 /* Find the first element matching the same opcode */
3092 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3095 /* Find the last element matching the same opcode */
3097 ctl3_max = ctl3_rewriters + ctl3_rsize;
3098 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3108 * Finds opcode object rewriter based on @code.
3110 * Returns pointer to handler or NULL.
3112 static struct opcode_obj_rewrite *
3113 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3115 struct opcode_obj_rewrite *rw, *lo, *hi;
3119 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3122 for (rw = lo; rw <= hi; rw++) {
3123 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3135 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3138 if (find_op_rw(cmd, puidx, NULL) == 0)
3144 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3146 struct opcode_obj_rewrite *rw;
3148 rw = find_op_rw(cmd, NULL, NULL);
3149 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3150 rw->update(cmd, idx);
3154 ipfw_init_obj_rewriter()
3157 ctl3_rewriters = NULL;
3162 ipfw_destroy_obj_rewriter()
3165 if (ctl3_rewriters != NULL)
3166 free(ctl3_rewriters, M_IPFW);
3167 ctl3_rewriters = NULL;
3172 * Adds one or more opcode object rewrite handlers to the global array.
3173 * Function may sleep.
3176 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3179 struct opcode_obj_rewrite *tmp;
3184 sz = ctl3_rsize + count;
3186 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3188 if (ctl3_rsize + count <= sz)
3195 /* Merge old & new arrays */
3196 sz = ctl3_rsize + count;
3197 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3198 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3199 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3200 /* Switch new and free old */
3201 if (ctl3_rewriters != NULL)
3202 free(ctl3_rewriters, M_IPFW);
3203 ctl3_rewriters = tmp;
3210 * Removes one or more object rewrite handlers from the global array.
3213 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3216 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3221 for (i = 0; i < count; i++) {
3222 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3225 for (ktmp = lo; ktmp <= hi; ktmp++) {
3226 if (ktmp->classifier != rw[i].classifier)
3229 ctl3_max = ctl3_rewriters + ctl3_rsize;
3230 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3231 memmove(ktmp, ktmp + 1, sz);
3238 if (ctl3_rsize == 0) {
3239 if (ctl3_rewriters != NULL)
3240 free(ctl3_rewriters, M_IPFW);
3241 ctl3_rewriters = NULL;
3250 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3251 struct named_object *no, void *arg)
3253 struct sockopt_data *sd;
3254 ipfw_obj_ntlv *ntlv;
3256 sd = (struct sockopt_data *)arg;
3257 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3260 ipfw_export_obj_ntlv(no, ntlv);
3265 * Lists all service objects.
3266 * Data layout (v0)(current):
3267 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3268 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3269 * Returns 0 on success
3272 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3273 struct sockopt_data *sd)
3275 ipfw_obj_lheader *hdr;
3278 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3282 IPFW_UH_RLOCK(chain);
3283 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3284 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3285 if (sd->valsize < hdr->size) {
3286 IPFW_UH_RUNLOCK(chain);
3290 hdr->objsize = sizeof(ipfw_obj_ntlv);
3292 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3293 export_objhash_ntlv_internal, sd);
3294 IPFW_UH_RUNLOCK(chain);
3299 * Compares two sopt handlers (code, version and handler ptr).
3300 * Used both as qsort() and bsearch().
3301 * Does not compare handler for latter case.
3303 * Returns 0 if match is found.
3306 compare_sh(const void *_a, const void *_b)
3308 const struct ipfw_sopt_handler *a, *b;
3310 a = (const struct ipfw_sopt_handler *)_a;
3311 b = (const struct ipfw_sopt_handler *)_b;
3313 if (a->opcode < b->opcode)
3315 else if (a->opcode > b->opcode)
3318 if (a->version < b->version)
3320 else if (a->version > b->version)
3323 /* bsearch helper */
3324 if (a->handler == NULL)
3327 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3329 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3336 * Finds sopt handler based on @code and @version.
3338 * Returns pointer to handler or NULL.
3340 static struct ipfw_sopt_handler *
3341 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3343 struct ipfw_sopt_handler *sh, h;
3345 memset(&h, 0, sizeof(h));
3347 h.version = version;
3348 h.handler = handler;
3350 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3351 ctl3_hsize, sizeof(h), compare_sh);
3357 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3359 struct ipfw_sopt_handler *sh;
3362 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3364 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3370 /* Copy handler data to requested buffer */
3378 find_unref_sh(struct ipfw_sopt_handler *psh)
3380 struct ipfw_sopt_handler *sh;
3383 sh = find_sh(psh->opcode, psh->version, NULL);
3384 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3391 ipfw_init_sopt_handler()
3395 IPFW_ADD_SOPT_HANDLER(1, scodes);
3399 ipfw_destroy_sopt_handler()
3402 IPFW_DEL_SOPT_HANDLER(1, scodes);
3403 CTL3_LOCK_DESTROY();
3407 * Adds one or more sockopt handlers to the global array.
3408 * Function may sleep.
3411 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3414 struct ipfw_sopt_handler *tmp;
3419 sz = ctl3_hsize + count;
3421 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3423 if (ctl3_hsize + count <= sz)
3430 /* Merge old & new arrays */
3431 sz = ctl3_hsize + count;
3432 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3433 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3434 qsort(tmp, sz, sizeof(*sh), compare_sh);
3435 /* Switch new and free old */
3436 if (ctl3_handlers != NULL)
3437 free(ctl3_handlers, M_IPFW);
3438 ctl3_handlers = tmp;
3446 * Removes one or more sockopt handlers from the global array.
3449 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3452 struct ipfw_sopt_handler *tmp, *h;
3457 for (i = 0; i < count; i++) {
3459 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3463 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3464 memmove(h, h + 1, sz);
3468 if (ctl3_hsize == 0) {
3469 if (ctl3_handlers != NULL)
3470 free(ctl3_handlers, M_IPFW);
3471 ctl3_handlers = NULL;
3482 * Writes data accumulated in @sd to sockopt buffer.
3483 * Zeroes internal @sd buffer.
3486 ipfw_flush_sopt_data(struct sockopt_data *sd)
3488 struct sockopt *sopt;
3498 if (sopt->sopt_dir == SOPT_GET) {
3499 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3504 memset(sd->kbuf, 0, sd->ksize);
3507 if (sd->ktotal + sd->ksize < sd->valsize)
3508 sd->kavail = sd->ksize;
3510 sd->kavail = sd->valsize - sd->ktotal;
3512 /* Update sopt buffer data */
3513 sopt->sopt_valsize = sd->ktotal;
3514 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3520 * Ensures that @sd buffer has contiguous @neeeded number of
3523 * Returns pointer to requested space or NULL.
3526 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3531 if (sd->kavail < needed) {
3533 * Flush data and try another time.
3535 error = ipfw_flush_sopt_data(sd);
3537 if (sd->kavail < needed || error != 0)
3541 addr = sd->kbuf + sd->koff;
3543 sd->kavail -= needed;
3548 * Requests @needed contiguous bytes from @sd buffer.
3549 * Function is used to notify subsystem that we are
3550 * interesed in first @needed bytes (request header)
3551 * and the rest buffer can be safely zeroed.
3553 * Returns pointer to requested space or NULL.
3556 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3560 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3564 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3570 * New sockopt handler.
3573 ipfw_ctl3(struct sockopt *sopt)
3576 size_t size, valsize;
3577 struct ip_fw_chain *chain;
3579 struct sockopt_data sdata;
3580 struct ipfw_sopt_handler h;
3581 ip_fw3_opheader *op3 = NULL;
3583 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3587 if (sopt->sopt_name != IP_FW3)
3588 return (ipfw_ctl(sopt));
3590 chain = &V_layer3_chain;
3593 /* Save original valsize before it is altered via sooptcopyin() */
3594 valsize = sopt->sopt_valsize;
3595 memset(&sdata, 0, sizeof(sdata));
3596 /* Read op3 header first to determine actual operation */
3597 op3 = (ip_fw3_opheader *)xbuf;
3598 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3601 sopt->sopt_valsize = valsize;
3604 * Find and reference command.
3606 error = find_ref_sh(op3->opcode, op3->version, &h);
3611 * Disallow modifications in really-really secure mode, but still allow
3612 * the logging counters to be reset.
3614 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3615 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3623 * Fill in sockopt_data structure that may be useful for
3624 * IP_FW3 get requests.
3627 if (valsize <= sizeof(xbuf)) {
3628 /* use on-stack buffer */
3630 sdata.ksize = sizeof(xbuf);
3631 sdata.kavail = valsize;
3635 * Determine opcode type/buffer size:
3636 * allocate sliding-window buf for data export or
3637 * contiguous buffer for special ops.
3639 if ((h.dir & HDIR_SET) != 0) {
3640 /* Set request. Allocate contigous buffer. */
3641 if (valsize > CTL3_LARGEBUF) {
3648 /* Get request. Allocate sliding window buffer */
3649 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3651 if (size < valsize) {
3652 /* We have to wire user buffer */
3653 error = vslock(sopt->sopt_val, valsize);
3660 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3662 sdata.kavail = size;
3666 sdata.sopt_val = sopt->sopt_val;
3667 sdata.valsize = valsize;
3670 * Copy either all request (if valsize < bsize_max)
3671 * or first bsize_max bytes to guarantee most consumers
3672 * that all necessary data has been copied).
3673 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3675 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3676 sizeof(ip_fw3_opheader))) != 0)
3678 op3 = (ip_fw3_opheader *)sdata.kbuf;
3680 /* Finally, run handler */
3681 error = h.handler(chain, op3, &sdata);
3684 /* Flush state and free buffers */
3686 error = ipfw_flush_sopt_data(&sdata);
3688 ipfw_flush_sopt_data(&sdata);
3691 vsunlock(sdata.sopt_val, valsize);
3693 /* Restore original pointer and set number of bytes written */
3694 sopt->sopt_val = sdata.sopt_val;
3695 sopt->sopt_valsize = sdata.ktotal;
3696 if (sdata.kbuf != xbuf)
3697 free(sdata.kbuf, M_TEMP);
3703 * {set|get}sockopt parser.
3706 ipfw_ctl(struct sockopt *sopt)
3708 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3710 size_t size, valsize;
3712 struct ip_fw_rule0 *rule;
3713 struct ip_fw_chain *chain;
3714 u_int32_t rulenum[2];
3716 struct rule_check_info ci;
3719 chain = &V_layer3_chain;
3722 /* Save original valsize before it is altered via sooptcopyin() */
3723 valsize = sopt->sopt_valsize;
3724 opt = sopt->sopt_name;
3727 * Disallow modifications in really-really secure mode, but still allow
3728 * the logging counters to be reset.
3730 if (opt == IP_FW_ADD ||
3731 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3732 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3740 * pass up a copy of the current rules. Static rules
3741 * come first (the last of which has number IPFW_DEFAULT_RULE),
3742 * followed by a possibly empty list of dynamic rule.
3743 * The last dynamic rule has NULL in the "next" field.
3745 * Note that the calculated size is used to bound the
3746 * amount of data returned to the user. The rule set may
3747 * change between calculating the size and returning the
3748 * data in which case we'll just return what fits.
3753 size = chain->static_len;
3754 size += ipfw_dyn_len();
3755 if (size >= sopt->sopt_valsize)
3757 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3758 IPFW_UH_RLOCK(chain);
3759 /* check again how much space we need */
3760 want = chain->static_len + ipfw_dyn_len();
3762 len = ipfw_getrules(chain, buf, size);
3763 IPFW_UH_RUNLOCK(chain);
3765 error = sooptcopyout(sopt, buf, len);
3773 /* locking is done within del_entry() */
3774 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3778 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3779 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3780 sizeof(struct ip_fw7) );
3782 memset(&ci, 0, sizeof(struct rule_check_info));
3785 * If the size of commands equals RULESIZE7 then we assume
3786 * a FreeBSD7.2 binary is talking to us (set is7=1).
3787 * is7 is persistent so the next 'ipfw list' command
3788 * will use this format.
3789 * NOTE: If wrong version is guessed (this can happen if
3790 * the first ipfw command is 'ipfw [pipe] list')
3791 * the ipfw binary may crash or loop infinitly...
3793 size = sopt->sopt_valsize;
3794 if (size == RULESIZE7(rule)) {
3796 error = convert_rule_to_8(rule);
3801 size = RULESIZE(rule);
3805 error = check_ipfw_rule0(rule, size, &ci);
3807 /* locking is done within add_rule() */
3808 struct ip_fw *krule;
3809 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3810 ci.urule = (caddr_t)rule;
3813 error = commit_rules(chain, &ci, 1);
3815 free_rule(ci.krule);
3816 else if (sopt->sopt_dir == SOPT_GET) {
3818 error = convert_rule_to_7(rule);
3819 size = RULESIZE7(rule);
3825 error = sooptcopyout(sopt, rule, size);
3833 * IP_FW_DEL is used for deleting single rules or sets,
3834 * and (ab)used to atomically manipulate sets. Argument size
3835 * is used to distinguish between the two:
3837 * delete single rule or set of rules,
3838 * or reassign rules (or sets) to a different set.
3839 * 2*sizeof(u_int32_t)
3840 * atomic disable/enable sets.
3841 * first u_int32_t contains sets to be disabled,
3842 * second u_int32_t contains sets to be enabled.
3844 error = sooptcopyin(sopt, rulenum,
3845 2*sizeof(u_int32_t), sizeof(u_int32_t));
3848 size = sopt->sopt_valsize;
3849 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3850 /* delete or reassign, locking done in del_entry() */
3851 error = del_entry(chain, rulenum[0]);
3852 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3853 IPFW_UH_WLOCK(chain);
3855 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3856 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3857 IPFW_UH_WUNLOCK(chain);
3863 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3865 if (sopt->sopt_val != 0) {
3866 error = sooptcopyin(sopt, rulenum,
3867 sizeof(u_int32_t), sizeof(u_int32_t));
3871 error = zero_entry(chain, rulenum[0],
3872 sopt->sopt_name == IP_FW_RESETLOG);
3875 /*--- TABLE opcodes ---*/
3876 case IP_FW_TABLE_ADD:
3877 case IP_FW_TABLE_DEL:
3879 ipfw_table_entry ent;
3880 struct tentry_info tei;
3882 struct table_value v;
3884 error = sooptcopyin(sopt, &ent,
3885 sizeof(ent), sizeof(ent));
3889 memset(&tei, 0, sizeof(tei));
3890 tei.paddr = &ent.addr;
3891 tei.subtype = AF_INET;
3892 tei.masklen = ent.masklen;
3893 ipfw_import_table_value_legacy(ent.value, &v);
3895 memset(&ti, 0, sizeof(ti));
3897 ti.type = IPFW_TABLE_CIDR;
3899 error = (opt == IP_FW_TABLE_ADD) ?
3900 add_table_entry(chain, &ti, &tei, 0, 1) :
3901 del_table_entry(chain, &ti, &tei, 0, 1);
3906 case IP_FW_TABLE_FLUSH:
3911 error = sooptcopyin(sopt, &tbl,
3912 sizeof(tbl), sizeof(tbl));
3915 memset(&ti, 0, sizeof(ti));
3917 error = flush_table(chain, &ti);
3921 case IP_FW_TABLE_GETSIZE:
3926 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3929 memset(&ti, 0, sizeof(ti));
3932 error = ipfw_count_table(chain, &ti, &cnt);
3933 IPFW_RUNLOCK(chain);
3936 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3940 case IP_FW_TABLE_LIST:
3945 if (sopt->sopt_valsize < sizeof(*tbl)) {
3949 size = sopt->sopt_valsize;
3950 tbl = malloc(size, M_TEMP, M_WAITOK);
3951 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3956 tbl->size = (size - sizeof(*tbl)) /
3957 sizeof(ipfw_table_entry);
3958 memset(&ti, 0, sizeof(ti));
3961 error = ipfw_dump_table_legacy(chain, &ti, tbl);
3962 IPFW_RUNLOCK(chain);
3967 error = sooptcopyout(sopt, tbl, size);
3972 /*--- NAT operations are protected by the IPFW_LOCK ---*/
3974 if (IPFW_NAT_LOADED)
3975 error = ipfw_nat_cfg_ptr(sopt);
3977 printf("IP_FW_NAT_CFG: %s\n",
3978 "ipfw_nat not present, please load it");
3984 if (IPFW_NAT_LOADED)
3985 error = ipfw_nat_del_ptr(sopt);
3987 printf("IP_FW_NAT_DEL: %s\n",
3988 "ipfw_nat not present, please load it");
3993 case IP_FW_NAT_GET_CONFIG:
3994 if (IPFW_NAT_LOADED)
3995 error = ipfw_nat_get_cfg_ptr(sopt);
3997 printf("IP_FW_NAT_GET_CFG: %s\n",
3998 "ipfw_nat not present, please load it");
4003 case IP_FW_NAT_GET_LOG:
4004 if (IPFW_NAT_LOADED)
4005 error = ipfw_nat_get_log_ptr(sopt);
4007 printf("IP_FW_NAT_GET_LOG: %s\n",
4008 "ipfw_nat not present, please load it");
4014 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4021 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4023 /* Functions to convert rules 7.2 <==> 8.0 */
4025 convert_rule_to_7(struct ip_fw_rule0 *rule)
4027 /* Used to modify original rule */
4028 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4029 /* copy of original rule, version 8 */
4030 struct ip_fw_rule0 *tmp;
4032 /* Used to copy commands */
4033 ipfw_insn *ccmd, *dst;
4034 int ll = 0, ccmdlen = 0;
4036 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4038 return 1; //XXX error
4040 bcopy(rule, tmp, RULE_MAXSIZE);
4043 //rule7->_pad = tmp->_pad;
4044 rule7->set = tmp->set;
4045 rule7->rulenum = tmp->rulenum;
4046 rule7->cmd_len = tmp->cmd_len;
4047 rule7->act_ofs = tmp->act_ofs;
4048 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4049 rule7->cmd_len = tmp->cmd_len;
4050 rule7->pcnt = tmp->pcnt;
4051 rule7->bcnt = tmp->bcnt;
4052 rule7->timestamp = tmp->timestamp;
4055 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4056 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4057 ccmdlen = F_LEN(ccmd);
4059 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4061 if (dst->opcode > O_NAT)
4062 /* O_REASS doesn't exists in 7.2 version, so
4063 * decrement opcode if it is after O_REASS
4068 printf("ipfw: opcode %d size truncated\n",
4079 convert_rule_to_8(struct ip_fw_rule0 *rule)
4081 /* Used to modify original rule */
4082 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4084 /* Used to copy commands */
4085 ipfw_insn *ccmd, *dst;
4086 int ll = 0, ccmdlen = 0;
4088 /* Copy of original rule */
4089 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4091 return 1; //XXX error
4094 bcopy(rule7, tmp, RULE_MAXSIZE);
4096 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4097 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4098 ccmdlen = F_LEN(ccmd);
4100 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4102 if (dst->opcode > O_NAT)
4103 /* O_REASS doesn't exists in 7.2 version, so
4104 * increment opcode if it is after O_REASS
4109 printf("ipfw: opcode %d size truncated\n",
4115 rule->_pad = tmp->_pad;
4116 rule->set = tmp->set;
4117 rule->rulenum = tmp->rulenum;
4118 rule->cmd_len = tmp->cmd_len;
4119 rule->act_ofs = tmp->act_ofs;
4120 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4121 rule->cmd_len = tmp->cmd_len;
4122 rule->id = 0; /* XXX see if is ok = 0 */
4123 rule->pcnt = tmp->pcnt;
4124 rule->bcnt = tmp->bcnt;
4125 rule->timestamp = tmp->timestamp;
4137 ipfw_init_srv(struct ip_fw_chain *ch)
4140 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4141 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4142 M_IPFW, M_WAITOK | M_ZERO);
4146 ipfw_destroy_srv(struct ip_fw_chain *ch)
4149 free(ch->srvstate, M_IPFW);
4150 ipfw_objhash_destroy(ch->srvmap);
4154 * Allocate new bitmask which can be used to enlarge/shrink
4155 * named instance index.
4158 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4164 KASSERT((items % BLOCK_ITEMS) == 0,
4165 ("bitmask size needs to power of 2 and greater or equal to %zu",
4168 max_blocks = items / BLOCK_ITEMS;
4170 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4171 /* Mark all as free */
4172 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4173 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4176 *pblocks = max_blocks;
4180 * Copy current bitmask index to new one.
4183 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4185 int old_blocks, new_blocks;
4186 u_long *old_idx, *new_idx;
4189 old_idx = ni->idx_mask;
4190 old_blocks = ni->max_blocks;
4192 new_blocks = *blocks;
4194 for (i = 0; i < IPFW_MAX_SETS; i++) {
4195 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4196 old_blocks * sizeof(u_long));
4201 * Swaps current @ni index with new one.
4204 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4209 old_idx = ni->idx_mask;
4210 old_blocks = ni->max_blocks;
4212 ni->idx_mask = *idx;
4213 ni->max_blocks = *blocks;
4215 /* Save old values */
4217 *blocks = old_blocks;
4221 ipfw_objhash_bitmap_free(void *idx, int blocks)
4228 * Creates named hash instance.
4229 * Must be called without holding any locks.
4230 * Return pointer to new instance.
4232 struct namedobj_instance *
4233 ipfw_objhash_create(uint32_t items)
4235 struct namedobj_instance *ni;
4239 size = sizeof(struct namedobj_instance) +
4240 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4241 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4243 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4244 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4245 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4247 ni->names = (struct namedobjects_head *)(ni +1);
4248 ni->values = &ni->names[ni->nn_size];
4250 for (i = 0; i < ni->nn_size; i++)
4251 TAILQ_INIT(&ni->names[i]);
4253 for (i = 0; i < ni->nv_size; i++)
4254 TAILQ_INIT(&ni->values[i]);
4256 /* Set default hashing/comparison functions */
4257 ni->hash_f = objhash_hash_name;
4258 ni->cmp_f = objhash_cmp_name;
4260 /* Allocate bitmask separately due to possible resize */
4261 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4267 ipfw_objhash_destroy(struct namedobj_instance *ni)
4270 free(ni->idx_mask, M_IPFW);
4275 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4276 objhash_cmp_f *cmp_f)
4279 ni->hash_f = hash_f;
4284 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4287 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4291 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4294 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4301 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4305 v = val % (ni->nv_size - 1);
4310 struct named_object *
4311 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4313 struct named_object *no;
4316 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4318 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4319 if (ni->cmp_f(no, name, set) == 0)
4327 * Find named object by @uid.
4328 * Check @tlvs for valid data inside.
4330 * Returns pointer to found TLV or NULL.
4333 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4335 ipfw_obj_ntlv *ntlv;
4339 pa = (uintptr_t)tlvs;
4342 for (; pa < pe; pa += l) {
4343 ntlv = (ipfw_obj_ntlv *)pa;
4344 l = ntlv->head.length;
4346 if (l != sizeof(*ntlv))
4349 if (ntlv->idx != uidx)
4352 * When userland has specified zero TLV type, do
4353 * not compare it with eltv. In some cases userland
4354 * doesn't know what type should it have. Use only
4355 * uidx and name for search named_object.
4357 if (ntlv->head.type != 0 &&
4358 ntlv->head.type != (uint16_t)etlv)
4361 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4371 * Finds object config based on either legacy index
4373 * Note @ti structure contains unchecked data from userland.
4375 * Returns 0 in success and fills in @pno with found config
4378 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4379 uint32_t etlv, struct named_object **pno)
4382 ipfw_obj_ntlv *ntlv;
4385 if (ti->tlvs == NULL)
4388 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4394 * Use set provided by @ti instead of @ntlv one.
4395 * This is needed due to different sets behavior
4396 * controlled by V_fw_tables_sets.
4399 *pno = ipfw_objhash_lookup_name(ni, set, name);
4406 * Find named object by name, considering also its TLV type.
4408 struct named_object *
4409 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4410 uint32_t type, const char *name)
4412 struct named_object *no;
4415 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4417 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4418 if (ni->cmp_f(no, name, set) == 0 &&
4419 no->etlv == (uint16_t)type)
4426 struct named_object *
4427 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4429 struct named_object *no;
4432 hash = objhash_hash_idx(ni, kidx);
4434 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4435 if (no->kidx == kidx)
4443 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4444 struct named_object *b)
4447 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4454 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4458 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4459 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4461 hash = objhash_hash_idx(ni, no->kidx);
4462 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4468 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4472 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4473 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4475 hash = objhash_hash_idx(ni, no->kidx);
4476 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4482 ipfw_objhash_count(struct namedobj_instance *ni)
4489 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4491 struct named_object *no;
4496 for (i = 0; i < ni->nn_size; i++) {
4497 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4498 if (no->etlv == type)
4506 * Runs @func for each found named object.
4507 * It is safe to delete objects from callback
4510 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4512 struct named_object *no, *no_tmp;
4515 for (i = 0; i < ni->nn_size; i++) {
4516 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4517 ret = f(ni, no, arg);
4526 * Runs @f for each found named object with type @type.
4527 * It is safe to delete objects from callback
4530 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4531 void *arg, uint16_t type)
4533 struct named_object *no, *no_tmp;
4536 for (i = 0; i < ni->nn_size; i++) {
4537 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4538 if (no->etlv != type)
4540 ret = f(ni, no, arg);
4549 * Removes index from given set.
4550 * Returns 0 on success.
4553 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4558 i = idx / BLOCK_ITEMS;
4559 v = idx % BLOCK_ITEMS;
4561 if (i >= ni->max_blocks)
4564 mask = &ni->idx_mask[i];
4566 if ((*mask & ((u_long)1 << v)) != 0)
4570 *mask |= (u_long)1 << v;
4572 /* Update free offset */
4573 if (ni->free_off[0] > i)
4574 ni->free_off[0] = i;
4580 * Allocate new index in given instance and stores in in @pidx.
4581 * Returns 0 on success.
4584 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4586 struct namedobj_instance *ni;
4590 ni = (struct namedobj_instance *)n;
4592 off = ni->free_off[0];
4593 mask = &ni->idx_mask[off];
4595 for (i = off; i < ni->max_blocks; i++, mask++) {
4596 if ((v = ffsl(*mask)) == 0)
4600 *mask &= ~ ((u_long)1 << (v - 1));
4602 ni->free_off[0] = i;
4604 v = BLOCK_ITEMS * i + v - 1;