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);
1182 * Changes set of given rule rannge @rt
1185 * Returns 0 on success.
1188 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1193 IPFW_UH_WLOCK(chain);
1196 * Move rules with matching paramenerts to a new set.
1197 * This one is much more complex. We have to ensure
1198 * that all referenced tables (if any) are referenced
1199 * by given rule subset only. Otherwise, we can't move
1200 * them to new set and have to return error.
1202 if ((i = move_objects(chain, rt)) != 0) {
1203 IPFW_UH_WUNLOCK(chain);
1207 /* XXX: We have to do swap holding WLOCK */
1208 for (i = 0; i < chain->n_rules; i++) {
1209 rule = chain->map[i];
1210 if (ipfw_match_range(rule, rt) == 0)
1212 rule->set = rt->new_set;
1215 IPFW_UH_WUNLOCK(chain);
1221 * Returns pointer to action instruction, skips all possible rule
1222 * modifiers like O_LOG, O_TAG, O_ALTQ.
1225 ipfw_get_action(struct ip_fw *rule)
1230 cmd = ACTION_PTR(rule);
1231 l = rule->cmd_len - rule->act_ofs;
1233 switch (cmd->opcode) {
1241 cmdlen = F_LEN(cmd);
1245 panic("%s: rule (%p) has not action opcode", __func__, rule);
1250 * Clear counters for a specific rule.
1251 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1252 * so we only care that rules do not disappear.
1255 clear_counters(struct ip_fw *rule, int log_only)
1257 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1260 IPFW_ZERO_RULE_COUNTER(rule);
1261 if (l->o.opcode == O_LOG)
1262 l->log_left = l->max_log;
1266 * Flushes rules counters and/or log values on matching range.
1268 * Returns number of items cleared.
1271 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1278 rt->flags |= IPFW_RCFLAG_DEFAULT;
1280 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1281 for (i = 0; i < chain->n_rules; i++) {
1282 rule = chain->map[i];
1283 if (ipfw_match_range(rule, rt) == 0)
1285 clear_counters(rule, log_only);
1288 IPFW_UH_WUNLOCK(chain);
1294 check_range_tlv(ipfw_range_tlv *rt)
1297 if (rt->head.length != sizeof(*rt))
1299 if (rt->start_rule > rt->end_rule)
1301 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1304 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1311 * Delete rules matching specified parameters
1312 * Data layout (v0)(current):
1313 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1314 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1316 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1318 * Returns 0 on success.
1321 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1322 struct sockopt_data *sd)
1324 ipfw_range_header *rh;
1327 if (sd->valsize != sizeof(*rh))
1330 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1332 if (check_range_tlv(&rh->range) != 0)
1336 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1339 /* Save number of rules deleted */
1340 rh->range.new_set = ndel;
1345 * Move rules/sets matching specified parameters
1346 * Data layout (v0)(current):
1347 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1349 * Returns 0 on success.
1352 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1353 struct sockopt_data *sd)
1355 ipfw_range_header *rh;
1357 if (sd->valsize != sizeof(*rh))
1360 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1362 if (check_range_tlv(&rh->range) != 0)
1365 return (move_range(chain, &rh->range));
1369 * Clear rule accounting data matching specified parameters
1370 * Data layout (v0)(current):
1371 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1372 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1374 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1376 * Returns 0 on success.
1379 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1380 struct sockopt_data *sd)
1382 ipfw_range_header *rh;
1386 if (sd->valsize != sizeof(*rh))
1389 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1391 if (check_range_tlv(&rh->range) != 0)
1394 log_only = (op3->opcode == IP_FW_XRESETLOG);
1396 num = clear_range(chain, &rh->range, log_only);
1398 if (rh->range.flags & IPFW_RCFLAG_ALL)
1399 msg = log_only ? "All logging counts reset" :
1400 "Accounting cleared";
1402 msg = log_only ? "logging count reset" : "cleared";
1405 int lev = LOG_SECURITY | LOG_NOTICE;
1406 log(lev, "ipfw: %s.\n", msg);
1409 /* Save number of rules cleared */
1410 rh->range.new_set = num;
1415 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1419 IPFW_UH_WLOCK_ASSERT(chain);
1421 /* Change enabled/disabled sets mask */
1422 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1423 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1425 V_set_disable = v_set;
1426 IPFW_WUNLOCK(chain);
1430 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1432 struct opcode_obj_rewrite *rw;
1436 IPFW_UH_WLOCK_ASSERT(chain);
1438 if (rt->set == rt->new_set) /* nothing to do */
1443 * Berfore moving the rules we need to check that
1444 * there aren't any conflicting named objects.
1446 for (rw = ctl3_rewriters;
1447 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1448 if (rw->manage_sets == NULL)
1450 i = rw->manage_sets(chain, (uint8_t)rt->set,
1451 (uint8_t)rt->new_set, TEST_ALL);
1456 /* Swap or move two sets */
1457 for (i = 0; i < chain->n_rules - 1; i++) {
1458 rule = chain->map[i];
1459 if (rule->set == (uint8_t)rt->set)
1460 rule->set = (uint8_t)rt->new_set;
1461 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1462 rule->set = (uint8_t)rt->set;
1464 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1465 if (rw->manage_sets == NULL)
1467 rw->manage_sets(chain, (uint8_t)rt->set,
1468 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1474 * Swaps or moves set
1475 * Data layout (v0)(current):
1476 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1478 * Returns 0 on success.
1481 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1482 struct sockopt_data *sd)
1484 ipfw_range_header *rh;
1487 if (sd->valsize != sizeof(*rh))
1490 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1492 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1494 /* enable_sets() expects bitmasks. */
1495 if (op3->opcode != IP_FW_SET_ENABLE &&
1496 (rh->range.set >= IPFW_MAX_SETS ||
1497 rh->range.new_set >= IPFW_MAX_SETS))
1501 IPFW_UH_WLOCK(chain);
1502 switch (op3->opcode) {
1503 case IP_FW_SET_SWAP:
1504 case IP_FW_SET_MOVE:
1505 ret = swap_sets(chain, &rh->range,
1506 op3->opcode == IP_FW_SET_MOVE);
1508 case IP_FW_SET_ENABLE:
1509 enable_sets(chain, &rh->range);
1512 IPFW_UH_WUNLOCK(chain);
1518 * Remove all rules with given number, or do set manipulation.
1519 * Assumes chain != NULL && *chain != NULL.
1521 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1522 * the next 8 bits are the new set; the top 8 bits indicate the command:
1524 * 0 delete rules numbered "rulenum"
1525 * 1 delete rules in set "rulenum"
1526 * 2 move rules "rulenum" to set "new_set"
1527 * 3 move rules from set "rulenum" to set "new_set"
1528 * 4 swap sets "rulenum" and "new_set"
1529 * 5 delete rules "rulenum" and set "new_set"
1532 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1534 uint32_t num; /* rule number or old_set */
1535 uint8_t cmd, new_set;
1541 cmd = (arg >> 24) & 0xff;
1542 new_set = (arg >> 16) & 0xff;
1544 if (cmd > 5 || new_set > RESVD_SET)
1546 if (cmd == 0 || cmd == 2 || cmd == 5) {
1547 if (num >= IPFW_DEFAULT_RULE)
1550 if (num > RESVD_SET) /* old_set */
1554 /* Convert old requests into new representation */
1555 memset(&rt, 0, sizeof(rt));
1556 rt.start_rule = num;
1559 rt.new_set = new_set;
1563 case 0: /* delete rules numbered "rulenum" */
1565 rt.flags |= IPFW_RCFLAG_ALL;
1567 rt.flags |= IPFW_RCFLAG_RANGE;
1570 case 1: /* delete rules in set "rulenum" */
1571 rt.flags |= IPFW_RCFLAG_SET;
1574 case 5: /* delete rules "rulenum" and set "new_set" */
1575 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1580 case 2: /* move rules "rulenum" to set "new_set" */
1581 rt.flags |= IPFW_RCFLAG_RANGE;
1583 case 3: /* move rules from set "rulenum" to set "new_set" */
1584 IPFW_UH_WLOCK(chain);
1585 error = swap_sets(chain, &rt, 1);
1586 IPFW_UH_WUNLOCK(chain);
1588 case 4: /* swap sets "rulenum" and "new_set" */
1589 IPFW_UH_WLOCK(chain);
1590 error = swap_sets(chain, &rt, 0);
1591 IPFW_UH_WUNLOCK(chain);
1598 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1601 if (ndel == 0 && (cmd != 1 && num != 0))
1607 return (move_range(chain, &rt));
1611 * Reset some or all counters on firewall rules.
1612 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1613 * the next 8 bits are the set number, the top 8 bits are the command:
1614 * 0 work with rules from all set's;
1615 * 1 work with rules only from specified set.
1616 * Specified rule number is zero if we want to clear all entries.
1617 * log_only is 1 if we only want to reset logs, zero otherwise.
1620 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1626 uint16_t rulenum = arg & 0xffff;
1627 uint8_t set = (arg >> 16) & 0xff;
1628 uint8_t cmd = (arg >> 24) & 0xff;
1632 if (cmd == 1 && set > RESVD_SET)
1635 IPFW_UH_RLOCK(chain);
1637 V_norule_counter = 0;
1638 for (i = 0; i < chain->n_rules; i++) {
1639 rule = chain->map[i];
1640 /* Skip rules not in our set. */
1641 if (cmd == 1 && rule->set != set)
1643 clear_counters(rule, log_only);
1645 msg = log_only ? "All logging counts reset" :
1646 "Accounting cleared";
1649 for (i = 0; i < chain->n_rules; i++) {
1650 rule = chain->map[i];
1651 if (rule->rulenum == rulenum) {
1652 if (cmd == 0 || rule->set == set)
1653 clear_counters(rule, log_only);
1656 if (rule->rulenum > rulenum)
1659 if (!cleared) { /* we did not find any matching rules */
1660 IPFW_UH_RUNLOCK(chain);
1663 msg = log_only ? "logging count reset" : "cleared";
1665 IPFW_UH_RUNLOCK(chain);
1668 int lev = LOG_SECURITY | LOG_NOTICE;
1671 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1673 log(lev, "ipfw: %s.\n", msg);
1680 * Check rule head in FreeBSD11 format
1684 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1685 struct rule_check_info *ci)
1689 if (size < sizeof(*rule)) {
1690 printf("ipfw: rule too short\n");
1694 /* Check for valid cmd_len */
1695 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1697 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1700 if (rule->act_ofs >= rule->cmd_len) {
1701 printf("ipfw: bogus action offset (%u > %u)\n",
1702 rule->act_ofs, rule->cmd_len - 1);
1706 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1709 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1713 * Check rule head in FreeBSD8 format
1717 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1718 struct rule_check_info *ci)
1722 if (size < sizeof(*rule)) {
1723 printf("ipfw: rule too short\n");
1727 /* Check for valid cmd_len */
1728 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1730 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1733 if (rule->act_ofs >= rule->cmd_len) {
1734 printf("ipfw: bogus action offset (%u > %u)\n",
1735 rule->act_ofs, rule->cmd_len - 1);
1739 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1742 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1746 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1754 * Now go for the individual checks. Very simple ones, basically only
1755 * instruction sizes.
1757 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1758 cmdlen = F_LEN(cmd);
1760 printf("ipfw: opcode %d size truncated\n",
1764 switch (cmd->opcode) {
1767 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1769 ci->object_opcodes++;
1780 case O_IPPRECEDENCE:
1799 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1803 case O_EXTERNAL_ACTION:
1804 if (cmd->arg1 == 0 ||
1805 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1806 printf("ipfw: invalid external "
1810 ci->object_opcodes++;
1812 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1818 cmdlen = F_LEN(cmd);
1819 if (cmd->opcode == O_EXTERNAL_DATA)
1821 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1822 printf("ipfw: invalid opcode "
1823 "next to external action %u\n",
1827 if (cmd->arg1 == 0 ||
1828 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1829 printf("ipfw: invalid external "
1830 "action instance opcode\n");
1833 ci->object_opcodes++;
1838 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1840 if (cmd->arg1 >= rt_numfibs) {
1841 printf("ipfw: invalid fib number %d\n",
1848 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1850 if ((cmd->arg1 != IP_FW_TARG) &&
1851 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1852 printf("ipfw: invalid fib number %d\n",
1853 cmd->arg1 & 0x7FFF);
1867 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1872 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1874 ci->object_opcodes++;
1878 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1881 ((ipfw_insn_log *)cmd)->log_left =
1882 ((ipfw_insn_log *)cmd)->max_log;
1888 /* only odd command lengths */
1889 if ((cmdlen & 1) == 0)
1895 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1896 printf("ipfw: invalid set size %d\n",
1900 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1905 case O_IP_SRC_LOOKUP:
1906 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1908 case O_IP_DST_LOOKUP:
1909 if (cmd->arg1 >= V_fw_tables_max) {
1910 printf("ipfw: invalid table number %d\n",
1914 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1915 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1916 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1918 ci->object_opcodes++;
1920 case O_IP_FLOW_LOOKUP:
1921 if (cmd->arg1 >= V_fw_tables_max) {
1922 printf("ipfw: invalid table number %d\n",
1926 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1927 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1929 ci->object_opcodes++;
1932 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1944 if (cmdlen < 1 || cmdlen > 31)
1949 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1955 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1956 if (cmdlen < 2 || cmdlen > 31)
1963 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1965 ci->object_opcodes++;
1969 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1975 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1980 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1985 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1992 if (ip_divert_ptr == NULL)
1998 if (ng_ipfw_input_p == NULL)
2003 if (!IPFW_NAT_LOADED)
2005 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
2009 ci->object_opcodes++;
2011 case O_FORWARD_MAC: /* XXX not implemented yet */
2024 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2028 printf("ipfw: opcode %d, multiple actions"
2035 printf("ipfw: opcode %d, action must be"
2044 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2045 F_INSN_SIZE(ipfw_insn))
2050 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2051 ((ipfw_insn_u32 *)cmd)->o.arg1)
2055 case O_IP6_SRC_MASK:
2056 case O_IP6_DST_MASK:
2057 if ( !(cmdlen & 1) || cmdlen > 127)
2061 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2067 switch (cmd->opcode) {
2077 case O_IP6_SRC_MASK:
2078 case O_IP6_DST_MASK:
2080 printf("ipfw: no IPv6 support in kernel\n");
2081 return (EPROTONOSUPPORT);
2084 printf("ipfw: opcode %d, unknown opcode\n",
2090 if (have_action == 0) {
2091 printf("ipfw: missing action\n");
2097 printf("ipfw: opcode %d size %d wrong\n",
2098 cmd->opcode, cmdlen);
2104 * Translation of requests for compatibility with FreeBSD 7.2/8.
2105 * a static variable tells us if we have an old client from userland,
2106 * and if necessary we translate requests and responses between the
2112 struct ip_fw7 *next; /* linked list of rules */
2113 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2114 /* 'next_rule' is used to pass up 'set_disable' status */
2116 uint16_t act_ofs; /* offset of action in 32-bit units */
2117 uint16_t cmd_len; /* # of 32-bit words in cmd */
2118 uint16_t rulenum; /* rule number */
2119 uint8_t set; /* rule set (0..31) */
2120 // #define RESVD_SET 31 /* set for default and persistent rules */
2121 uint8_t _pad; /* padding */
2122 // uint32_t id; /* rule id, only in v.8 */
2123 /* These fields are present in all rules. */
2124 uint64_t pcnt; /* Packet counter */
2125 uint64_t bcnt; /* Byte counter */
2126 uint32_t timestamp; /* tv_sec of last match */
2128 ipfw_insn cmd[1]; /* storage for commands */
2131 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2132 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2135 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2136 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2141 * Copy the static and dynamic rules to the supplied buffer
2142 * and return the amount of space actually used.
2143 * Must be run under IPFW_UH_RLOCK
2146 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2149 char *ep = bp + space;
2151 struct ip_fw_rule0 *dst;
2152 struct timeval boottime;
2153 int error, i, l, warnflag;
2154 time_t boot_seconds;
2158 getboottime(&boottime);
2159 boot_seconds = boottime.tv_sec;
2160 for (i = 0; i < chain->n_rules; i++) {
2161 rule = chain->map[i];
2164 /* Convert rule to FreeBSd 7.2 format */
2165 l = RULESIZE7(rule);
2166 if (bp + l + sizeof(uint32_t) <= ep) {
2167 bcopy(rule, bp, l + sizeof(uint32_t));
2168 error = set_legacy_obj_kidx(chain,
2169 (struct ip_fw_rule0 *)bp);
2172 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2174 return 0; /*XXX correct? */
2176 * XXX HACK. Store the disable mask in the "next"
2177 * pointer in a wild attempt to keep the ABI the same.
2178 * Why do we do this on EVERY rule?
2180 bcopy(&V_set_disable,
2181 &(((struct ip_fw7 *)bp)->next_rule),
2182 sizeof(V_set_disable));
2183 if (((struct ip_fw7 *)bp)->timestamp)
2184 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2187 continue; /* go to next rule */
2190 l = RULEUSIZE0(rule);
2191 if (bp + l > ep) { /* should not happen */
2192 printf("overflow dumping static rules\n");
2195 dst = (struct ip_fw_rule0 *)bp;
2196 export_rule0(rule, dst, l);
2197 error = set_legacy_obj_kidx(chain, dst);
2200 * XXX HACK. Store the disable mask in the "next"
2201 * pointer in a wild attempt to keep the ABI the same.
2202 * Why do we do this on EVERY rule?
2204 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2205 * so we need to fail _after_ saving at least one mask.
2207 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2209 dst->timestamp += boot_seconds;
2214 /* Non-fatal table rewrite error. */
2218 printf("Stop on rule %d. Fail to convert table\n",
2224 printf("ipfw: process %s is using legacy interfaces,"
2225 " consider rebuilding\n", "");
2226 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2227 return (bp - (char *)buf);
2232 uint32_t b; /* start rule */
2233 uint32_t e; /* end rule */
2234 uint32_t rcount; /* number of rules */
2235 uint32_t rsize; /* rules size */
2236 uint32_t tcount; /* number of tables */
2237 int rcounters; /* counters */
2238 uint32_t *bmask; /* index bitmask of used named objects */
2242 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2245 ntlv->head.type = no->etlv;
2246 ntlv->head.length = sizeof(*ntlv);
2247 ntlv->idx = no->kidx;
2248 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2252 * Export named object info in instance @ni, identified by @kidx
2253 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2255 * Returns 0 on success.
2258 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2259 struct sockopt_data *sd)
2261 struct named_object *no;
2262 ipfw_obj_ntlv *ntlv;
2264 no = ipfw_objhash_lookup_kidx(ni, kidx);
2265 KASSERT(no != NULL, ("invalid object kernel index passed"));
2267 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2271 ipfw_export_obj_ntlv(no, ntlv);
2276 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2277 struct sockopt_data *sd)
2281 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2282 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2284 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2292 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2293 struct sockopt_data *sd)
2295 ipfw_obj_ctlv *ctlv;
2298 MPASS(da->tcount > 0);
2300 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2303 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2304 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2306 ctlv->count = da->tcount;
2307 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2309 /* Dump table names first (if any) */
2310 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2313 /* Then dump another named objects */
2314 da->bmask += IPFW_TABLES_MAX / 32;
2315 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2319 * Dumps static rules with table TLVs in buffer @sd.
2321 * Returns 0 on success.
2324 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2325 struct sockopt_data *sd)
2327 ipfw_obj_ctlv *ctlv;
2328 struct ip_fw *krule;
2333 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2336 ctlv->head.type = IPFW_TLV_RULE_LIST;
2337 ctlv->head.length = da->rsize + sizeof(*ctlv);
2338 ctlv->count = da->rcount;
2340 for (i = da->b; i < da->e; i++) {
2341 krule = chain->map[i];
2343 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2344 if (da->rcounters != 0)
2345 l += sizeof(struct ip_fw_bcounter);
2346 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2350 export_rule1(krule, dst, l, da->rcounters);
2357 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2362 * Maintain separate bitmasks for table and non-table objects.
2364 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2366 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2369 bmask[bidx] |= 1 << (kidx % 32);
2374 * Marks every object index used in @rule with bit in @bmask.
2375 * Used to generate bitmask of referenced tables/objects for given ruleset
2379 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2380 struct dump_args *da)
2382 struct opcode_obj_rewrite *rw;
2391 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2392 cmdlen = F_LEN(cmd);
2394 rw = find_op_rw(cmd, &kidx, &subtype);
2398 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2404 * Dumps requested objects data
2405 * Data layout (version 0)(current):
2406 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2407 * size = ipfw_cfg_lheader.size
2408 * Reply: [ ipfw_cfg_lheader
2409 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2410 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2411 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2413 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2415 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2416 * The rest (size, count) are set to zero and needs to be ignored.
2418 * Returns 0 on success.
2421 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2422 struct sockopt_data *sd)
2424 struct dump_args da;
2425 ipfw_cfg_lheader *hdr;
2428 uint32_t hdr_flags, *bmask;
2431 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2437 memset(&da, 0, sizeof(da));
2439 * Allocate needed state.
2440 * Note we allocate 2xspace mask, for table & srv
2442 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2443 da.bmask = bmask = malloc(
2444 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2446 IPFW_UH_RLOCK(chain);
2449 * STAGE 1: Determine size/count for objects in range.
2450 * Prepare used tables bitmask.
2452 sz = sizeof(ipfw_cfg_lheader);
2453 da.e = chain->n_rules;
2455 if (hdr->end_rule != 0) {
2456 /* Handle custom range */
2457 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2458 rnum = IPFW_DEFAULT_RULE;
2459 da.b = ipfw_find_rule(chain, rnum, 0);
2460 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2461 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2462 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2465 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2466 for (i = da.b; i < da.e; i++) {
2467 rule = chain->map[i];
2468 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2470 /* Update bitmask of used objects for given range */
2471 mark_rule_objects(chain, rule, &da);
2473 /* Add counters if requested */
2474 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2475 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2478 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2481 if (hdr->flags & IPFW_CFG_GET_STATES) {
2482 sz += sizeof(ipfw_obj_ctlv) +
2483 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2488 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2489 sizeof(ipfw_obj_ctlv);
2492 * Fill header anyway.
2493 * Note we have to save header fields to stable storage
2494 * buffer inside @sd can be flushed after dumping rules
2497 hdr->set_mask = ~V_set_disable;
2498 hdr_flags = hdr->flags;
2501 if (sd->valsize < sz) {
2506 /* STAGE2: Store actual data */
2507 if (da.tcount > 0) {
2508 error = dump_named_objects(chain, &da, sd);
2513 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2514 error = dump_static_rules(chain, &da, sd);
2519 if (hdr_flags & IPFW_CFG_GET_STATES)
2520 error = ipfw_dump_states(chain, sd);
2523 IPFW_UH_RUNLOCK(chain);
2526 free(bmask, M_TEMP);
2532 ipfw_check_object_name_generic(const char *name)
2536 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2537 if (strnlen(name, nsize) == nsize)
2539 if (name[0] == '\0')
2545 * Creates non-existent objects referenced by rule.
2547 * Return 0 on success.
2550 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2551 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2553 struct opcode_obj_rewrite *rw;
2559 * Compatibility stuff: do actual creation for non-existing,
2560 * but referenced objects.
2562 for (p = oib; p < pidx; p++) {
2570 rw = find_op_rw(cmd + p->off, NULL, NULL);
2571 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2572 (cmd + p->off)->opcode));
2574 if (rw->create_object == NULL)
2577 error = rw->create_object(ch, ti, &kidx);
2584 * Error happened. We have to rollback everything.
2585 * Drop all already acquired references.
2588 unref_oib_objects(ch, cmd, oib, pidx);
2589 IPFW_UH_WUNLOCK(ch);
2598 * Compatibility function for old ipfw(8) binaries.
2599 * Rewrites table/nat kernel indices with userland ones.
2600 * Convert tables matching '/^\d+$/' to their atoi() value.
2601 * Use number 65535 for other tables.
2603 * Returns 0 on success.
2606 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2608 struct opcode_obj_rewrite *rw;
2609 struct named_object *no;
2613 int cmdlen, error, l;
2614 uint16_t kidx, uidx;
2622 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2623 cmdlen = F_LEN(cmd);
2625 /* Check if is index in given opcode */
2626 rw = find_op_rw(cmd, &kidx, &subtype);
2630 /* Try to find referenced kernel object */
2631 no = rw->find_bykidx(ch, kidx);
2635 val = strtol(no->name, &end, 10);
2636 if (*end == '\0' && val < 65535) {
2641 * We are called via legacy opcode.
2642 * Save error and show table as fake number
2643 * not to make ipfw(8) hang.
2649 rw->update(cmd, uidx);
2657 * Unreferences all already-referenced objects in given @cmd rule,
2658 * using information in @oib.
2660 * Used to rollback partially converted rule on error.
2663 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2664 struct obj_idx *end)
2666 struct opcode_obj_rewrite *rw;
2667 struct named_object *no;
2670 IPFW_UH_WLOCK_ASSERT(ch);
2672 for (p = oib; p < end; p++) {
2676 rw = find_op_rw(cmd + p->off, NULL, NULL);
2677 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2678 (cmd + p->off)->opcode));
2680 /* Find & unref by existing idx */
2681 no = rw->find_bykidx(ch, p->kidx);
2682 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2688 * Remove references from every object used in @rule.
2689 * Used at rule removal code.
2692 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2694 struct opcode_obj_rewrite *rw;
2695 struct named_object *no;
2701 IPFW_UH_WLOCK_ASSERT(ch);
2706 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2707 cmdlen = F_LEN(cmd);
2709 rw = find_op_rw(cmd, &kidx, &subtype);
2712 no = rw->find_bykidx(ch, kidx);
2714 KASSERT(no != NULL, ("object id %d not found", kidx));
2715 KASSERT(no->subtype == subtype,
2716 ("wrong type %d (%d) for object id %d",
2717 no->subtype, subtype, kidx));
2718 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2721 if (no->refcnt == 1 && rw->destroy_object != NULL)
2722 rw->destroy_object(ch, no);
2730 * Find and reference object (if any) stored in instruction @cmd.
2732 * Saves object info in @pidx, sets
2733 * - @unresolved to 1 if object should exists but not found
2735 * Returns non-zero value in case of error.
2738 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2739 struct obj_idx *pidx, int *unresolved)
2741 struct named_object *no;
2742 struct opcode_obj_rewrite *rw;
2745 /* Check if this opcode is candidate for rewrite */
2746 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2750 /* Need to rewrite. Save necessary fields */
2751 pidx->uidx = ti->uidx;
2752 pidx->type = ti->type;
2754 /* Try to find referenced kernel object */
2755 error = rw->find_byname(ch, ti, &no);
2760 * Report about unresolved object for automaic
2768 * Object is already exist.
2769 * Its subtype should match with expected value.
2771 if (ti->type != no->subtype)
2774 /* Bump refcount and update kidx. */
2776 rw->update(cmd, no->kidx);
2781 * Finds and bumps refcount for objects referenced by given @rule.
2782 * Auto-creates non-existing tables.
2783 * Fills in @oib array with userland/kernel indexes.
2785 * Returns 0 on success.
2788 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2789 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2791 struct obj_idx *pidx;
2793 int cmdlen, error, l, unresolved;
2803 /* Increase refcount on each existing referenced table. */
2804 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2805 cmdlen = F_LEN(cmd);
2808 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2812 * Compatibility stuff for old clients:
2813 * prepare to automaitcally create non-existing objects.
2815 if (unresolved != 0) {
2816 pidx->off = rule->cmd_len - l;
2822 /* Unref everything we have already done */
2823 unref_oib_objects(ch, rule->cmd, oib, pidx);
2824 IPFW_UH_WUNLOCK(ch);
2827 IPFW_UH_WUNLOCK(ch);
2829 /* Perform auto-creation for non-existing objects */
2831 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2833 /* Calculate real number of dynamic objects */
2834 ci->object_opcodes = (uint16_t)(pidx - oib);
2840 * Checks is opcode is referencing table of appropriate type.
2841 * Adds reference count for found table if true.
2842 * Rewrites user-supplied opcode values with kernel ones.
2844 * Returns 0 on success and appropriate error code otherwise.
2847 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2852 struct obj_idx *p, *pidx_first, *pidx_last;
2856 * Prepare an array for storing opcode indices.
2857 * Use stack allocation by default.
2859 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2861 pidx_first = ci->obuf;
2863 pidx_first = malloc(
2864 ci->object_opcodes * sizeof(struct obj_idx),
2865 M_IPFW, M_WAITOK | M_ZERO);
2869 memset(&ti, 0, sizeof(ti));
2871 /* Use set rule is assigned to. */
2872 ti.set = ci->krule->set;
2873 if (ci->ctlv != NULL) {
2874 ti.tlvs = (void *)(ci->ctlv + 1);
2875 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2878 /* Reference all used tables and other objects */
2879 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2883 * Note that ref_rule_objects() might have updated ci->object_opcodes
2884 * to reflect actual number of object opcodes.
2887 /* Perform rewrite of remaining opcodes */
2889 pidx_last = pidx_first + ci->object_opcodes;
2890 for (p = pidx_first; p < pidx_last; p++) {
2891 cmd = ci->krule->cmd + p->off;
2892 update_opcode_kidx(cmd, p->kidx);
2896 if (pidx_first != ci->obuf)
2897 free(pidx_first, M_IPFW);
2903 * Adds one or more rules to ipfw @chain.
2904 * Data layout (version 0)(current):
2908 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2909 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2914 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2915 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2918 * Rules in reply are modified to store their actual ruleset number.
2920 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2921 * according to their idx field and there has to be no duplicates.
2922 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2923 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2925 * Returns 0 on success.
2928 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2929 struct sockopt_data *sd)
2931 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2932 ipfw_obj_ntlv *ntlv;
2933 int clen, error, idx;
2934 uint32_t count, read;
2935 struct ip_fw_rule *r;
2936 struct rule_check_info rci, *ci, *cbuf;
2939 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2940 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2942 read = sizeof(ip_fw3_opheader);
2946 memset(&rci, 0, sizeof(struct rule_check_info));
2948 if (read + sizeof(*ctlv) > sd->valsize)
2951 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2952 clen = ctlv->head.length;
2953 /* Check size and alignment */
2954 if (clen > sd->valsize || clen < sizeof(*ctlv))
2956 if ((clen % sizeof(uint64_t)) != 0)
2960 * Some table names or other named objects.
2961 * Check for validness.
2963 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2964 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2969 * Ensure TLVs are sorted ascending and
2970 * there are no duplicates.
2973 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2975 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2978 error = ipfw_check_object_name_generic(ntlv->name);
2982 if (ntlv->idx <= idx)
2991 read += ctlv->head.length;
2992 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2995 if (read + sizeof(*ctlv) > sd->valsize)
2998 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2999 clen = ctlv->head.length;
3000 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
3002 if ((clen % sizeof(uint64_t)) != 0)
3006 * TODO: Permit adding multiple rules at once
3008 if (ctlv->count != 1)
3011 clen -= sizeof(*ctlv);
3013 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
3016 /* Allocate state for each rule or use stack */
3017 if (ctlv->count == 1) {
3018 memset(&rci, 0, sizeof(struct rule_check_info));
3021 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
3026 * Check each rule for validness.
3027 * Ensure numbered rules are sorted ascending
3028 * and properly aligned
3031 r = (struct ip_fw_rule *)(ctlv + 1);
3035 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3036 if (rsize > clen || ctlv->count <= count) {
3042 error = check_ipfw_rule1(r, rsize, ci);
3047 if (r->rulenum != 0 && r->rulenum < idx) {
3048 printf("rulenum %d idx %d\n", r->rulenum, idx);
3054 ci->urule = (caddr_t)r;
3056 rsize = roundup2(rsize, sizeof(uint64_t));
3058 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3063 if (ctlv->count != count || error != 0) {
3070 read += ctlv->head.length;
3071 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3074 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3075 if (cbuf != NULL && cbuf != &rci)
3081 * Passed rules seems to be valid.
3082 * Allocate storage and try to add them to chain.
3084 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3085 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3086 ci->krule = ipfw_alloc_rule(chain, clen);
3090 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3091 /* Free allocate krules */
3092 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3093 ipfw_free_rule(ci->krule);
3096 if (cbuf != NULL && cbuf != &rci)
3103 * Lists all sopts currently registered.
3104 * Data layout (v0)(current):
3105 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3106 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3108 * Returns 0 on success
3111 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3112 struct sockopt_data *sd)
3114 struct _ipfw_obj_lheader *olh;
3116 struct ipfw_sopt_handler *sh;
3117 uint32_t count, n, size;
3119 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3122 if (sd->valsize < olh->size)
3127 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3129 /* Fill in header regadless of buffer size */
3131 olh->objsize = sizeof(ipfw_sopt_info);
3133 if (size > olh->size) {
3140 for (n = 1; n <= count; n++) {
3141 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3142 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3143 sh = &ctl3_handlers[n];
3144 i->opcode = sh->opcode;
3145 i->version = sh->version;
3146 i->refcnt = sh->refcnt;
3154 * Compares two opcodes.
3155 * Used both in qsort() and bsearch().
3157 * Returns 0 if match is found.
3160 compare_opcodes(const void *_a, const void *_b)
3162 const struct opcode_obj_rewrite *a, *b;
3164 a = (const struct opcode_obj_rewrite *)_a;
3165 b = (const struct opcode_obj_rewrite *)_b;
3167 if (a->opcode < b->opcode)
3169 else if (a->opcode > b->opcode)
3176 * XXX: Rewrite bsearch()
3179 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3180 struct opcode_obj_rewrite **phi)
3182 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3184 memset(&h, 0, sizeof(h));
3187 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3188 ctl3_rsize, sizeof(h), compare_opcodes);
3192 /* Find the first element matching the same opcode */
3194 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3197 /* Find the last element matching the same opcode */
3199 ctl3_max = ctl3_rewriters + ctl3_rsize;
3200 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3210 * Finds opcode object rewriter based on @code.
3212 * Returns pointer to handler or NULL.
3214 static struct opcode_obj_rewrite *
3215 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3217 struct opcode_obj_rewrite *rw, *lo, *hi;
3221 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3224 for (rw = lo; rw <= hi; rw++) {
3225 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3237 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3240 if (find_op_rw(cmd, puidx, NULL) == NULL)
3246 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3248 struct opcode_obj_rewrite *rw;
3250 rw = find_op_rw(cmd, NULL, NULL);
3251 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3252 rw->update(cmd, idx);
3256 ipfw_init_obj_rewriter()
3259 ctl3_rewriters = NULL;
3264 ipfw_destroy_obj_rewriter()
3267 if (ctl3_rewriters != NULL)
3268 free(ctl3_rewriters, M_IPFW);
3269 ctl3_rewriters = NULL;
3274 * Adds one or more opcode object rewrite handlers to the global array.
3275 * Function may sleep.
3278 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3281 struct opcode_obj_rewrite *tmp;
3286 sz = ctl3_rsize + count;
3288 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3290 if (ctl3_rsize + count <= sz)
3297 /* Merge old & new arrays */
3298 sz = ctl3_rsize + count;
3299 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3300 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3301 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3302 /* Switch new and free old */
3303 if (ctl3_rewriters != NULL)
3304 free(ctl3_rewriters, M_IPFW);
3305 ctl3_rewriters = tmp;
3312 * Removes one or more object rewrite handlers from the global array.
3315 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3318 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3323 for (i = 0; i < count; i++) {
3324 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3327 for (ktmp = lo; ktmp <= hi; ktmp++) {
3328 if (ktmp->classifier != rw[i].classifier)
3331 ctl3_max = ctl3_rewriters + ctl3_rsize;
3332 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3333 memmove(ktmp, ktmp + 1, sz);
3340 if (ctl3_rsize == 0) {
3341 if (ctl3_rewriters != NULL)
3342 free(ctl3_rewriters, M_IPFW);
3343 ctl3_rewriters = NULL;
3352 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3353 struct named_object *no, void *arg)
3355 struct sockopt_data *sd;
3356 ipfw_obj_ntlv *ntlv;
3358 sd = (struct sockopt_data *)arg;
3359 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3362 ipfw_export_obj_ntlv(no, ntlv);
3367 * Lists all service objects.
3368 * Data layout (v0)(current):
3369 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3370 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3371 * Returns 0 on success
3374 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3375 struct sockopt_data *sd)
3377 ipfw_obj_lheader *hdr;
3380 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3384 IPFW_UH_RLOCK(chain);
3385 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3386 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3387 if (sd->valsize < hdr->size) {
3388 IPFW_UH_RUNLOCK(chain);
3392 hdr->objsize = sizeof(ipfw_obj_ntlv);
3394 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3395 export_objhash_ntlv_internal, sd);
3396 IPFW_UH_RUNLOCK(chain);
3401 * Compares two sopt handlers (code, version and handler ptr).
3402 * Used both as qsort() and bsearch().
3403 * Does not compare handler for latter case.
3405 * Returns 0 if match is found.
3408 compare_sh(const void *_a, const void *_b)
3410 const struct ipfw_sopt_handler *a, *b;
3412 a = (const struct ipfw_sopt_handler *)_a;
3413 b = (const struct ipfw_sopt_handler *)_b;
3415 if (a->opcode < b->opcode)
3417 else if (a->opcode > b->opcode)
3420 if (a->version < b->version)
3422 else if (a->version > b->version)
3425 /* bsearch helper */
3426 if (a->handler == NULL)
3429 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3431 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3438 * Finds sopt handler based on @code and @version.
3440 * Returns pointer to handler or NULL.
3442 static struct ipfw_sopt_handler *
3443 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3445 struct ipfw_sopt_handler *sh, h;
3447 memset(&h, 0, sizeof(h));
3449 h.version = version;
3450 h.handler = handler;
3452 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3453 ctl3_hsize, sizeof(h), compare_sh);
3459 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3461 struct ipfw_sopt_handler *sh;
3464 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3466 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3472 /* Copy handler data to requested buffer */
3480 find_unref_sh(struct ipfw_sopt_handler *psh)
3482 struct ipfw_sopt_handler *sh;
3485 sh = find_sh(psh->opcode, psh->version, NULL);
3486 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3493 ipfw_init_sopt_handler()
3497 IPFW_ADD_SOPT_HANDLER(1, scodes);
3501 ipfw_destroy_sopt_handler()
3504 IPFW_DEL_SOPT_HANDLER(1, scodes);
3505 CTL3_LOCK_DESTROY();
3509 * Adds one or more sockopt handlers to the global array.
3510 * Function may sleep.
3513 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3516 struct ipfw_sopt_handler *tmp;
3521 sz = ctl3_hsize + count;
3523 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3525 if (ctl3_hsize + count <= sz)
3532 /* Merge old & new arrays */
3533 sz = ctl3_hsize + count;
3534 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3535 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3536 qsort(tmp, sz, sizeof(*sh), compare_sh);
3537 /* Switch new and free old */
3538 if (ctl3_handlers != NULL)
3539 free(ctl3_handlers, M_IPFW);
3540 ctl3_handlers = tmp;
3548 * Removes one or more sockopt handlers from the global array.
3551 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3554 struct ipfw_sopt_handler *tmp, *h;
3559 for (i = 0; i < count; i++) {
3561 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3565 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3566 memmove(h, h + 1, sz);
3570 if (ctl3_hsize == 0) {
3571 if (ctl3_handlers != NULL)
3572 free(ctl3_handlers, M_IPFW);
3573 ctl3_handlers = NULL;
3584 * Writes data accumulated in @sd to sockopt buffer.
3585 * Zeroes internal @sd buffer.
3588 ipfw_flush_sopt_data(struct sockopt_data *sd)
3590 struct sockopt *sopt;
3600 if (sopt->sopt_dir == SOPT_GET) {
3601 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3606 memset(sd->kbuf, 0, sd->ksize);
3609 if (sd->ktotal + sd->ksize < sd->valsize)
3610 sd->kavail = sd->ksize;
3612 sd->kavail = sd->valsize - sd->ktotal;
3614 /* Update sopt buffer data */
3615 sopt->sopt_valsize = sd->ktotal;
3616 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3622 * Ensures that @sd buffer has contiguous @neeeded number of
3625 * Returns pointer to requested space or NULL.
3628 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3633 if (sd->kavail < needed) {
3635 * Flush data and try another time.
3637 error = ipfw_flush_sopt_data(sd);
3639 if (sd->kavail < needed || error != 0)
3643 addr = sd->kbuf + sd->koff;
3645 sd->kavail -= needed;
3650 * Requests @needed contiguous bytes from @sd buffer.
3651 * Function is used to notify subsystem that we are
3652 * interesed in first @needed bytes (request header)
3653 * and the rest buffer can be safely zeroed.
3655 * Returns pointer to requested space or NULL.
3658 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3662 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3666 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3672 * New sockopt handler.
3675 ipfw_ctl3(struct sockopt *sopt)
3678 size_t size, valsize;
3679 struct ip_fw_chain *chain;
3681 struct sockopt_data sdata;
3682 struct ipfw_sopt_handler h;
3683 ip_fw3_opheader *op3 = NULL;
3685 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3689 if (sopt->sopt_name != IP_FW3)
3690 return (ipfw_ctl(sopt));
3692 chain = &V_layer3_chain;
3695 /* Save original valsize before it is altered via sooptcopyin() */
3696 valsize = sopt->sopt_valsize;
3697 memset(&sdata, 0, sizeof(sdata));
3698 /* Read op3 header first to determine actual operation */
3699 op3 = (ip_fw3_opheader *)xbuf;
3700 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3703 sopt->sopt_valsize = valsize;
3706 * Find and reference command.
3708 error = find_ref_sh(op3->opcode, op3->version, &h);
3713 * Disallow modifications in really-really secure mode, but still allow
3714 * the logging counters to be reset.
3716 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3717 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3725 * Fill in sockopt_data structure that may be useful for
3726 * IP_FW3 get requests.
3729 if (valsize <= sizeof(xbuf)) {
3730 /* use on-stack buffer */
3732 sdata.ksize = sizeof(xbuf);
3733 sdata.kavail = valsize;
3737 * Determine opcode type/buffer size:
3738 * allocate sliding-window buf for data export or
3739 * contiguous buffer for special ops.
3741 if ((h.dir & HDIR_SET) != 0) {
3742 /* Set request. Allocate contigous buffer. */
3743 if (valsize > CTL3_LARGEBUF) {
3750 /* Get request. Allocate sliding window buffer */
3751 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3753 if (size < valsize) {
3754 /* We have to wire user buffer */
3755 error = vslock(sopt->sopt_val, valsize);
3762 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3764 sdata.kavail = size;
3768 sdata.sopt_val = sopt->sopt_val;
3769 sdata.valsize = valsize;
3772 * Copy either all request (if valsize < bsize_max)
3773 * or first bsize_max bytes to guarantee most consumers
3774 * that all necessary data has been copied).
3775 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3777 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3778 sizeof(ip_fw3_opheader))) != 0)
3780 op3 = (ip_fw3_opheader *)sdata.kbuf;
3782 /* Finally, run handler */
3783 error = h.handler(chain, op3, &sdata);
3786 /* Flush state and free buffers */
3788 error = ipfw_flush_sopt_data(&sdata);
3790 ipfw_flush_sopt_data(&sdata);
3793 vsunlock(sdata.sopt_val, valsize);
3795 /* Restore original pointer and set number of bytes written */
3796 sopt->sopt_val = sdata.sopt_val;
3797 sopt->sopt_valsize = sdata.ktotal;
3798 if (sdata.kbuf != xbuf)
3799 free(sdata.kbuf, M_TEMP);
3805 * {set|get}sockopt parser.
3808 ipfw_ctl(struct sockopt *sopt)
3810 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3812 size_t size, valsize;
3814 struct ip_fw_rule0 *rule;
3815 struct ip_fw_chain *chain;
3816 u_int32_t rulenum[2];
3818 struct rule_check_info ci;
3821 chain = &V_layer3_chain;
3824 /* Save original valsize before it is altered via sooptcopyin() */
3825 valsize = sopt->sopt_valsize;
3826 opt = sopt->sopt_name;
3829 * Disallow modifications in really-really secure mode, but still allow
3830 * the logging counters to be reset.
3832 if (opt == IP_FW_ADD ||
3833 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3834 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3842 * pass up a copy of the current rules. Static rules
3843 * come first (the last of which has number IPFW_DEFAULT_RULE),
3844 * followed by a possibly empty list of dynamic rule.
3845 * The last dynamic rule has NULL in the "next" field.
3847 * Note that the calculated size is used to bound the
3848 * amount of data returned to the user. The rule set may
3849 * change between calculating the size and returning the
3850 * data in which case we'll just return what fits.
3855 size = chain->static_len;
3856 size += ipfw_dyn_len();
3857 if (size >= sopt->sopt_valsize)
3859 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3860 IPFW_UH_RLOCK(chain);
3861 /* check again how much space we need */
3862 want = chain->static_len + ipfw_dyn_len();
3864 len = ipfw_getrules(chain, buf, size);
3865 IPFW_UH_RUNLOCK(chain);
3867 error = sooptcopyout(sopt, buf, len);
3875 /* locking is done within del_entry() */
3876 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3880 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3881 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3882 sizeof(struct ip_fw7) );
3884 memset(&ci, 0, sizeof(struct rule_check_info));
3887 * If the size of commands equals RULESIZE7 then we assume
3888 * a FreeBSD7.2 binary is talking to us (set is7=1).
3889 * is7 is persistent so the next 'ipfw list' command
3890 * will use this format.
3891 * NOTE: If wrong version is guessed (this can happen if
3892 * the first ipfw command is 'ipfw [pipe] list')
3893 * the ipfw binary may crash or loop infinitly...
3895 size = sopt->sopt_valsize;
3896 if (size == RULESIZE7(rule)) {
3898 error = convert_rule_to_8(rule);
3903 size = RULESIZE(rule);
3907 error = check_ipfw_rule0(rule, size, &ci);
3909 /* locking is done within add_rule() */
3910 struct ip_fw *krule;
3911 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3912 ci.urule = (caddr_t)rule;
3915 error = commit_rules(chain, &ci, 1);
3917 ipfw_free_rule(ci.krule);
3918 else if (sopt->sopt_dir == SOPT_GET) {
3920 error = convert_rule_to_7(rule);
3921 size = RULESIZE7(rule);
3927 error = sooptcopyout(sopt, rule, size);
3935 * IP_FW_DEL is used for deleting single rules or sets,
3936 * and (ab)used to atomically manipulate sets. Argument size
3937 * is used to distinguish between the two:
3939 * delete single rule or set of rules,
3940 * or reassign rules (or sets) to a different set.
3941 * 2*sizeof(u_int32_t)
3942 * atomic disable/enable sets.
3943 * first u_int32_t contains sets to be disabled,
3944 * second u_int32_t contains sets to be enabled.
3946 error = sooptcopyin(sopt, rulenum,
3947 2*sizeof(u_int32_t), sizeof(u_int32_t));
3950 size = sopt->sopt_valsize;
3951 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3952 /* delete or reassign, locking done in del_entry() */
3953 error = del_entry(chain, rulenum[0]);
3954 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3955 IPFW_UH_WLOCK(chain);
3957 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3958 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3959 IPFW_UH_WUNLOCK(chain);
3965 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3967 if (sopt->sopt_val != 0) {
3968 error = sooptcopyin(sopt, rulenum,
3969 sizeof(u_int32_t), sizeof(u_int32_t));
3973 error = zero_entry(chain, rulenum[0],
3974 sopt->sopt_name == IP_FW_RESETLOG);
3977 /*--- TABLE opcodes ---*/
3978 case IP_FW_TABLE_ADD:
3979 case IP_FW_TABLE_DEL:
3981 ipfw_table_entry ent;
3982 struct tentry_info tei;
3984 struct table_value v;
3986 error = sooptcopyin(sopt, &ent,
3987 sizeof(ent), sizeof(ent));
3991 memset(&tei, 0, sizeof(tei));
3992 tei.paddr = &ent.addr;
3993 tei.subtype = AF_INET;
3994 tei.masklen = ent.masklen;
3995 ipfw_import_table_value_legacy(ent.value, &v);
3997 memset(&ti, 0, sizeof(ti));
3999 ti.type = IPFW_TABLE_CIDR;
4001 error = (opt == IP_FW_TABLE_ADD) ?
4002 add_table_entry(chain, &ti, &tei, 0, 1) :
4003 del_table_entry(chain, &ti, &tei, 0, 1);
4008 case IP_FW_TABLE_FLUSH:
4013 error = sooptcopyin(sopt, &tbl,
4014 sizeof(tbl), sizeof(tbl));
4017 memset(&ti, 0, sizeof(ti));
4019 error = flush_table(chain, &ti);
4023 case IP_FW_TABLE_GETSIZE:
4028 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4031 memset(&ti, 0, sizeof(ti));
4034 error = ipfw_count_table(chain, &ti, &cnt);
4035 IPFW_RUNLOCK(chain);
4038 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4042 case IP_FW_TABLE_LIST:
4047 if (sopt->sopt_valsize < sizeof(*tbl)) {
4051 size = sopt->sopt_valsize;
4052 tbl = malloc(size, M_TEMP, M_WAITOK);
4053 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4058 tbl->size = (size - sizeof(*tbl)) /
4059 sizeof(ipfw_table_entry);
4060 memset(&ti, 0, sizeof(ti));
4063 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4064 IPFW_RUNLOCK(chain);
4069 error = sooptcopyout(sopt, tbl, size);
4074 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4076 if (IPFW_NAT_LOADED)
4077 error = ipfw_nat_cfg_ptr(sopt);
4079 printf("IP_FW_NAT_CFG: %s\n",
4080 "ipfw_nat not present, please load it");
4086 if (IPFW_NAT_LOADED)
4087 error = ipfw_nat_del_ptr(sopt);
4089 printf("IP_FW_NAT_DEL: %s\n",
4090 "ipfw_nat not present, please load it");
4095 case IP_FW_NAT_GET_CONFIG:
4096 if (IPFW_NAT_LOADED)
4097 error = ipfw_nat_get_cfg_ptr(sopt);
4099 printf("IP_FW_NAT_GET_CFG: %s\n",
4100 "ipfw_nat not present, please load it");
4105 case IP_FW_NAT_GET_LOG:
4106 if (IPFW_NAT_LOADED)
4107 error = ipfw_nat_get_log_ptr(sopt);
4109 printf("IP_FW_NAT_GET_LOG: %s\n",
4110 "ipfw_nat not present, please load it");
4116 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4123 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4125 /* Functions to convert rules 7.2 <==> 8.0 */
4127 convert_rule_to_7(struct ip_fw_rule0 *rule)
4129 /* Used to modify original rule */
4130 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4131 /* copy of original rule, version 8 */
4132 struct ip_fw_rule0 *tmp;
4134 /* Used to copy commands */
4135 ipfw_insn *ccmd, *dst;
4136 int ll = 0, ccmdlen = 0;
4138 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4140 return 1; //XXX error
4142 bcopy(rule, tmp, RULE_MAXSIZE);
4145 //rule7->_pad = tmp->_pad;
4146 rule7->set = tmp->set;
4147 rule7->rulenum = tmp->rulenum;
4148 rule7->cmd_len = tmp->cmd_len;
4149 rule7->act_ofs = tmp->act_ofs;
4150 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4151 rule7->cmd_len = tmp->cmd_len;
4152 rule7->pcnt = tmp->pcnt;
4153 rule7->bcnt = tmp->bcnt;
4154 rule7->timestamp = tmp->timestamp;
4157 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4158 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4159 ccmdlen = F_LEN(ccmd);
4161 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4163 if (dst->opcode > O_NAT)
4164 /* O_REASS doesn't exists in 7.2 version, so
4165 * decrement opcode if it is after O_REASS
4170 printf("ipfw: opcode %d size truncated\n",
4181 convert_rule_to_8(struct ip_fw_rule0 *rule)
4183 /* Used to modify original rule */
4184 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4186 /* Used to copy commands */
4187 ipfw_insn *ccmd, *dst;
4188 int ll = 0, ccmdlen = 0;
4190 /* Copy of original rule */
4191 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4193 return 1; //XXX error
4196 bcopy(rule7, tmp, RULE_MAXSIZE);
4198 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4199 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4200 ccmdlen = F_LEN(ccmd);
4202 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4204 if (dst->opcode > O_NAT)
4205 /* O_REASS doesn't exists in 7.2 version, so
4206 * increment opcode if it is after O_REASS
4211 printf("ipfw: opcode %d size truncated\n",
4217 rule->_pad = tmp->_pad;
4218 rule->set = tmp->set;
4219 rule->rulenum = tmp->rulenum;
4220 rule->cmd_len = tmp->cmd_len;
4221 rule->act_ofs = tmp->act_ofs;
4222 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4223 rule->cmd_len = tmp->cmd_len;
4224 rule->id = 0; /* XXX see if is ok = 0 */
4225 rule->pcnt = tmp->pcnt;
4226 rule->bcnt = tmp->bcnt;
4227 rule->timestamp = tmp->timestamp;
4239 ipfw_init_srv(struct ip_fw_chain *ch)
4242 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4243 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4244 M_IPFW, M_WAITOK | M_ZERO);
4248 ipfw_destroy_srv(struct ip_fw_chain *ch)
4251 free(ch->srvstate, M_IPFW);
4252 ipfw_objhash_destroy(ch->srvmap);
4256 * Allocate new bitmask which can be used to enlarge/shrink
4257 * named instance index.
4260 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4266 KASSERT((items % BLOCK_ITEMS) == 0,
4267 ("bitmask size needs to power of 2 and greater or equal to %zu",
4270 max_blocks = items / BLOCK_ITEMS;
4272 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4273 /* Mark all as free */
4274 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4275 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4278 *pblocks = max_blocks;
4282 * Copy current bitmask index to new one.
4285 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4287 int old_blocks, new_blocks;
4288 u_long *old_idx, *new_idx;
4291 old_idx = ni->idx_mask;
4292 old_blocks = ni->max_blocks;
4294 new_blocks = *blocks;
4296 for (i = 0; i < IPFW_MAX_SETS; i++) {
4297 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4298 old_blocks * sizeof(u_long));
4303 * Swaps current @ni index with new one.
4306 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4311 old_idx = ni->idx_mask;
4312 old_blocks = ni->max_blocks;
4314 ni->idx_mask = *idx;
4315 ni->max_blocks = *blocks;
4317 /* Save old values */
4319 *blocks = old_blocks;
4323 ipfw_objhash_bitmap_free(void *idx, int blocks)
4330 * Creates named hash instance.
4331 * Must be called without holding any locks.
4332 * Return pointer to new instance.
4334 struct namedobj_instance *
4335 ipfw_objhash_create(uint32_t items)
4337 struct namedobj_instance *ni;
4341 size = sizeof(struct namedobj_instance) +
4342 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4343 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4345 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4346 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4347 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4349 ni->names = (struct namedobjects_head *)(ni +1);
4350 ni->values = &ni->names[ni->nn_size];
4352 for (i = 0; i < ni->nn_size; i++)
4353 TAILQ_INIT(&ni->names[i]);
4355 for (i = 0; i < ni->nv_size; i++)
4356 TAILQ_INIT(&ni->values[i]);
4358 /* Set default hashing/comparison functions */
4359 ni->hash_f = objhash_hash_name;
4360 ni->cmp_f = objhash_cmp_name;
4362 /* Allocate bitmask separately due to possible resize */
4363 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4369 ipfw_objhash_destroy(struct namedobj_instance *ni)
4372 free(ni->idx_mask, M_IPFW);
4377 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4378 objhash_cmp_f *cmp_f)
4381 ni->hash_f = hash_f;
4386 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4389 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4393 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4396 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4403 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4407 v = val % (ni->nv_size - 1);
4412 struct named_object *
4413 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4415 struct named_object *no;
4418 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4420 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4421 if (ni->cmp_f(no, name, set) == 0)
4429 * Find named object by @uid.
4430 * Check @tlvs for valid data inside.
4432 * Returns pointer to found TLV or NULL.
4435 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4437 ipfw_obj_ntlv *ntlv;
4441 pa = (uintptr_t)tlvs;
4444 for (; pa < pe; pa += l) {
4445 ntlv = (ipfw_obj_ntlv *)pa;
4446 l = ntlv->head.length;
4448 if (l != sizeof(*ntlv))
4451 if (ntlv->idx != uidx)
4454 * When userland has specified zero TLV type, do
4455 * not compare it with eltv. In some cases userland
4456 * doesn't know what type should it have. Use only
4457 * uidx and name for search named_object.
4459 if (ntlv->head.type != 0 &&
4460 ntlv->head.type != (uint16_t)etlv)
4463 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4473 * Finds object config based on either legacy index
4475 * Note @ti structure contains unchecked data from userland.
4477 * Returns 0 in success and fills in @pno with found config
4480 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4481 uint32_t etlv, struct named_object **pno)
4484 ipfw_obj_ntlv *ntlv;
4487 if (ti->tlvs == NULL)
4490 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4496 * Use set provided by @ti instead of @ntlv one.
4497 * This is needed due to different sets behavior
4498 * controlled by V_fw_tables_sets.
4501 *pno = ipfw_objhash_lookup_name(ni, set, name);
4508 * Find named object by name, considering also its TLV type.
4510 struct named_object *
4511 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4512 uint32_t type, const char *name)
4514 struct named_object *no;
4517 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4519 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4520 if (ni->cmp_f(no, name, set) == 0 &&
4521 no->etlv == (uint16_t)type)
4528 struct named_object *
4529 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4531 struct named_object *no;
4534 hash = objhash_hash_idx(ni, kidx);
4536 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4537 if (no->kidx == kidx)
4545 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4546 struct named_object *b)
4549 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4556 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4560 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4561 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4563 hash = objhash_hash_idx(ni, no->kidx);
4564 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4570 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4574 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4575 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4577 hash = objhash_hash_idx(ni, no->kidx);
4578 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4584 ipfw_objhash_count(struct namedobj_instance *ni)
4591 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4593 struct named_object *no;
4598 for (i = 0; i < ni->nn_size; i++) {
4599 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4600 if (no->etlv == type)
4608 * Runs @func for each found named object.
4609 * It is safe to delete objects from callback
4612 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4614 struct named_object *no, *no_tmp;
4617 for (i = 0; i < ni->nn_size; i++) {
4618 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4619 ret = f(ni, no, arg);
4628 * Runs @f for each found named object with type @type.
4629 * It is safe to delete objects from callback
4632 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4633 void *arg, uint16_t type)
4635 struct named_object *no, *no_tmp;
4638 for (i = 0; i < ni->nn_size; i++) {
4639 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4640 if (no->etlv != type)
4642 ret = f(ni, no, arg);
4651 * Removes index from given set.
4652 * Returns 0 on success.
4655 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4660 i = idx / BLOCK_ITEMS;
4661 v = idx % BLOCK_ITEMS;
4663 if (i >= ni->max_blocks)
4666 mask = &ni->idx_mask[i];
4668 if ((*mask & ((u_long)1 << v)) != 0)
4672 *mask |= (u_long)1 << v;
4674 /* Update free offset */
4675 if (ni->free_off[0] > i)
4676 ni->free_off[0] = i;
4682 * Allocate new index in given instance and stores in in @pidx.
4683 * Returns 0 on success.
4686 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4688 struct namedobj_instance *ni;
4692 ni = (struct namedobj_instance *)n;
4694 off = ni->free_off[0];
4695 mask = &ni->idx_mask[off];
4697 for (i = off; i < ni->max_blocks; i++, mask++) {
4698 if ((v = ffsl(*mask)) == 0)
4702 *mask &= ~ ((u_long)1 << (v - 1));
4704 ni->free_off[0] = i;
4706 v = BLOCK_ITEMS * i + v - 1;