2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5 * Copyright (c) 2014 Yandex LLC
6 * Copyright (c) 2014 Alexander V. Chernikov
8 * Supported by: Valeria Paoli
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
36 * Control socket and rule management routines for ipfw.
37 * Control is currently implemented via IP_FW3 setsockopt() code.
43 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h> /* struct m_tag used by nested headers */
51 #include <sys/kernel.h>
55 #include <sys/rwlock.h>
56 #include <sys/rmlock.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/fnv_hash.h>
63 #include <net/route.h>
66 #include <vm/vm_extern.h>
68 #include <netinet/in.h>
69 #include <netinet/ip_var.h> /* hooks */
70 #include <netinet/ip_fw.h>
72 #include <netpfil/ipfw/ip_fw_private.h>
73 #include <netpfil/ipfw/ip_fw_table.h>
76 #include <security/mac/mac_framework.h>
79 static int ipfw_ctl(struct sockopt *sopt);
80 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
81 struct rule_check_info *ci);
82 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
83 struct rule_check_info *ci);
84 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
85 struct rule_check_info *ci);
86 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
87 struct rule_check_info *ci);
89 #define NAMEDOBJ_HASH_SIZE 32
91 struct namedobj_instance {
92 struct namedobjects_head *names;
93 struct namedobjects_head *values;
94 uint32_t nn_size; /* names hash size */
95 uint32_t nv_size; /* number hash size */
96 u_long *idx_mask; /* used items bitmask */
97 uint32_t max_blocks; /* number of "long" blocks in bitmask */
98 uint32_t count; /* number of items */
99 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
100 objhash_hash_f *hash_f;
101 objhash_cmp_f *cmp_f;
103 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
105 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
106 const void *key, uint32_t kopt);
107 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
108 static int objhash_cmp_name(struct named_object *no, const void *name,
111 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
113 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
114 struct sockopt_data *sd);
115 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
116 struct sockopt_data *sd);
117 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
118 struct sockopt_data *sd);
119 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
120 struct sockopt_data *sd);
121 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
122 struct sockopt_data *sd);
123 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
124 struct sockopt_data *sd);
125 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
126 struct sockopt_data *sd);
127 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
128 struct sockopt_data *sd);
130 /* ctl3 handler data */
131 struct mtx ctl3_lock;
132 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
133 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
134 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
135 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
137 static struct ipfw_sopt_handler *ctl3_handlers;
138 static size_t ctl3_hsize;
139 static uint64_t ctl3_refct, ctl3_gencnt;
140 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
141 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
143 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
145 static struct ipfw_sopt_handler scodes[] = {
146 { IP_FW_XGET, 0, HDIR_GET, dump_config },
147 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
148 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
149 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
150 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
151 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
152 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
153 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
154 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
155 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
156 { IP_FW_DUMP_SRVOBJECTS,0, HDIR_GET, dump_srvobjects },
160 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
161 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
162 uint16_t *puidx, uint8_t *ptype);
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 VNET_DEFINE_STATIC(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_pcpu(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
215 ipfw_free_rule(struct ip_fw *rule)
219 * We don't release refcnt here, since this function
220 * can be called without any locks held. The caller
221 * must release reference under IPFW_UH_WLOCK, and then
222 * call this function if refcount becomes 1.
224 if (rule->refcnt > 1)
226 uma_zfree_pcpu(V_ipfw_cntr_zone, rule->cntr);
232 * Find the smallest rule >= key, id.
233 * We could use bsearch but it is so simple that we code it directly
236 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
241 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
244 if (r->rulenum < key)
245 lo = i + 1; /* continue from the next one */
246 else if (r->rulenum > key)
247 hi = i; /* this might be good */
249 lo = i + 1; /* continue from the next one */
250 else /* r->id >= id */
251 hi = i; /* this might be good */
257 * Builds skipto cache on rule set @map.
260 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
265 IPFW_UH_WLOCK_ASSERT(chain);
268 rulenum = map[mi]->rulenum;
269 smap = chain->idxmap_back;
274 for (i = 0; i < 65536; i++) {
276 /* Use the same rule index until i < rulenum */
277 if (i != rulenum || i == 65535)
279 /* Find next rule with num > i */
280 rulenum = map[++mi]->rulenum;
282 rulenum = map[++mi]->rulenum;
287 * Swaps prepared (backup) index with current one.
290 swap_skipto_cache(struct ip_fw_chain *chain)
294 IPFW_UH_WLOCK_ASSERT(chain);
295 IPFW_WLOCK_ASSERT(chain);
298 chain->idxmap = chain->idxmap_back;
299 chain->idxmap_back = map;
303 * Allocate and initialize skipto cache.
306 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
308 int *idxmap, *idxmap_back;
310 idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
311 idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
314 * Note we may be called at any time after initialization,
315 * for example, on first skipto rule, so we need to
316 * provide valid chain->idxmap on return
319 IPFW_UH_WLOCK(chain);
320 if (chain->idxmap != NULL) {
321 IPFW_UH_WUNLOCK(chain);
322 free(idxmap, M_IPFW);
323 free(idxmap_back, M_IPFW);
327 /* Set backup pointer first to permit building cache */
328 chain->idxmap_back = idxmap_back;
329 update_skipto_cache(chain, chain->map);
331 /* It is now safe to set chain->idxmap ptr */
332 chain->idxmap = idxmap;
333 swap_skipto_cache(chain);
335 IPFW_UH_WUNLOCK(chain);
339 * Destroys skipto cache.
342 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
345 if (chain->idxmap != NULL)
346 free(chain->idxmap, M_IPFW);
347 if (chain->idxmap != NULL)
348 free(chain->idxmap_back, M_IPFW);
353 * allocate a new map, returns the chain locked. extra is the number
354 * of entries to add or delete.
356 static struct ip_fw **
357 get_map(struct ip_fw_chain *chain, int extra, int locked)
364 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
366 i = chain->n_rules + extra;
367 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
369 printf("%s: cannot allocate map\n", __FUNCTION__);
373 IPFW_UH_WLOCK(chain);
374 if (i >= chain->n_rules + extra) /* good */
376 /* otherwise we lost the race, free and retry */
378 IPFW_UH_WUNLOCK(chain);
384 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
386 static struct ip_fw **
387 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
389 struct ip_fw **old_map;
393 chain->n_rules = new_len;
394 old_map = chain->map;
395 chain->map = new_map;
396 swap_skipto_cache(chain);
403 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
405 struct timeval boottime;
407 cntr->size = sizeof(*cntr);
409 if (krule->cntr != NULL) {
410 cntr->pcnt = counter_u64_fetch(krule->cntr);
411 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
412 cntr->timestamp = krule->timestamp;
414 if (cntr->timestamp > 0) {
415 getboottime(&boottime);
416 cntr->timestamp += boottime.tv_sec;
421 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
423 struct timeval boottime;
425 if (krule->cntr != NULL) {
426 cntr->pcnt = counter_u64_fetch(krule->cntr);
427 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
428 cntr->timestamp = krule->timestamp;
430 if (cntr->timestamp > 0) {
431 getboottime(&boottime);
432 cntr->timestamp += boottime.tv_sec;
437 * Copies rule @urule from v1 userland format (current).
439 * Assume @krule is zeroed.
442 import_rule1(struct rule_check_info *ci)
444 struct ip_fw_rule *urule;
447 urule = (struct ip_fw_rule *)ci->urule;
448 krule = (struct ip_fw *)ci->krule;
451 krule->act_ofs = urule->act_ofs;
452 krule->cmd_len = urule->cmd_len;
453 krule->rulenum = urule->rulenum;
454 krule->set = urule->set;
455 krule->flags = urule->flags;
457 /* Save rulenum offset */
458 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
461 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
465 * Export rule into v1 format (Current).
467 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
469 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
471 * Assume @data is zeroed.
474 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
476 struct ip_fw_bcounter *cntr;
477 struct ip_fw_rule *urule;
480 /* Fill in TLV header */
481 tlv = (ipfw_obj_tlv *)data;
482 tlv->type = IPFW_TLV_RULE_ENT;
487 cntr = (struct ip_fw_bcounter *)(tlv + 1);
488 urule = (struct ip_fw_rule *)(cntr + 1);
489 export_cntr1_base(krule, cntr);
491 urule = (struct ip_fw_rule *)(tlv + 1);
494 urule->act_ofs = krule->act_ofs;
495 urule->cmd_len = krule->cmd_len;
496 urule->rulenum = krule->rulenum;
497 urule->set = krule->set;
498 urule->flags = krule->flags;
499 urule->id = krule->id;
502 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
507 * Copies rule @urule from FreeBSD8 userland format (v0)
509 * Assume @krule is zeroed.
512 import_rule0(struct rule_check_info *ci)
514 struct ip_fw_rule0 *urule;
518 ipfw_insn_limit *lcmd;
521 urule = (struct ip_fw_rule0 *)ci->urule;
522 krule = (struct ip_fw *)ci->krule;
525 krule->act_ofs = urule->act_ofs;
526 krule->cmd_len = urule->cmd_len;
527 krule->rulenum = urule->rulenum;
528 krule->set = urule->set;
529 if ((urule->_pad & 1) != 0)
530 krule->flags |= IPFW_RULE_NOOPT;
532 /* Save rulenum offset */
533 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
536 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
540 * 1) convert tablearg value from 65535 to 0
541 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
543 * 3) convert table number in iface opcodes to u16
544 * 4) convert old `nat global` into new 65535
550 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
553 switch (cmd->opcode) {
554 /* Opcodes supporting tablearg */
566 if (cmd->arg1 == IP_FW_TABLEARG)
567 cmd->arg1 = IP_FW_TARG;
568 else if (cmd->arg1 == 0)
569 cmd->arg1 = IP_FW_NAT44_GLOBAL;
573 if (cmd->arg1 == IP_FW_TABLEARG)
574 cmd->arg1 = IP_FW_TARG;
579 lcmd = (ipfw_insn_limit *)cmd;
580 if (lcmd->conn_limit == IP_FW_TABLEARG)
581 lcmd->conn_limit = IP_FW_TARG;
583 /* Interface tables */
587 /* Interface table, possibly */
588 cmdif = (ipfw_insn_if *)cmd;
589 if (cmdif->name[0] != '\1')
592 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
599 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
602 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
606 ipfw_insn_limit *lcmd;
610 memset(urule, 0, len);
611 urule->act_ofs = krule->act_ofs;
612 urule->cmd_len = krule->cmd_len;
613 urule->rulenum = krule->rulenum;
614 urule->set = krule->set;
615 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
619 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
621 /* Export counters */
622 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
626 * 1) convert tablearg value from 0 to 65535
627 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
628 * 3) convert table number in iface opcodes to int
634 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
637 switch (cmd->opcode) {
638 /* Opcodes supporting tablearg */
650 if (cmd->arg1 == IP_FW_TARG)
651 cmd->arg1 = IP_FW_TABLEARG;
652 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
657 if (cmd->arg1 == IP_FW_TARG)
658 cmd->arg1 = IP_FW_TABLEARG;
660 cmd->arg1 &= ~0x8000;
663 lcmd = (ipfw_insn_limit *)cmd;
664 if (lcmd->conn_limit == IP_FW_TARG)
665 lcmd->conn_limit = IP_FW_TABLEARG;
667 /* Interface tables */
671 /* Interface table, possibly */
672 cmdif = (ipfw_insn_if *)cmd;
673 if (cmdif->name[0] != '\1')
676 cmdif->p.glob = cmdif->p.kidx;
683 * Add new rule(s) to the list possibly creating rule number for each.
684 * Update the rule_number in the input struct so the caller knows it as well.
685 * Must be called without IPFW_UH held
688 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
690 int error, i, insert_before, tcount;
691 uint16_t rulenum, *pnum;
692 struct rule_check_info *ci;
694 struct ip_fw **map; /* the new array of pointers */
696 /* Check if we need to do table/obj index remap */
698 for (ci = rci, i = 0; i < count; ci++, i++) {
699 if (ci->object_opcodes == 0)
703 * Rule has some object opcodes.
704 * We need to find (and create non-existing)
705 * kernel objects, and reference existing ones.
707 error = rewrite_rule_uidx(chain, ci);
711 * rewrite failed, state for current rule
712 * has been reverted. Check if we need to
718 * We have some more table rules
719 * we need to rollback.
722 IPFW_UH_WLOCK(chain);
725 if (ci->object_opcodes == 0)
727 unref_rule_objects(chain,ci->krule);
730 IPFW_UH_WUNLOCK(chain);
740 /* get_map returns with IPFW_UH_WLOCK if successful */
741 map = get_map(chain, count, 0 /* not locked */);
745 IPFW_UH_WLOCK(chain);
746 for (ci = rci, i = 0; i < count; ci++, i++) {
747 if (ci->object_opcodes == 0)
750 unref_rule_objects(chain, ci->krule);
752 IPFW_UH_WUNLOCK(chain);
758 if (V_autoinc_step < 1)
760 else if (V_autoinc_step > 1000)
761 V_autoinc_step = 1000;
763 /* FIXME: Handle count > 1 */
766 rulenum = krule->rulenum;
768 /* find the insertion point, we will insert before */
769 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
770 i = ipfw_find_rule(chain, insert_before, 0);
771 /* duplicate first part */
773 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
775 /* duplicate remaining part, we always have the default rule */
776 bcopy(chain->map + i, map + i + 1,
777 sizeof(struct ip_fw *) *(chain->n_rules - i));
779 /* Compute rule number and write it back */
780 rulenum = i > 0 ? map[i-1]->rulenum : 0;
781 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
782 rulenum += V_autoinc_step;
783 krule->rulenum = rulenum;
784 /* Save number to userland rule */
785 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
789 krule->id = chain->id + 1;
790 update_skipto_cache(chain, map);
791 map = swap_map(chain, map, chain->n_rules + 1);
792 chain->static_len += RULEUSIZE0(krule);
793 IPFW_UH_WUNLOCK(chain);
800 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
805 map = get_map(chain, 1, locked);
808 if (chain->n_rules > 0)
809 bcopy(chain->map, map,
810 chain->n_rules * sizeof(struct ip_fw *));
811 map[chain->n_rules] = rule;
812 rule->rulenum = IPFW_DEFAULT_RULE;
813 rule->set = RESVD_SET;
814 rule->id = chain->id + 1;
815 /* We add rule in the end of chain, no need to update skipto cache */
816 map = swap_map(chain, map, chain->n_rules + 1);
817 chain->static_len += RULEUSIZE0(rule);
818 IPFW_UH_WUNLOCK(chain);
824 * Adds @rule to the list of rules to reap
827 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
831 IPFW_UH_WLOCK_ASSERT(chain);
833 /* Unlink rule from everywhere */
834 unref_rule_objects(chain, rule);
841 * Reclaim storage associated with a list of rules. This is
842 * typically the list created using remove_rule.
843 * A NULL pointer on input is handled correctly.
846 ipfw_reap_rules(struct ip_fw *head)
850 while ((rule = head) != NULL) {
852 ipfw_free_rule(rule);
858 * (default || reserved || !match_set || !match_number)
860 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
861 * // the default rule is always protected
863 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
864 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
866 * match_set ::= (cmd == 0 || rule->set == set)
867 * // set number is ignored for cmd == 0
869 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
870 * // number is ignored for cmd == 1 or n == 0
874 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
877 /* Don't match default rule for modification queries */
878 if (rule->rulenum == IPFW_DEFAULT_RULE &&
879 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
882 /* Don't match rules in reserved set for flush requests */
883 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
886 /* If we're filtering by set, don't match other sets */
887 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
890 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
891 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
897 struct manage_sets_args {
903 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
906 struct manage_sets_args *args;
908 args = (struct manage_sets_args *)arg;
909 if (no->set == (uint8_t)args->set)
910 no->set = args->new_set;
911 else if (no->set == args->new_set)
912 no->set = (uint8_t)args->set;
917 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
920 struct manage_sets_args *args;
922 args = (struct manage_sets_args *)arg;
923 if (no->set == (uint8_t)args->set)
924 no->set = args->new_set;
929 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
932 struct manage_sets_args *args;
934 args = (struct manage_sets_args *)arg;
935 if (no->set != (uint8_t)args->set)
937 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
938 no->etlv, no->name) != NULL)
944 * Generic function to handler moving and swapping sets.
947 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
948 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
950 struct manage_sets_args args;
951 struct named_object *no;
954 args.new_set = new_set;
957 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
960 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
963 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
967 * @set used to pass kidx.
968 * When @new_set is zero - reset object counter,
969 * otherwise increment it.
971 no = ipfw_objhash_lookup_kidx(ni, set);
978 /* @set used to pass kidx */
979 no = ipfw_objhash_lookup_kidx(ni, set);
981 * First check number of references:
982 * when it differs, this mean other rules are holding
983 * reference to given object, so it is not possible to
984 * change its set. Note that refcnt may account references
985 * to some going-to-be-added rules. Since we don't know
986 * their numbers (and even if they will be added) it is
987 * perfectly OK to return error here.
989 if (no->ocnt != no->refcnt)
991 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
996 /* @set used to pass kidx */
997 no = ipfw_objhash_lookup_kidx(ni, set);
1005 * Delete rules matching range @rt.
1006 * Saves number of deleted rules in @ndel.
1008 * Returns 0 on success.
1011 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1013 struct ip_fw *reap, *rule, **map;
1015 int i, n, ndyn, ofs;
1018 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1021 * Stage 1: Determine range to inspect.
1022 * Range is half-inclusive, e.g [start, end).
1025 end = chain->n_rules - 1;
1027 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1028 start = ipfw_find_rule(chain, rt->start_rule, 0);
1030 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1031 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1032 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1035 if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1037 * Requested deleting only for dynamic states.
1040 ipfw_expire_dyn_states(chain, rt);
1041 IPFW_UH_WUNLOCK(chain);
1045 /* Allocate new map of the same size */
1046 map = get_map(chain, 0, 1 /* locked */);
1048 IPFW_UH_WUNLOCK(chain);
1055 /* 1. bcopy the initial part of the map */
1057 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1058 /* 2. copy active rules between start and end */
1059 for (i = start; i < end; i++) {
1060 rule = chain->map[i];
1061 if (ipfw_match_range(rule, rt) == 0) {
1067 if (ipfw_is_dyn_rule(rule) != 0)
1070 /* 3. copy the final part of the map */
1071 bcopy(chain->map + end, map + ofs,
1072 (chain->n_rules - end) * sizeof(struct ip_fw *));
1073 /* 4. recalculate skipto cache */
1074 update_skipto_cache(chain, map);
1075 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1076 map = swap_map(chain, map, chain->n_rules - n);
1077 /* 6. Remove all dynamic states originated by deleted rules */
1079 ipfw_expire_dyn_states(chain, rt);
1080 /* 7. now remove the rules deleted from the old map */
1081 for (i = start; i < end; i++) {
1083 if (ipfw_match_range(rule, rt) == 0)
1085 chain->static_len -= RULEUSIZE0(rule);
1086 ipfw_reap_add(chain, &reap, rule);
1088 IPFW_UH_WUNLOCK(chain);
1090 ipfw_reap_rules(reap);
1098 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1100 struct opcode_obj_rewrite *rw;
1103 int cmdlen, i, l, c;
1106 IPFW_UH_WLOCK_ASSERT(ch);
1108 /* Stage 1: count number of references by given rules */
1109 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1111 if (ipfw_match_range(rule, rt) == 0)
1113 if (rule->set == rt->new_set) /* nothing to do */
1115 /* Search opcodes with named objects */
1116 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1117 l > 0; l -= cmdlen, cmd += cmdlen) {
1118 cmdlen = F_LEN(cmd);
1119 rw = find_op_rw(cmd, &kidx, NULL);
1120 if (rw == NULL || rw->manage_sets == NULL)
1123 * When manage_sets() returns non-zero value to
1124 * COUNT_ONE command, consider this as an object
1125 * doesn't support sets (e.g. disabled with sysctl).
1126 * So, skip checks for this object.
1128 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1133 if (c == 0) /* No objects found */
1135 /* Stage 2: verify "ownership" */
1136 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1138 if (ipfw_match_range(rule, rt) == 0)
1140 if (rule->set == rt->new_set) /* nothing to do */
1142 /* Search opcodes with named objects */
1143 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1144 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1145 cmdlen = F_LEN(cmd);
1146 rw = find_op_rw(cmd, &kidx, NULL);
1147 if (rw == NULL || rw->manage_sets == NULL)
1149 /* Test for ownership and conflicting names */
1150 c = rw->manage_sets(ch, kidx,
1151 (uint8_t)rt->new_set, TEST_ONE);
1154 /* Stage 3: change set and cleanup */
1155 for (i = 0; i < ch->n_rules - 1; i++) {
1157 if (ipfw_match_range(rule, rt) == 0)
1159 if (rule->set == rt->new_set) /* nothing to do */
1161 /* Search opcodes with named objects */
1162 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1163 l > 0; l -= cmdlen, cmd += cmdlen) {
1164 cmdlen = F_LEN(cmd);
1165 rw = find_op_rw(cmd, &kidx, NULL);
1166 if (rw == NULL || rw->manage_sets == NULL)
1168 /* cleanup object counter */
1169 rw->manage_sets(ch, kidx,
1170 0 /* reset counter */, COUNT_ONE);
1174 rw->manage_sets(ch, kidx,
1175 (uint8_t)rt->new_set, MOVE_ONE);
1180 * Changes set of given rule rannge @rt
1183 * Returns 0 on success.
1186 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1191 IPFW_UH_WLOCK(chain);
1194 * Move rules with matching paramenerts to a new set.
1195 * This one is much more complex. We have to ensure
1196 * that all referenced tables (if any) are referenced
1197 * by given rule subset only. Otherwise, we can't move
1198 * them to new set and have to return error.
1200 if ((i = move_objects(chain, rt)) != 0) {
1201 IPFW_UH_WUNLOCK(chain);
1205 /* XXX: We have to do swap holding WLOCK */
1206 for (i = 0; i < chain->n_rules; i++) {
1207 rule = chain->map[i];
1208 if (ipfw_match_range(rule, rt) == 0)
1210 rule->set = rt->new_set;
1213 IPFW_UH_WUNLOCK(chain);
1219 * Clear counters for a specific rule.
1220 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1221 * so we only care that rules do not disappear.
1224 clear_counters(struct ip_fw *rule, int log_only)
1226 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1229 IPFW_ZERO_RULE_COUNTER(rule);
1230 if (l->o.opcode == O_LOG)
1231 l->log_left = l->max_log;
1235 * Flushes rules counters and/or log values on matching range.
1237 * Returns number of items cleared.
1240 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1247 rt->flags |= IPFW_RCFLAG_DEFAULT;
1249 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1250 for (i = 0; i < chain->n_rules; i++) {
1251 rule = chain->map[i];
1252 if (ipfw_match_range(rule, rt) == 0)
1254 clear_counters(rule, log_only);
1257 IPFW_UH_WUNLOCK(chain);
1263 check_range_tlv(ipfw_range_tlv *rt)
1266 if (rt->head.length != sizeof(*rt))
1268 if (rt->start_rule > rt->end_rule)
1270 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1273 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1280 * Delete rules matching specified parameters
1281 * Data layout (v0)(current):
1282 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1283 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1285 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1287 * Returns 0 on success.
1290 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1291 struct sockopt_data *sd)
1293 ipfw_range_header *rh;
1296 if (sd->valsize != sizeof(*rh))
1299 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1301 if (check_range_tlv(&rh->range) != 0)
1305 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1308 /* Save number of rules deleted */
1309 rh->range.new_set = ndel;
1314 * Move rules/sets matching specified parameters
1315 * Data layout (v0)(current):
1316 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1318 * Returns 0 on success.
1321 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1322 struct sockopt_data *sd)
1324 ipfw_range_header *rh;
1326 if (sd->valsize != sizeof(*rh))
1329 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1331 if (check_range_tlv(&rh->range) != 0)
1334 return (move_range(chain, &rh->range));
1338 * Clear rule accounting data matching specified parameters
1339 * Data layout (v0)(current):
1340 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1341 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1343 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1345 * Returns 0 on success.
1348 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1349 struct sockopt_data *sd)
1351 ipfw_range_header *rh;
1355 if (sd->valsize != sizeof(*rh))
1358 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1360 if (check_range_tlv(&rh->range) != 0)
1363 log_only = (op3->opcode == IP_FW_XRESETLOG);
1365 num = clear_range(chain, &rh->range, log_only);
1367 if (rh->range.flags & IPFW_RCFLAG_ALL)
1368 msg = log_only ? "All logging counts reset" :
1369 "Accounting cleared";
1371 msg = log_only ? "logging count reset" : "cleared";
1374 int lev = LOG_SECURITY | LOG_NOTICE;
1375 log(lev, "ipfw: %s.\n", msg);
1378 /* Save number of rules cleared */
1379 rh->range.new_set = num;
1384 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1388 IPFW_UH_WLOCK_ASSERT(chain);
1390 /* Change enabled/disabled sets mask */
1391 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1392 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1394 V_set_disable = v_set;
1395 IPFW_WUNLOCK(chain);
1399 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1401 struct opcode_obj_rewrite *rw;
1405 IPFW_UH_WLOCK_ASSERT(chain);
1407 if (rt->set == rt->new_set) /* nothing to do */
1412 * Berfore moving the rules we need to check that
1413 * there aren't any conflicting named objects.
1415 for (rw = ctl3_rewriters;
1416 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1417 if (rw->manage_sets == NULL)
1419 i = rw->manage_sets(chain, (uint8_t)rt->set,
1420 (uint8_t)rt->new_set, TEST_ALL);
1425 /* Swap or move two sets */
1426 for (i = 0; i < chain->n_rules - 1; i++) {
1427 rule = chain->map[i];
1428 if (rule->set == (uint8_t)rt->set)
1429 rule->set = (uint8_t)rt->new_set;
1430 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1431 rule->set = (uint8_t)rt->set;
1433 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1434 if (rw->manage_sets == NULL)
1436 rw->manage_sets(chain, (uint8_t)rt->set,
1437 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1443 * Swaps or moves set
1444 * Data layout (v0)(current):
1445 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1447 * Returns 0 on success.
1450 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1451 struct sockopt_data *sd)
1453 ipfw_range_header *rh;
1456 if (sd->valsize != sizeof(*rh))
1459 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1461 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1463 /* enable_sets() expects bitmasks. */
1464 if (op3->opcode != IP_FW_SET_ENABLE &&
1465 (rh->range.set >= IPFW_MAX_SETS ||
1466 rh->range.new_set >= IPFW_MAX_SETS))
1470 IPFW_UH_WLOCK(chain);
1471 switch (op3->opcode) {
1472 case IP_FW_SET_SWAP:
1473 case IP_FW_SET_MOVE:
1474 ret = swap_sets(chain, &rh->range,
1475 op3->opcode == IP_FW_SET_MOVE);
1477 case IP_FW_SET_ENABLE:
1478 enable_sets(chain, &rh->range);
1481 IPFW_UH_WUNLOCK(chain);
1487 * Remove all rules with given number, or do set manipulation.
1488 * Assumes chain != NULL && *chain != NULL.
1490 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1491 * the next 8 bits are the new set; the top 8 bits indicate the command:
1493 * 0 delete rules numbered "rulenum"
1494 * 1 delete rules in set "rulenum"
1495 * 2 move rules "rulenum" to set "new_set"
1496 * 3 move rules from set "rulenum" to set "new_set"
1497 * 4 swap sets "rulenum" and "new_set"
1498 * 5 delete rules "rulenum" and set "new_set"
1501 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1503 uint32_t num; /* rule number or old_set */
1504 uint8_t cmd, new_set;
1510 cmd = (arg >> 24) & 0xff;
1511 new_set = (arg >> 16) & 0xff;
1513 if (cmd > 5 || new_set > RESVD_SET)
1515 if (cmd == 0 || cmd == 2 || cmd == 5) {
1516 if (num >= IPFW_DEFAULT_RULE)
1519 if (num > RESVD_SET) /* old_set */
1523 /* Convert old requests into new representation */
1524 memset(&rt, 0, sizeof(rt));
1525 rt.start_rule = num;
1528 rt.new_set = new_set;
1532 case 0: /* delete rules numbered "rulenum" */
1534 rt.flags |= IPFW_RCFLAG_ALL;
1536 rt.flags |= IPFW_RCFLAG_RANGE;
1539 case 1: /* delete rules in set "rulenum" */
1540 rt.flags |= IPFW_RCFLAG_SET;
1543 case 5: /* delete rules "rulenum" and set "new_set" */
1544 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1549 case 2: /* move rules "rulenum" to set "new_set" */
1550 rt.flags |= IPFW_RCFLAG_RANGE;
1552 case 3: /* move rules from set "rulenum" to set "new_set" */
1553 IPFW_UH_WLOCK(chain);
1554 error = swap_sets(chain, &rt, 1);
1555 IPFW_UH_WUNLOCK(chain);
1557 case 4: /* swap sets "rulenum" and "new_set" */
1558 IPFW_UH_WLOCK(chain);
1559 error = swap_sets(chain, &rt, 0);
1560 IPFW_UH_WUNLOCK(chain);
1567 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1570 if (ndel == 0 && (cmd != 1 && num != 0))
1576 return (move_range(chain, &rt));
1580 * Reset some or all counters on firewall rules.
1581 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1582 * the next 8 bits are the set number, the top 8 bits are the command:
1583 * 0 work with rules from all set's;
1584 * 1 work with rules only from specified set.
1585 * Specified rule number is zero if we want to clear all entries.
1586 * log_only is 1 if we only want to reset logs, zero otherwise.
1589 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1595 uint16_t rulenum = arg & 0xffff;
1596 uint8_t set = (arg >> 16) & 0xff;
1597 uint8_t cmd = (arg >> 24) & 0xff;
1601 if (cmd == 1 && set > RESVD_SET)
1604 IPFW_UH_RLOCK(chain);
1606 V_norule_counter = 0;
1607 for (i = 0; i < chain->n_rules; i++) {
1608 rule = chain->map[i];
1609 /* Skip rules not in our set. */
1610 if (cmd == 1 && rule->set != set)
1612 clear_counters(rule, log_only);
1614 msg = log_only ? "All logging counts reset" :
1615 "Accounting cleared";
1618 for (i = 0; i < chain->n_rules; i++) {
1619 rule = chain->map[i];
1620 if (rule->rulenum == rulenum) {
1621 if (cmd == 0 || rule->set == set)
1622 clear_counters(rule, log_only);
1625 if (rule->rulenum > rulenum)
1628 if (!cleared) { /* we did not find any matching rules */
1629 IPFW_UH_RUNLOCK(chain);
1632 msg = log_only ? "logging count reset" : "cleared";
1634 IPFW_UH_RUNLOCK(chain);
1637 int lev = LOG_SECURITY | LOG_NOTICE;
1640 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1642 log(lev, "ipfw: %s.\n", msg);
1649 * Check rule head in FreeBSD11 format
1653 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1654 struct rule_check_info *ci)
1658 if (size < sizeof(*rule)) {
1659 printf("ipfw: rule too short\n");
1663 /* Check for valid cmd_len */
1664 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1666 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1669 if (rule->act_ofs >= rule->cmd_len) {
1670 printf("ipfw: bogus action offset (%u > %u)\n",
1671 rule->act_ofs, rule->cmd_len - 1);
1675 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1678 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1682 * Check rule head in FreeBSD8 format
1686 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1687 struct rule_check_info *ci)
1691 if (size < sizeof(*rule)) {
1692 printf("ipfw: rule too short\n");
1696 /* Check for valid cmd_len */
1697 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1699 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1702 if (rule->act_ofs >= rule->cmd_len) {
1703 printf("ipfw: bogus action offset (%u > %u)\n",
1704 rule->act_ofs, rule->cmd_len - 1);
1708 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1711 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1715 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1723 * Now go for the individual checks. Very simple ones, basically only
1724 * instruction sizes.
1726 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1727 cmdlen = F_LEN(cmd);
1729 printf("ipfw: opcode %d size truncated\n",
1733 switch (cmd->opcode) {
1736 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1738 ci->object_opcodes++;
1749 case O_IPPRECEDENCE:
1768 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1772 case O_EXTERNAL_ACTION:
1773 if (cmd->arg1 == 0 ||
1774 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1775 printf("ipfw: invalid external "
1779 ci->object_opcodes++;
1781 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1787 cmdlen = F_LEN(cmd);
1788 if (cmd->opcode == O_EXTERNAL_DATA)
1790 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1791 printf("ipfw: invalid opcode "
1792 "next to external action %u\n",
1796 if (cmd->arg1 == 0 ||
1797 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1798 printf("ipfw: invalid external "
1799 "action instance opcode\n");
1802 ci->object_opcodes++;
1807 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1809 if (cmd->arg1 >= rt_numfibs) {
1810 printf("ipfw: invalid fib number %d\n",
1817 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1819 if ((cmd->arg1 != IP_FW_TARG) &&
1820 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1821 printf("ipfw: invalid fib number %d\n",
1822 cmd->arg1 & 0x7FFF);
1836 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1841 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1843 ci->object_opcodes++;
1847 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1850 ((ipfw_insn_log *)cmd)->log_left =
1851 ((ipfw_insn_log *)cmd)->max_log;
1857 /* only odd command lengths */
1858 if ((cmdlen & 1) == 0)
1864 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1865 printf("ipfw: invalid set size %d\n",
1869 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1874 case O_IP_SRC_LOOKUP:
1875 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1877 case O_IP_DST_LOOKUP:
1878 if (cmd->arg1 >= V_fw_tables_max) {
1879 printf("ipfw: invalid table number %d\n",
1883 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1884 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1885 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1887 ci->object_opcodes++;
1889 case O_IP_FLOW_LOOKUP:
1890 if (cmd->arg1 >= V_fw_tables_max) {
1891 printf("ipfw: invalid table number %d\n",
1895 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1896 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1898 ci->object_opcodes++;
1901 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1912 if (cmdlen < 1 || cmdlen > 31)
1917 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1923 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1924 if (cmdlen < 2 || cmdlen > 31)
1931 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1933 ci->object_opcodes++;
1937 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1943 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1948 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1953 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1960 if (ip_divert_ptr == NULL)
1966 if (ng_ipfw_input_p == NULL)
1971 if (!IPFW_NAT_LOADED)
1973 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1977 ci->object_opcodes++;
1979 case O_FORWARD_MAC: /* XXX not implemented yet */
1992 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1996 printf("ipfw: opcode %d, multiple actions"
2003 printf("ipfw: opcode %d, action must be"
2012 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2013 F_INSN_SIZE(ipfw_insn))
2018 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2019 ((ipfw_insn_u32 *)cmd)->o.arg1)
2023 case O_IP6_SRC_MASK:
2024 case O_IP6_DST_MASK:
2025 if ( !(cmdlen & 1) || cmdlen > 127)
2029 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2035 switch (cmd->opcode) {
2045 case O_IP6_SRC_MASK:
2046 case O_IP6_DST_MASK:
2048 printf("ipfw: no IPv6 support in kernel\n");
2049 return (EPROTONOSUPPORT);
2052 printf("ipfw: opcode %d, unknown opcode\n",
2058 if (have_action == 0) {
2059 printf("ipfw: missing action\n");
2065 printf("ipfw: opcode %d size %d wrong\n",
2066 cmd->opcode, cmdlen);
2072 * Translation of requests for compatibility with FreeBSD 7.2/8.
2073 * a static variable tells us if we have an old client from userland,
2074 * and if necessary we translate requests and responses between the
2080 struct ip_fw7 *next; /* linked list of rules */
2081 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2082 /* 'next_rule' is used to pass up 'set_disable' status */
2084 uint16_t act_ofs; /* offset of action in 32-bit units */
2085 uint16_t cmd_len; /* # of 32-bit words in cmd */
2086 uint16_t rulenum; /* rule number */
2087 uint8_t set; /* rule set (0..31) */
2088 // #define RESVD_SET 31 /* set for default and persistent rules */
2089 uint8_t _pad; /* padding */
2090 // uint32_t id; /* rule id, only in v.8 */
2091 /* These fields are present in all rules. */
2092 uint64_t pcnt; /* Packet counter */
2093 uint64_t bcnt; /* Byte counter */
2094 uint32_t timestamp; /* tv_sec of last match */
2096 ipfw_insn cmd[1]; /* storage for commands */
2099 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2100 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2103 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2104 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2109 * Copy the static and dynamic rules to the supplied buffer
2110 * and return the amount of space actually used.
2111 * Must be run under IPFW_UH_RLOCK
2114 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2117 char *ep = bp + space;
2119 struct ip_fw_rule0 *dst;
2120 struct timeval boottime;
2121 int error, i, l, warnflag;
2122 time_t boot_seconds;
2126 getboottime(&boottime);
2127 boot_seconds = boottime.tv_sec;
2128 for (i = 0; i < chain->n_rules; i++) {
2129 rule = chain->map[i];
2132 /* Convert rule to FreeBSd 7.2 format */
2133 l = RULESIZE7(rule);
2134 if (bp + l + sizeof(uint32_t) <= ep) {
2135 bcopy(rule, bp, l + sizeof(uint32_t));
2136 error = set_legacy_obj_kidx(chain,
2137 (struct ip_fw_rule0 *)bp);
2140 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2142 return 0; /*XXX correct? */
2144 * XXX HACK. Store the disable mask in the "next"
2145 * pointer in a wild attempt to keep the ABI the same.
2146 * Why do we do this on EVERY rule?
2148 bcopy(&V_set_disable,
2149 &(((struct ip_fw7 *)bp)->next_rule),
2150 sizeof(V_set_disable));
2151 if (((struct ip_fw7 *)bp)->timestamp)
2152 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2155 continue; /* go to next rule */
2158 l = RULEUSIZE0(rule);
2159 if (bp + l > ep) { /* should not happen */
2160 printf("overflow dumping static rules\n");
2163 dst = (struct ip_fw_rule0 *)bp;
2164 export_rule0(rule, dst, l);
2165 error = set_legacy_obj_kidx(chain, dst);
2168 * XXX HACK. Store the disable mask in the "next"
2169 * pointer in a wild attempt to keep the ABI the same.
2170 * Why do we do this on EVERY rule?
2172 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2173 * so we need to fail _after_ saving at least one mask.
2175 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2177 dst->timestamp += boot_seconds;
2182 /* Non-fatal table rewrite error. */
2186 printf("Stop on rule %d. Fail to convert table\n",
2192 printf("ipfw: process %s is using legacy interfaces,"
2193 " consider rebuilding\n", "");
2194 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2195 return (bp - (char *)buf);
2200 uint32_t b; /* start rule */
2201 uint32_t e; /* end rule */
2202 uint32_t rcount; /* number of rules */
2203 uint32_t rsize; /* rules size */
2204 uint32_t tcount; /* number of tables */
2205 int rcounters; /* counters */
2206 uint32_t *bmask; /* index bitmask of used named objects */
2210 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2213 ntlv->head.type = no->etlv;
2214 ntlv->head.length = sizeof(*ntlv);
2215 ntlv->idx = no->kidx;
2216 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2220 * Export named object info in instance @ni, identified by @kidx
2221 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2223 * Returns 0 on success.
2226 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2227 struct sockopt_data *sd)
2229 struct named_object *no;
2230 ipfw_obj_ntlv *ntlv;
2232 no = ipfw_objhash_lookup_kidx(ni, kidx);
2233 KASSERT(no != NULL, ("invalid object kernel index passed"));
2235 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2239 ipfw_export_obj_ntlv(no, ntlv);
2244 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2245 struct sockopt_data *sd)
2249 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2250 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2252 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2260 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2261 struct sockopt_data *sd)
2263 ipfw_obj_ctlv *ctlv;
2266 MPASS(da->tcount > 0);
2268 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2271 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2272 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2274 ctlv->count = da->tcount;
2275 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2277 /* Dump table names first (if any) */
2278 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2281 /* Then dump another named objects */
2282 da->bmask += IPFW_TABLES_MAX / 32;
2283 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2287 * Dumps static rules with table TLVs in buffer @sd.
2289 * Returns 0 on success.
2292 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2293 struct sockopt_data *sd)
2295 ipfw_obj_ctlv *ctlv;
2296 struct ip_fw *krule;
2301 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2304 ctlv->head.type = IPFW_TLV_RULE_LIST;
2305 ctlv->head.length = da->rsize + sizeof(*ctlv);
2306 ctlv->count = da->rcount;
2308 for (i = da->b; i < da->e; i++) {
2309 krule = chain->map[i];
2311 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2312 if (da->rcounters != 0)
2313 l += sizeof(struct ip_fw_bcounter);
2314 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2318 export_rule1(krule, dst, l, da->rcounters);
2325 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2330 * Maintain separate bitmasks for table and non-table objects.
2332 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2334 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2337 bmask[bidx] |= 1 << (kidx % 32);
2342 * Marks every object index used in @rule with bit in @bmask.
2343 * Used to generate bitmask of referenced tables/objects for given ruleset
2347 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2348 struct dump_args *da)
2350 struct opcode_obj_rewrite *rw;
2359 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2360 cmdlen = F_LEN(cmd);
2362 rw = find_op_rw(cmd, &kidx, &subtype);
2366 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2372 * Dumps requested objects data
2373 * Data layout (version 0)(current):
2374 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2375 * size = ipfw_cfg_lheader.size
2376 * Reply: [ ipfw_cfg_lheader
2377 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2378 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2379 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2381 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2383 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2384 * The rest (size, count) are set to zero and needs to be ignored.
2386 * Returns 0 on success.
2389 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2390 struct sockopt_data *sd)
2392 struct dump_args da;
2393 ipfw_cfg_lheader *hdr;
2396 uint32_t hdr_flags, *bmask;
2399 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2405 memset(&da, 0, sizeof(da));
2407 * Allocate needed state.
2408 * Note we allocate 2xspace mask, for table & srv
2410 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2411 da.bmask = bmask = malloc(
2412 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2414 IPFW_UH_RLOCK(chain);
2417 * STAGE 1: Determine size/count for objects in range.
2418 * Prepare used tables bitmask.
2420 sz = sizeof(ipfw_cfg_lheader);
2421 da.e = chain->n_rules;
2423 if (hdr->end_rule != 0) {
2424 /* Handle custom range */
2425 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2426 rnum = IPFW_DEFAULT_RULE;
2427 da.b = ipfw_find_rule(chain, rnum, 0);
2428 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2429 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2430 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2433 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2434 for (i = da.b; i < da.e; i++) {
2435 rule = chain->map[i];
2436 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2438 /* Update bitmask of used objects for given range */
2439 mark_rule_objects(chain, rule, &da);
2441 /* Add counters if requested */
2442 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2443 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2446 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2449 if (hdr->flags & IPFW_CFG_GET_STATES) {
2450 sz += sizeof(ipfw_obj_ctlv) +
2451 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2456 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2457 sizeof(ipfw_obj_ctlv);
2460 * Fill header anyway.
2461 * Note we have to save header fields to stable storage
2462 * buffer inside @sd can be flushed after dumping rules
2465 hdr->set_mask = ~V_set_disable;
2466 hdr_flags = hdr->flags;
2469 if (sd->valsize < sz) {
2474 /* STAGE2: Store actual data */
2475 if (da.tcount > 0) {
2476 error = dump_named_objects(chain, &da, sd);
2481 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2482 error = dump_static_rules(chain, &da, sd);
2487 if (hdr_flags & IPFW_CFG_GET_STATES)
2488 error = ipfw_dump_states(chain, sd);
2491 IPFW_UH_RUNLOCK(chain);
2494 free(bmask, M_TEMP);
2500 ipfw_check_object_name_generic(const char *name)
2504 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2505 if (strnlen(name, nsize) == nsize)
2507 if (name[0] == '\0')
2513 * Creates non-existent objects referenced by rule.
2515 * Return 0 on success.
2518 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2519 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2521 struct opcode_obj_rewrite *rw;
2527 * Compatibility stuff: do actual creation for non-existing,
2528 * but referenced objects.
2530 for (p = oib; p < pidx; p++) {
2538 rw = find_op_rw(cmd + p->off, NULL, NULL);
2539 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2540 (cmd + p->off)->opcode));
2542 if (rw->create_object == NULL)
2545 error = rw->create_object(ch, ti, &kidx);
2552 * Error happened. We have to rollback everything.
2553 * Drop all already acquired references.
2556 unref_oib_objects(ch, cmd, oib, pidx);
2557 IPFW_UH_WUNLOCK(ch);
2566 * Compatibility function for old ipfw(8) binaries.
2567 * Rewrites table/nat kernel indices with userland ones.
2568 * Convert tables matching '/^\d+$/' to their atoi() value.
2569 * Use number 65535 for other tables.
2571 * Returns 0 on success.
2574 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2576 struct opcode_obj_rewrite *rw;
2577 struct named_object *no;
2581 int cmdlen, error, l;
2582 uint16_t kidx, uidx;
2590 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2591 cmdlen = F_LEN(cmd);
2593 /* Check if is index in given opcode */
2594 rw = find_op_rw(cmd, &kidx, &subtype);
2598 /* Try to find referenced kernel object */
2599 no = rw->find_bykidx(ch, kidx);
2603 val = strtol(no->name, &end, 10);
2604 if (*end == '\0' && val < 65535) {
2609 * We are called via legacy opcode.
2610 * Save error and show table as fake number
2611 * not to make ipfw(8) hang.
2617 rw->update(cmd, uidx);
2625 * Unreferences all already-referenced objects in given @cmd rule,
2626 * using information in @oib.
2628 * Used to rollback partially converted rule on error.
2631 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2632 struct obj_idx *end)
2634 struct opcode_obj_rewrite *rw;
2635 struct named_object *no;
2638 IPFW_UH_WLOCK_ASSERT(ch);
2640 for (p = oib; p < end; p++) {
2644 rw = find_op_rw(cmd + p->off, NULL, NULL);
2645 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2646 (cmd + p->off)->opcode));
2648 /* Find & unref by existing idx */
2649 no = rw->find_bykidx(ch, p->kidx);
2650 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2656 * Remove references from every object used in @rule.
2657 * Used at rule removal code.
2660 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2662 struct opcode_obj_rewrite *rw;
2663 struct named_object *no;
2669 IPFW_UH_WLOCK_ASSERT(ch);
2674 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2675 cmdlen = F_LEN(cmd);
2677 rw = find_op_rw(cmd, &kidx, &subtype);
2680 no = rw->find_bykidx(ch, kidx);
2682 KASSERT(no != NULL, ("object id %d not found", kidx));
2683 KASSERT(no->subtype == subtype,
2684 ("wrong type %d (%d) for object id %d",
2685 no->subtype, subtype, kidx));
2686 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2689 if (no->refcnt == 1 && rw->destroy_object != NULL)
2690 rw->destroy_object(ch, no);
2698 * Find and reference object (if any) stored in instruction @cmd.
2700 * Saves object info in @pidx, sets
2701 * - @unresolved to 1 if object should exists but not found
2703 * Returns non-zero value in case of error.
2706 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2707 struct obj_idx *pidx, int *unresolved)
2709 struct named_object *no;
2710 struct opcode_obj_rewrite *rw;
2713 /* Check if this opcode is candidate for rewrite */
2714 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2718 /* Need to rewrite. Save necessary fields */
2719 pidx->uidx = ti->uidx;
2720 pidx->type = ti->type;
2722 /* Try to find referenced kernel object */
2723 error = rw->find_byname(ch, ti, &no);
2728 * Report about unresolved object for automaic
2736 * Object is already exist.
2737 * Its subtype should match with expected value.
2739 if (ti->type != no->subtype)
2742 /* Bump refcount and update kidx. */
2744 rw->update(cmd, no->kidx);
2749 * Finds and bumps refcount for objects referenced by given @rule.
2750 * Auto-creates non-existing tables.
2751 * Fills in @oib array with userland/kernel indexes.
2753 * Returns 0 on success.
2756 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2757 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2759 struct obj_idx *pidx;
2761 int cmdlen, error, l, unresolved;
2771 /* Increase refcount on each existing referenced table. */
2772 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2773 cmdlen = F_LEN(cmd);
2776 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2780 * Compatibility stuff for old clients:
2781 * prepare to automaitcally create non-existing objects.
2783 if (unresolved != 0) {
2784 pidx->off = rule->cmd_len - l;
2790 /* Unref everything we have already done */
2791 unref_oib_objects(ch, rule->cmd, oib, pidx);
2792 IPFW_UH_WUNLOCK(ch);
2795 IPFW_UH_WUNLOCK(ch);
2797 /* Perform auto-creation for non-existing objects */
2799 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2801 /* Calculate real number of dynamic objects */
2802 ci->object_opcodes = (uint16_t)(pidx - oib);
2808 * Checks is opcode is referencing table of appropriate type.
2809 * Adds reference count for found table if true.
2810 * Rewrites user-supplied opcode values with kernel ones.
2812 * Returns 0 on success and appropriate error code otherwise.
2815 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2820 struct obj_idx *p, *pidx_first, *pidx_last;
2824 * Prepare an array for storing opcode indices.
2825 * Use stack allocation by default.
2827 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2829 pidx_first = ci->obuf;
2831 pidx_first = malloc(
2832 ci->object_opcodes * sizeof(struct obj_idx),
2833 M_IPFW, M_WAITOK | M_ZERO);
2837 memset(&ti, 0, sizeof(ti));
2839 /* Use set rule is assigned to. */
2840 ti.set = ci->krule->set;
2841 if (ci->ctlv != NULL) {
2842 ti.tlvs = (void *)(ci->ctlv + 1);
2843 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2846 /* Reference all used tables and other objects */
2847 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2851 * Note that ref_rule_objects() might have updated ci->object_opcodes
2852 * to reflect actual number of object opcodes.
2855 /* Perform rewrite of remaining opcodes */
2857 pidx_last = pidx_first + ci->object_opcodes;
2858 for (p = pidx_first; p < pidx_last; p++) {
2859 cmd = ci->krule->cmd + p->off;
2860 update_opcode_kidx(cmd, p->kidx);
2864 if (pidx_first != ci->obuf)
2865 free(pidx_first, M_IPFW);
2871 * Adds one or more rules to ipfw @chain.
2872 * Data layout (version 0)(current):
2876 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2877 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2882 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2883 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2886 * Rules in reply are modified to store their actual ruleset number.
2888 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2889 * according to their idx field and there has to be no duplicates.
2890 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2891 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2893 * Returns 0 on success.
2896 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2897 struct sockopt_data *sd)
2899 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2900 ipfw_obj_ntlv *ntlv;
2901 int clen, error, idx;
2902 uint32_t count, read;
2903 struct ip_fw_rule *r;
2904 struct rule_check_info rci, *ci, *cbuf;
2907 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2908 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2910 read = sizeof(ip_fw3_opheader);
2914 memset(&rci, 0, sizeof(struct rule_check_info));
2916 if (read + sizeof(*ctlv) > sd->valsize)
2919 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2920 clen = ctlv->head.length;
2921 /* Check size and alignment */
2922 if (clen > sd->valsize || clen < sizeof(*ctlv))
2924 if ((clen % sizeof(uint64_t)) != 0)
2928 * Some table names or other named objects.
2929 * Check for validness.
2931 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2932 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2937 * Ensure TLVs are sorted ascending and
2938 * there are no duplicates.
2941 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2943 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2946 error = ipfw_check_object_name_generic(ntlv->name);
2950 if (ntlv->idx <= idx)
2959 read += ctlv->head.length;
2960 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2963 if (read + sizeof(*ctlv) > sd->valsize)
2966 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2967 clen = ctlv->head.length;
2968 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2970 if ((clen % sizeof(uint64_t)) != 0)
2974 * TODO: Permit adding multiple rules at once
2976 if (ctlv->count != 1)
2979 clen -= sizeof(*ctlv);
2981 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2984 /* Allocate state for each rule or use stack */
2985 if (ctlv->count == 1) {
2986 memset(&rci, 0, sizeof(struct rule_check_info));
2989 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2994 * Check each rule for validness.
2995 * Ensure numbered rules are sorted ascending
2996 * and properly aligned
2999 r = (struct ip_fw_rule *)(ctlv + 1);
3003 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3004 if (rsize > clen || ctlv->count <= count) {
3010 error = check_ipfw_rule1(r, rsize, ci);
3015 if (r->rulenum != 0 && r->rulenum < idx) {
3016 printf("rulenum %d idx %d\n", r->rulenum, idx);
3022 ci->urule = (caddr_t)r;
3024 rsize = roundup2(rsize, sizeof(uint64_t));
3026 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3031 if (ctlv->count != count || error != 0) {
3038 read += ctlv->head.length;
3039 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3042 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3043 if (cbuf != NULL && cbuf != &rci)
3049 * Passed rules seems to be valid.
3050 * Allocate storage and try to add them to chain.
3052 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3053 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3054 ci->krule = ipfw_alloc_rule(chain, clen);
3058 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3059 /* Free allocate krules */
3060 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3061 ipfw_free_rule(ci->krule);
3064 if (cbuf != NULL && cbuf != &rci)
3071 * Lists all sopts currently registered.
3072 * Data layout (v0)(current):
3073 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3074 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3076 * Returns 0 on success
3079 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3080 struct sockopt_data *sd)
3082 struct _ipfw_obj_lheader *olh;
3084 struct ipfw_sopt_handler *sh;
3085 uint32_t count, n, size;
3087 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3090 if (sd->valsize < olh->size)
3095 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3097 /* Fill in header regadless of buffer size */
3099 olh->objsize = sizeof(ipfw_sopt_info);
3101 if (size > olh->size) {
3108 for (n = 1; n <= count; n++) {
3109 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3110 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3111 sh = &ctl3_handlers[n];
3112 i->opcode = sh->opcode;
3113 i->version = sh->version;
3114 i->refcnt = sh->refcnt;
3122 * Compares two opcodes.
3123 * Used both in qsort() and bsearch().
3125 * Returns 0 if match is found.
3128 compare_opcodes(const void *_a, const void *_b)
3130 const struct opcode_obj_rewrite *a, *b;
3132 a = (const struct opcode_obj_rewrite *)_a;
3133 b = (const struct opcode_obj_rewrite *)_b;
3135 if (a->opcode < b->opcode)
3137 else if (a->opcode > b->opcode)
3144 * XXX: Rewrite bsearch()
3147 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3148 struct opcode_obj_rewrite **phi)
3150 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3152 memset(&h, 0, sizeof(h));
3155 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3156 ctl3_rsize, sizeof(h), compare_opcodes);
3160 /* Find the first element matching the same opcode */
3162 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3165 /* Find the last element matching the same opcode */
3167 ctl3_max = ctl3_rewriters + ctl3_rsize;
3168 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3178 * Finds opcode object rewriter based on @code.
3180 * Returns pointer to handler or NULL.
3182 static struct opcode_obj_rewrite *
3183 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3185 struct opcode_obj_rewrite *rw, *lo, *hi;
3189 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3192 for (rw = lo; rw <= hi; rw++) {
3193 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3205 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3208 if (find_op_rw(cmd, puidx, NULL) == NULL)
3214 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3216 struct opcode_obj_rewrite *rw;
3218 rw = find_op_rw(cmd, NULL, NULL);
3219 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3220 rw->update(cmd, idx);
3224 ipfw_init_obj_rewriter()
3227 ctl3_rewriters = NULL;
3232 ipfw_destroy_obj_rewriter()
3235 if (ctl3_rewriters != NULL)
3236 free(ctl3_rewriters, M_IPFW);
3237 ctl3_rewriters = NULL;
3242 * Adds one or more opcode object rewrite handlers to the global array.
3243 * Function may sleep.
3246 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3249 struct opcode_obj_rewrite *tmp;
3254 sz = ctl3_rsize + count;
3256 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3258 if (ctl3_rsize + count <= sz)
3265 /* Merge old & new arrays */
3266 sz = ctl3_rsize + count;
3267 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3268 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3269 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3270 /* Switch new and free old */
3271 if (ctl3_rewriters != NULL)
3272 free(ctl3_rewriters, M_IPFW);
3273 ctl3_rewriters = tmp;
3280 * Removes one or more object rewrite handlers from the global array.
3283 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3286 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3291 for (i = 0; i < count; i++) {
3292 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3295 for (ktmp = lo; ktmp <= hi; ktmp++) {
3296 if (ktmp->classifier != rw[i].classifier)
3299 ctl3_max = ctl3_rewriters + ctl3_rsize;
3300 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3301 memmove(ktmp, ktmp + 1, sz);
3308 if (ctl3_rsize == 0) {
3309 if (ctl3_rewriters != NULL)
3310 free(ctl3_rewriters, M_IPFW);
3311 ctl3_rewriters = NULL;
3320 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3321 struct named_object *no, void *arg)
3323 struct sockopt_data *sd;
3324 ipfw_obj_ntlv *ntlv;
3326 sd = (struct sockopt_data *)arg;
3327 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3330 ipfw_export_obj_ntlv(no, ntlv);
3335 * Lists all service objects.
3336 * Data layout (v0)(current):
3337 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3338 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3339 * Returns 0 on success
3342 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3343 struct sockopt_data *sd)
3345 ipfw_obj_lheader *hdr;
3348 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3352 IPFW_UH_RLOCK(chain);
3353 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3354 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3355 if (sd->valsize < hdr->size) {
3356 IPFW_UH_RUNLOCK(chain);
3360 hdr->objsize = sizeof(ipfw_obj_ntlv);
3362 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3363 export_objhash_ntlv_internal, sd);
3364 IPFW_UH_RUNLOCK(chain);
3369 * Compares two sopt handlers (code, version and handler ptr).
3370 * Used both as qsort() and bsearch().
3371 * Does not compare handler for latter case.
3373 * Returns 0 if match is found.
3376 compare_sh(const void *_a, const void *_b)
3378 const struct ipfw_sopt_handler *a, *b;
3380 a = (const struct ipfw_sopt_handler *)_a;
3381 b = (const struct ipfw_sopt_handler *)_b;
3383 if (a->opcode < b->opcode)
3385 else if (a->opcode > b->opcode)
3388 if (a->version < b->version)
3390 else if (a->version > b->version)
3393 /* bsearch helper */
3394 if (a->handler == NULL)
3397 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3399 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3406 * Finds sopt handler based on @code and @version.
3408 * Returns pointer to handler or NULL.
3410 static struct ipfw_sopt_handler *
3411 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3413 struct ipfw_sopt_handler *sh, h;
3415 memset(&h, 0, sizeof(h));
3417 h.version = version;
3418 h.handler = handler;
3420 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3421 ctl3_hsize, sizeof(h), compare_sh);
3427 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3429 struct ipfw_sopt_handler *sh;
3432 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3434 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3440 /* Copy handler data to requested buffer */
3448 find_unref_sh(struct ipfw_sopt_handler *psh)
3450 struct ipfw_sopt_handler *sh;
3453 sh = find_sh(psh->opcode, psh->version, NULL);
3454 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3461 ipfw_init_sopt_handler()
3465 IPFW_ADD_SOPT_HANDLER(1, scodes);
3469 ipfw_destroy_sopt_handler()
3472 IPFW_DEL_SOPT_HANDLER(1, scodes);
3473 CTL3_LOCK_DESTROY();
3477 * Adds one or more sockopt handlers to the global array.
3478 * Function may sleep.
3481 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3484 struct ipfw_sopt_handler *tmp;
3489 sz = ctl3_hsize + count;
3491 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3493 if (ctl3_hsize + count <= sz)
3500 /* Merge old & new arrays */
3501 sz = ctl3_hsize + count;
3502 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3503 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3504 qsort(tmp, sz, sizeof(*sh), compare_sh);
3505 /* Switch new and free old */
3506 if (ctl3_handlers != NULL)
3507 free(ctl3_handlers, M_IPFW);
3508 ctl3_handlers = tmp;
3516 * Removes one or more sockopt handlers from the global array.
3519 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3522 struct ipfw_sopt_handler *tmp, *h;
3527 for (i = 0; i < count; i++) {
3529 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3533 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3534 memmove(h, h + 1, sz);
3538 if (ctl3_hsize == 0) {
3539 if (ctl3_handlers != NULL)
3540 free(ctl3_handlers, M_IPFW);
3541 ctl3_handlers = NULL;
3552 * Writes data accumulated in @sd to sockopt buffer.
3553 * Zeroes internal @sd buffer.
3556 ipfw_flush_sopt_data(struct sockopt_data *sd)
3558 struct sockopt *sopt;
3568 if (sopt->sopt_dir == SOPT_GET) {
3569 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3574 memset(sd->kbuf, 0, sd->ksize);
3577 if (sd->ktotal + sd->ksize < sd->valsize)
3578 sd->kavail = sd->ksize;
3580 sd->kavail = sd->valsize - sd->ktotal;
3582 /* Update sopt buffer data */
3583 sopt->sopt_valsize = sd->ktotal;
3584 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3590 * Ensures that @sd buffer has contiguous @neeeded number of
3593 * Returns pointer to requested space or NULL.
3596 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3601 if (sd->kavail < needed) {
3603 * Flush data and try another time.
3605 error = ipfw_flush_sopt_data(sd);
3607 if (sd->kavail < needed || error != 0)
3611 addr = sd->kbuf + sd->koff;
3613 sd->kavail -= needed;
3618 * Requests @needed contiguous bytes from @sd buffer.
3619 * Function is used to notify subsystem that we are
3620 * interesed in first @needed bytes (request header)
3621 * and the rest buffer can be safely zeroed.
3623 * Returns pointer to requested space or NULL.
3626 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3630 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3634 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3640 * New sockopt handler.
3643 ipfw_ctl3(struct sockopt *sopt)
3646 size_t size, valsize;
3647 struct ip_fw_chain *chain;
3649 struct sockopt_data sdata;
3650 struct ipfw_sopt_handler h;
3651 ip_fw3_opheader *op3 = NULL;
3653 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3657 if (sopt->sopt_name != IP_FW3)
3658 return (ipfw_ctl(sopt));
3660 chain = &V_layer3_chain;
3663 /* Save original valsize before it is altered via sooptcopyin() */
3664 valsize = sopt->sopt_valsize;
3665 memset(&sdata, 0, sizeof(sdata));
3666 /* Read op3 header first to determine actual operation */
3667 op3 = (ip_fw3_opheader *)xbuf;
3668 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3671 sopt->sopt_valsize = valsize;
3674 * Find and reference command.
3676 error = find_ref_sh(op3->opcode, op3->version, &h);
3681 * Disallow modifications in really-really secure mode, but still allow
3682 * the logging counters to be reset.
3684 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3685 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3693 * Fill in sockopt_data structure that may be useful for
3694 * IP_FW3 get requests.
3697 if (valsize <= sizeof(xbuf)) {
3698 /* use on-stack buffer */
3700 sdata.ksize = sizeof(xbuf);
3701 sdata.kavail = valsize;
3705 * Determine opcode type/buffer size:
3706 * allocate sliding-window buf for data export or
3707 * contiguous buffer for special ops.
3709 if ((h.dir & HDIR_SET) != 0) {
3710 /* Set request. Allocate contigous buffer. */
3711 if (valsize > CTL3_LARGEBUF) {
3718 /* Get request. Allocate sliding window buffer */
3719 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3721 if (size < valsize) {
3722 /* We have to wire user buffer */
3723 error = vslock(sopt->sopt_val, valsize);
3730 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3732 sdata.kavail = size;
3736 sdata.sopt_val = sopt->sopt_val;
3737 sdata.valsize = valsize;
3740 * Copy either all request (if valsize < bsize_max)
3741 * or first bsize_max bytes to guarantee most consumers
3742 * that all necessary data has been copied).
3743 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3745 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3746 sizeof(ip_fw3_opheader))) != 0)
3748 op3 = (ip_fw3_opheader *)sdata.kbuf;
3750 /* Finally, run handler */
3751 error = h.handler(chain, op3, &sdata);
3754 /* Flush state and free buffers */
3756 error = ipfw_flush_sopt_data(&sdata);
3758 ipfw_flush_sopt_data(&sdata);
3761 vsunlock(sdata.sopt_val, valsize);
3763 /* Restore original pointer and set number of bytes written */
3764 sopt->sopt_val = sdata.sopt_val;
3765 sopt->sopt_valsize = sdata.ktotal;
3766 if (sdata.kbuf != xbuf)
3767 free(sdata.kbuf, M_TEMP);
3773 * {set|get}sockopt parser.
3776 ipfw_ctl(struct sockopt *sopt)
3778 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3780 size_t size, valsize;
3782 struct ip_fw_rule0 *rule;
3783 struct ip_fw_chain *chain;
3784 u_int32_t rulenum[2];
3786 struct rule_check_info ci;
3789 chain = &V_layer3_chain;
3792 /* Save original valsize before it is altered via sooptcopyin() */
3793 valsize = sopt->sopt_valsize;
3794 opt = sopt->sopt_name;
3797 * Disallow modifications in really-really secure mode, but still allow
3798 * the logging counters to be reset.
3800 if (opt == IP_FW_ADD ||
3801 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3802 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3810 * pass up a copy of the current rules. Static rules
3811 * come first (the last of which has number IPFW_DEFAULT_RULE),
3812 * followed by a possibly empty list of dynamic rule.
3813 * The last dynamic rule has NULL in the "next" field.
3815 * Note that the calculated size is used to bound the
3816 * amount of data returned to the user. The rule set may
3817 * change between calculating the size and returning the
3818 * data in which case we'll just return what fits.
3823 size = chain->static_len;
3824 size += ipfw_dyn_len();
3825 if (size >= sopt->sopt_valsize)
3827 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3828 IPFW_UH_RLOCK(chain);
3829 /* check again how much space we need */
3830 want = chain->static_len + ipfw_dyn_len();
3832 len = ipfw_getrules(chain, buf, size);
3833 IPFW_UH_RUNLOCK(chain);
3835 error = sooptcopyout(sopt, buf, len);
3843 /* locking is done within del_entry() */
3844 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3848 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3849 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3850 sizeof(struct ip_fw7) );
3852 memset(&ci, 0, sizeof(struct rule_check_info));
3855 * If the size of commands equals RULESIZE7 then we assume
3856 * a FreeBSD7.2 binary is talking to us (set is7=1).
3857 * is7 is persistent so the next 'ipfw list' command
3858 * will use this format.
3859 * NOTE: If wrong version is guessed (this can happen if
3860 * the first ipfw command is 'ipfw [pipe] list')
3861 * the ipfw binary may crash or loop infinitly...
3863 size = sopt->sopt_valsize;
3864 if (size == RULESIZE7(rule)) {
3866 error = convert_rule_to_8(rule);
3871 size = RULESIZE(rule);
3875 error = check_ipfw_rule0(rule, size, &ci);
3877 /* locking is done within add_rule() */
3878 struct ip_fw *krule;
3879 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3880 ci.urule = (caddr_t)rule;
3883 error = commit_rules(chain, &ci, 1);
3885 ipfw_free_rule(ci.krule);
3886 else if (sopt->sopt_dir == SOPT_GET) {
3888 error = convert_rule_to_7(rule);
3889 size = RULESIZE7(rule);
3895 error = sooptcopyout(sopt, rule, size);
3903 * IP_FW_DEL is used for deleting single rules or sets,
3904 * and (ab)used to atomically manipulate sets. Argument size
3905 * is used to distinguish between the two:
3907 * delete single rule or set of rules,
3908 * or reassign rules (or sets) to a different set.
3909 * 2*sizeof(u_int32_t)
3910 * atomic disable/enable sets.
3911 * first u_int32_t contains sets to be disabled,
3912 * second u_int32_t contains sets to be enabled.
3914 error = sooptcopyin(sopt, rulenum,
3915 2*sizeof(u_int32_t), sizeof(u_int32_t));
3918 size = sopt->sopt_valsize;
3919 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3920 /* delete or reassign, locking done in del_entry() */
3921 error = del_entry(chain, rulenum[0]);
3922 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3923 IPFW_UH_WLOCK(chain);
3925 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3926 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3927 IPFW_UH_WUNLOCK(chain);
3933 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3935 if (sopt->sopt_val != 0) {
3936 error = sooptcopyin(sopt, rulenum,
3937 sizeof(u_int32_t), sizeof(u_int32_t));
3941 error = zero_entry(chain, rulenum[0],
3942 sopt->sopt_name == IP_FW_RESETLOG);
3945 /*--- TABLE opcodes ---*/
3946 case IP_FW_TABLE_ADD:
3947 case IP_FW_TABLE_DEL:
3949 ipfw_table_entry ent;
3950 struct tentry_info tei;
3952 struct table_value v;
3954 error = sooptcopyin(sopt, &ent,
3955 sizeof(ent), sizeof(ent));
3959 memset(&tei, 0, sizeof(tei));
3960 tei.paddr = &ent.addr;
3961 tei.subtype = AF_INET;
3962 tei.masklen = ent.masklen;
3963 ipfw_import_table_value_legacy(ent.value, &v);
3965 memset(&ti, 0, sizeof(ti));
3967 ti.type = IPFW_TABLE_CIDR;
3969 error = (opt == IP_FW_TABLE_ADD) ?
3970 add_table_entry(chain, &ti, &tei, 0, 1) :
3971 del_table_entry(chain, &ti, &tei, 0, 1);
3976 case IP_FW_TABLE_FLUSH:
3981 error = sooptcopyin(sopt, &tbl,
3982 sizeof(tbl), sizeof(tbl));
3985 memset(&ti, 0, sizeof(ti));
3987 error = flush_table(chain, &ti);
3991 case IP_FW_TABLE_GETSIZE:
3996 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3999 memset(&ti, 0, sizeof(ti));
4002 error = ipfw_count_table(chain, &ti, &cnt);
4003 IPFW_RUNLOCK(chain);
4006 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4010 case IP_FW_TABLE_LIST:
4015 if (sopt->sopt_valsize < sizeof(*tbl)) {
4019 size = sopt->sopt_valsize;
4020 tbl = malloc(size, M_TEMP, M_WAITOK);
4021 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4026 tbl->size = (size - sizeof(*tbl)) /
4027 sizeof(ipfw_table_entry);
4028 memset(&ti, 0, sizeof(ti));
4031 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4032 IPFW_RUNLOCK(chain);
4037 error = sooptcopyout(sopt, tbl, size);
4042 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4044 if (IPFW_NAT_LOADED)
4045 error = ipfw_nat_cfg_ptr(sopt);
4047 printf("IP_FW_NAT_CFG: %s\n",
4048 "ipfw_nat not present, please load it");
4054 if (IPFW_NAT_LOADED)
4055 error = ipfw_nat_del_ptr(sopt);
4057 printf("IP_FW_NAT_DEL: %s\n",
4058 "ipfw_nat not present, please load it");
4063 case IP_FW_NAT_GET_CONFIG:
4064 if (IPFW_NAT_LOADED)
4065 error = ipfw_nat_get_cfg_ptr(sopt);
4067 printf("IP_FW_NAT_GET_CFG: %s\n",
4068 "ipfw_nat not present, please load it");
4073 case IP_FW_NAT_GET_LOG:
4074 if (IPFW_NAT_LOADED)
4075 error = ipfw_nat_get_log_ptr(sopt);
4077 printf("IP_FW_NAT_GET_LOG: %s\n",
4078 "ipfw_nat not present, please load it");
4084 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4091 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4093 /* Functions to convert rules 7.2 <==> 8.0 */
4095 convert_rule_to_7(struct ip_fw_rule0 *rule)
4097 /* Used to modify original rule */
4098 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4099 /* copy of original rule, version 8 */
4100 struct ip_fw_rule0 *tmp;
4102 /* Used to copy commands */
4103 ipfw_insn *ccmd, *dst;
4104 int ll = 0, ccmdlen = 0;
4106 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4108 return 1; //XXX error
4110 bcopy(rule, tmp, RULE_MAXSIZE);
4113 //rule7->_pad = tmp->_pad;
4114 rule7->set = tmp->set;
4115 rule7->rulenum = tmp->rulenum;
4116 rule7->cmd_len = tmp->cmd_len;
4117 rule7->act_ofs = tmp->act_ofs;
4118 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4119 rule7->cmd_len = tmp->cmd_len;
4120 rule7->pcnt = tmp->pcnt;
4121 rule7->bcnt = tmp->bcnt;
4122 rule7->timestamp = tmp->timestamp;
4125 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4126 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4127 ccmdlen = F_LEN(ccmd);
4129 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4131 if (dst->opcode > O_NAT)
4132 /* O_REASS doesn't exists in 7.2 version, so
4133 * decrement opcode if it is after O_REASS
4138 printf("ipfw: opcode %d size truncated\n",
4149 convert_rule_to_8(struct ip_fw_rule0 *rule)
4151 /* Used to modify original rule */
4152 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4154 /* Used to copy commands */
4155 ipfw_insn *ccmd, *dst;
4156 int ll = 0, ccmdlen = 0;
4158 /* Copy of original rule */
4159 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4161 return 1; //XXX error
4164 bcopy(rule7, tmp, RULE_MAXSIZE);
4166 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4167 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4168 ccmdlen = F_LEN(ccmd);
4170 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4172 if (dst->opcode > O_NAT)
4173 /* O_REASS doesn't exists in 7.2 version, so
4174 * increment opcode if it is after O_REASS
4179 printf("ipfw: opcode %d size truncated\n",
4185 rule->_pad = tmp->_pad;
4186 rule->set = tmp->set;
4187 rule->rulenum = tmp->rulenum;
4188 rule->cmd_len = tmp->cmd_len;
4189 rule->act_ofs = tmp->act_ofs;
4190 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4191 rule->cmd_len = tmp->cmd_len;
4192 rule->id = 0; /* XXX see if is ok = 0 */
4193 rule->pcnt = tmp->pcnt;
4194 rule->bcnt = tmp->bcnt;
4195 rule->timestamp = tmp->timestamp;
4207 ipfw_init_srv(struct ip_fw_chain *ch)
4210 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4211 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4212 M_IPFW, M_WAITOK | M_ZERO);
4216 ipfw_destroy_srv(struct ip_fw_chain *ch)
4219 free(ch->srvstate, M_IPFW);
4220 ipfw_objhash_destroy(ch->srvmap);
4224 * Allocate new bitmask which can be used to enlarge/shrink
4225 * named instance index.
4228 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4234 KASSERT((items % BLOCK_ITEMS) == 0,
4235 ("bitmask size needs to power of 2 and greater or equal to %zu",
4238 max_blocks = items / BLOCK_ITEMS;
4240 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4241 /* Mark all as free */
4242 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4243 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4246 *pblocks = max_blocks;
4250 * Copy current bitmask index to new one.
4253 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4255 int old_blocks, new_blocks;
4256 u_long *old_idx, *new_idx;
4259 old_idx = ni->idx_mask;
4260 old_blocks = ni->max_blocks;
4262 new_blocks = *blocks;
4264 for (i = 0; i < IPFW_MAX_SETS; i++) {
4265 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4266 old_blocks * sizeof(u_long));
4271 * Swaps current @ni index with new one.
4274 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4279 old_idx = ni->idx_mask;
4280 old_blocks = ni->max_blocks;
4282 ni->idx_mask = *idx;
4283 ni->max_blocks = *blocks;
4285 /* Save old values */
4287 *blocks = old_blocks;
4291 ipfw_objhash_bitmap_free(void *idx, int blocks)
4298 * Creates named hash instance.
4299 * Must be called without holding any locks.
4300 * Return pointer to new instance.
4302 struct namedobj_instance *
4303 ipfw_objhash_create(uint32_t items)
4305 struct namedobj_instance *ni;
4309 size = sizeof(struct namedobj_instance) +
4310 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4311 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4313 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4314 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4315 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4317 ni->names = (struct namedobjects_head *)(ni +1);
4318 ni->values = &ni->names[ni->nn_size];
4320 for (i = 0; i < ni->nn_size; i++)
4321 TAILQ_INIT(&ni->names[i]);
4323 for (i = 0; i < ni->nv_size; i++)
4324 TAILQ_INIT(&ni->values[i]);
4326 /* Set default hashing/comparison functions */
4327 ni->hash_f = objhash_hash_name;
4328 ni->cmp_f = objhash_cmp_name;
4330 /* Allocate bitmask separately due to possible resize */
4331 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4337 ipfw_objhash_destroy(struct namedobj_instance *ni)
4340 free(ni->idx_mask, M_IPFW);
4345 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4346 objhash_cmp_f *cmp_f)
4349 ni->hash_f = hash_f;
4354 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4357 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4361 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4364 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4371 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4375 v = val % (ni->nv_size - 1);
4380 struct named_object *
4381 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4383 struct named_object *no;
4386 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4388 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4389 if (ni->cmp_f(no, name, set) == 0)
4397 * Find named object by @uid.
4398 * Check @tlvs for valid data inside.
4400 * Returns pointer to found TLV or NULL.
4403 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4405 ipfw_obj_ntlv *ntlv;
4409 pa = (uintptr_t)tlvs;
4412 for (; pa < pe; pa += l) {
4413 ntlv = (ipfw_obj_ntlv *)pa;
4414 l = ntlv->head.length;
4416 if (l != sizeof(*ntlv))
4419 if (ntlv->idx != uidx)
4422 * When userland has specified zero TLV type, do
4423 * not compare it with eltv. In some cases userland
4424 * doesn't know what type should it have. Use only
4425 * uidx and name for search named_object.
4427 if (ntlv->head.type != 0 &&
4428 ntlv->head.type != (uint16_t)etlv)
4431 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4441 * Finds object config based on either legacy index
4443 * Note @ti structure contains unchecked data from userland.
4445 * Returns 0 in success and fills in @pno with found config
4448 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4449 uint32_t etlv, struct named_object **pno)
4452 ipfw_obj_ntlv *ntlv;
4455 if (ti->tlvs == NULL)
4458 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4464 * Use set provided by @ti instead of @ntlv one.
4465 * This is needed due to different sets behavior
4466 * controlled by V_fw_tables_sets.
4469 *pno = ipfw_objhash_lookup_name(ni, set, name);
4476 * Find named object by name, considering also its TLV type.
4478 struct named_object *
4479 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4480 uint32_t type, const char *name)
4482 struct named_object *no;
4485 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4487 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4488 if (ni->cmp_f(no, name, set) == 0 &&
4489 no->etlv == (uint16_t)type)
4496 struct named_object *
4497 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4499 struct named_object *no;
4502 hash = objhash_hash_idx(ni, kidx);
4504 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4505 if (no->kidx == kidx)
4513 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4514 struct named_object *b)
4517 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4524 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4528 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4529 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4531 hash = objhash_hash_idx(ni, no->kidx);
4532 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4538 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4542 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4543 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4545 hash = objhash_hash_idx(ni, no->kidx);
4546 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4552 ipfw_objhash_count(struct namedobj_instance *ni)
4559 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4561 struct named_object *no;
4566 for (i = 0; i < ni->nn_size; i++) {
4567 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4568 if (no->etlv == type)
4576 * Runs @func for each found named object.
4577 * It is safe to delete objects from callback
4580 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4582 struct named_object *no, *no_tmp;
4585 for (i = 0; i < ni->nn_size; i++) {
4586 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4587 ret = f(ni, no, arg);
4596 * Runs @f for each found named object with type @type.
4597 * It is safe to delete objects from callback
4600 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4601 void *arg, uint16_t type)
4603 struct named_object *no, *no_tmp;
4606 for (i = 0; i < ni->nn_size; i++) {
4607 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4608 if (no->etlv != type)
4610 ret = f(ni, no, arg);
4619 * Removes index from given set.
4620 * Returns 0 on success.
4623 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4628 i = idx / BLOCK_ITEMS;
4629 v = idx % BLOCK_ITEMS;
4631 if (i >= ni->max_blocks)
4634 mask = &ni->idx_mask[i];
4636 if ((*mask & ((u_long)1 << v)) != 0)
4640 *mask |= (u_long)1 << v;
4642 /* Update free offset */
4643 if (ni->free_off[0] > i)
4644 ni->free_off[0] = i;
4650 * Allocate new index in given instance and stores in in @pidx.
4651 * Returns 0 on success.
4654 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4656 struct namedobj_instance *ni;
4660 ni = (struct namedobj_instance *)n;
4662 off = ni->free_off[0];
4663 mask = &ni->idx_mask[off];
4665 for (i = off; i < ni->max_blocks; i++, mask++) {
4666 if ((v = ffsl(*mask)) == 0)
4670 *mask &= ~ ((u_long)1 << (v - 1));
4672 ni->free_off[0] = i;
4674 v = BLOCK_ITEMS * i + v - 1;