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);
231 * Find the smallest rule >= key, id.
232 * We could use bsearch but it is so simple that we code it directly
235 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
240 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
243 if (r->rulenum < key)
244 lo = i + 1; /* continue from the next one */
245 else if (r->rulenum > key)
246 hi = i; /* this might be good */
248 lo = i + 1; /* continue from the next one */
249 else /* r->id >= id */
250 hi = i; /* this might be good */
256 * Builds skipto cache on rule set @map.
259 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
264 IPFW_UH_WLOCK_ASSERT(chain);
267 rulenum = map[mi]->rulenum;
268 smap = chain->idxmap_back;
273 for (i = 0; i < 65536; i++) {
275 /* Use the same rule index until i < rulenum */
276 if (i != rulenum || i == 65535)
278 /* Find next rule with num > i */
279 rulenum = map[++mi]->rulenum;
281 rulenum = map[++mi]->rulenum;
286 * Swaps prepared (backup) index with current one.
289 swap_skipto_cache(struct ip_fw_chain *chain)
293 IPFW_UH_WLOCK_ASSERT(chain);
294 IPFW_WLOCK_ASSERT(chain);
297 chain->idxmap = chain->idxmap_back;
298 chain->idxmap_back = map;
302 * Allocate and initialize skipto cache.
305 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
307 int *idxmap, *idxmap_back;
309 idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
310 idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
313 * Note we may be called at any time after initialization,
314 * for example, on first skipto rule, so we need to
315 * provide valid chain->idxmap on return
318 IPFW_UH_WLOCK(chain);
319 if (chain->idxmap != NULL) {
320 IPFW_UH_WUNLOCK(chain);
321 free(idxmap, M_IPFW);
322 free(idxmap_back, M_IPFW);
326 /* Set backup pointer first to permit building cache */
327 chain->idxmap_back = idxmap_back;
328 update_skipto_cache(chain, chain->map);
330 /* It is now safe to set chain->idxmap ptr */
331 chain->idxmap = idxmap;
332 swap_skipto_cache(chain);
334 IPFW_UH_WUNLOCK(chain);
338 * Destroys skipto cache.
341 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
344 if (chain->idxmap != NULL)
345 free(chain->idxmap, M_IPFW);
346 if (chain->idxmap != NULL)
347 free(chain->idxmap_back, M_IPFW);
351 * allocate a new map, returns the chain locked. extra is the number
352 * of entries to add or delete.
354 static struct ip_fw **
355 get_map(struct ip_fw_chain *chain, int extra, int locked)
362 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
364 i = chain->n_rules + extra;
365 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
367 printf("%s: cannot allocate map\n", __FUNCTION__);
371 IPFW_UH_WLOCK(chain);
372 if (i >= chain->n_rules + extra) /* good */
374 /* otherwise we lost the race, free and retry */
376 IPFW_UH_WUNLOCK(chain);
382 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
384 static struct ip_fw **
385 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
387 struct ip_fw **old_map;
391 chain->n_rules = new_len;
392 old_map = chain->map;
393 chain->map = new_map;
394 swap_skipto_cache(chain);
400 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
402 struct timeval boottime;
404 cntr->size = sizeof(*cntr);
406 if (krule->cntr != NULL) {
407 cntr->pcnt = counter_u64_fetch(krule->cntr);
408 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
409 cntr->timestamp = krule->timestamp;
411 if (cntr->timestamp > 0) {
412 getboottime(&boottime);
413 cntr->timestamp += boottime.tv_sec;
418 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
420 struct timeval boottime;
422 if (krule->cntr != NULL) {
423 cntr->pcnt = counter_u64_fetch(krule->cntr);
424 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
425 cntr->timestamp = krule->timestamp;
427 if (cntr->timestamp > 0) {
428 getboottime(&boottime);
429 cntr->timestamp += boottime.tv_sec;
434 * Copies rule @urule from v1 userland format (current).
436 * Assume @krule is zeroed.
439 import_rule1(struct rule_check_info *ci)
441 struct ip_fw_rule *urule;
444 urule = (struct ip_fw_rule *)ci->urule;
445 krule = (struct ip_fw *)ci->krule;
448 krule->act_ofs = urule->act_ofs;
449 krule->cmd_len = urule->cmd_len;
450 krule->rulenum = urule->rulenum;
451 krule->set = urule->set;
452 krule->flags = urule->flags;
454 /* Save rulenum offset */
455 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
458 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
462 * Export rule into v1 format (Current).
464 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
466 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
468 * Assume @data is zeroed.
471 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
473 struct ip_fw_bcounter *cntr;
474 struct ip_fw_rule *urule;
477 /* Fill in TLV header */
478 tlv = (ipfw_obj_tlv *)data;
479 tlv->type = IPFW_TLV_RULE_ENT;
484 cntr = (struct ip_fw_bcounter *)(tlv + 1);
485 urule = (struct ip_fw_rule *)(cntr + 1);
486 export_cntr1_base(krule, cntr);
488 urule = (struct ip_fw_rule *)(tlv + 1);
491 urule->act_ofs = krule->act_ofs;
492 urule->cmd_len = krule->cmd_len;
493 urule->rulenum = krule->rulenum;
494 urule->set = krule->set;
495 urule->flags = krule->flags;
496 urule->id = krule->id;
499 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
503 * Copies rule @urule from FreeBSD8 userland format (v0)
505 * Assume @krule is zeroed.
508 import_rule0(struct rule_check_info *ci)
510 struct ip_fw_rule0 *urule;
514 ipfw_insn_limit *lcmd;
517 urule = (struct ip_fw_rule0 *)ci->urule;
518 krule = (struct ip_fw *)ci->krule;
521 krule->act_ofs = urule->act_ofs;
522 krule->cmd_len = urule->cmd_len;
523 krule->rulenum = urule->rulenum;
524 krule->set = urule->set;
525 if ((urule->_pad & 1) != 0)
526 krule->flags |= IPFW_RULE_NOOPT;
528 /* Save rulenum offset */
529 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
532 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
536 * 1) convert tablearg value from 65535 to 0
537 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
539 * 3) convert table number in iface opcodes to u16
540 * 4) convert old `nat global` into new 65535
546 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
549 switch (cmd->opcode) {
550 /* Opcodes supporting tablearg */
562 if (cmd->arg1 == IP_FW_TABLEARG)
563 cmd->arg1 = IP_FW_TARG;
564 else if (cmd->arg1 == 0)
565 cmd->arg1 = IP_FW_NAT44_GLOBAL;
569 if (cmd->arg1 == IP_FW_TABLEARG)
570 cmd->arg1 = IP_FW_TARG;
575 lcmd = (ipfw_insn_limit *)cmd;
576 if (lcmd->conn_limit == IP_FW_TABLEARG)
577 lcmd->conn_limit = IP_FW_TARG;
579 /* Interface tables */
583 /* Interface table, possibly */
584 cmdif = (ipfw_insn_if *)cmd;
585 if (cmdif->name[0] != '\1')
588 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
595 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
598 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
602 ipfw_insn_limit *lcmd;
606 memset(urule, 0, len);
607 urule->act_ofs = krule->act_ofs;
608 urule->cmd_len = krule->cmd_len;
609 urule->rulenum = krule->rulenum;
610 urule->set = krule->set;
611 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
615 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
617 /* Export counters */
618 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
622 * 1) convert tablearg value from 0 to 65535
623 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
624 * 3) convert table number in iface opcodes to int
630 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
633 switch (cmd->opcode) {
634 /* Opcodes supporting tablearg */
646 if (cmd->arg1 == IP_FW_TARG)
647 cmd->arg1 = IP_FW_TABLEARG;
648 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
653 if (cmd->arg1 == IP_FW_TARG)
654 cmd->arg1 = IP_FW_TABLEARG;
656 cmd->arg1 &= ~0x8000;
659 lcmd = (ipfw_insn_limit *)cmd;
660 if (lcmd->conn_limit == IP_FW_TARG)
661 lcmd->conn_limit = IP_FW_TABLEARG;
663 /* Interface tables */
667 /* Interface table, possibly */
668 cmdif = (ipfw_insn_if *)cmd;
669 if (cmdif->name[0] != '\1')
672 cmdif->p.glob = cmdif->p.kidx;
679 * Add new rule(s) to the list possibly creating rule number for each.
680 * Update the rule_number in the input struct so the caller knows it as well.
681 * Must be called without IPFW_UH held
684 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
686 int error, i, insert_before, tcount;
687 uint16_t rulenum, *pnum;
688 struct rule_check_info *ci;
690 struct ip_fw **map; /* the new array of pointers */
692 /* Check if we need to do table/obj index remap */
694 for (ci = rci, i = 0; i < count; ci++, i++) {
695 if (ci->object_opcodes == 0)
699 * Rule has some object opcodes.
700 * We need to find (and create non-existing)
701 * kernel objects, and reference existing ones.
703 error = rewrite_rule_uidx(chain, ci);
706 * rewrite failed, state for current rule
707 * has been reverted. Check if we need to
712 * We have some more table rules
713 * we need to rollback.
716 IPFW_UH_WLOCK(chain);
719 if (ci->object_opcodes == 0)
721 unref_rule_objects(chain,ci->krule);
723 IPFW_UH_WUNLOCK(chain);
732 /* get_map returns with IPFW_UH_WLOCK if successful */
733 map = get_map(chain, count, 0 /* not locked */);
737 IPFW_UH_WLOCK(chain);
738 for (ci = rci, i = 0; i < count; ci++, i++) {
739 if (ci->object_opcodes == 0)
742 unref_rule_objects(chain, ci->krule);
744 IPFW_UH_WUNLOCK(chain);
750 if (V_autoinc_step < 1)
752 else if (V_autoinc_step > 1000)
753 V_autoinc_step = 1000;
755 /* FIXME: Handle count > 1 */
758 rulenum = krule->rulenum;
760 /* find the insertion point, we will insert before */
761 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
762 i = ipfw_find_rule(chain, insert_before, 0);
763 /* duplicate first part */
765 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
767 /* duplicate remaining part, we always have the default rule */
768 bcopy(chain->map + i, map + i + 1,
769 sizeof(struct ip_fw *) *(chain->n_rules - i));
771 /* Compute rule number and write it back */
772 rulenum = i > 0 ? map[i-1]->rulenum : 0;
773 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
774 rulenum += V_autoinc_step;
775 krule->rulenum = rulenum;
776 /* Save number to userland rule */
777 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
781 krule->id = chain->id + 1;
782 update_skipto_cache(chain, map);
783 map = swap_map(chain, map, chain->n_rules + 1);
784 chain->static_len += RULEUSIZE0(krule);
785 IPFW_UH_WUNLOCK(chain);
792 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
797 map = get_map(chain, 1, locked);
800 if (chain->n_rules > 0)
801 bcopy(chain->map, map,
802 chain->n_rules * sizeof(struct ip_fw *));
803 map[chain->n_rules] = rule;
804 rule->rulenum = IPFW_DEFAULT_RULE;
805 rule->set = RESVD_SET;
806 rule->id = chain->id + 1;
807 /* We add rule in the end of chain, no need to update skipto cache */
808 map = swap_map(chain, map, chain->n_rules + 1);
809 chain->static_len += RULEUSIZE0(rule);
810 IPFW_UH_WUNLOCK(chain);
816 * Adds @rule to the list of rules to reap
819 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
823 IPFW_UH_WLOCK_ASSERT(chain);
825 /* Unlink rule from everywhere */
826 unref_rule_objects(chain, rule);
833 * Reclaim storage associated with a list of rules. This is
834 * typically the list created using remove_rule.
835 * A NULL pointer on input is handled correctly.
838 ipfw_reap_rules(struct ip_fw *head)
842 while ((rule = head) != NULL) {
844 ipfw_free_rule(rule);
850 * (default || reserved || !match_set || !match_number)
852 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
853 * // the default rule is always protected
855 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
856 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
858 * match_set ::= (cmd == 0 || rule->set == set)
859 * // set number is ignored for cmd == 0
861 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
862 * // number is ignored for cmd == 1 or n == 0
866 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
869 /* Don't match default rule for modification queries */
870 if (rule->rulenum == IPFW_DEFAULT_RULE &&
871 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
874 /* Don't match rules in reserved set for flush requests */
875 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
878 /* If we're filtering by set, don't match other sets */
879 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
882 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
883 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
889 struct manage_sets_args {
895 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
898 struct manage_sets_args *args;
900 args = (struct manage_sets_args *)arg;
901 if (no->set == (uint8_t)args->set)
902 no->set = args->new_set;
903 else if (no->set == args->new_set)
904 no->set = (uint8_t)args->set;
909 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
912 struct manage_sets_args *args;
914 args = (struct manage_sets_args *)arg;
915 if (no->set == (uint8_t)args->set)
916 no->set = args->new_set;
921 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
924 struct manage_sets_args *args;
926 args = (struct manage_sets_args *)arg;
927 if (no->set != (uint8_t)args->set)
929 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
930 no->etlv, no->name) != NULL)
936 * Generic function to handler moving and swapping sets.
939 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
940 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
942 struct manage_sets_args args;
943 struct named_object *no;
946 args.new_set = new_set;
949 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
952 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
955 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
959 * @set used to pass kidx.
960 * When @new_set is zero - reset object counter,
961 * otherwise increment it.
963 no = ipfw_objhash_lookup_kidx(ni, set);
970 /* @set used to pass kidx */
971 no = ipfw_objhash_lookup_kidx(ni, set);
973 * First check number of references:
974 * when it differs, this mean other rules are holding
975 * reference to given object, so it is not possible to
976 * change its set. Note that refcnt may account references
977 * to some going-to-be-added rules. Since we don't know
978 * their numbers (and even if they will be added) it is
979 * perfectly OK to return error here.
981 if (no->ocnt != no->refcnt)
983 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
988 /* @set used to pass kidx */
989 no = ipfw_objhash_lookup_kidx(ni, set);
997 * Delete rules matching range @rt.
998 * Saves number of deleted rules in @ndel.
1000 * Returns 0 on success.
1003 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1005 struct ip_fw *reap, *rule, **map;
1007 int i, n, ndyn, ofs;
1010 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1013 * Stage 1: Determine range to inspect.
1014 * Range is half-inclusive, e.g [start, end).
1017 end = chain->n_rules - 1;
1019 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1020 start = ipfw_find_rule(chain, rt->start_rule, 0);
1022 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1023 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1024 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1027 if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1029 * Requested deleting only for dynamic states.
1032 ipfw_expire_dyn_states(chain, rt);
1033 IPFW_UH_WUNLOCK(chain);
1037 /* Allocate new map of the same size */
1038 map = get_map(chain, 0, 1 /* locked */);
1040 IPFW_UH_WUNLOCK(chain);
1047 /* 1. bcopy the initial part of the map */
1049 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1050 /* 2. copy active rules between start and end */
1051 for (i = start; i < end; i++) {
1052 rule = chain->map[i];
1053 if (ipfw_match_range(rule, rt) == 0) {
1059 if (ipfw_is_dyn_rule(rule) != 0)
1062 /* 3. copy the final part of the map */
1063 bcopy(chain->map + end, map + ofs,
1064 (chain->n_rules - end) * sizeof(struct ip_fw *));
1065 /* 4. recalculate skipto cache */
1066 update_skipto_cache(chain, map);
1067 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1068 map = swap_map(chain, map, chain->n_rules - n);
1069 /* 6. Remove all dynamic states originated by deleted rules */
1071 ipfw_expire_dyn_states(chain, rt);
1072 /* 7. now remove the rules deleted from the old map */
1073 for (i = start; i < end; i++) {
1075 if (ipfw_match_range(rule, rt) == 0)
1077 chain->static_len -= RULEUSIZE0(rule);
1078 ipfw_reap_add(chain, &reap, rule);
1080 IPFW_UH_WUNLOCK(chain);
1082 ipfw_reap_rules(reap);
1090 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1092 struct opcode_obj_rewrite *rw;
1095 int cmdlen, i, l, c;
1098 IPFW_UH_WLOCK_ASSERT(ch);
1100 /* Stage 1: count number of references by given rules */
1101 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1103 if (ipfw_match_range(rule, rt) == 0)
1105 if (rule->set == rt->new_set) /* nothing to do */
1107 /* Search opcodes with named objects */
1108 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1109 l > 0; l -= cmdlen, cmd += cmdlen) {
1110 cmdlen = F_LEN(cmd);
1111 rw = find_op_rw(cmd, &kidx, NULL);
1112 if (rw == NULL || rw->manage_sets == NULL)
1115 * When manage_sets() returns non-zero value to
1116 * COUNT_ONE command, consider this as an object
1117 * doesn't support sets (e.g. disabled with sysctl).
1118 * So, skip checks for this object.
1120 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1125 if (c == 0) /* No objects found */
1127 /* Stage 2: verify "ownership" */
1128 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1130 if (ipfw_match_range(rule, rt) == 0)
1132 if (rule->set == rt->new_set) /* nothing to do */
1134 /* Search opcodes with named objects */
1135 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1136 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1137 cmdlen = F_LEN(cmd);
1138 rw = find_op_rw(cmd, &kidx, NULL);
1139 if (rw == NULL || rw->manage_sets == NULL)
1141 /* Test for ownership and conflicting names */
1142 c = rw->manage_sets(ch, kidx,
1143 (uint8_t)rt->new_set, TEST_ONE);
1146 /* Stage 3: change set and cleanup */
1147 for (i = 0; i < ch->n_rules - 1; i++) {
1149 if (ipfw_match_range(rule, rt) == 0)
1151 if (rule->set == rt->new_set) /* nothing to do */
1153 /* Search opcodes with named objects */
1154 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1155 l > 0; l -= cmdlen, cmd += cmdlen) {
1156 cmdlen = F_LEN(cmd);
1157 rw = find_op_rw(cmd, &kidx, NULL);
1158 if (rw == NULL || rw->manage_sets == NULL)
1160 /* cleanup object counter */
1161 rw->manage_sets(ch, kidx,
1162 0 /* reset counter */, COUNT_ONE);
1166 rw->manage_sets(ch, kidx,
1167 (uint8_t)rt->new_set, MOVE_ONE);
1174 * Changes set of given rule rannge @rt
1177 * Returns 0 on success.
1180 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1185 IPFW_UH_WLOCK(chain);
1188 * Move rules with matching paramenerts to a new set.
1189 * This one is much more complex. We have to ensure
1190 * that all referenced tables (if any) are referenced
1191 * by given rule subset only. Otherwise, we can't move
1192 * them to new set and have to return error.
1194 if ((i = move_objects(chain, rt)) != 0) {
1195 IPFW_UH_WUNLOCK(chain);
1199 /* XXX: We have to do swap holding WLOCK */
1200 for (i = 0; i < chain->n_rules; i++) {
1201 rule = chain->map[i];
1202 if (ipfw_match_range(rule, rt) == 0)
1204 rule->set = rt->new_set;
1207 IPFW_UH_WUNLOCK(chain);
1213 * Returns pointer to action instruction, skips all possible rule
1214 * modifiers like O_LOG, O_TAG, O_ALTQ.
1217 ipfw_get_action(struct ip_fw *rule)
1222 cmd = ACTION_PTR(rule);
1223 l = rule->cmd_len - rule->act_ofs;
1225 switch (cmd->opcode) {
1233 cmdlen = F_LEN(cmd);
1237 panic("%s: rule (%p) has not action opcode", __func__, rule);
1242 * Clear counters for a specific rule.
1243 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1244 * so we only care that rules do not disappear.
1247 clear_counters(struct ip_fw *rule, int log_only)
1249 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1252 IPFW_ZERO_RULE_COUNTER(rule);
1253 if (l->o.opcode == O_LOG)
1254 l->log_left = l->max_log;
1258 * Flushes rules counters and/or log values on matching range.
1260 * Returns number of items cleared.
1263 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1270 rt->flags |= IPFW_RCFLAG_DEFAULT;
1272 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1273 for (i = 0; i < chain->n_rules; i++) {
1274 rule = chain->map[i];
1275 if (ipfw_match_range(rule, rt) == 0)
1277 clear_counters(rule, log_only);
1280 IPFW_UH_WUNLOCK(chain);
1286 check_range_tlv(ipfw_range_tlv *rt)
1289 if (rt->head.length != sizeof(*rt))
1291 if (rt->start_rule > rt->end_rule)
1293 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1296 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1303 * Delete rules matching specified parameters
1304 * Data layout (v0)(current):
1305 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1306 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1308 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1310 * Returns 0 on success.
1313 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1314 struct sockopt_data *sd)
1316 ipfw_range_header *rh;
1319 if (sd->valsize != sizeof(*rh))
1322 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1324 if (check_range_tlv(&rh->range) != 0)
1328 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1331 /* Save number of rules deleted */
1332 rh->range.new_set = ndel;
1337 * Move rules/sets matching specified parameters
1338 * Data layout (v0)(current):
1339 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1341 * Returns 0 on success.
1344 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1345 struct sockopt_data *sd)
1347 ipfw_range_header *rh;
1349 if (sd->valsize != sizeof(*rh))
1352 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1354 if (check_range_tlv(&rh->range) != 0)
1357 return (move_range(chain, &rh->range));
1361 * Clear rule accounting data matching specified parameters
1362 * Data layout (v0)(current):
1363 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1364 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1366 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1368 * Returns 0 on success.
1371 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1372 struct sockopt_data *sd)
1374 ipfw_range_header *rh;
1378 if (sd->valsize != sizeof(*rh))
1381 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1383 if (check_range_tlv(&rh->range) != 0)
1386 log_only = (op3->opcode == IP_FW_XRESETLOG);
1388 num = clear_range(chain, &rh->range, log_only);
1390 if (rh->range.flags & IPFW_RCFLAG_ALL)
1391 msg = log_only ? "All logging counts reset" :
1392 "Accounting cleared";
1394 msg = log_only ? "logging count reset" : "cleared";
1397 int lev = LOG_SECURITY | LOG_NOTICE;
1398 log(lev, "ipfw: %s.\n", msg);
1401 /* Save number of rules cleared */
1402 rh->range.new_set = num;
1407 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1411 IPFW_UH_WLOCK_ASSERT(chain);
1413 /* Change enabled/disabled sets mask */
1414 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1415 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1417 V_set_disable = v_set;
1418 IPFW_WUNLOCK(chain);
1422 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1424 struct opcode_obj_rewrite *rw;
1428 IPFW_UH_WLOCK_ASSERT(chain);
1430 if (rt->set == rt->new_set) /* nothing to do */
1435 * Berfore moving the rules we need to check that
1436 * there aren't any conflicting named objects.
1438 for (rw = ctl3_rewriters;
1439 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1440 if (rw->manage_sets == NULL)
1442 i = rw->manage_sets(chain, (uint8_t)rt->set,
1443 (uint8_t)rt->new_set, TEST_ALL);
1448 /* Swap or move two sets */
1449 for (i = 0; i < chain->n_rules - 1; i++) {
1450 rule = chain->map[i];
1451 if (rule->set == (uint8_t)rt->set)
1452 rule->set = (uint8_t)rt->new_set;
1453 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1454 rule->set = (uint8_t)rt->set;
1456 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1457 if (rw->manage_sets == NULL)
1459 rw->manage_sets(chain, (uint8_t)rt->set,
1460 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1466 * Swaps or moves set
1467 * Data layout (v0)(current):
1468 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1470 * Returns 0 on success.
1473 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1474 struct sockopt_data *sd)
1476 ipfw_range_header *rh;
1479 if (sd->valsize != sizeof(*rh))
1482 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1484 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1486 /* enable_sets() expects bitmasks. */
1487 if (op3->opcode != IP_FW_SET_ENABLE &&
1488 (rh->range.set >= IPFW_MAX_SETS ||
1489 rh->range.new_set >= IPFW_MAX_SETS))
1493 IPFW_UH_WLOCK(chain);
1494 switch (op3->opcode) {
1495 case IP_FW_SET_SWAP:
1496 case IP_FW_SET_MOVE:
1497 ret = swap_sets(chain, &rh->range,
1498 op3->opcode == IP_FW_SET_MOVE);
1500 case IP_FW_SET_ENABLE:
1501 enable_sets(chain, &rh->range);
1504 IPFW_UH_WUNLOCK(chain);
1510 * Remove all rules with given number, or do set manipulation.
1511 * Assumes chain != NULL && *chain != NULL.
1513 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1514 * the next 8 bits are the new set; the top 8 bits indicate the command:
1516 * 0 delete rules numbered "rulenum"
1517 * 1 delete rules in set "rulenum"
1518 * 2 move rules "rulenum" to set "new_set"
1519 * 3 move rules from set "rulenum" to set "new_set"
1520 * 4 swap sets "rulenum" and "new_set"
1521 * 5 delete rules "rulenum" and set "new_set"
1524 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1526 uint32_t num; /* rule number or old_set */
1527 uint8_t cmd, new_set;
1533 cmd = (arg >> 24) & 0xff;
1534 new_set = (arg >> 16) & 0xff;
1536 if (cmd > 5 || new_set > RESVD_SET)
1538 if (cmd == 0 || cmd == 2 || cmd == 5) {
1539 if (num >= IPFW_DEFAULT_RULE)
1542 if (num > RESVD_SET) /* old_set */
1546 /* Convert old requests into new representation */
1547 memset(&rt, 0, sizeof(rt));
1548 rt.start_rule = num;
1551 rt.new_set = new_set;
1555 case 0: /* delete rules numbered "rulenum" */
1557 rt.flags |= IPFW_RCFLAG_ALL;
1559 rt.flags |= IPFW_RCFLAG_RANGE;
1562 case 1: /* delete rules in set "rulenum" */
1563 rt.flags |= IPFW_RCFLAG_SET;
1566 case 5: /* delete rules "rulenum" and set "new_set" */
1567 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1572 case 2: /* move rules "rulenum" to set "new_set" */
1573 rt.flags |= IPFW_RCFLAG_RANGE;
1575 case 3: /* move rules from set "rulenum" to set "new_set" */
1576 IPFW_UH_WLOCK(chain);
1577 error = swap_sets(chain, &rt, 1);
1578 IPFW_UH_WUNLOCK(chain);
1580 case 4: /* swap sets "rulenum" and "new_set" */
1581 IPFW_UH_WLOCK(chain);
1582 error = swap_sets(chain, &rt, 0);
1583 IPFW_UH_WUNLOCK(chain);
1590 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1593 if (ndel == 0 && (cmd != 1 && num != 0))
1599 return (move_range(chain, &rt));
1603 * Reset some or all counters on firewall rules.
1604 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1605 * the next 8 bits are the set number, the top 8 bits are the command:
1606 * 0 work with rules from all set's;
1607 * 1 work with rules only from specified set.
1608 * Specified rule number is zero if we want to clear all entries.
1609 * log_only is 1 if we only want to reset logs, zero otherwise.
1612 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1618 uint16_t rulenum = arg & 0xffff;
1619 uint8_t set = (arg >> 16) & 0xff;
1620 uint8_t cmd = (arg >> 24) & 0xff;
1624 if (cmd == 1 && set > RESVD_SET)
1627 IPFW_UH_RLOCK(chain);
1629 V_norule_counter = 0;
1630 for (i = 0; i < chain->n_rules; i++) {
1631 rule = chain->map[i];
1632 /* Skip rules not in our set. */
1633 if (cmd == 1 && rule->set != set)
1635 clear_counters(rule, log_only);
1637 msg = log_only ? "All logging counts reset" :
1638 "Accounting cleared";
1641 for (i = 0; i < chain->n_rules; i++) {
1642 rule = chain->map[i];
1643 if (rule->rulenum == rulenum) {
1644 if (cmd == 0 || rule->set == set)
1645 clear_counters(rule, log_only);
1648 if (rule->rulenum > rulenum)
1651 if (!cleared) { /* we did not find any matching rules */
1652 IPFW_UH_RUNLOCK(chain);
1655 msg = log_only ? "logging count reset" : "cleared";
1657 IPFW_UH_RUNLOCK(chain);
1660 int lev = LOG_SECURITY | LOG_NOTICE;
1663 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1665 log(lev, "ipfw: %s.\n", msg);
1671 * Check rule head in FreeBSD11 format
1675 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1676 struct rule_check_info *ci)
1680 if (size < sizeof(*rule)) {
1681 printf("ipfw: rule too short\n");
1685 /* Check for valid cmd_len */
1686 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1688 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1691 if (rule->act_ofs >= rule->cmd_len) {
1692 printf("ipfw: bogus action offset (%u > %u)\n",
1693 rule->act_ofs, rule->cmd_len - 1);
1697 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1700 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1704 * Check rule head in FreeBSD8 format
1708 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1709 struct rule_check_info *ci)
1713 if (size < sizeof(*rule)) {
1714 printf("ipfw: rule too short\n");
1718 /* Check for valid cmd_len */
1719 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1721 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1724 if (rule->act_ofs >= rule->cmd_len) {
1725 printf("ipfw: bogus action offset (%u > %u)\n",
1726 rule->act_ofs, rule->cmd_len - 1);
1730 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1733 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1737 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1745 * Now go for the individual checks. Very simple ones, basically only
1746 * instruction sizes.
1748 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1749 cmdlen = F_LEN(cmd);
1751 printf("ipfw: opcode %d size truncated\n",
1755 switch (cmd->opcode) {
1758 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1760 ci->object_opcodes++;
1771 case O_IPPRECEDENCE:
1790 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1794 case O_EXTERNAL_ACTION:
1795 if (cmd->arg1 == 0 ||
1796 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1797 printf("ipfw: invalid external "
1801 ci->object_opcodes++;
1803 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1809 cmdlen = F_LEN(cmd);
1810 if (cmd->opcode == O_EXTERNAL_DATA)
1812 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1813 printf("ipfw: invalid opcode "
1814 "next to external action %u\n",
1818 if (cmd->arg1 == 0 ||
1819 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1820 printf("ipfw: invalid external "
1821 "action instance opcode\n");
1824 ci->object_opcodes++;
1829 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1831 if (cmd->arg1 >= rt_numfibs) {
1832 printf("ipfw: invalid fib number %d\n",
1839 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1841 if ((cmd->arg1 != IP_FW_TARG) &&
1842 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1843 printf("ipfw: invalid fib number %d\n",
1844 cmd->arg1 & 0x7FFF);
1858 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1863 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1865 ci->object_opcodes++;
1869 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1872 ((ipfw_insn_log *)cmd)->log_left =
1873 ((ipfw_insn_log *)cmd)->max_log;
1879 /* only odd command lengths */
1880 if ((cmdlen & 1) == 0)
1886 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1887 printf("ipfw: invalid set size %d\n",
1891 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1896 case O_IP_SRC_LOOKUP:
1897 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1899 case O_IP_DST_LOOKUP:
1900 if (cmd->arg1 >= V_fw_tables_max) {
1901 printf("ipfw: invalid table number %d\n",
1905 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1906 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1907 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1909 ci->object_opcodes++;
1911 case O_IP_FLOW_LOOKUP:
1912 if (cmd->arg1 >= V_fw_tables_max) {
1913 printf("ipfw: invalid table number %d\n",
1917 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1918 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1920 ci->object_opcodes++;
1923 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1935 if (cmdlen < 1 || cmdlen > 31)
1940 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1946 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1947 if (cmdlen < 2 || cmdlen > 31)
1954 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1956 ci->object_opcodes++;
1960 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1966 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1971 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1976 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1983 if (ip_divert_ptr == NULL)
1989 if (ng_ipfw_input_p == NULL)
1994 if (!IPFW_NAT_LOADED)
1996 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
2000 ci->object_opcodes++;
2002 case O_FORWARD_MAC: /* XXX not implemented yet */
2015 if (cmdlen != F_INSN_SIZE(ipfw_insn))
2019 printf("ipfw: opcode %d, multiple actions"
2026 printf("ipfw: opcode %d, action must be"
2035 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2036 F_INSN_SIZE(ipfw_insn))
2041 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2042 ((ipfw_insn_u32 *)cmd)->o.arg1)
2046 case O_IP6_SRC_MASK:
2047 case O_IP6_DST_MASK:
2048 if ( !(cmdlen & 1) || cmdlen > 127)
2052 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2058 switch (cmd->opcode) {
2068 case O_IP6_SRC_MASK:
2069 case O_IP6_DST_MASK:
2071 printf("ipfw: no IPv6 support in kernel\n");
2072 return (EPROTONOSUPPORT);
2075 printf("ipfw: opcode %d, unknown opcode\n",
2081 if (have_action == 0) {
2082 printf("ipfw: missing action\n");
2088 printf("ipfw: opcode %d size %d wrong\n",
2089 cmd->opcode, cmdlen);
2094 * Translation of requests for compatibility with FreeBSD 7.2/8.
2095 * a static variable tells us if we have an old client from userland,
2096 * and if necessary we translate requests and responses between the
2102 struct ip_fw7 *next; /* linked list of rules */
2103 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2104 /* 'next_rule' is used to pass up 'set_disable' status */
2106 uint16_t act_ofs; /* offset of action in 32-bit units */
2107 uint16_t cmd_len; /* # of 32-bit words in cmd */
2108 uint16_t rulenum; /* rule number */
2109 uint8_t set; /* rule set (0..31) */
2110 // #define RESVD_SET 31 /* set for default and persistent rules */
2111 uint8_t _pad; /* padding */
2112 // uint32_t id; /* rule id, only in v.8 */
2113 /* These fields are present in all rules. */
2114 uint64_t pcnt; /* Packet counter */
2115 uint64_t bcnt; /* Byte counter */
2116 uint32_t timestamp; /* tv_sec of last match */
2118 ipfw_insn cmd[1]; /* storage for commands */
2121 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2122 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2125 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2126 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2130 * Copy the static and dynamic rules to the supplied buffer
2131 * and return the amount of space actually used.
2132 * Must be run under IPFW_UH_RLOCK
2135 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2138 char *ep = bp + space;
2140 struct ip_fw_rule0 *dst;
2141 struct timeval boottime;
2142 int error, i, l, warnflag;
2143 time_t boot_seconds;
2147 getboottime(&boottime);
2148 boot_seconds = boottime.tv_sec;
2149 for (i = 0; i < chain->n_rules; i++) {
2150 rule = chain->map[i];
2153 /* Convert rule to FreeBSd 7.2 format */
2154 l = RULESIZE7(rule);
2155 if (bp + l + sizeof(uint32_t) <= ep) {
2156 bcopy(rule, bp, l + sizeof(uint32_t));
2157 error = set_legacy_obj_kidx(chain,
2158 (struct ip_fw_rule0 *)bp);
2161 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2163 return 0; /*XXX correct? */
2165 * XXX HACK. Store the disable mask in the "next"
2166 * pointer in a wild attempt to keep the ABI the same.
2167 * Why do we do this on EVERY rule?
2169 bcopy(&V_set_disable,
2170 &(((struct ip_fw7 *)bp)->next_rule),
2171 sizeof(V_set_disable));
2172 if (((struct ip_fw7 *)bp)->timestamp)
2173 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2176 continue; /* go to next rule */
2179 l = RULEUSIZE0(rule);
2180 if (bp + l > ep) { /* should not happen */
2181 printf("overflow dumping static rules\n");
2184 dst = (struct ip_fw_rule0 *)bp;
2185 export_rule0(rule, dst, l);
2186 error = set_legacy_obj_kidx(chain, dst);
2189 * XXX HACK. Store the disable mask in the "next"
2190 * pointer in a wild attempt to keep the ABI the same.
2191 * Why do we do this on EVERY rule?
2193 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2194 * so we need to fail _after_ saving at least one mask.
2196 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2198 dst->timestamp += boot_seconds;
2203 /* Non-fatal table rewrite error. */
2207 printf("Stop on rule %d. Fail to convert table\n",
2213 printf("ipfw: process %s is using legacy interfaces,"
2214 " consider rebuilding\n", "");
2215 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2216 return (bp - (char *)buf);
2220 uint32_t b; /* start rule */
2221 uint32_t e; /* end rule */
2222 uint32_t rcount; /* number of rules */
2223 uint32_t rsize; /* rules size */
2224 uint32_t tcount; /* number of tables */
2225 int rcounters; /* counters */
2226 uint32_t *bmask; /* index bitmask of used named objects */
2230 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2233 ntlv->head.type = no->etlv;
2234 ntlv->head.length = sizeof(*ntlv);
2235 ntlv->idx = no->kidx;
2236 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2240 * Export named object info in instance @ni, identified by @kidx
2241 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2243 * Returns 0 on success.
2246 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2247 struct sockopt_data *sd)
2249 struct named_object *no;
2250 ipfw_obj_ntlv *ntlv;
2252 no = ipfw_objhash_lookup_kidx(ni, kidx);
2253 KASSERT(no != NULL, ("invalid object kernel index passed"));
2255 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2259 ipfw_export_obj_ntlv(no, ntlv);
2264 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2265 struct sockopt_data *sd)
2269 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2270 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2272 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2280 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2281 struct sockopt_data *sd)
2283 ipfw_obj_ctlv *ctlv;
2286 MPASS(da->tcount > 0);
2288 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2291 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2292 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2294 ctlv->count = da->tcount;
2295 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2297 /* Dump table names first (if any) */
2298 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2301 /* Then dump another named objects */
2302 da->bmask += IPFW_TABLES_MAX / 32;
2303 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2307 * Dumps static rules with table TLVs in buffer @sd.
2309 * Returns 0 on success.
2312 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2313 struct sockopt_data *sd)
2315 ipfw_obj_ctlv *ctlv;
2316 struct ip_fw *krule;
2321 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2324 ctlv->head.type = IPFW_TLV_RULE_LIST;
2325 ctlv->head.length = da->rsize + sizeof(*ctlv);
2326 ctlv->count = da->rcount;
2328 for (i = da->b; i < da->e; i++) {
2329 krule = chain->map[i];
2331 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2332 if (da->rcounters != 0)
2333 l += sizeof(struct ip_fw_bcounter);
2334 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2338 export_rule1(krule, dst, l, da->rcounters);
2345 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2350 * Maintain separate bitmasks for table and non-table objects.
2352 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2354 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2357 bmask[bidx] |= 1 << (kidx % 32);
2362 * Marks every object index used in @rule with bit in @bmask.
2363 * Used to generate bitmask of referenced tables/objects for given ruleset
2367 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2368 struct dump_args *da)
2370 struct opcode_obj_rewrite *rw;
2379 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2380 cmdlen = F_LEN(cmd);
2382 rw = find_op_rw(cmd, &kidx, &subtype);
2386 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2392 * Dumps requested objects data
2393 * Data layout (version 0)(current):
2394 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2395 * size = ipfw_cfg_lheader.size
2396 * Reply: [ ipfw_cfg_lheader
2397 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2398 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2399 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2401 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2403 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2404 * The rest (size, count) are set to zero and needs to be ignored.
2406 * Returns 0 on success.
2409 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2410 struct sockopt_data *sd)
2412 struct dump_args da;
2413 ipfw_cfg_lheader *hdr;
2416 uint32_t hdr_flags, *bmask;
2419 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2425 memset(&da, 0, sizeof(da));
2427 * Allocate needed state.
2428 * Note we allocate 2xspace mask, for table & srv
2430 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2431 da.bmask = bmask = malloc(
2432 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2434 IPFW_UH_RLOCK(chain);
2437 * STAGE 1: Determine size/count for objects in range.
2438 * Prepare used tables bitmask.
2440 sz = sizeof(ipfw_cfg_lheader);
2441 da.e = chain->n_rules;
2443 if (hdr->end_rule != 0) {
2444 /* Handle custom range */
2445 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2446 rnum = IPFW_DEFAULT_RULE;
2447 da.b = ipfw_find_rule(chain, rnum, 0);
2448 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2449 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2450 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2453 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2454 for (i = da.b; i < da.e; i++) {
2455 rule = chain->map[i];
2456 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2458 /* Update bitmask of used objects for given range */
2459 mark_rule_objects(chain, rule, &da);
2461 /* Add counters if requested */
2462 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2463 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2466 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2469 if (hdr->flags & IPFW_CFG_GET_STATES) {
2470 sz += sizeof(ipfw_obj_ctlv) +
2471 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2476 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2477 sizeof(ipfw_obj_ctlv);
2480 * Fill header anyway.
2481 * Note we have to save header fields to stable storage
2482 * buffer inside @sd can be flushed after dumping rules
2485 hdr->set_mask = ~V_set_disable;
2486 hdr_flags = hdr->flags;
2489 if (sd->valsize < sz) {
2494 /* STAGE2: Store actual data */
2495 if (da.tcount > 0) {
2496 error = dump_named_objects(chain, &da, sd);
2501 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2502 error = dump_static_rules(chain, &da, sd);
2507 if (hdr_flags & IPFW_CFG_GET_STATES)
2508 error = ipfw_dump_states(chain, sd);
2511 IPFW_UH_RUNLOCK(chain);
2514 free(bmask, M_TEMP);
2520 ipfw_check_object_name_generic(const char *name)
2524 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2525 if (strnlen(name, nsize) == nsize)
2527 if (name[0] == '\0')
2533 * Creates non-existent objects referenced by rule.
2535 * Return 0 on success.
2538 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2539 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2541 struct opcode_obj_rewrite *rw;
2547 * Compatibility stuff: do actual creation for non-existing,
2548 * but referenced objects.
2550 for (p = oib; p < pidx; p++) {
2558 rw = find_op_rw(cmd + p->off, NULL, NULL);
2559 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2560 (cmd + p->off)->opcode));
2562 if (rw->create_object == NULL)
2565 error = rw->create_object(ch, ti, &kidx);
2572 * Error happened. We have to rollback everything.
2573 * Drop all already acquired references.
2576 unref_oib_objects(ch, cmd, oib, pidx);
2577 IPFW_UH_WUNLOCK(ch);
2586 * Compatibility function for old ipfw(8) binaries.
2587 * Rewrites table/nat kernel indices with userland ones.
2588 * Convert tables matching '/^\d+$/' to their atoi() value.
2589 * Use number 65535 for other tables.
2591 * Returns 0 on success.
2594 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2596 struct opcode_obj_rewrite *rw;
2597 struct named_object *no;
2601 int cmdlen, error, l;
2602 uint16_t kidx, uidx;
2610 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2611 cmdlen = F_LEN(cmd);
2613 /* Check if is index in given opcode */
2614 rw = find_op_rw(cmd, &kidx, &subtype);
2618 /* Try to find referenced kernel object */
2619 no = rw->find_bykidx(ch, kidx);
2623 val = strtol(no->name, &end, 10);
2624 if (*end == '\0' && val < 65535) {
2628 * We are called via legacy opcode.
2629 * Save error and show table as fake number
2630 * not to make ipfw(8) hang.
2636 rw->update(cmd, uidx);
2643 * Unreferences all already-referenced objects in given @cmd rule,
2644 * using information in @oib.
2646 * Used to rollback partially converted rule on error.
2649 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2650 struct obj_idx *end)
2652 struct opcode_obj_rewrite *rw;
2653 struct named_object *no;
2656 IPFW_UH_WLOCK_ASSERT(ch);
2658 for (p = oib; p < end; p++) {
2662 rw = find_op_rw(cmd + p->off, NULL, NULL);
2663 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2664 (cmd + p->off)->opcode));
2666 /* Find & unref by existing idx */
2667 no = rw->find_bykidx(ch, p->kidx);
2668 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2674 * Remove references from every object used in @rule.
2675 * Used at rule removal code.
2678 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2680 struct opcode_obj_rewrite *rw;
2681 struct named_object *no;
2687 IPFW_UH_WLOCK_ASSERT(ch);
2692 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2693 cmdlen = F_LEN(cmd);
2695 rw = find_op_rw(cmd, &kidx, &subtype);
2698 no = rw->find_bykidx(ch, kidx);
2700 KASSERT(no != NULL, ("object id %d not found", kidx));
2701 KASSERT(no->subtype == subtype,
2702 ("wrong type %d (%d) for object id %d",
2703 no->subtype, subtype, kidx));
2704 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2707 if (no->refcnt == 1 && rw->destroy_object != NULL)
2708 rw->destroy_object(ch, no);
2715 * Find and reference object (if any) stored in instruction @cmd.
2717 * Saves object info in @pidx, sets
2718 * - @unresolved to 1 if object should exists but not found
2720 * Returns non-zero value in case of error.
2723 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2724 struct obj_idx *pidx, int *unresolved)
2726 struct named_object *no;
2727 struct opcode_obj_rewrite *rw;
2730 /* Check if this opcode is candidate for rewrite */
2731 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2735 /* Need to rewrite. Save necessary fields */
2736 pidx->uidx = ti->uidx;
2737 pidx->type = ti->type;
2739 /* Try to find referenced kernel object */
2740 error = rw->find_byname(ch, ti, &no);
2745 * Report about unresolved object for automaic
2753 * Object is already exist.
2754 * Its subtype should match with expected value.
2756 if (ti->type != no->subtype)
2759 /* Bump refcount and update kidx. */
2761 rw->update(cmd, no->kidx);
2766 * Finds and bumps refcount for objects referenced by given @rule.
2767 * Auto-creates non-existing tables.
2768 * Fills in @oib array with userland/kernel indexes.
2770 * Returns 0 on success.
2773 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2774 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2776 struct obj_idx *pidx;
2778 int cmdlen, error, l, unresolved;
2788 /* Increase refcount on each existing referenced table. */
2789 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2790 cmdlen = F_LEN(cmd);
2793 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2797 * Compatibility stuff for old clients:
2798 * prepare to automaitcally create non-existing objects.
2800 if (unresolved != 0) {
2801 pidx->off = rule->cmd_len - l;
2807 /* Unref everything we have already done */
2808 unref_oib_objects(ch, rule->cmd, oib, pidx);
2809 IPFW_UH_WUNLOCK(ch);
2812 IPFW_UH_WUNLOCK(ch);
2814 /* Perform auto-creation for non-existing objects */
2816 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2818 /* Calculate real number of dynamic objects */
2819 ci->object_opcodes = (uint16_t)(pidx - oib);
2825 * Checks is opcode is referencing table of appropriate type.
2826 * Adds reference count for found table if true.
2827 * Rewrites user-supplied opcode values with kernel ones.
2829 * Returns 0 on success and appropriate error code otherwise.
2832 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2837 struct obj_idx *p, *pidx_first, *pidx_last;
2841 * Prepare an array for storing opcode indices.
2842 * Use stack allocation by default.
2844 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2846 pidx_first = ci->obuf;
2848 pidx_first = malloc(
2849 ci->object_opcodes * sizeof(struct obj_idx),
2850 M_IPFW, M_WAITOK | M_ZERO);
2854 memset(&ti, 0, sizeof(ti));
2856 /* Use set rule is assigned to. */
2857 ti.set = ci->krule->set;
2858 if (ci->ctlv != NULL) {
2859 ti.tlvs = (void *)(ci->ctlv + 1);
2860 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2863 /* Reference all used tables and other objects */
2864 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2868 * Note that ref_rule_objects() might have updated ci->object_opcodes
2869 * to reflect actual number of object opcodes.
2872 /* Perform rewrite of remaining opcodes */
2874 pidx_last = pidx_first + ci->object_opcodes;
2875 for (p = pidx_first; p < pidx_last; p++) {
2876 cmd = ci->krule->cmd + p->off;
2877 update_opcode_kidx(cmd, p->kidx);
2881 if (pidx_first != ci->obuf)
2882 free(pidx_first, M_IPFW);
2888 * Adds one or more rules to ipfw @chain.
2889 * Data layout (version 0)(current):
2893 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2894 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2899 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2900 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2903 * Rules in reply are modified to store their actual ruleset number.
2905 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2906 * according to their idx field and there has to be no duplicates.
2907 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2908 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2910 * Returns 0 on success.
2913 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2914 struct sockopt_data *sd)
2916 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2917 ipfw_obj_ntlv *ntlv;
2918 int clen, error, idx;
2919 uint32_t count, read;
2920 struct ip_fw_rule *r;
2921 struct rule_check_info rci, *ci, *cbuf;
2924 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2925 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2927 read = sizeof(ip_fw3_opheader);
2931 memset(&rci, 0, sizeof(struct rule_check_info));
2933 if (read + sizeof(*ctlv) > sd->valsize)
2936 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2937 clen = ctlv->head.length;
2938 /* Check size and alignment */
2939 if (clen > sd->valsize || clen < sizeof(*ctlv))
2941 if ((clen % sizeof(uint64_t)) != 0)
2945 * Some table names or other named objects.
2946 * Check for validness.
2948 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2949 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2954 * Ensure TLVs are sorted ascending and
2955 * there are no duplicates.
2958 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2960 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2963 error = ipfw_check_object_name_generic(ntlv->name);
2967 if (ntlv->idx <= idx)
2976 read += ctlv->head.length;
2977 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2980 if (read + sizeof(*ctlv) > sd->valsize)
2983 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2984 clen = ctlv->head.length;
2985 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2987 if ((clen % sizeof(uint64_t)) != 0)
2991 * TODO: Permit adding multiple rules at once
2993 if (ctlv->count != 1)
2996 clen -= sizeof(*ctlv);
2998 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
3001 /* Allocate state for each rule or use stack */
3002 if (ctlv->count == 1) {
3003 memset(&rci, 0, sizeof(struct rule_check_info));
3006 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
3011 * Check each rule for validness.
3012 * Ensure numbered rules are sorted ascending
3013 * and properly aligned
3016 r = (struct ip_fw_rule *)(ctlv + 1);
3020 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3021 if (rsize > clen || ctlv->count <= count) {
3027 error = check_ipfw_rule1(r, rsize, ci);
3032 if (r->rulenum != 0 && r->rulenum < idx) {
3033 printf("rulenum %d idx %d\n", r->rulenum, idx);
3039 ci->urule = (caddr_t)r;
3041 rsize = roundup2(rsize, sizeof(uint64_t));
3043 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3048 if (ctlv->count != count || error != 0) {
3055 read += ctlv->head.length;
3056 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3059 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3060 if (cbuf != NULL && cbuf != &rci)
3066 * Passed rules seems to be valid.
3067 * Allocate storage and try to add them to chain.
3069 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3070 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3071 ci->krule = ipfw_alloc_rule(chain, clen);
3075 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3076 /* Free allocate krules */
3077 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3078 ipfw_free_rule(ci->krule);
3081 if (cbuf != NULL && cbuf != &rci)
3088 * Lists all sopts currently registered.
3089 * Data layout (v0)(current):
3090 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3091 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3093 * Returns 0 on success
3096 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3097 struct sockopt_data *sd)
3099 struct _ipfw_obj_lheader *olh;
3101 struct ipfw_sopt_handler *sh;
3102 uint32_t count, n, size;
3104 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3107 if (sd->valsize < olh->size)
3112 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3114 /* Fill in header regadless of buffer size */
3116 olh->objsize = sizeof(ipfw_sopt_info);
3118 if (size > olh->size) {
3125 for (n = 1; n <= count; n++) {
3126 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3127 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3128 sh = &ctl3_handlers[n];
3129 i->opcode = sh->opcode;
3130 i->version = sh->version;
3131 i->refcnt = sh->refcnt;
3139 * Compares two opcodes.
3140 * Used both in qsort() and bsearch().
3142 * Returns 0 if match is found.
3145 compare_opcodes(const void *_a, const void *_b)
3147 const struct opcode_obj_rewrite *a, *b;
3149 a = (const struct opcode_obj_rewrite *)_a;
3150 b = (const struct opcode_obj_rewrite *)_b;
3152 if (a->opcode < b->opcode)
3154 else if (a->opcode > b->opcode)
3161 * XXX: Rewrite bsearch()
3164 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3165 struct opcode_obj_rewrite **phi)
3167 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3169 memset(&h, 0, sizeof(h));
3172 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3173 ctl3_rsize, sizeof(h), compare_opcodes);
3177 /* Find the first element matching the same opcode */
3179 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3182 /* Find the last element matching the same opcode */
3184 ctl3_max = ctl3_rewriters + ctl3_rsize;
3185 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3195 * Finds opcode object rewriter based on @code.
3197 * Returns pointer to handler or NULL.
3199 static struct opcode_obj_rewrite *
3200 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3202 struct opcode_obj_rewrite *rw, *lo, *hi;
3206 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3209 for (rw = lo; rw <= hi; rw++) {
3210 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3222 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3225 if (find_op_rw(cmd, puidx, NULL) == NULL)
3231 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3233 struct opcode_obj_rewrite *rw;
3235 rw = find_op_rw(cmd, NULL, NULL);
3236 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3237 rw->update(cmd, idx);
3241 ipfw_init_obj_rewriter()
3244 ctl3_rewriters = NULL;
3249 ipfw_destroy_obj_rewriter()
3252 if (ctl3_rewriters != NULL)
3253 free(ctl3_rewriters, M_IPFW);
3254 ctl3_rewriters = NULL;
3259 * Adds one or more opcode object rewrite handlers to the global array.
3260 * Function may sleep.
3263 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3266 struct opcode_obj_rewrite *tmp;
3271 sz = ctl3_rsize + count;
3273 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3275 if (ctl3_rsize + count <= sz)
3282 /* Merge old & new arrays */
3283 sz = ctl3_rsize + count;
3284 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3285 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3286 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3287 /* Switch new and free old */
3288 if (ctl3_rewriters != NULL)
3289 free(ctl3_rewriters, M_IPFW);
3290 ctl3_rewriters = tmp;
3297 * Removes one or more object rewrite handlers from the global array.
3300 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3303 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3308 for (i = 0; i < count; i++) {
3309 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3312 for (ktmp = lo; ktmp <= hi; ktmp++) {
3313 if (ktmp->classifier != rw[i].classifier)
3316 ctl3_max = ctl3_rewriters + ctl3_rsize;
3317 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3318 memmove(ktmp, ktmp + 1, sz);
3324 if (ctl3_rsize == 0) {
3325 if (ctl3_rewriters != NULL)
3326 free(ctl3_rewriters, M_IPFW);
3327 ctl3_rewriters = NULL;
3336 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3337 struct named_object *no, void *arg)
3339 struct sockopt_data *sd;
3340 ipfw_obj_ntlv *ntlv;
3342 sd = (struct sockopt_data *)arg;
3343 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3346 ipfw_export_obj_ntlv(no, ntlv);
3351 * Lists all service objects.
3352 * Data layout (v0)(current):
3353 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3354 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3355 * Returns 0 on success
3358 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3359 struct sockopt_data *sd)
3361 ipfw_obj_lheader *hdr;
3364 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3368 IPFW_UH_RLOCK(chain);
3369 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3370 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3371 if (sd->valsize < hdr->size) {
3372 IPFW_UH_RUNLOCK(chain);
3376 hdr->objsize = sizeof(ipfw_obj_ntlv);
3378 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3379 export_objhash_ntlv_internal, sd);
3380 IPFW_UH_RUNLOCK(chain);
3385 * Compares two sopt handlers (code, version and handler ptr).
3386 * Used both as qsort() and bsearch().
3387 * Does not compare handler for latter case.
3389 * Returns 0 if match is found.
3392 compare_sh(const void *_a, const void *_b)
3394 const struct ipfw_sopt_handler *a, *b;
3396 a = (const struct ipfw_sopt_handler *)_a;
3397 b = (const struct ipfw_sopt_handler *)_b;
3399 if (a->opcode < b->opcode)
3401 else if (a->opcode > b->opcode)
3404 if (a->version < b->version)
3406 else if (a->version > b->version)
3409 /* bsearch helper */
3410 if (a->handler == NULL)
3413 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3415 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3422 * Finds sopt handler based on @code and @version.
3424 * Returns pointer to handler or NULL.
3426 static struct ipfw_sopt_handler *
3427 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3429 struct ipfw_sopt_handler *sh, h;
3431 memset(&h, 0, sizeof(h));
3433 h.version = version;
3434 h.handler = handler;
3436 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3437 ctl3_hsize, sizeof(h), compare_sh);
3443 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3445 struct ipfw_sopt_handler *sh;
3448 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3450 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3456 /* Copy handler data to requested buffer */
3464 find_unref_sh(struct ipfw_sopt_handler *psh)
3466 struct ipfw_sopt_handler *sh;
3469 sh = find_sh(psh->opcode, psh->version, NULL);
3470 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3477 ipfw_init_sopt_handler()
3481 IPFW_ADD_SOPT_HANDLER(1, scodes);
3485 ipfw_destroy_sopt_handler()
3488 IPFW_DEL_SOPT_HANDLER(1, scodes);
3489 CTL3_LOCK_DESTROY();
3493 * Adds one or more sockopt handlers to the global array.
3494 * Function may sleep.
3497 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3500 struct ipfw_sopt_handler *tmp;
3505 sz = ctl3_hsize + count;
3507 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3509 if (ctl3_hsize + count <= sz)
3516 /* Merge old & new arrays */
3517 sz = ctl3_hsize + count;
3518 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3519 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3520 qsort(tmp, sz, sizeof(*sh), compare_sh);
3521 /* Switch new and free old */
3522 if (ctl3_handlers != NULL)
3523 free(ctl3_handlers, M_IPFW);
3524 ctl3_handlers = tmp;
3532 * Removes one or more sockopt handlers from the global array.
3535 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3538 struct ipfw_sopt_handler *tmp, *h;
3543 for (i = 0; i < count; i++) {
3545 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3549 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3550 memmove(h, h + 1, sz);
3554 if (ctl3_hsize == 0) {
3555 if (ctl3_handlers != NULL)
3556 free(ctl3_handlers, M_IPFW);
3557 ctl3_handlers = NULL;
3568 * Writes data accumulated in @sd to sockopt buffer.
3569 * Zeroes internal @sd buffer.
3572 ipfw_flush_sopt_data(struct sockopt_data *sd)
3574 struct sockopt *sopt;
3584 if (sopt->sopt_dir == SOPT_GET) {
3585 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3590 memset(sd->kbuf, 0, sd->ksize);
3593 if (sd->ktotal + sd->ksize < sd->valsize)
3594 sd->kavail = sd->ksize;
3596 sd->kavail = sd->valsize - sd->ktotal;
3598 /* Update sopt buffer data */
3599 sopt->sopt_valsize = sd->ktotal;
3600 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3606 * Ensures that @sd buffer has contiguous @neeeded number of
3609 * Returns pointer to requested space or NULL.
3612 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3617 if (sd->kavail < needed) {
3619 * Flush data and try another time.
3621 error = ipfw_flush_sopt_data(sd);
3623 if (sd->kavail < needed || error != 0)
3627 addr = sd->kbuf + sd->koff;
3629 sd->kavail -= needed;
3634 * Requests @needed contiguous bytes from @sd buffer.
3635 * Function is used to notify subsystem that we are
3636 * interesed in first @needed bytes (request header)
3637 * and the rest buffer can be safely zeroed.
3639 * Returns pointer to requested space or NULL.
3642 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3646 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3650 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3656 * New sockopt handler.
3659 ipfw_ctl3(struct sockopt *sopt)
3662 size_t size, valsize;
3663 struct ip_fw_chain *chain;
3665 struct sockopt_data sdata;
3666 struct ipfw_sopt_handler h;
3667 ip_fw3_opheader *op3 = NULL;
3669 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3673 if (sopt->sopt_name != IP_FW3)
3674 return (ipfw_ctl(sopt));
3676 chain = &V_layer3_chain;
3679 /* Save original valsize before it is altered via sooptcopyin() */
3680 valsize = sopt->sopt_valsize;
3681 memset(&sdata, 0, sizeof(sdata));
3682 /* Read op3 header first to determine actual operation */
3683 op3 = (ip_fw3_opheader *)xbuf;
3684 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3687 sopt->sopt_valsize = valsize;
3690 * Find and reference command.
3692 error = find_ref_sh(op3->opcode, op3->version, &h);
3697 * Disallow modifications in really-really secure mode, but still allow
3698 * the logging counters to be reset.
3700 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3701 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3709 * Fill in sockopt_data structure that may be useful for
3710 * IP_FW3 get requests.
3713 if (valsize <= sizeof(xbuf)) {
3714 /* use on-stack buffer */
3716 sdata.ksize = sizeof(xbuf);
3717 sdata.kavail = valsize;
3720 * Determine opcode type/buffer size:
3721 * allocate sliding-window buf for data export or
3722 * contiguous buffer for special ops.
3724 if ((h.dir & HDIR_SET) != 0) {
3725 /* Set request. Allocate contigous buffer. */
3726 if (valsize > CTL3_LARGEBUF) {
3733 /* Get request. Allocate sliding window buffer */
3734 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3736 if (size < valsize) {
3737 /* We have to wire user buffer */
3738 error = vslock(sopt->sopt_val, valsize);
3745 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3747 sdata.kavail = size;
3751 sdata.sopt_val = sopt->sopt_val;
3752 sdata.valsize = valsize;
3755 * Copy either all request (if valsize < bsize_max)
3756 * or first bsize_max bytes to guarantee most consumers
3757 * that all necessary data has been copied).
3758 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3760 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3761 sizeof(ip_fw3_opheader))) != 0)
3763 op3 = (ip_fw3_opheader *)sdata.kbuf;
3765 /* Finally, run handler */
3766 error = h.handler(chain, op3, &sdata);
3769 /* Flush state and free buffers */
3771 error = ipfw_flush_sopt_data(&sdata);
3773 ipfw_flush_sopt_data(&sdata);
3776 vsunlock(sdata.sopt_val, valsize);
3778 /* Restore original pointer and set number of bytes written */
3779 sopt->sopt_val = sdata.sopt_val;
3780 sopt->sopt_valsize = sdata.ktotal;
3781 if (sdata.kbuf != xbuf)
3782 free(sdata.kbuf, M_TEMP);
3788 * {set|get}sockopt parser.
3791 ipfw_ctl(struct sockopt *sopt)
3793 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3795 size_t size, valsize;
3797 struct ip_fw_rule0 *rule;
3798 struct ip_fw_chain *chain;
3799 u_int32_t rulenum[2];
3801 struct rule_check_info ci;
3804 chain = &V_layer3_chain;
3807 /* Save original valsize before it is altered via sooptcopyin() */
3808 valsize = sopt->sopt_valsize;
3809 opt = sopt->sopt_name;
3812 * Disallow modifications in really-really secure mode, but still allow
3813 * the logging counters to be reset.
3815 if (opt == IP_FW_ADD ||
3816 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3817 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3825 * pass up a copy of the current rules. Static rules
3826 * come first (the last of which has number IPFW_DEFAULT_RULE),
3827 * followed by a possibly empty list of dynamic rule.
3828 * The last dynamic rule has NULL in the "next" field.
3830 * Note that the calculated size is used to bound the
3831 * amount of data returned to the user. The rule set may
3832 * change between calculating the size and returning the
3833 * data in which case we'll just return what fits.
3838 size = chain->static_len;
3839 size += ipfw_dyn_len();
3840 if (size >= sopt->sopt_valsize)
3842 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3843 IPFW_UH_RLOCK(chain);
3844 /* check again how much space we need */
3845 want = chain->static_len + ipfw_dyn_len();
3847 len = ipfw_getrules(chain, buf, size);
3848 IPFW_UH_RUNLOCK(chain);
3850 error = sooptcopyout(sopt, buf, len);
3858 /* locking is done within del_entry() */
3859 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3863 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3864 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3865 sizeof(struct ip_fw7) );
3867 memset(&ci, 0, sizeof(struct rule_check_info));
3870 * If the size of commands equals RULESIZE7 then we assume
3871 * a FreeBSD7.2 binary is talking to us (set is7=1).
3872 * is7 is persistent so the next 'ipfw list' command
3873 * will use this format.
3874 * NOTE: If wrong version is guessed (this can happen if
3875 * the first ipfw command is 'ipfw [pipe] list')
3876 * the ipfw binary may crash or loop infinitly...
3878 size = sopt->sopt_valsize;
3879 if (size == RULESIZE7(rule)) {
3881 error = convert_rule_to_8(rule);
3886 size = RULESIZE(rule);
3890 error = check_ipfw_rule0(rule, size, &ci);
3892 /* locking is done within add_rule() */
3893 struct ip_fw *krule;
3894 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3895 ci.urule = (caddr_t)rule;
3898 error = commit_rules(chain, &ci, 1);
3900 ipfw_free_rule(ci.krule);
3901 else if (sopt->sopt_dir == SOPT_GET) {
3903 error = convert_rule_to_7(rule);
3904 size = RULESIZE7(rule);
3910 error = sooptcopyout(sopt, rule, size);
3918 * IP_FW_DEL is used for deleting single rules or sets,
3919 * and (ab)used to atomically manipulate sets. Argument size
3920 * is used to distinguish between the two:
3922 * delete single rule or set of rules,
3923 * or reassign rules (or sets) to a different set.
3924 * 2*sizeof(u_int32_t)
3925 * atomic disable/enable sets.
3926 * first u_int32_t contains sets to be disabled,
3927 * second u_int32_t contains sets to be enabled.
3929 error = sooptcopyin(sopt, rulenum,
3930 2*sizeof(u_int32_t), sizeof(u_int32_t));
3933 size = sopt->sopt_valsize;
3934 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3935 /* delete or reassign, locking done in del_entry() */
3936 error = del_entry(chain, rulenum[0]);
3937 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3938 IPFW_UH_WLOCK(chain);
3940 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3941 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3942 IPFW_UH_WUNLOCK(chain);
3948 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3950 if (sopt->sopt_val != 0) {
3951 error = sooptcopyin(sopt, rulenum,
3952 sizeof(u_int32_t), sizeof(u_int32_t));
3956 error = zero_entry(chain, rulenum[0],
3957 sopt->sopt_name == IP_FW_RESETLOG);
3960 /*--- TABLE opcodes ---*/
3961 case IP_FW_TABLE_ADD:
3962 case IP_FW_TABLE_DEL:
3964 ipfw_table_entry ent;
3965 struct tentry_info tei;
3967 struct table_value v;
3969 error = sooptcopyin(sopt, &ent,
3970 sizeof(ent), sizeof(ent));
3974 memset(&tei, 0, sizeof(tei));
3975 tei.paddr = &ent.addr;
3976 tei.subtype = AF_INET;
3977 tei.masklen = ent.masklen;
3978 ipfw_import_table_value_legacy(ent.value, &v);
3980 memset(&ti, 0, sizeof(ti));
3982 ti.type = IPFW_TABLE_CIDR;
3984 error = (opt == IP_FW_TABLE_ADD) ?
3985 add_table_entry(chain, &ti, &tei, 0, 1) :
3986 del_table_entry(chain, &ti, &tei, 0, 1);
3990 case IP_FW_TABLE_FLUSH:
3995 error = sooptcopyin(sopt, &tbl,
3996 sizeof(tbl), sizeof(tbl));
3999 memset(&ti, 0, sizeof(ti));
4001 error = flush_table(chain, &ti);
4005 case IP_FW_TABLE_GETSIZE:
4010 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4013 memset(&ti, 0, sizeof(ti));
4016 error = ipfw_count_table(chain, &ti, &cnt);
4017 IPFW_RUNLOCK(chain);
4020 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4024 case IP_FW_TABLE_LIST:
4029 if (sopt->sopt_valsize < sizeof(*tbl)) {
4033 size = sopt->sopt_valsize;
4034 tbl = malloc(size, M_TEMP, M_WAITOK);
4035 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4040 tbl->size = (size - sizeof(*tbl)) /
4041 sizeof(ipfw_table_entry);
4042 memset(&ti, 0, sizeof(ti));
4045 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4046 IPFW_RUNLOCK(chain);
4051 error = sooptcopyout(sopt, tbl, size);
4056 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4058 if (IPFW_NAT_LOADED)
4059 error = ipfw_nat_cfg_ptr(sopt);
4061 printf("IP_FW_NAT_CFG: %s\n",
4062 "ipfw_nat not present, please load it");
4068 if (IPFW_NAT_LOADED)
4069 error = ipfw_nat_del_ptr(sopt);
4071 printf("IP_FW_NAT_DEL: %s\n",
4072 "ipfw_nat not present, please load it");
4077 case IP_FW_NAT_GET_CONFIG:
4078 if (IPFW_NAT_LOADED)
4079 error = ipfw_nat_get_cfg_ptr(sopt);
4081 printf("IP_FW_NAT_GET_CFG: %s\n",
4082 "ipfw_nat not present, please load it");
4087 case IP_FW_NAT_GET_LOG:
4088 if (IPFW_NAT_LOADED)
4089 error = ipfw_nat_get_log_ptr(sopt);
4091 printf("IP_FW_NAT_GET_LOG: %s\n",
4092 "ipfw_nat not present, please load it");
4098 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4105 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4107 /* Functions to convert rules 7.2 <==> 8.0 */
4109 convert_rule_to_7(struct ip_fw_rule0 *rule)
4111 /* Used to modify original rule */
4112 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4113 /* copy of original rule, version 8 */
4114 struct ip_fw_rule0 *tmp;
4116 /* Used to copy commands */
4117 ipfw_insn *ccmd, *dst;
4118 int ll = 0, ccmdlen = 0;
4120 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4122 return 1; //XXX error
4124 bcopy(rule, tmp, RULE_MAXSIZE);
4127 //rule7->_pad = tmp->_pad;
4128 rule7->set = tmp->set;
4129 rule7->rulenum = tmp->rulenum;
4130 rule7->cmd_len = tmp->cmd_len;
4131 rule7->act_ofs = tmp->act_ofs;
4132 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4133 rule7->cmd_len = tmp->cmd_len;
4134 rule7->pcnt = tmp->pcnt;
4135 rule7->bcnt = tmp->bcnt;
4136 rule7->timestamp = tmp->timestamp;
4139 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4140 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4141 ccmdlen = F_LEN(ccmd);
4143 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4145 if (dst->opcode > O_NAT)
4146 /* O_REASS doesn't exists in 7.2 version, so
4147 * decrement opcode if it is after O_REASS
4152 printf("ipfw: opcode %d size truncated\n",
4163 convert_rule_to_8(struct ip_fw_rule0 *rule)
4165 /* Used to modify original rule */
4166 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4168 /* Used to copy commands */
4169 ipfw_insn *ccmd, *dst;
4170 int ll = 0, ccmdlen = 0;
4172 /* Copy of original rule */
4173 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4175 return 1; //XXX error
4178 bcopy(rule7, tmp, RULE_MAXSIZE);
4180 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4181 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4182 ccmdlen = F_LEN(ccmd);
4184 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4186 if (dst->opcode > O_NAT)
4187 /* O_REASS doesn't exists in 7.2 version, so
4188 * increment opcode if it is after O_REASS
4193 printf("ipfw: opcode %d size truncated\n",
4199 rule->_pad = tmp->_pad;
4200 rule->set = tmp->set;
4201 rule->rulenum = tmp->rulenum;
4202 rule->cmd_len = tmp->cmd_len;
4203 rule->act_ofs = tmp->act_ofs;
4204 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4205 rule->cmd_len = tmp->cmd_len;
4206 rule->id = 0; /* XXX see if is ok = 0 */
4207 rule->pcnt = tmp->pcnt;
4208 rule->bcnt = tmp->bcnt;
4209 rule->timestamp = tmp->timestamp;
4221 ipfw_init_srv(struct ip_fw_chain *ch)
4224 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4225 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4226 M_IPFW, M_WAITOK | M_ZERO);
4230 ipfw_destroy_srv(struct ip_fw_chain *ch)
4233 free(ch->srvstate, M_IPFW);
4234 ipfw_objhash_destroy(ch->srvmap);
4238 * Allocate new bitmask which can be used to enlarge/shrink
4239 * named instance index.
4242 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4248 KASSERT((items % BLOCK_ITEMS) == 0,
4249 ("bitmask size needs to power of 2 and greater or equal to %zu",
4252 max_blocks = items / BLOCK_ITEMS;
4254 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4255 /* Mark all as free */
4256 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4257 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4260 *pblocks = max_blocks;
4264 * Copy current bitmask index to new one.
4267 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4269 int old_blocks, new_blocks;
4270 u_long *old_idx, *new_idx;
4273 old_idx = ni->idx_mask;
4274 old_blocks = ni->max_blocks;
4276 new_blocks = *blocks;
4278 for (i = 0; i < IPFW_MAX_SETS; i++) {
4279 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4280 old_blocks * sizeof(u_long));
4285 * Swaps current @ni index with new one.
4288 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4293 old_idx = ni->idx_mask;
4294 old_blocks = ni->max_blocks;
4296 ni->idx_mask = *idx;
4297 ni->max_blocks = *blocks;
4299 /* Save old values */
4301 *blocks = old_blocks;
4305 ipfw_objhash_bitmap_free(void *idx, int blocks)
4312 * Creates named hash instance.
4313 * Must be called without holding any locks.
4314 * Return pointer to new instance.
4316 struct namedobj_instance *
4317 ipfw_objhash_create(uint32_t items)
4319 struct namedobj_instance *ni;
4323 size = sizeof(struct namedobj_instance) +
4324 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4325 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4327 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4328 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4329 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4331 ni->names = (struct namedobjects_head *)(ni +1);
4332 ni->values = &ni->names[ni->nn_size];
4334 for (i = 0; i < ni->nn_size; i++)
4335 TAILQ_INIT(&ni->names[i]);
4337 for (i = 0; i < ni->nv_size; i++)
4338 TAILQ_INIT(&ni->values[i]);
4340 /* Set default hashing/comparison functions */
4341 ni->hash_f = objhash_hash_name;
4342 ni->cmp_f = objhash_cmp_name;
4344 /* Allocate bitmask separately due to possible resize */
4345 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4351 ipfw_objhash_destroy(struct namedobj_instance *ni)
4354 free(ni->idx_mask, M_IPFW);
4359 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4360 objhash_cmp_f *cmp_f)
4363 ni->hash_f = hash_f;
4368 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4371 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4375 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4378 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4385 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4389 v = val % (ni->nv_size - 1);
4394 struct named_object *
4395 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4397 struct named_object *no;
4400 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4402 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4403 if (ni->cmp_f(no, name, set) == 0)
4411 * Find named object by @uid.
4412 * Check @tlvs for valid data inside.
4414 * Returns pointer to found TLV or NULL.
4417 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4419 ipfw_obj_ntlv *ntlv;
4423 pa = (uintptr_t)tlvs;
4426 for (; pa < pe; pa += l) {
4427 ntlv = (ipfw_obj_ntlv *)pa;
4428 l = ntlv->head.length;
4430 if (l != sizeof(*ntlv))
4433 if (ntlv->idx != uidx)
4436 * When userland has specified zero TLV type, do
4437 * not compare it with eltv. In some cases userland
4438 * doesn't know what type should it have. Use only
4439 * uidx and name for search named_object.
4441 if (ntlv->head.type != 0 &&
4442 ntlv->head.type != (uint16_t)etlv)
4445 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4455 * Finds object config based on either legacy index
4457 * Note @ti structure contains unchecked data from userland.
4459 * Returns 0 in success and fills in @pno with found config
4462 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4463 uint32_t etlv, struct named_object **pno)
4466 ipfw_obj_ntlv *ntlv;
4469 if (ti->tlvs == NULL)
4472 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4478 * Use set provided by @ti instead of @ntlv one.
4479 * This is needed due to different sets behavior
4480 * controlled by V_fw_tables_sets.
4483 *pno = ipfw_objhash_lookup_name(ni, set, name);
4490 * Find named object by name, considering also its TLV type.
4492 struct named_object *
4493 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4494 uint32_t type, const char *name)
4496 struct named_object *no;
4499 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4501 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4502 if (ni->cmp_f(no, name, set) == 0 &&
4503 no->etlv == (uint16_t)type)
4510 struct named_object *
4511 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4513 struct named_object *no;
4516 hash = objhash_hash_idx(ni, kidx);
4518 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4519 if (no->kidx == kidx)
4527 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4528 struct named_object *b)
4531 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4538 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4542 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4543 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4545 hash = objhash_hash_idx(ni, no->kidx);
4546 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4552 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4556 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4557 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4559 hash = objhash_hash_idx(ni, no->kidx);
4560 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4566 ipfw_objhash_count(struct namedobj_instance *ni)
4573 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4575 struct named_object *no;
4580 for (i = 0; i < ni->nn_size; i++) {
4581 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4582 if (no->etlv == type)
4590 * Runs @func for each found named object.
4591 * It is safe to delete objects from callback
4594 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4596 struct named_object *no, *no_tmp;
4599 for (i = 0; i < ni->nn_size; i++) {
4600 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4601 ret = f(ni, no, arg);
4610 * Runs @f for each found named object with type @type.
4611 * It is safe to delete objects from callback
4614 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4615 void *arg, uint16_t type)
4617 struct named_object *no, *no_tmp;
4620 for (i = 0; i < ni->nn_size; i++) {
4621 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4622 if (no->etlv != type)
4624 ret = f(ni, no, arg);
4633 * Removes index from given set.
4634 * Returns 0 on success.
4637 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4642 i = idx / BLOCK_ITEMS;
4643 v = idx % BLOCK_ITEMS;
4645 if (i >= ni->max_blocks)
4648 mask = &ni->idx_mask[i];
4650 if ((*mask & ((u_long)1 << v)) != 0)
4654 *mask |= (u_long)1 << v;
4656 /* Update free offset */
4657 if (ni->free_off[0] > i)
4658 ni->free_off[0] = i;
4664 * Allocate new index in given instance and stores in in @pidx.
4665 * Returns 0 on success.
4668 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4670 struct namedobj_instance *ni;
4674 ni = (struct namedobj_instance *)n;
4676 off = ni->free_off[0];
4677 mask = &ni->idx_mask[off];
4679 for (i = off; i < ni->max_blocks; i++, mask++) {
4680 if ((v = ffsl(*mask)) == 0)
4684 *mask &= ~ ((u_long)1 << (v - 1));
4686 ni->free_off[0] = i;
4688 v = BLOCK_ITEMS * i + v - 1;