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>
64 #include <net/route.h>
67 #include <vm/vm_extern.h>
69 #include <netinet/in.h>
70 #include <netinet/ip_var.h> /* hooks */
71 #include <netinet/ip_fw.h>
73 #include <netpfil/ipfw/ip_fw_private.h>
74 #include <netpfil/ipfw/ip_fw_table.h>
77 #include <security/mac/mac_framework.h>
80 static int ipfw_ctl(struct sockopt *sopt);
81 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
82 struct rule_check_info *ci);
83 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
84 struct rule_check_info *ci);
85 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
86 struct rule_check_info *ci);
87 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
88 struct rule_check_info *ci);
90 #define NAMEDOBJ_HASH_SIZE 32
92 struct namedobj_instance {
93 struct namedobjects_head *names;
94 struct namedobjects_head *values;
95 uint32_t nn_size; /* names hash size */
96 uint32_t nv_size; /* number hash size */
97 u_long *idx_mask; /* used items bitmask */
98 uint32_t max_blocks; /* number of "long" blocks in bitmask */
99 uint32_t count; /* number of items */
100 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
101 objhash_hash_f *hash_f;
102 objhash_cmp_f *cmp_f;
104 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
106 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
107 const void *key, uint32_t kopt);
108 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
109 static int objhash_cmp_name(struct named_object *no, const void *name,
112 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
114 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
115 struct sockopt_data *sd);
116 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
117 struct sockopt_data *sd);
118 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
119 struct sockopt_data *sd);
120 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
121 struct sockopt_data *sd);
122 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
123 struct sockopt_data *sd);
124 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
125 struct sockopt_data *sd);
126 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
127 struct sockopt_data *sd);
128 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
129 struct sockopt_data *sd);
131 /* ctl3 handler data */
132 struct mtx ctl3_lock;
133 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
134 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
135 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
136 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
138 static struct ipfw_sopt_handler *ctl3_handlers;
139 static size_t ctl3_hsize;
140 static uint64_t ctl3_refct, ctl3_gencnt;
141 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
142 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
144 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
146 static struct ipfw_sopt_handler scodes[] = {
147 { IP_FW_XGET, 0, HDIR_GET, dump_config },
148 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
149 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
150 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
151 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
152 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
153 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
154 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
155 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
156 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
157 { IP_FW_DUMP_SRVOBJECTS,0, HDIR_GET, dump_srvobjects },
161 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
162 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
163 uint16_t *puidx, uint8_t *ptype);
164 static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
166 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
167 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
168 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
169 struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
170 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
171 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
172 struct obj_idx *oib, struct obj_idx *end);
173 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
174 struct sockopt_data *sd);
177 * Opcode object rewriter variables
179 struct opcode_obj_rewrite *ctl3_rewriters;
180 static size_t ctl3_rsize;
183 * static variables followed by global ones
186 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
187 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
193 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
194 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
195 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
199 ipfw_destroy_counters()
202 uma_zdestroy(V_ipfw_cntr_zone);
206 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
210 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
211 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
217 free_rule(struct ip_fw *rule)
220 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
226 * Find the smallest rule >= key, id.
227 * We could use bsearch but it is so simple that we code it directly
230 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
235 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
238 if (r->rulenum < key)
239 lo = i + 1; /* continue from the next one */
240 else if (r->rulenum > key)
241 hi = i; /* this might be good */
243 lo = i + 1; /* continue from the next one */
244 else /* r->id >= id */
245 hi = i; /* this might be good */
251 * Builds skipto cache on rule set @map.
254 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
259 IPFW_UH_WLOCK_ASSERT(chain);
262 rulenum = map[mi]->rulenum;
263 smap = chain->idxmap_back;
268 for (i = 0; i < 65536; i++) {
270 /* Use the same rule index until i < rulenum */
271 if (i != rulenum || i == 65535)
273 /* Find next rule with num > i */
274 rulenum = map[++mi]->rulenum;
276 rulenum = map[++mi]->rulenum;
281 * Swaps prepared (backup) index with current one.
284 swap_skipto_cache(struct ip_fw_chain *chain)
288 IPFW_UH_WLOCK_ASSERT(chain);
289 IPFW_WLOCK_ASSERT(chain);
292 chain->idxmap = chain->idxmap_back;
293 chain->idxmap_back = map;
297 * Allocate and initialize skipto cache.
300 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
302 int *idxmap, *idxmap_back;
304 idxmap = malloc(65536 * sizeof(uint32_t *), M_IPFW,
306 idxmap_back = malloc(65536 * sizeof(uint32_t *), M_IPFW,
310 * Note we may be called at any time after initialization,
311 * for example, on first skipto rule, so we need to
312 * provide valid chain->idxmap on return
315 IPFW_UH_WLOCK(chain);
316 if (chain->idxmap != NULL) {
317 IPFW_UH_WUNLOCK(chain);
318 free(idxmap, M_IPFW);
319 free(idxmap_back, M_IPFW);
323 /* Set backup pointer first to permit building cache */
324 chain->idxmap_back = idxmap_back;
325 update_skipto_cache(chain, chain->map);
327 /* It is now safe to set chain->idxmap ptr */
328 chain->idxmap = idxmap;
329 swap_skipto_cache(chain);
331 IPFW_UH_WUNLOCK(chain);
335 * Destroys skipto cache.
338 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
341 if (chain->idxmap != NULL)
342 free(chain->idxmap, M_IPFW);
343 if (chain->idxmap != NULL)
344 free(chain->idxmap_back, M_IPFW);
349 * allocate a new map, returns the chain locked. extra is the number
350 * of entries to add or delete.
352 static struct ip_fw **
353 get_map(struct ip_fw_chain *chain, int extra, int locked)
360 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
362 i = chain->n_rules + extra;
363 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
365 printf("%s: cannot allocate map\n", __FUNCTION__);
369 IPFW_UH_WLOCK(chain);
370 if (i >= chain->n_rules + extra) /* good */
372 /* otherwise we lost the race, free and retry */
374 IPFW_UH_WUNLOCK(chain);
380 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
382 static struct ip_fw **
383 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
385 struct ip_fw **old_map;
389 chain->n_rules = new_len;
390 old_map = chain->map;
391 chain->map = new_map;
392 swap_skipto_cache(chain);
399 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
401 struct timeval boottime;
403 cntr->size = sizeof(*cntr);
405 if (krule->cntr != NULL) {
406 cntr->pcnt = counter_u64_fetch(krule->cntr);
407 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
408 cntr->timestamp = krule->timestamp;
410 if (cntr->timestamp > 0) {
411 getboottime(&boottime);
412 cntr->timestamp += boottime.tv_sec;
417 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
419 struct timeval boottime;
421 if (krule->cntr != NULL) {
422 cntr->pcnt = counter_u64_fetch(krule->cntr);
423 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
424 cntr->timestamp = krule->timestamp;
426 if (cntr->timestamp > 0) {
427 getboottime(&boottime);
428 cntr->timestamp += boottime.tv_sec;
433 * Copies rule @urule from v1 userland format (current).
435 * Assume @krule is zeroed.
438 import_rule1(struct rule_check_info *ci)
440 struct ip_fw_rule *urule;
443 urule = (struct ip_fw_rule *)ci->urule;
444 krule = (struct ip_fw *)ci->krule;
447 krule->act_ofs = urule->act_ofs;
448 krule->cmd_len = urule->cmd_len;
449 krule->rulenum = urule->rulenum;
450 krule->set = urule->set;
451 krule->flags = urule->flags;
453 /* Save rulenum offset */
454 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
457 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
461 * Export rule into v1 format (Current).
463 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
465 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
467 * Assume @data is zeroed.
470 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
472 struct ip_fw_bcounter *cntr;
473 struct ip_fw_rule *urule;
476 /* Fill in TLV header */
477 tlv = (ipfw_obj_tlv *)data;
478 tlv->type = IPFW_TLV_RULE_ENT;
483 cntr = (struct ip_fw_bcounter *)(tlv + 1);
484 urule = (struct ip_fw_rule *)(cntr + 1);
485 export_cntr1_base(krule, cntr);
487 urule = (struct ip_fw_rule *)(tlv + 1);
490 urule->act_ofs = krule->act_ofs;
491 urule->cmd_len = krule->cmd_len;
492 urule->rulenum = krule->rulenum;
493 urule->set = krule->set;
494 urule->flags = krule->flags;
495 urule->id = krule->id;
498 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);
707 * rewrite failed, state for current rule
708 * has been reverted. Check if we need to
714 * We have some more table rules
715 * we need to rollback.
718 IPFW_UH_WLOCK(chain);
721 if (ci->object_opcodes == 0)
723 unref_rule_objects(chain,ci->krule);
726 IPFW_UH_WUNLOCK(chain);
736 /* get_map returns with IPFW_UH_WLOCK if successful */
737 map = get_map(chain, count, 0 /* not locked */);
741 IPFW_UH_WLOCK(chain);
742 for (ci = rci, i = 0; i < count; ci++, i++) {
743 if (ci->object_opcodes == 0)
746 unref_rule_objects(chain, ci->krule);
748 IPFW_UH_WUNLOCK(chain);
754 if (V_autoinc_step < 1)
756 else if (V_autoinc_step > 1000)
757 V_autoinc_step = 1000;
759 /* FIXME: Handle count > 1 */
762 rulenum = krule->rulenum;
764 /* find the insertion point, we will insert before */
765 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
766 i = ipfw_find_rule(chain, insert_before, 0);
767 /* duplicate first part */
769 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
771 /* duplicate remaining part, we always have the default rule */
772 bcopy(chain->map + i, map + i + 1,
773 sizeof(struct ip_fw *) *(chain->n_rules - i));
775 /* Compute rule number and write it back */
776 rulenum = i > 0 ? map[i-1]->rulenum : 0;
777 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
778 rulenum += V_autoinc_step;
779 krule->rulenum = rulenum;
780 /* Save number to userland rule */
781 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
785 krule->id = chain->id + 1;
786 update_skipto_cache(chain, map);
787 map = swap_map(chain, map, chain->n_rules + 1);
788 chain->static_len += RULEUSIZE0(krule);
789 IPFW_UH_WUNLOCK(chain);
796 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
801 map = get_map(chain, 1, locked);
804 if (chain->n_rules > 0)
805 bcopy(chain->map, map,
806 chain->n_rules * sizeof(struct ip_fw *));
807 map[chain->n_rules] = rule;
808 rule->rulenum = IPFW_DEFAULT_RULE;
809 rule->set = RESVD_SET;
810 rule->id = chain->id + 1;
811 /* We add rule in the end of chain, no need to update skipto cache */
812 map = swap_map(chain, map, chain->n_rules + 1);
813 chain->static_len += RULEUSIZE0(rule);
814 IPFW_UH_WUNLOCK(chain);
820 * Adds @rule to the list of rules to reap
823 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
827 IPFW_UH_WLOCK_ASSERT(chain);
829 /* Unlink rule from everywhere */
830 unref_rule_objects(chain, rule);
832 *((struct ip_fw **)rule) = *head;
837 * Reclaim storage associated with a list of rules. This is
838 * typically the list created using remove_rule.
839 * A NULL pointer on input is handled correctly.
842 ipfw_reap_rules(struct ip_fw *head)
846 while ((rule = head) != NULL) {
847 head = *((struct ip_fw **)head);
854 * (default || reserved || !match_set || !match_number)
856 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
857 * // the default rule is always protected
859 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
860 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
862 * match_set ::= (cmd == 0 || rule->set == set)
863 * // set number is ignored for cmd == 0
865 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
866 * // number is ignored for cmd == 1 or n == 0
870 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
873 /* Don't match default rule for modification queries */
874 if (rule->rulenum == IPFW_DEFAULT_RULE &&
875 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
878 /* Don't match rules in reserved set for flush requests */
879 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
882 /* If we're filtering by set, don't match other sets */
883 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
886 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
887 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
893 struct manage_sets_args {
899 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
902 struct manage_sets_args *args;
904 args = (struct manage_sets_args *)arg;
905 if (no->set == (uint8_t)args->set)
906 no->set = args->new_set;
907 else if (no->set == args->new_set)
908 no->set = (uint8_t)args->set;
913 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
916 struct manage_sets_args *args;
918 args = (struct manage_sets_args *)arg;
919 if (no->set == (uint8_t)args->set)
920 no->set = args->new_set;
925 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
928 struct manage_sets_args *args;
930 args = (struct manage_sets_args *)arg;
931 if (no->set != (uint8_t)args->set)
933 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
934 no->etlv, no->name) != NULL)
940 * Generic function to handler moving and swapping sets.
943 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
944 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
946 struct manage_sets_args args;
947 struct named_object *no;
950 args.new_set = new_set;
953 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
956 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
959 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
963 * @set used to pass kidx.
964 * When @new_set is zero - reset object counter,
965 * otherwise increment it.
967 no = ipfw_objhash_lookup_kidx(ni, set);
974 /* @set used to pass kidx */
975 no = ipfw_objhash_lookup_kidx(ni, set);
977 * First check number of references:
978 * when it differs, this mean other rules are holding
979 * reference to given object, so it is not possible to
980 * change its set. Note that refcnt may account references
981 * to some going-to-be-added rules. Since we don't know
982 * their numbers (and even if they will be added) it is
983 * perfectly OK to return error here.
985 if (no->ocnt != no->refcnt)
987 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
992 /* @set used to pass kidx */
993 no = ipfw_objhash_lookup_kidx(ni, set);
1001 * Delete rules matching range @rt.
1002 * Saves number of deleted rules in @ndel.
1004 * Returns 0 on success.
1007 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1009 struct ip_fw *reap, *rule, **map;
1011 int i, n, ndyn, ofs;
1014 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1017 * Stage 1: Determine range to inspect.
1018 * Range is half-inclusive, e.g [start, end).
1021 end = chain->n_rules - 1;
1023 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1024 start = ipfw_find_rule(chain, rt->start_rule, 0);
1026 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1027 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1028 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1031 /* Allocate new map of the same size */
1032 map = get_map(chain, 0, 1 /* locked */);
1034 IPFW_UH_WUNLOCK(chain);
1041 /* 1. bcopy the initial part of the map */
1043 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1044 /* 2. copy active rules between start and end */
1045 for (i = start; i < end; i++) {
1046 rule = chain->map[i];
1047 if (ipfw_match_range(rule, rt) == 0) {
1053 if (ipfw_is_dyn_rule(rule) != 0)
1056 /* 3. copy the final part of the map */
1057 bcopy(chain->map + end, map + ofs,
1058 (chain->n_rules - end) * sizeof(struct ip_fw *));
1059 /* 4. recalculate skipto cache */
1060 update_skipto_cache(chain, map);
1061 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1062 map = swap_map(chain, map, chain->n_rules - n);
1063 /* 6. Remove all dynamic states originated by deleted rules */
1065 ipfw_expire_dyn_states(chain, rt);
1066 /* 7. now remove the rules deleted from the old map */
1067 for (i = start; i < end; i++) {
1069 if (ipfw_match_range(rule, rt) == 0)
1071 chain->static_len -= RULEUSIZE0(rule);
1072 ipfw_reap_add(chain, &reap, rule);
1074 IPFW_UH_WUNLOCK(chain);
1076 ipfw_reap_rules(reap);
1084 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1086 struct opcode_obj_rewrite *rw;
1089 int cmdlen, i, l, c;
1092 IPFW_UH_WLOCK_ASSERT(ch);
1094 /* Stage 1: count number of references by given rules */
1095 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1097 if (ipfw_match_range(rule, rt) == 0)
1099 if (rule->set == rt->new_set) /* nothing to do */
1101 /* Search opcodes with named objects */
1102 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1103 l > 0; l -= cmdlen, cmd += cmdlen) {
1104 cmdlen = F_LEN(cmd);
1105 rw = find_op_rw(cmd, &kidx, NULL);
1106 if (rw == NULL || rw->manage_sets == NULL)
1109 * When manage_sets() returns non-zero value to
1110 * COUNT_ONE command, consider this as an object
1111 * doesn't support sets (e.g. disabled with sysctl).
1112 * So, skip checks for this object.
1114 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1119 if (c == 0) /* No objects found */
1121 /* Stage 2: verify "ownership" */
1122 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1124 if (ipfw_match_range(rule, rt) == 0)
1126 if (rule->set == rt->new_set) /* nothing to do */
1128 /* Search opcodes with named objects */
1129 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1130 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1131 cmdlen = F_LEN(cmd);
1132 rw = find_op_rw(cmd, &kidx, NULL);
1133 if (rw == NULL || rw->manage_sets == NULL)
1135 /* Test for ownership and conflicting names */
1136 c = rw->manage_sets(ch, kidx,
1137 (uint8_t)rt->new_set, TEST_ONE);
1140 /* Stage 3: change set and cleanup */
1141 for (i = 0; i < ch->n_rules - 1; i++) {
1143 if (ipfw_match_range(rule, rt) == 0)
1145 if (rule->set == rt->new_set) /* nothing to do */
1147 /* Search opcodes with named objects */
1148 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1149 l > 0; l -= cmdlen, cmd += cmdlen) {
1150 cmdlen = F_LEN(cmd);
1151 rw = find_op_rw(cmd, &kidx, NULL);
1152 if (rw == NULL || rw->manage_sets == NULL)
1154 /* cleanup object counter */
1155 rw->manage_sets(ch, kidx,
1156 0 /* reset counter */, COUNT_ONE);
1160 rw->manage_sets(ch, kidx,
1161 (uint8_t)rt->new_set, MOVE_ONE);
1166 * Changes set of given rule rannge @rt
1169 * Returns 0 on success.
1172 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1177 IPFW_UH_WLOCK(chain);
1180 * Move rules with matching paramenerts to a new set.
1181 * This one is much more complex. We have to ensure
1182 * that all referenced tables (if any) are referenced
1183 * by given rule subset only. Otherwise, we can't move
1184 * them to new set and have to return error.
1186 if ((i = move_objects(chain, rt)) != 0) {
1187 IPFW_UH_WUNLOCK(chain);
1191 /* XXX: We have to do swap holding WLOCK */
1192 for (i = 0; i < chain->n_rules; i++) {
1193 rule = chain->map[i];
1194 if (ipfw_match_range(rule, rt) == 0)
1196 rule->set = rt->new_set;
1199 IPFW_UH_WUNLOCK(chain);
1205 * Clear counters for a specific rule.
1206 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1207 * so we only care that rules do not disappear.
1210 clear_counters(struct ip_fw *rule, int log_only)
1212 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1215 IPFW_ZERO_RULE_COUNTER(rule);
1216 if (l->o.opcode == O_LOG)
1217 l->log_left = l->max_log;
1221 * Flushes rules counters and/or log values on matching range.
1223 * Returns number of items cleared.
1226 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1233 rt->flags |= IPFW_RCFLAG_DEFAULT;
1235 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1236 for (i = 0; i < chain->n_rules; i++) {
1237 rule = chain->map[i];
1238 if (ipfw_match_range(rule, rt) == 0)
1240 clear_counters(rule, log_only);
1243 IPFW_UH_WUNLOCK(chain);
1249 check_range_tlv(ipfw_range_tlv *rt)
1252 if (rt->head.length != sizeof(*rt))
1254 if (rt->start_rule > rt->end_rule)
1256 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1259 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1266 * Delete rules matching specified parameters
1267 * Data layout (v0)(current):
1268 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1269 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1271 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1273 * Returns 0 on success.
1276 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1277 struct sockopt_data *sd)
1279 ipfw_range_header *rh;
1282 if (sd->valsize != sizeof(*rh))
1285 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1287 if (check_range_tlv(&rh->range) != 0)
1291 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1294 /* Save number of rules deleted */
1295 rh->range.new_set = ndel;
1300 * Move rules/sets matching specified parameters
1301 * Data layout (v0)(current):
1302 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1304 * Returns 0 on success.
1307 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1308 struct sockopt_data *sd)
1310 ipfw_range_header *rh;
1312 if (sd->valsize != sizeof(*rh))
1315 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1317 if (check_range_tlv(&rh->range) != 0)
1320 return (move_range(chain, &rh->range));
1324 * Clear rule accounting data matching specified parameters
1325 * Data layout (v0)(current):
1326 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1327 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1329 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1331 * Returns 0 on success.
1334 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1335 struct sockopt_data *sd)
1337 ipfw_range_header *rh;
1341 if (sd->valsize != sizeof(*rh))
1344 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1346 if (check_range_tlv(&rh->range) != 0)
1349 log_only = (op3->opcode == IP_FW_XRESETLOG);
1351 num = clear_range(chain, &rh->range, log_only);
1353 if (rh->range.flags & IPFW_RCFLAG_ALL)
1354 msg = log_only ? "All logging counts reset" :
1355 "Accounting cleared";
1357 msg = log_only ? "logging count reset" : "cleared";
1360 int lev = LOG_SECURITY | LOG_NOTICE;
1361 log(lev, "ipfw: %s.\n", msg);
1364 /* Save number of rules cleared */
1365 rh->range.new_set = num;
1370 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1374 IPFW_UH_WLOCK_ASSERT(chain);
1376 /* Change enabled/disabled sets mask */
1377 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1378 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1380 V_set_disable = v_set;
1381 IPFW_WUNLOCK(chain);
1385 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1387 struct opcode_obj_rewrite *rw;
1391 IPFW_UH_WLOCK_ASSERT(chain);
1393 if (rt->set == rt->new_set) /* nothing to do */
1398 * Berfore moving the rules we need to check that
1399 * there aren't any conflicting named objects.
1401 for (rw = ctl3_rewriters;
1402 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1403 if (rw->manage_sets == NULL)
1405 i = rw->manage_sets(chain, (uint8_t)rt->set,
1406 (uint8_t)rt->new_set, TEST_ALL);
1411 /* Swap or move two sets */
1412 for (i = 0; i < chain->n_rules - 1; i++) {
1413 rule = chain->map[i];
1414 if (rule->set == (uint8_t)rt->set)
1415 rule->set = (uint8_t)rt->new_set;
1416 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1417 rule->set = (uint8_t)rt->set;
1419 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1420 if (rw->manage_sets == NULL)
1422 rw->manage_sets(chain, (uint8_t)rt->set,
1423 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1429 * Swaps or moves set
1430 * Data layout (v0)(current):
1431 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1433 * Returns 0 on success.
1436 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1437 struct sockopt_data *sd)
1439 ipfw_range_header *rh;
1442 if (sd->valsize != sizeof(*rh))
1445 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1447 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1449 /* enable_sets() expects bitmasks. */
1450 if (op3->opcode != IP_FW_SET_ENABLE &&
1451 (rh->range.set >= IPFW_MAX_SETS ||
1452 rh->range.new_set >= IPFW_MAX_SETS))
1456 IPFW_UH_WLOCK(chain);
1457 switch (op3->opcode) {
1458 case IP_FW_SET_SWAP:
1459 case IP_FW_SET_MOVE:
1460 ret = swap_sets(chain, &rh->range,
1461 op3->opcode == IP_FW_SET_MOVE);
1463 case IP_FW_SET_ENABLE:
1464 enable_sets(chain, &rh->range);
1467 IPFW_UH_WUNLOCK(chain);
1473 * Remove all rules with given number, or do set manipulation.
1474 * Assumes chain != NULL && *chain != NULL.
1476 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1477 * the next 8 bits are the new set; the top 8 bits indicate the command:
1479 * 0 delete rules numbered "rulenum"
1480 * 1 delete rules in set "rulenum"
1481 * 2 move rules "rulenum" to set "new_set"
1482 * 3 move rules from set "rulenum" to set "new_set"
1483 * 4 swap sets "rulenum" and "new_set"
1484 * 5 delete rules "rulenum" and set "new_set"
1487 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1489 uint32_t num; /* rule number or old_set */
1490 uint8_t cmd, new_set;
1496 cmd = (arg >> 24) & 0xff;
1497 new_set = (arg >> 16) & 0xff;
1499 if (cmd > 5 || new_set > RESVD_SET)
1501 if (cmd == 0 || cmd == 2 || cmd == 5) {
1502 if (num >= IPFW_DEFAULT_RULE)
1505 if (num > RESVD_SET) /* old_set */
1509 /* Convert old requests into new representation */
1510 memset(&rt, 0, sizeof(rt));
1511 rt.start_rule = num;
1514 rt.new_set = new_set;
1518 case 0: /* delete rules numbered "rulenum" */
1520 rt.flags |= IPFW_RCFLAG_ALL;
1522 rt.flags |= IPFW_RCFLAG_RANGE;
1525 case 1: /* delete rules in set "rulenum" */
1526 rt.flags |= IPFW_RCFLAG_SET;
1529 case 5: /* delete rules "rulenum" and set "new_set" */
1530 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1535 case 2: /* move rules "rulenum" to set "new_set" */
1536 rt.flags |= IPFW_RCFLAG_RANGE;
1538 case 3: /* move rules from set "rulenum" to set "new_set" */
1539 IPFW_UH_WLOCK(chain);
1540 error = swap_sets(chain, &rt, 1);
1541 IPFW_UH_WUNLOCK(chain);
1543 case 4: /* swap sets "rulenum" and "new_set" */
1544 IPFW_UH_WLOCK(chain);
1545 error = swap_sets(chain, &rt, 0);
1546 IPFW_UH_WUNLOCK(chain);
1553 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1556 if (ndel == 0 && (cmd != 1 && num != 0))
1562 return (move_range(chain, &rt));
1566 * Reset some or all counters on firewall rules.
1567 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1568 * the next 8 bits are the set number, the top 8 bits are the command:
1569 * 0 work with rules from all set's;
1570 * 1 work with rules only from specified set.
1571 * Specified rule number is zero if we want to clear all entries.
1572 * log_only is 1 if we only want to reset logs, zero otherwise.
1575 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1581 uint16_t rulenum = arg & 0xffff;
1582 uint8_t set = (arg >> 16) & 0xff;
1583 uint8_t cmd = (arg >> 24) & 0xff;
1587 if (cmd == 1 && set > RESVD_SET)
1590 IPFW_UH_RLOCK(chain);
1592 V_norule_counter = 0;
1593 for (i = 0; i < chain->n_rules; i++) {
1594 rule = chain->map[i];
1595 /* Skip rules not in our set. */
1596 if (cmd == 1 && rule->set != set)
1598 clear_counters(rule, log_only);
1600 msg = log_only ? "All logging counts reset" :
1601 "Accounting cleared";
1604 for (i = 0; i < chain->n_rules; i++) {
1605 rule = chain->map[i];
1606 if (rule->rulenum == rulenum) {
1607 if (cmd == 0 || rule->set == set)
1608 clear_counters(rule, log_only);
1611 if (rule->rulenum > rulenum)
1614 if (!cleared) { /* we did not find any matching rules */
1615 IPFW_UH_RUNLOCK(chain);
1618 msg = log_only ? "logging count reset" : "cleared";
1620 IPFW_UH_RUNLOCK(chain);
1623 int lev = LOG_SECURITY | LOG_NOTICE;
1626 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1628 log(lev, "ipfw: %s.\n", msg);
1635 * Check rule head in FreeBSD11 format
1639 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1640 struct rule_check_info *ci)
1644 if (size < sizeof(*rule)) {
1645 printf("ipfw: rule too short\n");
1649 /* Check for valid cmd_len */
1650 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1652 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1655 if (rule->act_ofs >= rule->cmd_len) {
1656 printf("ipfw: bogus action offset (%u > %u)\n",
1657 rule->act_ofs, rule->cmd_len - 1);
1661 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1664 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1668 * Check rule head in FreeBSD8 format
1672 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1673 struct rule_check_info *ci)
1677 if (size < sizeof(*rule)) {
1678 printf("ipfw: rule too short\n");
1682 /* Check for valid cmd_len */
1683 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1685 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1688 if (rule->act_ofs >= rule->cmd_len) {
1689 printf("ipfw: bogus action offset (%u > %u)\n",
1690 rule->act_ofs, rule->cmd_len - 1);
1694 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1697 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1701 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1709 * Now go for the individual checks. Very simple ones, basically only
1710 * instruction sizes.
1712 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1713 cmdlen = F_LEN(cmd);
1715 printf("ipfw: opcode %d size truncated\n",
1719 switch (cmd->opcode) {
1722 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1724 ci->object_opcodes++;
1735 case O_IPPRECEDENCE:
1753 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1757 case O_EXTERNAL_ACTION:
1758 if (cmd->arg1 == 0 ||
1759 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1760 printf("ipfw: invalid external "
1764 ci->object_opcodes++;
1766 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1772 cmdlen = F_LEN(cmd);
1773 if (cmd->opcode == O_EXTERNAL_DATA)
1775 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1776 printf("ipfw: invalid opcode "
1777 "next to external action %u\n",
1781 if (cmd->arg1 == 0 ||
1782 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1783 printf("ipfw: invalid external "
1784 "action instance opcode\n");
1787 ci->object_opcodes++;
1792 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1794 if (cmd->arg1 >= rt_numfibs) {
1795 printf("ipfw: invalid fib number %d\n",
1802 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1804 if ((cmd->arg1 != IP_FW_TARG) &&
1805 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1806 printf("ipfw: invalid fib number %d\n",
1807 cmd->arg1 & 0x7FFF);
1821 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1826 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1828 ci->object_opcodes++;
1832 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1835 ((ipfw_insn_log *)cmd)->log_left =
1836 ((ipfw_insn_log *)cmd)->max_log;
1842 /* only odd command lengths */
1843 if ((cmdlen & 1) == 0)
1849 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1850 printf("ipfw: invalid set size %d\n",
1854 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1859 case O_IP_SRC_LOOKUP:
1860 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1862 case O_IP_DST_LOOKUP:
1863 if (cmd->arg1 >= V_fw_tables_max) {
1864 printf("ipfw: invalid table number %d\n",
1868 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1869 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1870 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1872 ci->object_opcodes++;
1874 case O_IP_FLOW_LOOKUP:
1875 if (cmd->arg1 >= V_fw_tables_max) {
1876 printf("ipfw: invalid table number %d\n",
1880 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1881 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1883 ci->object_opcodes++;
1886 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1897 if (cmdlen < 1 || cmdlen > 31)
1902 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1908 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1909 if (cmdlen < 2 || cmdlen > 31)
1916 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1918 ci->object_opcodes++;
1922 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1928 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1933 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1938 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1945 if (ip_divert_ptr == NULL)
1951 if (ng_ipfw_input_p == NULL)
1956 if (!IPFW_NAT_LOADED)
1958 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1962 ci->object_opcodes++;
1964 case O_FORWARD_MAC: /* XXX not implemented yet */
1977 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1981 printf("ipfw: opcode %d, multiple actions"
1988 printf("ipfw: opcode %d, action must be"
1997 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1998 F_INSN_SIZE(ipfw_insn))
2003 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2004 ((ipfw_insn_u32 *)cmd)->o.arg1)
2008 case O_IP6_SRC_MASK:
2009 case O_IP6_DST_MASK:
2010 if ( !(cmdlen & 1) || cmdlen > 127)
2014 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2020 switch (cmd->opcode) {
2030 case O_IP6_SRC_MASK:
2031 case O_IP6_DST_MASK:
2033 printf("ipfw: no IPv6 support in kernel\n");
2034 return (EPROTONOSUPPORT);
2037 printf("ipfw: opcode %d, unknown opcode\n",
2043 if (have_action == 0) {
2044 printf("ipfw: missing action\n");
2050 printf("ipfw: opcode %d size %d wrong\n",
2051 cmd->opcode, cmdlen);
2057 * Translation of requests for compatibility with FreeBSD 7.2/8.
2058 * a static variable tells us if we have an old client from userland,
2059 * and if necessary we translate requests and responses between the
2065 struct ip_fw7 *next; /* linked list of rules */
2066 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2067 /* 'next_rule' is used to pass up 'set_disable' status */
2069 uint16_t act_ofs; /* offset of action in 32-bit units */
2070 uint16_t cmd_len; /* # of 32-bit words in cmd */
2071 uint16_t rulenum; /* rule number */
2072 uint8_t set; /* rule set (0..31) */
2073 // #define RESVD_SET 31 /* set for default and persistent rules */
2074 uint8_t _pad; /* padding */
2075 // uint32_t id; /* rule id, only in v.8 */
2076 /* These fields are present in all rules. */
2077 uint64_t pcnt; /* Packet counter */
2078 uint64_t bcnt; /* Byte counter */
2079 uint32_t timestamp; /* tv_sec of last match */
2081 ipfw_insn cmd[1]; /* storage for commands */
2084 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2085 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2088 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2089 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2094 * Copy the static and dynamic rules to the supplied buffer
2095 * and return the amount of space actually used.
2096 * Must be run under IPFW_UH_RLOCK
2099 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2102 char *ep = bp + space;
2104 struct ip_fw_rule0 *dst;
2105 struct timeval boottime;
2106 int error, i, l, warnflag;
2107 time_t boot_seconds;
2111 getboottime(&boottime);
2112 boot_seconds = boottime.tv_sec;
2113 for (i = 0; i < chain->n_rules; i++) {
2114 rule = chain->map[i];
2117 /* Convert rule to FreeBSd 7.2 format */
2118 l = RULESIZE7(rule);
2119 if (bp + l + sizeof(uint32_t) <= ep) {
2120 bcopy(rule, bp, l + sizeof(uint32_t));
2121 error = set_legacy_obj_kidx(chain,
2122 (struct ip_fw_rule0 *)bp);
2125 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2127 return 0; /*XXX correct? */
2129 * XXX HACK. Store the disable mask in the "next"
2130 * pointer in a wild attempt to keep the ABI the same.
2131 * Why do we do this on EVERY rule?
2133 bcopy(&V_set_disable,
2134 &(((struct ip_fw7 *)bp)->next_rule),
2135 sizeof(V_set_disable));
2136 if (((struct ip_fw7 *)bp)->timestamp)
2137 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2140 continue; /* go to next rule */
2143 l = RULEUSIZE0(rule);
2144 if (bp + l > ep) { /* should not happen */
2145 printf("overflow dumping static rules\n");
2148 dst = (struct ip_fw_rule0 *)bp;
2149 export_rule0(rule, dst, l);
2150 error = set_legacy_obj_kidx(chain, dst);
2153 * XXX HACK. Store the disable mask in the "next"
2154 * pointer in a wild attempt to keep the ABI the same.
2155 * Why do we do this on EVERY rule?
2157 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2158 * so we need to fail _after_ saving at least one mask.
2160 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2162 dst->timestamp += boot_seconds;
2167 /* Non-fatal table rewrite error. */
2171 printf("Stop on rule %d. Fail to convert table\n",
2177 printf("ipfw: process %s is using legacy interfaces,"
2178 " consider rebuilding\n", "");
2179 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2180 return (bp - (char *)buf);
2185 uint32_t b; /* start rule */
2186 uint32_t e; /* end rule */
2187 uint32_t rcount; /* number of rules */
2188 uint32_t rsize; /* rules size */
2189 uint32_t tcount; /* number of tables */
2190 int rcounters; /* counters */
2194 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2197 ntlv->head.type = no->etlv;
2198 ntlv->head.length = sizeof(*ntlv);
2199 ntlv->idx = no->kidx;
2200 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2204 * Export named object info in instance @ni, identified by @kidx
2205 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2207 * Returns 0 on success.
2210 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2211 struct sockopt_data *sd)
2213 struct named_object *no;
2214 ipfw_obj_ntlv *ntlv;
2216 no = ipfw_objhash_lookup_kidx(ni, kidx);
2217 KASSERT(no != NULL, ("invalid object kernel index passed"));
2219 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2223 ipfw_export_obj_ntlv(no, ntlv);
2228 * Dumps static rules with table TLVs in buffer @sd.
2230 * Returns 0 on success.
2233 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2234 uint32_t *bmask, struct sockopt_data *sd)
2239 ipfw_obj_ctlv *ctlv;
2240 struct ip_fw *krule;
2241 struct namedobj_instance *ni;
2244 /* Dump table names first (if any) */
2245 if (da->tcount > 0) {
2247 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2250 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2251 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2253 ctlv->count = da->tcount;
2254 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2258 tcount = da->tcount;
2259 ni = ipfw_get_table_objhash(chain);
2260 while (tcount > 0) {
2261 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
2266 /* Jump to shared named object bitmask */
2267 if (i >= IPFW_TABLES_MAX) {
2268 ni = CHAIN_TO_SRV(chain);
2269 i -= IPFW_TABLES_MAX;
2270 bmask += IPFW_TABLES_MAX / 32;
2273 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2281 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2284 ctlv->head.type = IPFW_TLV_RULE_LIST;
2285 ctlv->head.length = da->rsize + sizeof(*ctlv);
2286 ctlv->count = da->rcount;
2288 for (i = da->b; i < da->e; i++) {
2289 krule = chain->map[i];
2291 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2292 if (da->rcounters != 0)
2293 l += sizeof(struct ip_fw_bcounter);
2294 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2298 export_rule1(krule, dst, l, da->rcounters);
2305 * Marks every object index used in @rule with bit in @bmask.
2306 * Used to generate bitmask of referenced tables/objects for given ruleset
2309 * Returns number of newly-referenced objects.
2312 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
2315 struct opcode_obj_rewrite *rw;
2317 int bidx, cmdlen, l, count;
2325 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2326 cmdlen = F_LEN(cmd);
2328 rw = find_op_rw(cmd, &kidx, &subtype);
2334 * Maintain separate bitmasks for table and
2335 * non-table objects.
2337 if (rw->etlv != IPFW_TLV_TBL_NAME)
2338 bidx += IPFW_TABLES_MAX / 32;
2340 if ((bmask[bidx] & (1 << (kidx % 32))) == 0)
2343 bmask[bidx] |= 1 << (kidx % 32);
2350 * Dumps requested objects data
2351 * Data layout (version 0)(current):
2352 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2353 * size = ipfw_cfg_lheader.size
2354 * Reply: [ ipfw_cfg_lheader
2355 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2356 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2357 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2359 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2361 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2362 * The rest (size, count) are set to zero and needs to be ignored.
2364 * Returns 0 on success.
2367 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2368 struct sockopt_data *sd)
2370 ipfw_cfg_lheader *hdr;
2375 struct dump_args da;
2378 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2384 /* Allocate needed state. Note we allocate 2xspace mask, for table&srv */
2385 if (hdr->flags & IPFW_CFG_GET_STATIC)
2386 bmask = malloc(IPFW_TABLES_MAX / 4, M_TEMP, M_WAITOK | M_ZERO);
2388 IPFW_UH_RLOCK(chain);
2391 * STAGE 1: Determine size/count for objects in range.
2392 * Prepare used tables bitmask.
2394 sz = sizeof(ipfw_cfg_lheader);
2395 memset(&da, 0, sizeof(da));
2398 da.e = chain->n_rules;
2400 if (hdr->end_rule != 0) {
2401 /* Handle custom range */
2402 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2403 rnum = IPFW_DEFAULT_RULE;
2404 da.b = ipfw_find_rule(chain, rnum, 0);
2405 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2406 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2407 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2410 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2411 for (i = da.b; i < da.e; i++) {
2412 rule = chain->map[i];
2413 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2415 /* Update bitmask of used objects for given range */
2416 da.tcount += mark_object_kidx(chain, rule, bmask);
2418 /* Add counters if requested */
2419 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2420 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2425 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2426 sizeof(ipfw_obj_ctlv);
2427 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2430 if (hdr->flags & IPFW_CFG_GET_STATES)
2431 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2432 sizeof(ipfw_obj_ctlv);
2436 * Fill header anyway.
2437 * Note we have to save header fields to stable storage
2438 * buffer inside @sd can be flushed after dumping rules
2441 hdr->set_mask = ~V_set_disable;
2442 hdr_flags = hdr->flags;
2445 if (sd->valsize < sz) {
2450 /* STAGE2: Store actual data */
2451 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2452 error = dump_static_rules(chain, &da, bmask, sd);
2457 if (hdr_flags & IPFW_CFG_GET_STATES)
2458 error = ipfw_dump_states(chain, sd);
2461 IPFW_UH_RUNLOCK(chain);
2464 free(bmask, M_TEMP);
2470 ipfw_check_object_name_generic(const char *name)
2474 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2475 if (strnlen(name, nsize) == nsize)
2477 if (name[0] == '\0')
2483 * Creates non-existent objects referenced by rule.
2485 * Return 0 on success.
2488 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2489 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2491 struct opcode_obj_rewrite *rw;
2497 * Compatibility stuff: do actual creation for non-existing,
2498 * but referenced objects.
2500 for (p = oib; p < pidx; p++) {
2508 rw = find_op_rw(cmd + p->off, NULL, NULL);
2509 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2510 (cmd + p->off)->opcode));
2512 if (rw->create_object == NULL)
2515 error = rw->create_object(ch, ti, &kidx);
2522 * Error happened. We have to rollback everything.
2523 * Drop all already acquired references.
2526 unref_oib_objects(ch, cmd, oib, pidx);
2527 IPFW_UH_WUNLOCK(ch);
2536 * Compatibility function for old ipfw(8) binaries.
2537 * Rewrites table/nat kernel indices with userland ones.
2538 * Convert tables matching '/^\d+$/' to their atoi() value.
2539 * Use number 65535 for other tables.
2541 * Returns 0 on success.
2544 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2546 struct opcode_obj_rewrite *rw;
2547 struct named_object *no;
2551 int cmdlen, error, l;
2552 uint16_t kidx, uidx;
2560 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2561 cmdlen = F_LEN(cmd);
2563 /* Check if is index in given opcode */
2564 rw = find_op_rw(cmd, &kidx, &subtype);
2568 /* Try to find referenced kernel object */
2569 no = rw->find_bykidx(ch, kidx);
2573 val = strtol(no->name, &end, 10);
2574 if (*end == '\0' && val < 65535) {
2579 * We are called via legacy opcode.
2580 * Save error and show table as fake number
2581 * not to make ipfw(8) hang.
2587 rw->update(cmd, uidx);
2595 * Unreferences all already-referenced objects in given @cmd rule,
2596 * using information in @oib.
2598 * Used to rollback partially converted rule on error.
2601 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2602 struct obj_idx *end)
2604 struct opcode_obj_rewrite *rw;
2605 struct named_object *no;
2608 IPFW_UH_WLOCK_ASSERT(ch);
2610 for (p = oib; p < end; p++) {
2614 rw = find_op_rw(cmd + p->off, NULL, NULL);
2615 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2616 (cmd + p->off)->opcode));
2618 /* Find & unref by existing idx */
2619 no = rw->find_bykidx(ch, p->kidx);
2620 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2626 * Remove references from every object used in @rule.
2627 * Used at rule removal code.
2630 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2632 struct opcode_obj_rewrite *rw;
2633 struct named_object *no;
2639 IPFW_UH_WLOCK_ASSERT(ch);
2644 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2645 cmdlen = F_LEN(cmd);
2647 rw = find_op_rw(cmd, &kidx, &subtype);
2650 no = rw->find_bykidx(ch, kidx);
2652 KASSERT(no != NULL, ("object id %d not found", kidx));
2653 KASSERT(no->subtype == subtype,
2654 ("wrong type %d (%d) for object id %d",
2655 no->subtype, subtype, kidx));
2656 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2659 if (no->refcnt == 1 && rw->destroy_object != NULL)
2660 rw->destroy_object(ch, no);
2668 * Find and reference object (if any) stored in instruction @cmd.
2670 * Saves object info in @pidx, sets
2671 * - @unresolved to 1 if object should exists but not found
2673 * Returns non-zero value in case of error.
2676 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2677 struct obj_idx *pidx, int *unresolved)
2679 struct named_object *no;
2680 struct opcode_obj_rewrite *rw;
2683 /* Check if this opcode is candidate for rewrite */
2684 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2688 /* Need to rewrite. Save necessary fields */
2689 pidx->uidx = ti->uidx;
2690 pidx->type = ti->type;
2692 /* Try to find referenced kernel object */
2693 error = rw->find_byname(ch, ti, &no);
2698 * Report about unresolved object for automaic
2706 * Object is already exist.
2707 * Its subtype should match with expected value.
2709 if (ti->type != no->subtype)
2712 /* Bump refcount and update kidx. */
2714 rw->update(cmd, no->kidx);
2719 * Finds and bumps refcount for objects referenced by given @rule.
2720 * Auto-creates non-existing tables.
2721 * Fills in @oib array with userland/kernel indexes.
2723 * Returns 0 on success.
2726 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2727 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2729 struct obj_idx *pidx;
2731 int cmdlen, error, l, unresolved;
2741 /* Increase refcount on each existing referenced table. */
2742 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2743 cmdlen = F_LEN(cmd);
2746 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2750 * Compatibility stuff for old clients:
2751 * prepare to automaitcally create non-existing objects.
2753 if (unresolved != 0) {
2754 pidx->off = rule->cmd_len - l;
2760 /* Unref everything we have already done */
2761 unref_oib_objects(ch, rule->cmd, oib, pidx);
2762 IPFW_UH_WUNLOCK(ch);
2765 IPFW_UH_WUNLOCK(ch);
2767 /* Perform auto-creation for non-existing objects */
2769 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2771 /* Calculate real number of dynamic objects */
2772 ci->object_opcodes = (uint16_t)(pidx - oib);
2778 * Checks is opcode is referencing table of appropriate type.
2779 * Adds reference count for found table if true.
2780 * Rewrites user-supplied opcode values with kernel ones.
2782 * Returns 0 on success and appropriate error code otherwise.
2785 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2790 struct obj_idx *p, *pidx_first, *pidx_last;
2794 * Prepare an array for storing opcode indices.
2795 * Use stack allocation by default.
2797 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2799 pidx_first = ci->obuf;
2801 pidx_first = malloc(
2802 ci->object_opcodes * sizeof(struct obj_idx),
2803 M_IPFW, M_WAITOK | M_ZERO);
2807 memset(&ti, 0, sizeof(ti));
2809 /* Use set rule is assigned to. */
2810 ti.set = ci->krule->set;
2811 if (ci->ctlv != NULL) {
2812 ti.tlvs = (void *)(ci->ctlv + 1);
2813 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2816 /* Reference all used tables and other objects */
2817 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2821 * Note that ref_rule_objects() might have updated ci->object_opcodes
2822 * to reflect actual number of object opcodes.
2825 /* Perform rewrite of remaining opcodes */
2827 pidx_last = pidx_first + ci->object_opcodes;
2828 for (p = pidx_first; p < pidx_last; p++) {
2829 cmd = ci->krule->cmd + p->off;
2830 update_opcode_kidx(cmd, p->kidx);
2834 if (pidx_first != ci->obuf)
2835 free(pidx_first, M_IPFW);
2841 * Adds one or more rules to ipfw @chain.
2842 * Data layout (version 0)(current):
2846 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2847 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2852 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2853 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2856 * Rules in reply are modified to store their actual ruleset number.
2858 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2859 * according to their idx field and there has to be no duplicates.
2860 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2861 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2863 * Returns 0 on success.
2866 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2867 struct sockopt_data *sd)
2869 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2870 ipfw_obj_ntlv *ntlv;
2871 int clen, error, idx;
2872 uint32_t count, read;
2873 struct ip_fw_rule *r;
2874 struct rule_check_info rci, *ci, *cbuf;
2877 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2878 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2880 read = sizeof(ip_fw3_opheader);
2884 memset(&rci, 0, sizeof(struct rule_check_info));
2886 if (read + sizeof(*ctlv) > sd->valsize)
2889 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2890 clen = ctlv->head.length;
2891 /* Check size and alignment */
2892 if (clen > sd->valsize || clen < sizeof(*ctlv))
2894 if ((clen % sizeof(uint64_t)) != 0)
2898 * Some table names or other named objects.
2899 * Check for validness.
2901 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2902 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2907 * Ensure TLVs are sorted ascending and
2908 * there are no duplicates.
2911 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2913 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2916 error = ipfw_check_object_name_generic(ntlv->name);
2920 if (ntlv->idx <= idx)
2929 read += ctlv->head.length;
2930 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2933 if (read + sizeof(*ctlv) > sd->valsize)
2936 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2937 clen = ctlv->head.length;
2938 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2940 if ((clen % sizeof(uint64_t)) != 0)
2944 * TODO: Permit adding multiple rules at once
2946 if (ctlv->count != 1)
2949 clen -= sizeof(*ctlv);
2951 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2954 /* Allocate state for each rule or use stack */
2955 if (ctlv->count == 1) {
2956 memset(&rci, 0, sizeof(struct rule_check_info));
2959 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2964 * Check each rule for validness.
2965 * Ensure numbered rules are sorted ascending
2966 * and properly aligned
2969 r = (struct ip_fw_rule *)(ctlv + 1);
2973 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2974 if (rsize > clen || ctlv->count <= count) {
2980 error = check_ipfw_rule1(r, rsize, ci);
2985 if (r->rulenum != 0 && r->rulenum < idx) {
2986 printf("rulenum %d idx %d\n", r->rulenum, idx);
2992 ci->urule = (caddr_t)r;
2994 rsize = roundup2(rsize, sizeof(uint64_t));
2996 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3001 if (ctlv->count != count || error != 0) {
3008 read += ctlv->head.length;
3009 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3012 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3013 if (cbuf != NULL && cbuf != &rci)
3019 * Passed rules seems to be valid.
3020 * Allocate storage and try to add them to chain.
3022 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3023 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3024 ci->krule = ipfw_alloc_rule(chain, clen);
3028 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3029 /* Free allocate krules */
3030 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3031 free_rule(ci->krule);
3034 if (cbuf != NULL && cbuf != &rci)
3041 * Lists all sopts currently registered.
3042 * Data layout (v0)(current):
3043 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3044 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3046 * Returns 0 on success
3049 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3050 struct sockopt_data *sd)
3052 struct _ipfw_obj_lheader *olh;
3054 struct ipfw_sopt_handler *sh;
3055 uint32_t count, n, size;
3057 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3060 if (sd->valsize < olh->size)
3065 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3067 /* Fill in header regadless of buffer size */
3069 olh->objsize = sizeof(ipfw_sopt_info);
3071 if (size > olh->size) {
3078 for (n = 1; n <= count; n++) {
3079 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3080 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3081 sh = &ctl3_handlers[n];
3082 i->opcode = sh->opcode;
3083 i->version = sh->version;
3084 i->refcnt = sh->refcnt;
3092 * Compares two opcodes.
3093 * Used both in qsort() and bsearch().
3095 * Returns 0 if match is found.
3098 compare_opcodes(const void *_a, const void *_b)
3100 const struct opcode_obj_rewrite *a, *b;
3102 a = (const struct opcode_obj_rewrite *)_a;
3103 b = (const struct opcode_obj_rewrite *)_b;
3105 if (a->opcode < b->opcode)
3107 else if (a->opcode > b->opcode)
3114 * XXX: Rewrite bsearch()
3117 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3118 struct opcode_obj_rewrite **phi)
3120 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3122 memset(&h, 0, sizeof(h));
3125 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3126 ctl3_rsize, sizeof(h), compare_opcodes);
3130 /* Find the first element matching the same opcode */
3132 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3135 /* Find the last element matching the same opcode */
3137 ctl3_max = ctl3_rewriters + ctl3_rsize;
3138 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3148 * Finds opcode object rewriter based on @code.
3150 * Returns pointer to handler or NULL.
3152 static struct opcode_obj_rewrite *
3153 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3155 struct opcode_obj_rewrite *rw, *lo, *hi;
3159 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3162 for (rw = lo; rw <= hi; rw++) {
3163 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3175 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3178 if (find_op_rw(cmd, puidx, NULL) == NULL)
3184 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3186 struct opcode_obj_rewrite *rw;
3188 rw = find_op_rw(cmd, NULL, NULL);
3189 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3190 rw->update(cmd, idx);
3194 ipfw_init_obj_rewriter()
3197 ctl3_rewriters = NULL;
3202 ipfw_destroy_obj_rewriter()
3205 if (ctl3_rewriters != NULL)
3206 free(ctl3_rewriters, M_IPFW);
3207 ctl3_rewriters = NULL;
3212 * Adds one or more opcode object rewrite handlers to the global array.
3213 * Function may sleep.
3216 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3219 struct opcode_obj_rewrite *tmp;
3224 sz = ctl3_rsize + count;
3226 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3228 if (ctl3_rsize + count <= sz)
3235 /* Merge old & new arrays */
3236 sz = ctl3_rsize + count;
3237 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3238 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3239 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3240 /* Switch new and free old */
3241 if (ctl3_rewriters != NULL)
3242 free(ctl3_rewriters, M_IPFW);
3243 ctl3_rewriters = tmp;
3250 * Removes one or more object rewrite handlers from the global array.
3253 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3256 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3261 for (i = 0; i < count; i++) {
3262 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3265 for (ktmp = lo; ktmp <= hi; ktmp++) {
3266 if (ktmp->classifier != rw[i].classifier)
3269 ctl3_max = ctl3_rewriters + ctl3_rsize;
3270 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3271 memmove(ktmp, ktmp + 1, sz);
3278 if (ctl3_rsize == 0) {
3279 if (ctl3_rewriters != NULL)
3280 free(ctl3_rewriters, M_IPFW);
3281 ctl3_rewriters = NULL;
3290 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3291 struct named_object *no, void *arg)
3293 struct sockopt_data *sd;
3294 ipfw_obj_ntlv *ntlv;
3296 sd = (struct sockopt_data *)arg;
3297 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3300 ipfw_export_obj_ntlv(no, ntlv);
3305 * Lists all service objects.
3306 * Data layout (v0)(current):
3307 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3308 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3309 * Returns 0 on success
3312 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3313 struct sockopt_data *sd)
3315 ipfw_obj_lheader *hdr;
3318 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3322 IPFW_UH_RLOCK(chain);
3323 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3324 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3325 if (sd->valsize < hdr->size) {
3326 IPFW_UH_RUNLOCK(chain);
3330 hdr->objsize = sizeof(ipfw_obj_ntlv);
3332 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3333 export_objhash_ntlv_internal, sd);
3334 IPFW_UH_RUNLOCK(chain);
3339 * Compares two sopt handlers (code, version and handler ptr).
3340 * Used both as qsort() and bsearch().
3341 * Does not compare handler for latter case.
3343 * Returns 0 if match is found.
3346 compare_sh(const void *_a, const void *_b)
3348 const struct ipfw_sopt_handler *a, *b;
3350 a = (const struct ipfw_sopt_handler *)_a;
3351 b = (const struct ipfw_sopt_handler *)_b;
3353 if (a->opcode < b->opcode)
3355 else if (a->opcode > b->opcode)
3358 if (a->version < b->version)
3360 else if (a->version > b->version)
3363 /* bsearch helper */
3364 if (a->handler == NULL)
3367 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3369 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3376 * Finds sopt handler based on @code and @version.
3378 * Returns pointer to handler or NULL.
3380 static struct ipfw_sopt_handler *
3381 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3383 struct ipfw_sopt_handler *sh, h;
3385 memset(&h, 0, sizeof(h));
3387 h.version = version;
3388 h.handler = handler;
3390 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3391 ctl3_hsize, sizeof(h), compare_sh);
3397 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3399 struct ipfw_sopt_handler *sh;
3402 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3404 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3410 /* Copy handler data to requested buffer */
3418 find_unref_sh(struct ipfw_sopt_handler *psh)
3420 struct ipfw_sopt_handler *sh;
3423 sh = find_sh(psh->opcode, psh->version, NULL);
3424 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3431 ipfw_init_sopt_handler()
3435 IPFW_ADD_SOPT_HANDLER(1, scodes);
3439 ipfw_destroy_sopt_handler()
3442 IPFW_DEL_SOPT_HANDLER(1, scodes);
3443 CTL3_LOCK_DESTROY();
3447 * Adds one or more sockopt handlers to the global array.
3448 * Function may sleep.
3451 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3454 struct ipfw_sopt_handler *tmp;
3459 sz = ctl3_hsize + count;
3461 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3463 if (ctl3_hsize + count <= sz)
3470 /* Merge old & new arrays */
3471 sz = ctl3_hsize + count;
3472 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3473 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3474 qsort(tmp, sz, sizeof(*sh), compare_sh);
3475 /* Switch new and free old */
3476 if (ctl3_handlers != NULL)
3477 free(ctl3_handlers, M_IPFW);
3478 ctl3_handlers = tmp;
3486 * Removes one or more sockopt handlers from the global array.
3489 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3492 struct ipfw_sopt_handler *tmp, *h;
3497 for (i = 0; i < count; i++) {
3499 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3503 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3504 memmove(h, h + 1, sz);
3508 if (ctl3_hsize == 0) {
3509 if (ctl3_handlers != NULL)
3510 free(ctl3_handlers, M_IPFW);
3511 ctl3_handlers = NULL;
3522 * Writes data accumulated in @sd to sockopt buffer.
3523 * Zeroes internal @sd buffer.
3526 ipfw_flush_sopt_data(struct sockopt_data *sd)
3528 struct sockopt *sopt;
3538 if (sopt->sopt_dir == SOPT_GET) {
3539 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3544 memset(sd->kbuf, 0, sd->ksize);
3547 if (sd->ktotal + sd->ksize < sd->valsize)
3548 sd->kavail = sd->ksize;
3550 sd->kavail = sd->valsize - sd->ktotal;
3552 /* Update sopt buffer data */
3553 sopt->sopt_valsize = sd->ktotal;
3554 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3560 * Ensures that @sd buffer has contiguous @neeeded number of
3563 * Returns pointer to requested space or NULL.
3566 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3571 if (sd->kavail < needed) {
3573 * Flush data and try another time.
3575 error = ipfw_flush_sopt_data(sd);
3577 if (sd->kavail < needed || error != 0)
3581 addr = sd->kbuf + sd->koff;
3583 sd->kavail -= needed;
3588 * Requests @needed contiguous bytes from @sd buffer.
3589 * Function is used to notify subsystem that we are
3590 * interesed in first @needed bytes (request header)
3591 * and the rest buffer can be safely zeroed.
3593 * Returns pointer to requested space or NULL.
3596 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3600 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3604 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3610 * New sockopt handler.
3613 ipfw_ctl3(struct sockopt *sopt)
3616 size_t size, valsize;
3617 struct ip_fw_chain *chain;
3619 struct sockopt_data sdata;
3620 struct ipfw_sopt_handler h;
3621 ip_fw3_opheader *op3 = NULL;
3623 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3627 if (sopt->sopt_name != IP_FW3)
3628 return (ipfw_ctl(sopt));
3630 chain = &V_layer3_chain;
3633 /* Save original valsize before it is altered via sooptcopyin() */
3634 valsize = sopt->sopt_valsize;
3635 memset(&sdata, 0, sizeof(sdata));
3636 /* Read op3 header first to determine actual operation */
3637 op3 = (ip_fw3_opheader *)xbuf;
3638 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3641 sopt->sopt_valsize = valsize;
3644 * Find and reference command.
3646 error = find_ref_sh(op3->opcode, op3->version, &h);
3651 * Disallow modifications in really-really secure mode, but still allow
3652 * the logging counters to be reset.
3654 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3655 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3663 * Fill in sockopt_data structure that may be useful for
3664 * IP_FW3 get requests.
3667 if (valsize <= sizeof(xbuf)) {
3668 /* use on-stack buffer */
3670 sdata.ksize = sizeof(xbuf);
3671 sdata.kavail = valsize;
3675 * Determine opcode type/buffer size:
3676 * allocate sliding-window buf for data export or
3677 * contiguous buffer for special ops.
3679 if ((h.dir & HDIR_SET) != 0) {
3680 /* Set request. Allocate contigous buffer. */
3681 if (valsize > CTL3_LARGEBUF) {
3688 /* Get request. Allocate sliding window buffer */
3689 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3691 if (size < valsize) {
3692 /* We have to wire user buffer */
3693 error = vslock(sopt->sopt_val, valsize);
3700 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3702 sdata.kavail = size;
3706 sdata.sopt_val = sopt->sopt_val;
3707 sdata.valsize = valsize;
3710 * Copy either all request (if valsize < bsize_max)
3711 * or first bsize_max bytes to guarantee most consumers
3712 * that all necessary data has been copied).
3713 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3715 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3716 sizeof(ip_fw3_opheader))) != 0)
3718 op3 = (ip_fw3_opheader *)sdata.kbuf;
3720 /* Finally, run handler */
3721 error = h.handler(chain, op3, &sdata);
3724 /* Flush state and free buffers */
3726 error = ipfw_flush_sopt_data(&sdata);
3728 ipfw_flush_sopt_data(&sdata);
3731 vsunlock(sdata.sopt_val, valsize);
3733 /* Restore original pointer and set number of bytes written */
3734 sopt->sopt_val = sdata.sopt_val;
3735 sopt->sopt_valsize = sdata.ktotal;
3736 if (sdata.kbuf != xbuf)
3737 free(sdata.kbuf, M_TEMP);
3743 * {set|get}sockopt parser.
3746 ipfw_ctl(struct sockopt *sopt)
3748 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3750 size_t size, valsize;
3752 struct ip_fw_rule0 *rule;
3753 struct ip_fw_chain *chain;
3754 u_int32_t rulenum[2];
3756 struct rule_check_info ci;
3759 chain = &V_layer3_chain;
3762 /* Save original valsize before it is altered via sooptcopyin() */
3763 valsize = sopt->sopt_valsize;
3764 opt = sopt->sopt_name;
3767 * Disallow modifications in really-really secure mode, but still allow
3768 * the logging counters to be reset.
3770 if (opt == IP_FW_ADD ||
3771 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3772 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3780 * pass up a copy of the current rules. Static rules
3781 * come first (the last of which has number IPFW_DEFAULT_RULE),
3782 * followed by a possibly empty list of dynamic rule.
3783 * The last dynamic rule has NULL in the "next" field.
3785 * Note that the calculated size is used to bound the
3786 * amount of data returned to the user. The rule set may
3787 * change between calculating the size and returning the
3788 * data in which case we'll just return what fits.
3793 size = chain->static_len;
3794 size += ipfw_dyn_len();
3795 if (size >= sopt->sopt_valsize)
3797 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3798 IPFW_UH_RLOCK(chain);
3799 /* check again how much space we need */
3800 want = chain->static_len + ipfw_dyn_len();
3802 len = ipfw_getrules(chain, buf, size);
3803 IPFW_UH_RUNLOCK(chain);
3805 error = sooptcopyout(sopt, buf, len);
3813 /* locking is done within del_entry() */
3814 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3818 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3819 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3820 sizeof(struct ip_fw7) );
3822 memset(&ci, 0, sizeof(struct rule_check_info));
3825 * If the size of commands equals RULESIZE7 then we assume
3826 * a FreeBSD7.2 binary is talking to us (set is7=1).
3827 * is7 is persistent so the next 'ipfw list' command
3828 * will use this format.
3829 * NOTE: If wrong version is guessed (this can happen if
3830 * the first ipfw command is 'ipfw [pipe] list')
3831 * the ipfw binary may crash or loop infinitly...
3833 size = sopt->sopt_valsize;
3834 if (size == RULESIZE7(rule)) {
3836 error = convert_rule_to_8(rule);
3841 size = RULESIZE(rule);
3845 error = check_ipfw_rule0(rule, size, &ci);
3847 /* locking is done within add_rule() */
3848 struct ip_fw *krule;
3849 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3850 ci.urule = (caddr_t)rule;
3853 error = commit_rules(chain, &ci, 1);
3855 free_rule(ci.krule);
3856 else if (sopt->sopt_dir == SOPT_GET) {
3858 error = convert_rule_to_7(rule);
3859 size = RULESIZE7(rule);
3865 error = sooptcopyout(sopt, rule, size);
3873 * IP_FW_DEL is used for deleting single rules or sets,
3874 * and (ab)used to atomically manipulate sets. Argument size
3875 * is used to distinguish between the two:
3877 * delete single rule or set of rules,
3878 * or reassign rules (or sets) to a different set.
3879 * 2*sizeof(u_int32_t)
3880 * atomic disable/enable sets.
3881 * first u_int32_t contains sets to be disabled,
3882 * second u_int32_t contains sets to be enabled.
3884 error = sooptcopyin(sopt, rulenum,
3885 2*sizeof(u_int32_t), sizeof(u_int32_t));
3888 size = sopt->sopt_valsize;
3889 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3890 /* delete or reassign, locking done in del_entry() */
3891 error = del_entry(chain, rulenum[0]);
3892 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3893 IPFW_UH_WLOCK(chain);
3895 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3896 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3897 IPFW_UH_WUNLOCK(chain);
3903 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3905 if (sopt->sopt_val != 0) {
3906 error = sooptcopyin(sopt, rulenum,
3907 sizeof(u_int32_t), sizeof(u_int32_t));
3911 error = zero_entry(chain, rulenum[0],
3912 sopt->sopt_name == IP_FW_RESETLOG);
3915 /*--- TABLE opcodes ---*/
3916 case IP_FW_TABLE_ADD:
3917 case IP_FW_TABLE_DEL:
3919 ipfw_table_entry ent;
3920 struct tentry_info tei;
3922 struct table_value v;
3924 error = sooptcopyin(sopt, &ent,
3925 sizeof(ent), sizeof(ent));
3929 memset(&tei, 0, sizeof(tei));
3930 tei.paddr = &ent.addr;
3931 tei.subtype = AF_INET;
3932 tei.masklen = ent.masklen;
3933 ipfw_import_table_value_legacy(ent.value, &v);
3935 memset(&ti, 0, sizeof(ti));
3937 ti.type = IPFW_TABLE_CIDR;
3939 error = (opt == IP_FW_TABLE_ADD) ?
3940 add_table_entry(chain, &ti, &tei, 0, 1) :
3941 del_table_entry(chain, &ti, &tei, 0, 1);
3946 case IP_FW_TABLE_FLUSH:
3951 error = sooptcopyin(sopt, &tbl,
3952 sizeof(tbl), sizeof(tbl));
3955 memset(&ti, 0, sizeof(ti));
3957 error = flush_table(chain, &ti);
3961 case IP_FW_TABLE_GETSIZE:
3966 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3969 memset(&ti, 0, sizeof(ti));
3972 error = ipfw_count_table(chain, &ti, &cnt);
3973 IPFW_RUNLOCK(chain);
3976 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3980 case IP_FW_TABLE_LIST:
3985 if (sopt->sopt_valsize < sizeof(*tbl)) {
3989 size = sopt->sopt_valsize;
3990 tbl = malloc(size, M_TEMP, M_WAITOK);
3991 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3996 tbl->size = (size - sizeof(*tbl)) /
3997 sizeof(ipfw_table_entry);
3998 memset(&ti, 0, sizeof(ti));
4001 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4002 IPFW_RUNLOCK(chain);
4007 error = sooptcopyout(sopt, tbl, size);
4012 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4014 if (IPFW_NAT_LOADED)
4015 error = ipfw_nat_cfg_ptr(sopt);
4017 printf("IP_FW_NAT_CFG: %s\n",
4018 "ipfw_nat not present, please load it");
4024 if (IPFW_NAT_LOADED)
4025 error = ipfw_nat_del_ptr(sopt);
4027 printf("IP_FW_NAT_DEL: %s\n",
4028 "ipfw_nat not present, please load it");
4033 case IP_FW_NAT_GET_CONFIG:
4034 if (IPFW_NAT_LOADED)
4035 error = ipfw_nat_get_cfg_ptr(sopt);
4037 printf("IP_FW_NAT_GET_CFG: %s\n",
4038 "ipfw_nat not present, please load it");
4043 case IP_FW_NAT_GET_LOG:
4044 if (IPFW_NAT_LOADED)
4045 error = ipfw_nat_get_log_ptr(sopt);
4047 printf("IP_FW_NAT_GET_LOG: %s\n",
4048 "ipfw_nat not present, please load it");
4054 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4061 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4063 /* Functions to convert rules 7.2 <==> 8.0 */
4065 convert_rule_to_7(struct ip_fw_rule0 *rule)
4067 /* Used to modify original rule */
4068 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4069 /* copy of original rule, version 8 */
4070 struct ip_fw_rule0 *tmp;
4072 /* Used to copy commands */
4073 ipfw_insn *ccmd, *dst;
4074 int ll = 0, ccmdlen = 0;
4076 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4078 return 1; //XXX error
4080 bcopy(rule, tmp, RULE_MAXSIZE);
4083 //rule7->_pad = tmp->_pad;
4084 rule7->set = tmp->set;
4085 rule7->rulenum = tmp->rulenum;
4086 rule7->cmd_len = tmp->cmd_len;
4087 rule7->act_ofs = tmp->act_ofs;
4088 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4089 rule7->cmd_len = tmp->cmd_len;
4090 rule7->pcnt = tmp->pcnt;
4091 rule7->bcnt = tmp->bcnt;
4092 rule7->timestamp = tmp->timestamp;
4095 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4096 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4097 ccmdlen = F_LEN(ccmd);
4099 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4101 if (dst->opcode > O_NAT)
4102 /* O_REASS doesn't exists in 7.2 version, so
4103 * decrement opcode if it is after O_REASS
4108 printf("ipfw: opcode %d size truncated\n",
4119 convert_rule_to_8(struct ip_fw_rule0 *rule)
4121 /* Used to modify original rule */
4122 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4124 /* Used to copy commands */
4125 ipfw_insn *ccmd, *dst;
4126 int ll = 0, ccmdlen = 0;
4128 /* Copy of original rule */
4129 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4131 return 1; //XXX error
4134 bcopy(rule7, tmp, RULE_MAXSIZE);
4136 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4137 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4138 ccmdlen = F_LEN(ccmd);
4140 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4142 if (dst->opcode > O_NAT)
4143 /* O_REASS doesn't exists in 7.2 version, so
4144 * increment opcode if it is after O_REASS
4149 printf("ipfw: opcode %d size truncated\n",
4155 rule->_pad = tmp->_pad;
4156 rule->set = tmp->set;
4157 rule->rulenum = tmp->rulenum;
4158 rule->cmd_len = tmp->cmd_len;
4159 rule->act_ofs = tmp->act_ofs;
4160 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4161 rule->cmd_len = tmp->cmd_len;
4162 rule->id = 0; /* XXX see if is ok = 0 */
4163 rule->pcnt = tmp->pcnt;
4164 rule->bcnt = tmp->bcnt;
4165 rule->timestamp = tmp->timestamp;
4177 ipfw_init_srv(struct ip_fw_chain *ch)
4180 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4181 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4182 M_IPFW, M_WAITOK | M_ZERO);
4186 ipfw_destroy_srv(struct ip_fw_chain *ch)
4189 free(ch->srvstate, M_IPFW);
4190 ipfw_objhash_destroy(ch->srvmap);
4194 * Allocate new bitmask which can be used to enlarge/shrink
4195 * named instance index.
4198 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4204 KASSERT((items % BLOCK_ITEMS) == 0,
4205 ("bitmask size needs to power of 2 and greater or equal to %zu",
4208 max_blocks = items / BLOCK_ITEMS;
4210 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4211 /* Mark all as free */
4212 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4213 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4216 *pblocks = max_blocks;
4220 * Copy current bitmask index to new one.
4223 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4225 int old_blocks, new_blocks;
4226 u_long *old_idx, *new_idx;
4229 old_idx = ni->idx_mask;
4230 old_blocks = ni->max_blocks;
4232 new_blocks = *blocks;
4234 for (i = 0; i < IPFW_MAX_SETS; i++) {
4235 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4236 old_blocks * sizeof(u_long));
4241 * Swaps current @ni index with new one.
4244 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4249 old_idx = ni->idx_mask;
4250 old_blocks = ni->max_blocks;
4252 ni->idx_mask = *idx;
4253 ni->max_blocks = *blocks;
4255 /* Save old values */
4257 *blocks = old_blocks;
4261 ipfw_objhash_bitmap_free(void *idx, int blocks)
4268 * Creates named hash instance.
4269 * Must be called without holding any locks.
4270 * Return pointer to new instance.
4272 struct namedobj_instance *
4273 ipfw_objhash_create(uint32_t items)
4275 struct namedobj_instance *ni;
4279 size = sizeof(struct namedobj_instance) +
4280 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4281 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4283 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4284 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4285 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4287 ni->names = (struct namedobjects_head *)(ni +1);
4288 ni->values = &ni->names[ni->nn_size];
4290 for (i = 0; i < ni->nn_size; i++)
4291 TAILQ_INIT(&ni->names[i]);
4293 for (i = 0; i < ni->nv_size; i++)
4294 TAILQ_INIT(&ni->values[i]);
4296 /* Set default hashing/comparison functions */
4297 ni->hash_f = objhash_hash_name;
4298 ni->cmp_f = objhash_cmp_name;
4300 /* Allocate bitmask separately due to possible resize */
4301 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4307 ipfw_objhash_destroy(struct namedobj_instance *ni)
4310 free(ni->idx_mask, M_IPFW);
4315 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4316 objhash_cmp_f *cmp_f)
4319 ni->hash_f = hash_f;
4324 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4327 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4331 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4334 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4341 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4345 v = val % (ni->nv_size - 1);
4350 struct named_object *
4351 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4353 struct named_object *no;
4356 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4358 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4359 if (ni->cmp_f(no, name, set) == 0)
4367 * Find named object by @uid.
4368 * Check @tlvs for valid data inside.
4370 * Returns pointer to found TLV or NULL.
4373 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4375 ipfw_obj_ntlv *ntlv;
4379 pa = (uintptr_t)tlvs;
4382 for (; pa < pe; pa += l) {
4383 ntlv = (ipfw_obj_ntlv *)pa;
4384 l = ntlv->head.length;
4386 if (l != sizeof(*ntlv))
4389 if (ntlv->idx != uidx)
4392 * When userland has specified zero TLV type, do
4393 * not compare it with eltv. In some cases userland
4394 * doesn't know what type should it have. Use only
4395 * uidx and name for search named_object.
4397 if (ntlv->head.type != 0 &&
4398 ntlv->head.type != (uint16_t)etlv)
4401 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4411 * Finds object config based on either legacy index
4413 * Note @ti structure contains unchecked data from userland.
4415 * Returns 0 in success and fills in @pno with found config
4418 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4419 uint32_t etlv, struct named_object **pno)
4422 ipfw_obj_ntlv *ntlv;
4425 if (ti->tlvs == NULL)
4428 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4434 * Use set provided by @ti instead of @ntlv one.
4435 * This is needed due to different sets behavior
4436 * controlled by V_fw_tables_sets.
4439 *pno = ipfw_objhash_lookup_name(ni, set, name);
4446 * Find named object by name, considering also its TLV type.
4448 struct named_object *
4449 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4450 uint32_t type, const char *name)
4452 struct named_object *no;
4455 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4457 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4458 if (ni->cmp_f(no, name, set) == 0 &&
4459 no->etlv == (uint16_t)type)
4466 struct named_object *
4467 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4469 struct named_object *no;
4472 hash = objhash_hash_idx(ni, kidx);
4474 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4475 if (no->kidx == kidx)
4483 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4484 struct named_object *b)
4487 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4494 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4498 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4499 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4501 hash = objhash_hash_idx(ni, no->kidx);
4502 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4508 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4512 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4513 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4515 hash = objhash_hash_idx(ni, no->kidx);
4516 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4522 ipfw_objhash_count(struct namedobj_instance *ni)
4529 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4531 struct named_object *no;
4536 for (i = 0; i < ni->nn_size; i++) {
4537 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4538 if (no->etlv == type)
4546 * Runs @func for each found named object.
4547 * It is safe to delete objects from callback
4550 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4552 struct named_object *no, *no_tmp;
4555 for (i = 0; i < ni->nn_size; i++) {
4556 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4557 ret = f(ni, no, arg);
4566 * Runs @f for each found named object with type @type.
4567 * It is safe to delete objects from callback
4570 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4571 void *arg, uint16_t type)
4573 struct named_object *no, *no_tmp;
4576 for (i = 0; i < ni->nn_size; i++) {
4577 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4578 if (no->etlv != type)
4580 ret = f(ni, no, arg);
4589 * Removes index from given set.
4590 * Returns 0 on success.
4593 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4598 i = idx / BLOCK_ITEMS;
4599 v = idx % BLOCK_ITEMS;
4601 if (i >= ni->max_blocks)
4604 mask = &ni->idx_mask[i];
4606 if ((*mask & ((u_long)1 << v)) != 0)
4610 *mask |= (u_long)1 << v;
4612 /* Update free offset */
4613 if (ni->free_off[0] > i)
4614 ni->free_off[0] = i;
4620 * Allocate new index in given instance and stores in in @pidx.
4621 * Returns 0 on success.
4624 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4626 struct namedobj_instance *ni;
4630 ni = (struct namedobj_instance *)n;
4632 off = ni->free_off[0];
4633 mask = &ni->idx_mask[off];
4635 for (i = off; i < ni->max_blocks; i++, mask++) {
4636 if ((v = ffsl(*mask)) == 0)
4640 *mask &= ~ ((u_long)1 << (v - 1));
4642 ni->free_off[0] = i;
4644 v = BLOCK_ITEMS * i + v - 1;