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 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
165 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
166 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
167 struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
168 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
169 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
170 struct obj_idx *oib, struct obj_idx *end);
171 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
172 struct sockopt_data *sd);
175 * Opcode object rewriter variables
177 struct opcode_obj_rewrite *ctl3_rewriters;
178 static size_t ctl3_rsize;
181 * static variables followed by global ones
184 VNET_DEFINE_STATIC(uma_zone_t, ipfw_cntr_zone);
185 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
191 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
192 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
193 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
197 ipfw_destroy_counters()
200 uma_zdestroy(V_ipfw_cntr_zone);
204 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
208 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
209 rule->cntr = uma_zalloc_pcpu(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
216 ipfw_free_rule(struct ip_fw *rule)
220 * We don't release refcnt here, since this function
221 * can be called without any locks held. The caller
222 * must release reference under IPFW_UH_WLOCK, and then
223 * call this function if refcount becomes 1.
225 if (rule->refcnt > 1)
227 uma_zfree_pcpu(V_ipfw_cntr_zone, rule->cntr);
233 * Find the smallest rule >= key, id.
234 * We could use bsearch but it is so simple that we code it directly
237 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
242 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
245 if (r->rulenum < key)
246 lo = i + 1; /* continue from the next one */
247 else if (r->rulenum > key)
248 hi = i; /* this might be good */
250 lo = i + 1; /* continue from the next one */
251 else /* r->id >= id */
252 hi = i; /* this might be good */
258 * Builds skipto cache on rule set @map.
261 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
266 IPFW_UH_WLOCK_ASSERT(chain);
269 rulenum = map[mi]->rulenum;
270 smap = chain->idxmap_back;
275 for (i = 0; i < 65536; i++) {
277 /* Use the same rule index until i < rulenum */
278 if (i != rulenum || i == 65535)
280 /* Find next rule with num > i */
281 rulenum = map[++mi]->rulenum;
283 rulenum = map[++mi]->rulenum;
288 * Swaps prepared (backup) index with current one.
291 swap_skipto_cache(struct ip_fw_chain *chain)
295 IPFW_UH_WLOCK_ASSERT(chain);
296 IPFW_WLOCK_ASSERT(chain);
299 chain->idxmap = chain->idxmap_back;
300 chain->idxmap_back = map;
304 * Allocate and initialize skipto cache.
307 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
309 int *idxmap, *idxmap_back;
311 idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
312 idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
315 * Note we may be called at any time after initialization,
316 * for example, on first skipto rule, so we need to
317 * provide valid chain->idxmap on return
320 IPFW_UH_WLOCK(chain);
321 if (chain->idxmap != NULL) {
322 IPFW_UH_WUNLOCK(chain);
323 free(idxmap, M_IPFW);
324 free(idxmap_back, M_IPFW);
328 /* Set backup pointer first to permit building cache */
329 chain->idxmap_back = idxmap_back;
330 update_skipto_cache(chain, chain->map);
332 /* It is now safe to set chain->idxmap ptr */
333 chain->idxmap = idxmap;
334 swap_skipto_cache(chain);
336 IPFW_UH_WUNLOCK(chain);
340 * Destroys skipto cache.
343 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
346 if (chain->idxmap != NULL)
347 free(chain->idxmap, M_IPFW);
348 if (chain->idxmap != NULL)
349 free(chain->idxmap_back, M_IPFW);
354 * allocate a new map, returns the chain locked. extra is the number
355 * of entries to add or delete.
357 static struct ip_fw **
358 get_map(struct ip_fw_chain *chain, int extra, int locked)
365 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
367 i = chain->n_rules + extra;
368 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
370 printf("%s: cannot allocate map\n", __FUNCTION__);
374 IPFW_UH_WLOCK(chain);
375 if (i >= chain->n_rules + extra) /* good */
377 /* otherwise we lost the race, free and retry */
379 IPFW_UH_WUNLOCK(chain);
385 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
387 static struct ip_fw **
388 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
390 struct ip_fw **old_map;
394 chain->n_rules = new_len;
395 old_map = chain->map;
396 chain->map = new_map;
397 swap_skipto_cache(chain);
404 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
406 struct timeval boottime;
408 cntr->size = sizeof(*cntr);
410 if (krule->cntr != NULL) {
411 cntr->pcnt = counter_u64_fetch(krule->cntr);
412 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
413 cntr->timestamp = krule->timestamp;
415 if (cntr->timestamp > 0) {
416 getboottime(&boottime);
417 cntr->timestamp += boottime.tv_sec;
422 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
424 struct timeval boottime;
426 if (krule->cntr != NULL) {
427 cntr->pcnt = counter_u64_fetch(krule->cntr);
428 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
429 cntr->timestamp = krule->timestamp;
431 if (cntr->timestamp > 0) {
432 getboottime(&boottime);
433 cntr->timestamp += boottime.tv_sec;
438 * Copies rule @urule from v1 userland format (current).
440 * Assume @krule is zeroed.
443 import_rule1(struct rule_check_info *ci)
445 struct ip_fw_rule *urule;
448 urule = (struct ip_fw_rule *)ci->urule;
449 krule = (struct ip_fw *)ci->krule;
452 krule->act_ofs = urule->act_ofs;
453 krule->cmd_len = urule->cmd_len;
454 krule->rulenum = urule->rulenum;
455 krule->set = urule->set;
456 krule->flags = urule->flags;
458 /* Save rulenum offset */
459 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
462 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
466 * Export rule into v1 format (Current).
468 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
470 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
472 * Assume @data is zeroed.
475 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
477 struct ip_fw_bcounter *cntr;
478 struct ip_fw_rule *urule;
481 /* Fill in TLV header */
482 tlv = (ipfw_obj_tlv *)data;
483 tlv->type = IPFW_TLV_RULE_ENT;
488 cntr = (struct ip_fw_bcounter *)(tlv + 1);
489 urule = (struct ip_fw_rule *)(cntr + 1);
490 export_cntr1_base(krule, cntr);
492 urule = (struct ip_fw_rule *)(tlv + 1);
495 urule->act_ofs = krule->act_ofs;
496 urule->cmd_len = krule->cmd_len;
497 urule->rulenum = krule->rulenum;
498 urule->set = krule->set;
499 urule->flags = krule->flags;
500 urule->id = krule->id;
503 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
508 * Copies rule @urule from FreeBSD8 userland format (v0)
510 * Assume @krule is zeroed.
513 import_rule0(struct rule_check_info *ci)
515 struct ip_fw_rule0 *urule;
519 ipfw_insn_limit *lcmd;
522 urule = (struct ip_fw_rule0 *)ci->urule;
523 krule = (struct ip_fw *)ci->krule;
526 krule->act_ofs = urule->act_ofs;
527 krule->cmd_len = urule->cmd_len;
528 krule->rulenum = urule->rulenum;
529 krule->set = urule->set;
530 if ((urule->_pad & 1) != 0)
531 krule->flags |= IPFW_RULE_NOOPT;
533 /* Save rulenum offset */
534 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
537 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
541 * 1) convert tablearg value from 65535 to 0
542 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
544 * 3) convert table number in iface opcodes to u16
545 * 4) convert old `nat global` into new 65535
551 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
554 switch (cmd->opcode) {
555 /* Opcodes supporting tablearg */
567 if (cmd->arg1 == IP_FW_TABLEARG)
568 cmd->arg1 = IP_FW_TARG;
569 else if (cmd->arg1 == 0)
570 cmd->arg1 = IP_FW_NAT44_GLOBAL;
574 if (cmd->arg1 == IP_FW_TABLEARG)
575 cmd->arg1 = IP_FW_TARG;
580 lcmd = (ipfw_insn_limit *)cmd;
581 if (lcmd->conn_limit == IP_FW_TABLEARG)
582 lcmd->conn_limit = IP_FW_TARG;
584 /* Interface tables */
588 /* Interface table, possibly */
589 cmdif = (ipfw_insn_if *)cmd;
590 if (cmdif->name[0] != '\1')
593 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
600 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
603 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
607 ipfw_insn_limit *lcmd;
611 memset(urule, 0, len);
612 urule->act_ofs = krule->act_ofs;
613 urule->cmd_len = krule->cmd_len;
614 urule->rulenum = krule->rulenum;
615 urule->set = krule->set;
616 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
620 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
622 /* Export counters */
623 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
627 * 1) convert tablearg value from 0 to 65535
628 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
629 * 3) convert table number in iface opcodes to int
635 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
638 switch (cmd->opcode) {
639 /* Opcodes supporting tablearg */
651 if (cmd->arg1 == IP_FW_TARG)
652 cmd->arg1 = IP_FW_TABLEARG;
653 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
658 if (cmd->arg1 == IP_FW_TARG)
659 cmd->arg1 = IP_FW_TABLEARG;
661 cmd->arg1 &= ~0x8000;
664 lcmd = (ipfw_insn_limit *)cmd;
665 if (lcmd->conn_limit == IP_FW_TARG)
666 lcmd->conn_limit = IP_FW_TABLEARG;
668 /* Interface tables */
672 /* Interface table, possibly */
673 cmdif = (ipfw_insn_if *)cmd;
674 if (cmdif->name[0] != '\1')
677 cmdif->p.glob = cmdif->p.kidx;
684 * Add new rule(s) to the list possibly creating rule number for each.
685 * Update the rule_number in the input struct so the caller knows it as well.
686 * Must be called without IPFW_UH held
689 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
691 int error, i, insert_before, tcount;
692 uint16_t rulenum, *pnum;
693 struct rule_check_info *ci;
695 struct ip_fw **map; /* the new array of pointers */
697 /* Check if we need to do table/obj index remap */
699 for (ci = rci, i = 0; i < count; ci++, i++) {
700 if (ci->object_opcodes == 0)
704 * Rule has some object opcodes.
705 * We need to find (and create non-existing)
706 * kernel objects, and reference existing ones.
708 error = rewrite_rule_uidx(chain, ci);
712 * rewrite failed, state for current rule
713 * has been reverted. Check if we need to
719 * We have some more table rules
720 * we need to rollback.
723 IPFW_UH_WLOCK(chain);
726 if (ci->object_opcodes == 0)
728 unref_rule_objects(chain,ci->krule);
731 IPFW_UH_WUNLOCK(chain);
741 /* get_map returns with IPFW_UH_WLOCK if successful */
742 map = get_map(chain, count, 0 /* not locked */);
746 IPFW_UH_WLOCK(chain);
747 for (ci = rci, i = 0; i < count; ci++, i++) {
748 if (ci->object_opcodes == 0)
751 unref_rule_objects(chain, ci->krule);
753 IPFW_UH_WUNLOCK(chain);
759 if (V_autoinc_step < 1)
761 else if (V_autoinc_step > 1000)
762 V_autoinc_step = 1000;
764 /* FIXME: Handle count > 1 */
767 rulenum = krule->rulenum;
769 /* find the insertion point, we will insert before */
770 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
771 i = ipfw_find_rule(chain, insert_before, 0);
772 /* duplicate first part */
774 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
776 /* duplicate remaining part, we always have the default rule */
777 bcopy(chain->map + i, map + i + 1,
778 sizeof(struct ip_fw *) *(chain->n_rules - i));
780 /* Compute rule number and write it back */
781 rulenum = i > 0 ? map[i-1]->rulenum : 0;
782 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
783 rulenum += V_autoinc_step;
784 krule->rulenum = rulenum;
785 /* Save number to userland rule */
786 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
790 krule->id = chain->id + 1;
791 update_skipto_cache(chain, map);
792 map = swap_map(chain, map, chain->n_rules + 1);
793 chain->static_len += RULEUSIZE0(krule);
794 IPFW_UH_WUNLOCK(chain);
801 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
806 map = get_map(chain, 1, locked);
809 if (chain->n_rules > 0)
810 bcopy(chain->map, map,
811 chain->n_rules * sizeof(struct ip_fw *));
812 map[chain->n_rules] = rule;
813 rule->rulenum = IPFW_DEFAULT_RULE;
814 rule->set = RESVD_SET;
815 rule->id = chain->id + 1;
816 /* We add rule in the end of chain, no need to update skipto cache */
817 map = swap_map(chain, map, chain->n_rules + 1);
818 chain->static_len += RULEUSIZE0(rule);
819 IPFW_UH_WUNLOCK(chain);
825 * Adds @rule to the list of rules to reap
828 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
832 IPFW_UH_WLOCK_ASSERT(chain);
834 /* Unlink rule from everywhere */
835 unref_rule_objects(chain, rule);
842 * Reclaim storage associated with a list of rules. This is
843 * typically the list created using remove_rule.
844 * A NULL pointer on input is handled correctly.
847 ipfw_reap_rules(struct ip_fw *head)
851 while ((rule = head) != NULL) {
853 ipfw_free_rule(rule);
859 * (default || reserved || !match_set || !match_number)
861 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
862 * // the default rule is always protected
864 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
865 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
867 * match_set ::= (cmd == 0 || rule->set == set)
868 * // set number is ignored for cmd == 0
870 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
871 * // number is ignored for cmd == 1 or n == 0
875 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
878 /* Don't match default rule for modification queries */
879 if (rule->rulenum == IPFW_DEFAULT_RULE &&
880 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
883 /* Don't match rules in reserved set for flush requests */
884 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
887 /* If we're filtering by set, don't match other sets */
888 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
891 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
892 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
898 struct manage_sets_args {
904 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
907 struct manage_sets_args *args;
909 args = (struct manage_sets_args *)arg;
910 if (no->set == (uint8_t)args->set)
911 no->set = args->new_set;
912 else if (no->set == args->new_set)
913 no->set = (uint8_t)args->set;
918 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
921 struct manage_sets_args *args;
923 args = (struct manage_sets_args *)arg;
924 if (no->set == (uint8_t)args->set)
925 no->set = args->new_set;
930 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
933 struct manage_sets_args *args;
935 args = (struct manage_sets_args *)arg;
936 if (no->set != (uint8_t)args->set)
938 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
939 no->etlv, no->name) != NULL)
945 * Generic function to handler moving and swapping sets.
948 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
949 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
951 struct manage_sets_args args;
952 struct named_object *no;
955 args.new_set = new_set;
958 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
961 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
964 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
968 * @set used to pass kidx.
969 * When @new_set is zero - reset object counter,
970 * otherwise increment it.
972 no = ipfw_objhash_lookup_kidx(ni, set);
979 /* @set used to pass kidx */
980 no = ipfw_objhash_lookup_kidx(ni, set);
982 * First check number of references:
983 * when it differs, this mean other rules are holding
984 * reference to given object, so it is not possible to
985 * change its set. Note that refcnt may account references
986 * to some going-to-be-added rules. Since we don't know
987 * their numbers (and even if they will be added) it is
988 * perfectly OK to return error here.
990 if (no->ocnt != no->refcnt)
992 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
997 /* @set used to pass kidx */
998 no = ipfw_objhash_lookup_kidx(ni, set);
1006 * Delete rules matching range @rt.
1007 * Saves number of deleted rules in @ndel.
1009 * Returns 0 on success.
1012 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1014 struct ip_fw *reap, *rule, **map;
1016 int i, n, ndyn, ofs;
1019 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1022 * Stage 1: Determine range to inspect.
1023 * Range is half-inclusive, e.g [start, end).
1026 end = chain->n_rules - 1;
1028 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1029 start = ipfw_find_rule(chain, rt->start_rule, 0);
1031 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1032 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1033 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1036 if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1038 * Requested deleting only for dynamic states.
1041 ipfw_expire_dyn_states(chain, rt);
1042 IPFW_UH_WUNLOCK(chain);
1046 /* Allocate new map of the same size */
1047 map = get_map(chain, 0, 1 /* locked */);
1049 IPFW_UH_WUNLOCK(chain);
1056 /* 1. bcopy the initial part of the map */
1058 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1059 /* 2. copy active rules between start and end */
1060 for (i = start; i < end; i++) {
1061 rule = chain->map[i];
1062 if (ipfw_match_range(rule, rt) == 0) {
1068 if (ipfw_is_dyn_rule(rule) != 0)
1071 /* 3. copy the final part of the map */
1072 bcopy(chain->map + end, map + ofs,
1073 (chain->n_rules - end) * sizeof(struct ip_fw *));
1074 /* 4. recalculate skipto cache */
1075 update_skipto_cache(chain, map);
1076 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1077 map = swap_map(chain, map, chain->n_rules - n);
1078 /* 6. Remove all dynamic states originated by deleted rules */
1080 ipfw_expire_dyn_states(chain, rt);
1081 /* 7. now remove the rules deleted from the old map */
1082 for (i = start; i < end; i++) {
1084 if (ipfw_match_range(rule, rt) == 0)
1086 chain->static_len -= RULEUSIZE0(rule);
1087 ipfw_reap_add(chain, &reap, rule);
1089 IPFW_UH_WUNLOCK(chain);
1091 ipfw_reap_rules(reap);
1099 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1101 struct opcode_obj_rewrite *rw;
1104 int cmdlen, i, l, c;
1107 IPFW_UH_WLOCK_ASSERT(ch);
1109 /* Stage 1: count number of references by given rules */
1110 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1112 if (ipfw_match_range(rule, rt) == 0)
1114 if (rule->set == rt->new_set) /* nothing to do */
1116 /* Search opcodes with named objects */
1117 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1118 l > 0; l -= cmdlen, cmd += cmdlen) {
1119 cmdlen = F_LEN(cmd);
1120 rw = find_op_rw(cmd, &kidx, NULL);
1121 if (rw == NULL || rw->manage_sets == NULL)
1124 * When manage_sets() returns non-zero value to
1125 * COUNT_ONE command, consider this as an object
1126 * doesn't support sets (e.g. disabled with sysctl).
1127 * So, skip checks for this object.
1129 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1134 if (c == 0) /* No objects found */
1136 /* Stage 2: verify "ownership" */
1137 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1139 if (ipfw_match_range(rule, rt) == 0)
1141 if (rule->set == rt->new_set) /* nothing to do */
1143 /* Search opcodes with named objects */
1144 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1145 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1146 cmdlen = F_LEN(cmd);
1147 rw = find_op_rw(cmd, &kidx, NULL);
1148 if (rw == NULL || rw->manage_sets == NULL)
1150 /* Test for ownership and conflicting names */
1151 c = rw->manage_sets(ch, kidx,
1152 (uint8_t)rt->new_set, TEST_ONE);
1155 /* Stage 3: change set and cleanup */
1156 for (i = 0; i < ch->n_rules - 1; i++) {
1158 if (ipfw_match_range(rule, rt) == 0)
1160 if (rule->set == rt->new_set) /* nothing to do */
1162 /* Search opcodes with named objects */
1163 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1164 l > 0; l -= cmdlen, cmd += cmdlen) {
1165 cmdlen = F_LEN(cmd);
1166 rw = find_op_rw(cmd, &kidx, NULL);
1167 if (rw == NULL || rw->manage_sets == NULL)
1169 /* cleanup object counter */
1170 rw->manage_sets(ch, kidx,
1171 0 /* reset counter */, COUNT_ONE);
1175 rw->manage_sets(ch, kidx,
1176 (uint8_t)rt->new_set, MOVE_ONE);
1181 * Changes set of given rule rannge @rt
1184 * Returns 0 on success.
1187 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1192 IPFW_UH_WLOCK(chain);
1195 * Move rules with matching paramenerts to a new set.
1196 * This one is much more complex. We have to ensure
1197 * that all referenced tables (if any) are referenced
1198 * by given rule subset only. Otherwise, we can't move
1199 * them to new set and have to return error.
1201 if ((i = move_objects(chain, rt)) != 0) {
1202 IPFW_UH_WUNLOCK(chain);
1206 /* XXX: We have to do swap holding WLOCK */
1207 for (i = 0; i < chain->n_rules; i++) {
1208 rule = chain->map[i];
1209 if (ipfw_match_range(rule, rt) == 0)
1211 rule->set = rt->new_set;
1214 IPFW_UH_WUNLOCK(chain);
1220 * Clear counters for a specific rule.
1221 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1222 * so we only care that rules do not disappear.
1225 clear_counters(struct ip_fw *rule, int log_only)
1227 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1230 IPFW_ZERO_RULE_COUNTER(rule);
1231 if (l->o.opcode == O_LOG)
1232 l->log_left = l->max_log;
1236 * Flushes rules counters and/or log values on matching range.
1238 * Returns number of items cleared.
1241 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1248 rt->flags |= IPFW_RCFLAG_DEFAULT;
1250 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1251 for (i = 0; i < chain->n_rules; i++) {
1252 rule = chain->map[i];
1253 if (ipfw_match_range(rule, rt) == 0)
1255 clear_counters(rule, log_only);
1258 IPFW_UH_WUNLOCK(chain);
1264 check_range_tlv(ipfw_range_tlv *rt)
1267 if (rt->head.length != sizeof(*rt))
1269 if (rt->start_rule > rt->end_rule)
1271 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1274 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1281 * Delete rules matching specified parameters
1282 * Data layout (v0)(current):
1283 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1284 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1286 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1288 * Returns 0 on success.
1291 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1292 struct sockopt_data *sd)
1294 ipfw_range_header *rh;
1297 if (sd->valsize != sizeof(*rh))
1300 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1302 if (check_range_tlv(&rh->range) != 0)
1306 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1309 /* Save number of rules deleted */
1310 rh->range.new_set = ndel;
1315 * Move rules/sets matching specified parameters
1316 * Data layout (v0)(current):
1317 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1319 * Returns 0 on success.
1322 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1323 struct sockopt_data *sd)
1325 ipfw_range_header *rh;
1327 if (sd->valsize != sizeof(*rh))
1330 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1332 if (check_range_tlv(&rh->range) != 0)
1335 return (move_range(chain, &rh->range));
1339 * Clear rule accounting data matching specified parameters
1340 * Data layout (v0)(current):
1341 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1342 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1344 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1346 * Returns 0 on success.
1349 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1350 struct sockopt_data *sd)
1352 ipfw_range_header *rh;
1356 if (sd->valsize != sizeof(*rh))
1359 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1361 if (check_range_tlv(&rh->range) != 0)
1364 log_only = (op3->opcode == IP_FW_XRESETLOG);
1366 num = clear_range(chain, &rh->range, log_only);
1368 if (rh->range.flags & IPFW_RCFLAG_ALL)
1369 msg = log_only ? "All logging counts reset" :
1370 "Accounting cleared";
1372 msg = log_only ? "logging count reset" : "cleared";
1375 int lev = LOG_SECURITY | LOG_NOTICE;
1376 log(lev, "ipfw: %s.\n", msg);
1379 /* Save number of rules cleared */
1380 rh->range.new_set = num;
1385 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1389 IPFW_UH_WLOCK_ASSERT(chain);
1391 /* Change enabled/disabled sets mask */
1392 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1393 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1395 V_set_disable = v_set;
1396 IPFW_WUNLOCK(chain);
1400 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1402 struct opcode_obj_rewrite *rw;
1406 IPFW_UH_WLOCK_ASSERT(chain);
1408 if (rt->set == rt->new_set) /* nothing to do */
1413 * Berfore moving the rules we need to check that
1414 * there aren't any conflicting named objects.
1416 for (rw = ctl3_rewriters;
1417 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1418 if (rw->manage_sets == NULL)
1420 i = rw->manage_sets(chain, (uint8_t)rt->set,
1421 (uint8_t)rt->new_set, TEST_ALL);
1426 /* Swap or move two sets */
1427 for (i = 0; i < chain->n_rules - 1; i++) {
1428 rule = chain->map[i];
1429 if (rule->set == (uint8_t)rt->set)
1430 rule->set = (uint8_t)rt->new_set;
1431 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1432 rule->set = (uint8_t)rt->set;
1434 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1435 if (rw->manage_sets == NULL)
1437 rw->manage_sets(chain, (uint8_t)rt->set,
1438 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1444 * Swaps or moves set
1445 * Data layout (v0)(current):
1446 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1448 * Returns 0 on success.
1451 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1452 struct sockopt_data *sd)
1454 ipfw_range_header *rh;
1457 if (sd->valsize != sizeof(*rh))
1460 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1462 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1464 /* enable_sets() expects bitmasks. */
1465 if (op3->opcode != IP_FW_SET_ENABLE &&
1466 (rh->range.set >= IPFW_MAX_SETS ||
1467 rh->range.new_set >= IPFW_MAX_SETS))
1471 IPFW_UH_WLOCK(chain);
1472 switch (op3->opcode) {
1473 case IP_FW_SET_SWAP:
1474 case IP_FW_SET_MOVE:
1475 ret = swap_sets(chain, &rh->range,
1476 op3->opcode == IP_FW_SET_MOVE);
1478 case IP_FW_SET_ENABLE:
1479 enable_sets(chain, &rh->range);
1482 IPFW_UH_WUNLOCK(chain);
1488 * Remove all rules with given number, or do set manipulation.
1489 * Assumes chain != NULL && *chain != NULL.
1491 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1492 * the next 8 bits are the new set; the top 8 bits indicate the command:
1494 * 0 delete rules numbered "rulenum"
1495 * 1 delete rules in set "rulenum"
1496 * 2 move rules "rulenum" to set "new_set"
1497 * 3 move rules from set "rulenum" to set "new_set"
1498 * 4 swap sets "rulenum" and "new_set"
1499 * 5 delete rules "rulenum" and set "new_set"
1502 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1504 uint32_t num; /* rule number or old_set */
1505 uint8_t cmd, new_set;
1511 cmd = (arg >> 24) & 0xff;
1512 new_set = (arg >> 16) & 0xff;
1514 if (cmd > 5 || new_set > RESVD_SET)
1516 if (cmd == 0 || cmd == 2 || cmd == 5) {
1517 if (num >= IPFW_DEFAULT_RULE)
1520 if (num > RESVD_SET) /* old_set */
1524 /* Convert old requests into new representation */
1525 memset(&rt, 0, sizeof(rt));
1526 rt.start_rule = num;
1529 rt.new_set = new_set;
1533 case 0: /* delete rules numbered "rulenum" */
1535 rt.flags |= IPFW_RCFLAG_ALL;
1537 rt.flags |= IPFW_RCFLAG_RANGE;
1540 case 1: /* delete rules in set "rulenum" */
1541 rt.flags |= IPFW_RCFLAG_SET;
1544 case 5: /* delete rules "rulenum" and set "new_set" */
1545 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1550 case 2: /* move rules "rulenum" to set "new_set" */
1551 rt.flags |= IPFW_RCFLAG_RANGE;
1553 case 3: /* move rules from set "rulenum" to set "new_set" */
1554 IPFW_UH_WLOCK(chain);
1555 error = swap_sets(chain, &rt, 1);
1556 IPFW_UH_WUNLOCK(chain);
1558 case 4: /* swap sets "rulenum" and "new_set" */
1559 IPFW_UH_WLOCK(chain);
1560 error = swap_sets(chain, &rt, 0);
1561 IPFW_UH_WUNLOCK(chain);
1568 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1571 if (ndel == 0 && (cmd != 1 && num != 0))
1577 return (move_range(chain, &rt));
1581 * Reset some or all counters on firewall rules.
1582 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1583 * the next 8 bits are the set number, the top 8 bits are the command:
1584 * 0 work with rules from all set's;
1585 * 1 work with rules only from specified set.
1586 * Specified rule number is zero if we want to clear all entries.
1587 * log_only is 1 if we only want to reset logs, zero otherwise.
1590 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1596 uint16_t rulenum = arg & 0xffff;
1597 uint8_t set = (arg >> 16) & 0xff;
1598 uint8_t cmd = (arg >> 24) & 0xff;
1602 if (cmd == 1 && set > RESVD_SET)
1605 IPFW_UH_RLOCK(chain);
1607 V_norule_counter = 0;
1608 for (i = 0; i < chain->n_rules; i++) {
1609 rule = chain->map[i];
1610 /* Skip rules not in our set. */
1611 if (cmd == 1 && rule->set != set)
1613 clear_counters(rule, log_only);
1615 msg = log_only ? "All logging counts reset" :
1616 "Accounting cleared";
1619 for (i = 0; i < chain->n_rules; i++) {
1620 rule = chain->map[i];
1621 if (rule->rulenum == rulenum) {
1622 if (cmd == 0 || rule->set == set)
1623 clear_counters(rule, log_only);
1626 if (rule->rulenum > rulenum)
1629 if (!cleared) { /* we did not find any matching rules */
1630 IPFW_UH_RUNLOCK(chain);
1633 msg = log_only ? "logging count reset" : "cleared";
1635 IPFW_UH_RUNLOCK(chain);
1638 int lev = LOG_SECURITY | LOG_NOTICE;
1641 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1643 log(lev, "ipfw: %s.\n", msg);
1650 * Check rule head in FreeBSD11 format
1654 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1655 struct rule_check_info *ci)
1659 if (size < sizeof(*rule)) {
1660 printf("ipfw: rule too short\n");
1664 /* Check for valid cmd_len */
1665 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1667 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1670 if (rule->act_ofs >= rule->cmd_len) {
1671 printf("ipfw: bogus action offset (%u > %u)\n",
1672 rule->act_ofs, rule->cmd_len - 1);
1676 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1679 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1683 * Check rule head in FreeBSD8 format
1687 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1688 struct rule_check_info *ci)
1692 if (size < sizeof(*rule)) {
1693 printf("ipfw: rule too short\n");
1697 /* Check for valid cmd_len */
1698 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1700 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1703 if (rule->act_ofs >= rule->cmd_len) {
1704 printf("ipfw: bogus action offset (%u > %u)\n",
1705 rule->act_ofs, rule->cmd_len - 1);
1709 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1712 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1716 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1724 * Now go for the individual checks. Very simple ones, basically only
1725 * instruction sizes.
1727 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1728 cmdlen = F_LEN(cmd);
1730 printf("ipfw: opcode %d size truncated\n",
1734 switch (cmd->opcode) {
1737 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1739 ci->object_opcodes++;
1750 case O_IPPRECEDENCE:
1769 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1773 case O_EXTERNAL_ACTION:
1774 if (cmd->arg1 == 0 ||
1775 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1776 printf("ipfw: invalid external "
1780 ci->object_opcodes++;
1782 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1788 cmdlen = F_LEN(cmd);
1789 if (cmd->opcode == O_EXTERNAL_DATA)
1791 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1792 printf("ipfw: invalid opcode "
1793 "next to external action %u\n",
1797 if (cmd->arg1 == 0 ||
1798 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1799 printf("ipfw: invalid external "
1800 "action instance opcode\n");
1803 ci->object_opcodes++;
1808 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1810 if (cmd->arg1 >= rt_numfibs) {
1811 printf("ipfw: invalid fib number %d\n",
1818 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1820 if ((cmd->arg1 != IP_FW_TARG) &&
1821 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1822 printf("ipfw: invalid fib number %d\n",
1823 cmd->arg1 & 0x7FFF);
1837 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1842 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1844 ci->object_opcodes++;
1848 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1851 ((ipfw_insn_log *)cmd)->log_left =
1852 ((ipfw_insn_log *)cmd)->max_log;
1858 /* only odd command lengths */
1859 if ((cmdlen & 1) == 0)
1865 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1866 printf("ipfw: invalid set size %d\n",
1870 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1875 case O_IP_SRC_LOOKUP:
1876 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1878 case O_IP_DST_LOOKUP:
1879 if (cmd->arg1 >= V_fw_tables_max) {
1880 printf("ipfw: invalid table number %d\n",
1884 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1885 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1886 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1888 ci->object_opcodes++;
1890 case O_IP_FLOW_LOOKUP:
1891 if (cmd->arg1 >= V_fw_tables_max) {
1892 printf("ipfw: invalid table number %d\n",
1896 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1897 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1899 ci->object_opcodes++;
1902 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1913 if (cmdlen < 1 || cmdlen > 31)
1918 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1924 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1925 if (cmdlen < 2 || cmdlen > 31)
1932 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1934 ci->object_opcodes++;
1938 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1944 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1949 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1954 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1961 if (ip_divert_ptr == NULL)
1967 if (ng_ipfw_input_p == NULL)
1972 if (!IPFW_NAT_LOADED)
1974 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1978 ci->object_opcodes++;
1980 case O_FORWARD_MAC: /* XXX not implemented yet */
1993 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1997 printf("ipfw: opcode %d, multiple actions"
2004 printf("ipfw: opcode %d, action must be"
2013 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2014 F_INSN_SIZE(ipfw_insn))
2019 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2020 ((ipfw_insn_u32 *)cmd)->o.arg1)
2024 case O_IP6_SRC_MASK:
2025 case O_IP6_DST_MASK:
2026 if ( !(cmdlen & 1) || cmdlen > 127)
2030 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2036 switch (cmd->opcode) {
2046 case O_IP6_SRC_MASK:
2047 case O_IP6_DST_MASK:
2049 printf("ipfw: no IPv6 support in kernel\n");
2050 return (EPROTONOSUPPORT);
2053 printf("ipfw: opcode %d, unknown opcode\n",
2059 if (have_action == 0) {
2060 printf("ipfw: missing action\n");
2066 printf("ipfw: opcode %d size %d wrong\n",
2067 cmd->opcode, cmdlen);
2073 * Translation of requests for compatibility with FreeBSD 7.2/8.
2074 * a static variable tells us if we have an old client from userland,
2075 * and if necessary we translate requests and responses between the
2081 struct ip_fw7 *next; /* linked list of rules */
2082 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2083 /* 'next_rule' is used to pass up 'set_disable' status */
2085 uint16_t act_ofs; /* offset of action in 32-bit units */
2086 uint16_t cmd_len; /* # of 32-bit words in cmd */
2087 uint16_t rulenum; /* rule number */
2088 uint8_t set; /* rule set (0..31) */
2089 // #define RESVD_SET 31 /* set for default and persistent rules */
2090 uint8_t _pad; /* padding */
2091 // uint32_t id; /* rule id, only in v.8 */
2092 /* These fields are present in all rules. */
2093 uint64_t pcnt; /* Packet counter */
2094 uint64_t bcnt; /* Byte counter */
2095 uint32_t timestamp; /* tv_sec of last match */
2097 ipfw_insn cmd[1]; /* storage for commands */
2100 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2101 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2104 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2105 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2110 * Copy the static and dynamic rules to the supplied buffer
2111 * and return the amount of space actually used.
2112 * Must be run under IPFW_UH_RLOCK
2115 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2118 char *ep = bp + space;
2120 struct ip_fw_rule0 *dst;
2121 struct timeval boottime;
2122 int error, i, l, warnflag;
2123 time_t boot_seconds;
2127 getboottime(&boottime);
2128 boot_seconds = boottime.tv_sec;
2129 for (i = 0; i < chain->n_rules; i++) {
2130 rule = chain->map[i];
2133 /* Convert rule to FreeBSd 7.2 format */
2134 l = RULESIZE7(rule);
2135 if (bp + l + sizeof(uint32_t) <= ep) {
2136 bcopy(rule, bp, l + sizeof(uint32_t));
2137 error = set_legacy_obj_kidx(chain,
2138 (struct ip_fw_rule0 *)bp);
2141 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2143 return 0; /*XXX correct? */
2145 * XXX HACK. Store the disable mask in the "next"
2146 * pointer in a wild attempt to keep the ABI the same.
2147 * Why do we do this on EVERY rule?
2149 bcopy(&V_set_disable,
2150 &(((struct ip_fw7 *)bp)->next_rule),
2151 sizeof(V_set_disable));
2152 if (((struct ip_fw7 *)bp)->timestamp)
2153 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2156 continue; /* go to next rule */
2159 l = RULEUSIZE0(rule);
2160 if (bp + l > ep) { /* should not happen */
2161 printf("overflow dumping static rules\n");
2164 dst = (struct ip_fw_rule0 *)bp;
2165 export_rule0(rule, dst, l);
2166 error = set_legacy_obj_kidx(chain, dst);
2169 * XXX HACK. Store the disable mask in the "next"
2170 * pointer in a wild attempt to keep the ABI the same.
2171 * Why do we do this on EVERY rule?
2173 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2174 * so we need to fail _after_ saving at least one mask.
2176 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2178 dst->timestamp += boot_seconds;
2183 /* Non-fatal table rewrite error. */
2187 printf("Stop on rule %d. Fail to convert table\n",
2193 printf("ipfw: process %s is using legacy interfaces,"
2194 " consider rebuilding\n", "");
2195 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2196 return (bp - (char *)buf);
2201 uint32_t b; /* start rule */
2202 uint32_t e; /* end rule */
2203 uint32_t rcount; /* number of rules */
2204 uint32_t rsize; /* rules size */
2205 uint32_t tcount; /* number of tables */
2206 int rcounters; /* counters */
2207 uint32_t *bmask; /* index bitmask of used named objects */
2211 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2214 ntlv->head.type = no->etlv;
2215 ntlv->head.length = sizeof(*ntlv);
2216 ntlv->idx = no->kidx;
2217 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2221 * Export named object info in instance @ni, identified by @kidx
2222 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2224 * Returns 0 on success.
2227 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2228 struct sockopt_data *sd)
2230 struct named_object *no;
2231 ipfw_obj_ntlv *ntlv;
2233 no = ipfw_objhash_lookup_kidx(ni, kidx);
2234 KASSERT(no != NULL, ("invalid object kernel index passed"));
2236 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2240 ipfw_export_obj_ntlv(no, ntlv);
2245 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2246 struct sockopt_data *sd)
2250 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2251 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2253 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2261 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2262 struct sockopt_data *sd)
2264 ipfw_obj_ctlv *ctlv;
2267 MPASS(da->tcount > 0);
2269 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2272 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2273 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2275 ctlv->count = da->tcount;
2276 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2278 /* Dump table names first (if any) */
2279 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2282 /* Then dump another named objects */
2283 da->bmask += IPFW_TABLES_MAX / 32;
2284 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2288 * Dumps static rules with table TLVs in buffer @sd.
2290 * Returns 0 on success.
2293 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2294 struct sockopt_data *sd)
2296 ipfw_obj_ctlv *ctlv;
2297 struct ip_fw *krule;
2302 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2305 ctlv->head.type = IPFW_TLV_RULE_LIST;
2306 ctlv->head.length = da->rsize + sizeof(*ctlv);
2307 ctlv->count = da->rcount;
2309 for (i = da->b; i < da->e; i++) {
2310 krule = chain->map[i];
2312 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2313 if (da->rcounters != 0)
2314 l += sizeof(struct ip_fw_bcounter);
2315 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2319 export_rule1(krule, dst, l, da->rcounters);
2326 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2331 * Maintain separate bitmasks for table and non-table objects.
2333 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2335 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2338 bmask[bidx] |= 1 << (kidx % 32);
2343 * Marks every object index used in @rule with bit in @bmask.
2344 * Used to generate bitmask of referenced tables/objects for given ruleset
2348 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2349 struct dump_args *da)
2351 struct opcode_obj_rewrite *rw;
2360 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2361 cmdlen = F_LEN(cmd);
2363 rw = find_op_rw(cmd, &kidx, &subtype);
2367 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2373 * Dumps requested objects data
2374 * Data layout (version 0)(current):
2375 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2376 * size = ipfw_cfg_lheader.size
2377 * Reply: [ ipfw_cfg_lheader
2378 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2379 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2380 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2382 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2384 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2385 * The rest (size, count) are set to zero and needs to be ignored.
2387 * Returns 0 on success.
2390 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2391 struct sockopt_data *sd)
2393 struct dump_args da;
2394 ipfw_cfg_lheader *hdr;
2397 uint32_t hdr_flags, *bmask;
2400 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2406 memset(&da, 0, sizeof(da));
2408 * Allocate needed state.
2409 * Note we allocate 2xspace mask, for table & srv
2411 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2412 da.bmask = bmask = malloc(
2413 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2415 IPFW_UH_RLOCK(chain);
2418 * STAGE 1: Determine size/count for objects in range.
2419 * Prepare used tables bitmask.
2421 sz = sizeof(ipfw_cfg_lheader);
2422 da.e = chain->n_rules;
2424 if (hdr->end_rule != 0) {
2425 /* Handle custom range */
2426 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2427 rnum = IPFW_DEFAULT_RULE;
2428 da.b = ipfw_find_rule(chain, rnum, 0);
2429 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2430 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2431 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2434 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2435 for (i = da.b; i < da.e; i++) {
2436 rule = chain->map[i];
2437 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2439 /* Update bitmask of used objects for given range */
2440 mark_rule_objects(chain, rule, &da);
2442 /* Add counters if requested */
2443 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2444 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2447 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2450 if (hdr->flags & IPFW_CFG_GET_STATES) {
2451 sz += sizeof(ipfw_obj_ctlv) +
2452 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2457 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2458 sizeof(ipfw_obj_ctlv);
2461 * Fill header anyway.
2462 * Note we have to save header fields to stable storage
2463 * buffer inside @sd can be flushed after dumping rules
2466 hdr->set_mask = ~V_set_disable;
2467 hdr_flags = hdr->flags;
2470 if (sd->valsize < sz) {
2475 /* STAGE2: Store actual data */
2476 if (da.tcount > 0) {
2477 error = dump_named_objects(chain, &da, sd);
2482 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2483 error = dump_static_rules(chain, &da, sd);
2488 if (hdr_flags & IPFW_CFG_GET_STATES)
2489 error = ipfw_dump_states(chain, sd);
2492 IPFW_UH_RUNLOCK(chain);
2495 free(bmask, M_TEMP);
2501 ipfw_check_object_name_generic(const char *name)
2505 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2506 if (strnlen(name, nsize) == nsize)
2508 if (name[0] == '\0')
2514 * Creates non-existent objects referenced by rule.
2516 * Return 0 on success.
2519 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2520 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2522 struct opcode_obj_rewrite *rw;
2528 * Compatibility stuff: do actual creation for non-existing,
2529 * but referenced objects.
2531 for (p = oib; p < pidx; p++) {
2539 rw = find_op_rw(cmd + p->off, NULL, NULL);
2540 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2541 (cmd + p->off)->opcode));
2543 if (rw->create_object == NULL)
2546 error = rw->create_object(ch, ti, &kidx);
2553 * Error happened. We have to rollback everything.
2554 * Drop all already acquired references.
2557 unref_oib_objects(ch, cmd, oib, pidx);
2558 IPFW_UH_WUNLOCK(ch);
2567 * Compatibility function for old ipfw(8) binaries.
2568 * Rewrites table/nat kernel indices with userland ones.
2569 * Convert tables matching '/^\d+$/' to their atoi() value.
2570 * Use number 65535 for other tables.
2572 * Returns 0 on success.
2575 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2577 struct opcode_obj_rewrite *rw;
2578 struct named_object *no;
2582 int cmdlen, error, l;
2583 uint16_t kidx, uidx;
2591 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2592 cmdlen = F_LEN(cmd);
2594 /* Check if is index in given opcode */
2595 rw = find_op_rw(cmd, &kidx, &subtype);
2599 /* Try to find referenced kernel object */
2600 no = rw->find_bykidx(ch, kidx);
2604 val = strtol(no->name, &end, 10);
2605 if (*end == '\0' && val < 65535) {
2610 * We are called via legacy opcode.
2611 * Save error and show table as fake number
2612 * not to make ipfw(8) hang.
2618 rw->update(cmd, uidx);
2626 * Unreferences all already-referenced objects in given @cmd rule,
2627 * using information in @oib.
2629 * Used to rollback partially converted rule on error.
2632 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2633 struct obj_idx *end)
2635 struct opcode_obj_rewrite *rw;
2636 struct named_object *no;
2639 IPFW_UH_WLOCK_ASSERT(ch);
2641 for (p = oib; p < end; p++) {
2645 rw = find_op_rw(cmd + p->off, NULL, NULL);
2646 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2647 (cmd + p->off)->opcode));
2649 /* Find & unref by existing idx */
2650 no = rw->find_bykidx(ch, p->kidx);
2651 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2657 * Remove references from every object used in @rule.
2658 * Used at rule removal code.
2661 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2663 struct opcode_obj_rewrite *rw;
2664 struct named_object *no;
2670 IPFW_UH_WLOCK_ASSERT(ch);
2675 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2676 cmdlen = F_LEN(cmd);
2678 rw = find_op_rw(cmd, &kidx, &subtype);
2681 no = rw->find_bykidx(ch, kidx);
2683 KASSERT(no != NULL, ("object id %d not found", kidx));
2684 KASSERT(no->subtype == subtype,
2685 ("wrong type %d (%d) for object id %d",
2686 no->subtype, subtype, kidx));
2687 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2690 if (no->refcnt == 1 && rw->destroy_object != NULL)
2691 rw->destroy_object(ch, no);
2699 * Find and reference object (if any) stored in instruction @cmd.
2701 * Saves object info in @pidx, sets
2702 * - @unresolved to 1 if object should exists but not found
2704 * Returns non-zero value in case of error.
2707 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2708 struct obj_idx *pidx, int *unresolved)
2710 struct named_object *no;
2711 struct opcode_obj_rewrite *rw;
2714 /* Check if this opcode is candidate for rewrite */
2715 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2719 /* Need to rewrite. Save necessary fields */
2720 pidx->uidx = ti->uidx;
2721 pidx->type = ti->type;
2723 /* Try to find referenced kernel object */
2724 error = rw->find_byname(ch, ti, &no);
2729 * Report about unresolved object for automaic
2737 * Object is already exist.
2738 * Its subtype should match with expected value.
2740 if (ti->type != no->subtype)
2743 /* Bump refcount and update kidx. */
2745 rw->update(cmd, no->kidx);
2750 * Finds and bumps refcount for objects referenced by given @rule.
2751 * Auto-creates non-existing tables.
2752 * Fills in @oib array with userland/kernel indexes.
2754 * Returns 0 on success.
2757 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2758 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2760 struct obj_idx *pidx;
2762 int cmdlen, error, l, unresolved;
2772 /* Increase refcount on each existing referenced table. */
2773 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2774 cmdlen = F_LEN(cmd);
2777 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2781 * Compatibility stuff for old clients:
2782 * prepare to automaitcally create non-existing objects.
2784 if (unresolved != 0) {
2785 pidx->off = rule->cmd_len - l;
2791 /* Unref everything we have already done */
2792 unref_oib_objects(ch, rule->cmd, oib, pidx);
2793 IPFW_UH_WUNLOCK(ch);
2796 IPFW_UH_WUNLOCK(ch);
2798 /* Perform auto-creation for non-existing objects */
2800 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2802 /* Calculate real number of dynamic objects */
2803 ci->object_opcodes = (uint16_t)(pidx - oib);
2809 * Checks is opcode is referencing table of appropriate type.
2810 * Adds reference count for found table if true.
2811 * Rewrites user-supplied opcode values with kernel ones.
2813 * Returns 0 on success and appropriate error code otherwise.
2816 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2821 struct obj_idx *p, *pidx_first, *pidx_last;
2825 * Prepare an array for storing opcode indices.
2826 * Use stack allocation by default.
2828 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2830 pidx_first = ci->obuf;
2832 pidx_first = malloc(
2833 ci->object_opcodes * sizeof(struct obj_idx),
2834 M_IPFW, M_WAITOK | M_ZERO);
2838 memset(&ti, 0, sizeof(ti));
2840 /* Use set rule is assigned to. */
2841 ti.set = ci->krule->set;
2842 if (ci->ctlv != NULL) {
2843 ti.tlvs = (void *)(ci->ctlv + 1);
2844 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2847 /* Reference all used tables and other objects */
2848 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2852 * Note that ref_rule_objects() might have updated ci->object_opcodes
2853 * to reflect actual number of object opcodes.
2856 /* Perform rewrite of remaining opcodes */
2858 pidx_last = pidx_first + ci->object_opcodes;
2859 for (p = pidx_first; p < pidx_last; p++) {
2860 cmd = ci->krule->cmd + p->off;
2861 update_opcode_kidx(cmd, p->kidx);
2865 if (pidx_first != ci->obuf)
2866 free(pidx_first, M_IPFW);
2872 * Adds one or more rules to ipfw @chain.
2873 * Data layout (version 0)(current):
2877 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2878 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2883 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2884 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2887 * Rules in reply are modified to store their actual ruleset number.
2889 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2890 * according to their idx field and there has to be no duplicates.
2891 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2892 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2894 * Returns 0 on success.
2897 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2898 struct sockopt_data *sd)
2900 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2901 ipfw_obj_ntlv *ntlv;
2902 int clen, error, idx;
2903 uint32_t count, read;
2904 struct ip_fw_rule *r;
2905 struct rule_check_info rci, *ci, *cbuf;
2908 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2909 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2911 read = sizeof(ip_fw3_opheader);
2915 memset(&rci, 0, sizeof(struct rule_check_info));
2917 if (read + sizeof(*ctlv) > sd->valsize)
2920 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2921 clen = ctlv->head.length;
2922 /* Check size and alignment */
2923 if (clen > sd->valsize || clen < sizeof(*ctlv))
2925 if ((clen % sizeof(uint64_t)) != 0)
2929 * Some table names or other named objects.
2930 * Check for validness.
2932 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2933 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2938 * Ensure TLVs are sorted ascending and
2939 * there are no duplicates.
2942 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2944 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2947 error = ipfw_check_object_name_generic(ntlv->name);
2951 if (ntlv->idx <= idx)
2960 read += ctlv->head.length;
2961 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2964 if (read + sizeof(*ctlv) > sd->valsize)
2967 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2968 clen = ctlv->head.length;
2969 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2971 if ((clen % sizeof(uint64_t)) != 0)
2975 * TODO: Permit adding multiple rules at once
2977 if (ctlv->count != 1)
2980 clen -= sizeof(*ctlv);
2982 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2985 /* Allocate state for each rule or use stack */
2986 if (ctlv->count == 1) {
2987 memset(&rci, 0, sizeof(struct rule_check_info));
2990 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2995 * Check each rule for validness.
2996 * Ensure numbered rules are sorted ascending
2997 * and properly aligned
3000 r = (struct ip_fw_rule *)(ctlv + 1);
3004 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3005 if (rsize > clen || ctlv->count <= count) {
3011 error = check_ipfw_rule1(r, rsize, ci);
3016 if (r->rulenum != 0 && r->rulenum < idx) {
3017 printf("rulenum %d idx %d\n", r->rulenum, idx);
3023 ci->urule = (caddr_t)r;
3025 rsize = roundup2(rsize, sizeof(uint64_t));
3027 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3032 if (ctlv->count != count || error != 0) {
3039 read += ctlv->head.length;
3040 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3043 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3044 if (cbuf != NULL && cbuf != &rci)
3050 * Passed rules seems to be valid.
3051 * Allocate storage and try to add them to chain.
3053 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3054 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3055 ci->krule = ipfw_alloc_rule(chain, clen);
3059 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3060 /* Free allocate krules */
3061 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3062 ipfw_free_rule(ci->krule);
3065 if (cbuf != NULL && cbuf != &rci)
3072 * Lists all sopts currently registered.
3073 * Data layout (v0)(current):
3074 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3075 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3077 * Returns 0 on success
3080 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3081 struct sockopt_data *sd)
3083 struct _ipfw_obj_lheader *olh;
3085 struct ipfw_sopt_handler *sh;
3086 uint32_t count, n, size;
3088 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3091 if (sd->valsize < olh->size)
3096 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3098 /* Fill in header regadless of buffer size */
3100 olh->objsize = sizeof(ipfw_sopt_info);
3102 if (size > olh->size) {
3109 for (n = 1; n <= count; n++) {
3110 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3111 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3112 sh = &ctl3_handlers[n];
3113 i->opcode = sh->opcode;
3114 i->version = sh->version;
3115 i->refcnt = sh->refcnt;
3123 * Compares two opcodes.
3124 * Used both in qsort() and bsearch().
3126 * Returns 0 if match is found.
3129 compare_opcodes(const void *_a, const void *_b)
3131 const struct opcode_obj_rewrite *a, *b;
3133 a = (const struct opcode_obj_rewrite *)_a;
3134 b = (const struct opcode_obj_rewrite *)_b;
3136 if (a->opcode < b->opcode)
3138 else if (a->opcode > b->opcode)
3145 * XXX: Rewrite bsearch()
3148 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3149 struct opcode_obj_rewrite **phi)
3151 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3153 memset(&h, 0, sizeof(h));
3156 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3157 ctl3_rsize, sizeof(h), compare_opcodes);
3161 /* Find the first element matching the same opcode */
3163 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3166 /* Find the last element matching the same opcode */
3168 ctl3_max = ctl3_rewriters + ctl3_rsize;
3169 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3179 * Finds opcode object rewriter based on @code.
3181 * Returns pointer to handler or NULL.
3183 static struct opcode_obj_rewrite *
3184 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3186 struct opcode_obj_rewrite *rw, *lo, *hi;
3190 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3193 for (rw = lo; rw <= hi; rw++) {
3194 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3206 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3209 if (find_op_rw(cmd, puidx, NULL) == NULL)
3215 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3217 struct opcode_obj_rewrite *rw;
3219 rw = find_op_rw(cmd, NULL, NULL);
3220 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3221 rw->update(cmd, idx);
3225 ipfw_init_obj_rewriter()
3228 ctl3_rewriters = NULL;
3233 ipfw_destroy_obj_rewriter()
3236 if (ctl3_rewriters != NULL)
3237 free(ctl3_rewriters, M_IPFW);
3238 ctl3_rewriters = NULL;
3243 * Adds one or more opcode object rewrite handlers to the global array.
3244 * Function may sleep.
3247 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3250 struct opcode_obj_rewrite *tmp;
3255 sz = ctl3_rsize + count;
3257 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3259 if (ctl3_rsize + count <= sz)
3266 /* Merge old & new arrays */
3267 sz = ctl3_rsize + count;
3268 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3269 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3270 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3271 /* Switch new and free old */
3272 if (ctl3_rewriters != NULL)
3273 free(ctl3_rewriters, M_IPFW);
3274 ctl3_rewriters = tmp;
3281 * Removes one or more object rewrite handlers from the global array.
3284 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3287 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3292 for (i = 0; i < count; i++) {
3293 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3296 for (ktmp = lo; ktmp <= hi; ktmp++) {
3297 if (ktmp->classifier != rw[i].classifier)
3300 ctl3_max = ctl3_rewriters + ctl3_rsize;
3301 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3302 memmove(ktmp, ktmp + 1, sz);
3309 if (ctl3_rsize == 0) {
3310 if (ctl3_rewriters != NULL)
3311 free(ctl3_rewriters, M_IPFW);
3312 ctl3_rewriters = NULL;
3321 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3322 struct named_object *no, void *arg)
3324 struct sockopt_data *sd;
3325 ipfw_obj_ntlv *ntlv;
3327 sd = (struct sockopt_data *)arg;
3328 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3331 ipfw_export_obj_ntlv(no, ntlv);
3336 * Lists all service objects.
3337 * Data layout (v0)(current):
3338 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3339 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3340 * Returns 0 on success
3343 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3344 struct sockopt_data *sd)
3346 ipfw_obj_lheader *hdr;
3349 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3353 IPFW_UH_RLOCK(chain);
3354 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3355 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3356 if (sd->valsize < hdr->size) {
3357 IPFW_UH_RUNLOCK(chain);
3361 hdr->objsize = sizeof(ipfw_obj_ntlv);
3363 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3364 export_objhash_ntlv_internal, sd);
3365 IPFW_UH_RUNLOCK(chain);
3370 * Compares two sopt handlers (code, version and handler ptr).
3371 * Used both as qsort() and bsearch().
3372 * Does not compare handler for latter case.
3374 * Returns 0 if match is found.
3377 compare_sh(const void *_a, const void *_b)
3379 const struct ipfw_sopt_handler *a, *b;
3381 a = (const struct ipfw_sopt_handler *)_a;
3382 b = (const struct ipfw_sopt_handler *)_b;
3384 if (a->opcode < b->opcode)
3386 else if (a->opcode > b->opcode)
3389 if (a->version < b->version)
3391 else if (a->version > b->version)
3394 /* bsearch helper */
3395 if (a->handler == NULL)
3398 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3400 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3407 * Finds sopt handler based on @code and @version.
3409 * Returns pointer to handler or NULL.
3411 static struct ipfw_sopt_handler *
3412 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3414 struct ipfw_sopt_handler *sh, h;
3416 memset(&h, 0, sizeof(h));
3418 h.version = version;
3419 h.handler = handler;
3421 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3422 ctl3_hsize, sizeof(h), compare_sh);
3428 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3430 struct ipfw_sopt_handler *sh;
3433 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3435 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3441 /* Copy handler data to requested buffer */
3449 find_unref_sh(struct ipfw_sopt_handler *psh)
3451 struct ipfw_sopt_handler *sh;
3454 sh = find_sh(psh->opcode, psh->version, NULL);
3455 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3462 ipfw_init_sopt_handler()
3466 IPFW_ADD_SOPT_HANDLER(1, scodes);
3470 ipfw_destroy_sopt_handler()
3473 IPFW_DEL_SOPT_HANDLER(1, scodes);
3474 CTL3_LOCK_DESTROY();
3478 * Adds one or more sockopt handlers to the global array.
3479 * Function may sleep.
3482 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3485 struct ipfw_sopt_handler *tmp;
3490 sz = ctl3_hsize + count;
3492 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3494 if (ctl3_hsize + count <= sz)
3501 /* Merge old & new arrays */
3502 sz = ctl3_hsize + count;
3503 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3504 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3505 qsort(tmp, sz, sizeof(*sh), compare_sh);
3506 /* Switch new and free old */
3507 if (ctl3_handlers != NULL)
3508 free(ctl3_handlers, M_IPFW);
3509 ctl3_handlers = tmp;
3517 * Removes one or more sockopt handlers from the global array.
3520 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3523 struct ipfw_sopt_handler *tmp, *h;
3528 for (i = 0; i < count; i++) {
3530 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3534 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3535 memmove(h, h + 1, sz);
3539 if (ctl3_hsize == 0) {
3540 if (ctl3_handlers != NULL)
3541 free(ctl3_handlers, M_IPFW);
3542 ctl3_handlers = NULL;
3553 * Writes data accumulated in @sd to sockopt buffer.
3554 * Zeroes internal @sd buffer.
3557 ipfw_flush_sopt_data(struct sockopt_data *sd)
3559 struct sockopt *sopt;
3569 if (sopt->sopt_dir == SOPT_GET) {
3570 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3575 memset(sd->kbuf, 0, sd->ksize);
3578 if (sd->ktotal + sd->ksize < sd->valsize)
3579 sd->kavail = sd->ksize;
3581 sd->kavail = sd->valsize - sd->ktotal;
3583 /* Update sopt buffer data */
3584 sopt->sopt_valsize = sd->ktotal;
3585 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3591 * Ensures that @sd buffer has contiguous @neeeded number of
3594 * Returns pointer to requested space or NULL.
3597 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3602 if (sd->kavail < needed) {
3604 * Flush data and try another time.
3606 error = ipfw_flush_sopt_data(sd);
3608 if (sd->kavail < needed || error != 0)
3612 addr = sd->kbuf + sd->koff;
3614 sd->kavail -= needed;
3619 * Requests @needed contiguous bytes from @sd buffer.
3620 * Function is used to notify subsystem that we are
3621 * interesed in first @needed bytes (request header)
3622 * and the rest buffer can be safely zeroed.
3624 * Returns pointer to requested space or NULL.
3627 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3631 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3635 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3641 * New sockopt handler.
3644 ipfw_ctl3(struct sockopt *sopt)
3647 size_t size, valsize;
3648 struct ip_fw_chain *chain;
3650 struct sockopt_data sdata;
3651 struct ipfw_sopt_handler h;
3652 ip_fw3_opheader *op3 = NULL;
3654 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3658 if (sopt->sopt_name != IP_FW3)
3659 return (ipfw_ctl(sopt));
3661 chain = &V_layer3_chain;
3664 /* Save original valsize before it is altered via sooptcopyin() */
3665 valsize = sopt->sopt_valsize;
3666 memset(&sdata, 0, sizeof(sdata));
3667 /* Read op3 header first to determine actual operation */
3668 op3 = (ip_fw3_opheader *)xbuf;
3669 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3672 sopt->sopt_valsize = valsize;
3675 * Find and reference command.
3677 error = find_ref_sh(op3->opcode, op3->version, &h);
3682 * Disallow modifications in really-really secure mode, but still allow
3683 * the logging counters to be reset.
3685 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3686 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3694 * Fill in sockopt_data structure that may be useful for
3695 * IP_FW3 get requests.
3698 if (valsize <= sizeof(xbuf)) {
3699 /* use on-stack buffer */
3701 sdata.ksize = sizeof(xbuf);
3702 sdata.kavail = valsize;
3706 * Determine opcode type/buffer size:
3707 * allocate sliding-window buf for data export or
3708 * contiguous buffer for special ops.
3710 if ((h.dir & HDIR_SET) != 0) {
3711 /* Set request. Allocate contigous buffer. */
3712 if (valsize > CTL3_LARGEBUF) {
3719 /* Get request. Allocate sliding window buffer */
3720 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3722 if (size < valsize) {
3723 /* We have to wire user buffer */
3724 error = vslock(sopt->sopt_val, valsize);
3731 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3733 sdata.kavail = size;
3737 sdata.sopt_val = sopt->sopt_val;
3738 sdata.valsize = valsize;
3741 * Copy either all request (if valsize < bsize_max)
3742 * or first bsize_max bytes to guarantee most consumers
3743 * that all necessary data has been copied).
3744 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3746 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3747 sizeof(ip_fw3_opheader))) != 0)
3749 op3 = (ip_fw3_opheader *)sdata.kbuf;
3751 /* Finally, run handler */
3752 error = h.handler(chain, op3, &sdata);
3755 /* Flush state and free buffers */
3757 error = ipfw_flush_sopt_data(&sdata);
3759 ipfw_flush_sopt_data(&sdata);
3762 vsunlock(sdata.sopt_val, valsize);
3764 /* Restore original pointer and set number of bytes written */
3765 sopt->sopt_val = sdata.sopt_val;
3766 sopt->sopt_valsize = sdata.ktotal;
3767 if (sdata.kbuf != xbuf)
3768 free(sdata.kbuf, M_TEMP);
3774 * {set|get}sockopt parser.
3777 ipfw_ctl(struct sockopt *sopt)
3779 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3781 size_t size, valsize;
3783 struct ip_fw_rule0 *rule;
3784 struct ip_fw_chain *chain;
3785 u_int32_t rulenum[2];
3787 struct rule_check_info ci;
3790 chain = &V_layer3_chain;
3793 /* Save original valsize before it is altered via sooptcopyin() */
3794 valsize = sopt->sopt_valsize;
3795 opt = sopt->sopt_name;
3798 * Disallow modifications in really-really secure mode, but still allow
3799 * the logging counters to be reset.
3801 if (opt == IP_FW_ADD ||
3802 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3803 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3811 * pass up a copy of the current rules. Static rules
3812 * come first (the last of which has number IPFW_DEFAULT_RULE),
3813 * followed by a possibly empty list of dynamic rule.
3814 * The last dynamic rule has NULL in the "next" field.
3816 * Note that the calculated size is used to bound the
3817 * amount of data returned to the user. The rule set may
3818 * change between calculating the size and returning the
3819 * data in which case we'll just return what fits.
3824 size = chain->static_len;
3825 size += ipfw_dyn_len();
3826 if (size >= sopt->sopt_valsize)
3828 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3829 IPFW_UH_RLOCK(chain);
3830 /* check again how much space we need */
3831 want = chain->static_len + ipfw_dyn_len();
3833 len = ipfw_getrules(chain, buf, size);
3834 IPFW_UH_RUNLOCK(chain);
3836 error = sooptcopyout(sopt, buf, len);
3844 /* locking is done within del_entry() */
3845 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3849 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3850 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3851 sizeof(struct ip_fw7) );
3853 memset(&ci, 0, sizeof(struct rule_check_info));
3856 * If the size of commands equals RULESIZE7 then we assume
3857 * a FreeBSD7.2 binary is talking to us (set is7=1).
3858 * is7 is persistent so the next 'ipfw list' command
3859 * will use this format.
3860 * NOTE: If wrong version is guessed (this can happen if
3861 * the first ipfw command is 'ipfw [pipe] list')
3862 * the ipfw binary may crash or loop infinitly...
3864 size = sopt->sopt_valsize;
3865 if (size == RULESIZE7(rule)) {
3867 error = convert_rule_to_8(rule);
3872 size = RULESIZE(rule);
3876 error = check_ipfw_rule0(rule, size, &ci);
3878 /* locking is done within add_rule() */
3879 struct ip_fw *krule;
3880 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3881 ci.urule = (caddr_t)rule;
3884 error = commit_rules(chain, &ci, 1);
3886 ipfw_free_rule(ci.krule);
3887 else if (sopt->sopt_dir == SOPT_GET) {
3889 error = convert_rule_to_7(rule);
3890 size = RULESIZE7(rule);
3896 error = sooptcopyout(sopt, rule, size);
3904 * IP_FW_DEL is used for deleting single rules or sets,
3905 * and (ab)used to atomically manipulate sets. Argument size
3906 * is used to distinguish between the two:
3908 * delete single rule or set of rules,
3909 * or reassign rules (or sets) to a different set.
3910 * 2*sizeof(u_int32_t)
3911 * atomic disable/enable sets.
3912 * first u_int32_t contains sets to be disabled,
3913 * second u_int32_t contains sets to be enabled.
3915 error = sooptcopyin(sopt, rulenum,
3916 2*sizeof(u_int32_t), sizeof(u_int32_t));
3919 size = sopt->sopt_valsize;
3920 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3921 /* delete or reassign, locking done in del_entry() */
3922 error = del_entry(chain, rulenum[0]);
3923 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3924 IPFW_UH_WLOCK(chain);
3926 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3927 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3928 IPFW_UH_WUNLOCK(chain);
3934 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3936 if (sopt->sopt_val != 0) {
3937 error = sooptcopyin(sopt, rulenum,
3938 sizeof(u_int32_t), sizeof(u_int32_t));
3942 error = zero_entry(chain, rulenum[0],
3943 sopt->sopt_name == IP_FW_RESETLOG);
3946 /*--- TABLE opcodes ---*/
3947 case IP_FW_TABLE_ADD:
3948 case IP_FW_TABLE_DEL:
3950 ipfw_table_entry ent;
3951 struct tentry_info tei;
3953 struct table_value v;
3955 error = sooptcopyin(sopt, &ent,
3956 sizeof(ent), sizeof(ent));
3960 memset(&tei, 0, sizeof(tei));
3961 tei.paddr = &ent.addr;
3962 tei.subtype = AF_INET;
3963 tei.masklen = ent.masklen;
3964 ipfw_import_table_value_legacy(ent.value, &v);
3966 memset(&ti, 0, sizeof(ti));
3968 ti.type = IPFW_TABLE_CIDR;
3970 error = (opt == IP_FW_TABLE_ADD) ?
3971 add_table_entry(chain, &ti, &tei, 0, 1) :
3972 del_table_entry(chain, &ti, &tei, 0, 1);
3977 case IP_FW_TABLE_FLUSH:
3982 error = sooptcopyin(sopt, &tbl,
3983 sizeof(tbl), sizeof(tbl));
3986 memset(&ti, 0, sizeof(ti));
3988 error = flush_table(chain, &ti);
3992 case IP_FW_TABLE_GETSIZE:
3997 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4000 memset(&ti, 0, sizeof(ti));
4003 error = ipfw_count_table(chain, &ti, &cnt);
4004 IPFW_RUNLOCK(chain);
4007 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4011 case IP_FW_TABLE_LIST:
4016 if (sopt->sopt_valsize < sizeof(*tbl)) {
4020 size = sopt->sopt_valsize;
4021 tbl = malloc(size, M_TEMP, M_WAITOK);
4022 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4027 tbl->size = (size - sizeof(*tbl)) /
4028 sizeof(ipfw_table_entry);
4029 memset(&ti, 0, sizeof(ti));
4032 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4033 IPFW_RUNLOCK(chain);
4038 error = sooptcopyout(sopt, tbl, size);
4043 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4045 if (IPFW_NAT_LOADED)
4046 error = ipfw_nat_cfg_ptr(sopt);
4048 printf("IP_FW_NAT_CFG: %s\n",
4049 "ipfw_nat not present, please load it");
4055 if (IPFW_NAT_LOADED)
4056 error = ipfw_nat_del_ptr(sopt);
4058 printf("IP_FW_NAT_DEL: %s\n",
4059 "ipfw_nat not present, please load it");
4064 case IP_FW_NAT_GET_CONFIG:
4065 if (IPFW_NAT_LOADED)
4066 error = ipfw_nat_get_cfg_ptr(sopt);
4068 printf("IP_FW_NAT_GET_CFG: %s\n",
4069 "ipfw_nat not present, please load it");
4074 case IP_FW_NAT_GET_LOG:
4075 if (IPFW_NAT_LOADED)
4076 error = ipfw_nat_get_log_ptr(sopt);
4078 printf("IP_FW_NAT_GET_LOG: %s\n",
4079 "ipfw_nat not present, please load it");
4085 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4092 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4094 /* Functions to convert rules 7.2 <==> 8.0 */
4096 convert_rule_to_7(struct ip_fw_rule0 *rule)
4098 /* Used to modify original rule */
4099 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4100 /* copy of original rule, version 8 */
4101 struct ip_fw_rule0 *tmp;
4103 /* Used to copy commands */
4104 ipfw_insn *ccmd, *dst;
4105 int ll = 0, ccmdlen = 0;
4107 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4109 return 1; //XXX error
4111 bcopy(rule, tmp, RULE_MAXSIZE);
4114 //rule7->_pad = tmp->_pad;
4115 rule7->set = tmp->set;
4116 rule7->rulenum = tmp->rulenum;
4117 rule7->cmd_len = tmp->cmd_len;
4118 rule7->act_ofs = tmp->act_ofs;
4119 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4120 rule7->cmd_len = tmp->cmd_len;
4121 rule7->pcnt = tmp->pcnt;
4122 rule7->bcnt = tmp->bcnt;
4123 rule7->timestamp = tmp->timestamp;
4126 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4127 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4128 ccmdlen = F_LEN(ccmd);
4130 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4132 if (dst->opcode > O_NAT)
4133 /* O_REASS doesn't exists in 7.2 version, so
4134 * decrement opcode if it is after O_REASS
4139 printf("ipfw: opcode %d size truncated\n",
4150 convert_rule_to_8(struct ip_fw_rule0 *rule)
4152 /* Used to modify original rule */
4153 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4155 /* Used to copy commands */
4156 ipfw_insn *ccmd, *dst;
4157 int ll = 0, ccmdlen = 0;
4159 /* Copy of original rule */
4160 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4162 return 1; //XXX error
4165 bcopy(rule7, tmp, RULE_MAXSIZE);
4167 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4168 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4169 ccmdlen = F_LEN(ccmd);
4171 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4173 if (dst->opcode > O_NAT)
4174 /* O_REASS doesn't exists in 7.2 version, so
4175 * increment opcode if it is after O_REASS
4180 printf("ipfw: opcode %d size truncated\n",
4186 rule->_pad = tmp->_pad;
4187 rule->set = tmp->set;
4188 rule->rulenum = tmp->rulenum;
4189 rule->cmd_len = tmp->cmd_len;
4190 rule->act_ofs = tmp->act_ofs;
4191 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4192 rule->cmd_len = tmp->cmd_len;
4193 rule->id = 0; /* XXX see if is ok = 0 */
4194 rule->pcnt = tmp->pcnt;
4195 rule->bcnt = tmp->bcnt;
4196 rule->timestamp = tmp->timestamp;
4208 ipfw_init_srv(struct ip_fw_chain *ch)
4211 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4212 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4213 M_IPFW, M_WAITOK | M_ZERO);
4217 ipfw_destroy_srv(struct ip_fw_chain *ch)
4220 free(ch->srvstate, M_IPFW);
4221 ipfw_objhash_destroy(ch->srvmap);
4225 * Allocate new bitmask which can be used to enlarge/shrink
4226 * named instance index.
4229 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4235 KASSERT((items % BLOCK_ITEMS) == 0,
4236 ("bitmask size needs to power of 2 and greater or equal to %zu",
4239 max_blocks = items / BLOCK_ITEMS;
4241 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4242 /* Mark all as free */
4243 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4244 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4247 *pblocks = max_blocks;
4251 * Copy current bitmask index to new one.
4254 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4256 int old_blocks, new_blocks;
4257 u_long *old_idx, *new_idx;
4260 old_idx = ni->idx_mask;
4261 old_blocks = ni->max_blocks;
4263 new_blocks = *blocks;
4265 for (i = 0; i < IPFW_MAX_SETS; i++) {
4266 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4267 old_blocks * sizeof(u_long));
4272 * Swaps current @ni index with new one.
4275 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4280 old_idx = ni->idx_mask;
4281 old_blocks = ni->max_blocks;
4283 ni->idx_mask = *idx;
4284 ni->max_blocks = *blocks;
4286 /* Save old values */
4288 *blocks = old_blocks;
4292 ipfw_objhash_bitmap_free(void *idx, int blocks)
4299 * Creates named hash instance.
4300 * Must be called without holding any locks.
4301 * Return pointer to new instance.
4303 struct namedobj_instance *
4304 ipfw_objhash_create(uint32_t items)
4306 struct namedobj_instance *ni;
4310 size = sizeof(struct namedobj_instance) +
4311 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4312 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4314 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4315 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4316 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4318 ni->names = (struct namedobjects_head *)(ni +1);
4319 ni->values = &ni->names[ni->nn_size];
4321 for (i = 0; i < ni->nn_size; i++)
4322 TAILQ_INIT(&ni->names[i]);
4324 for (i = 0; i < ni->nv_size; i++)
4325 TAILQ_INIT(&ni->values[i]);
4327 /* Set default hashing/comparison functions */
4328 ni->hash_f = objhash_hash_name;
4329 ni->cmp_f = objhash_cmp_name;
4331 /* Allocate bitmask separately due to possible resize */
4332 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4338 ipfw_objhash_destroy(struct namedobj_instance *ni)
4341 free(ni->idx_mask, M_IPFW);
4346 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4347 objhash_cmp_f *cmp_f)
4350 ni->hash_f = hash_f;
4355 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4358 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4362 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4365 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4372 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4376 v = val % (ni->nv_size - 1);
4381 struct named_object *
4382 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4384 struct named_object *no;
4387 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4389 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4390 if (ni->cmp_f(no, name, set) == 0)
4398 * Find named object by @uid.
4399 * Check @tlvs for valid data inside.
4401 * Returns pointer to found TLV or NULL.
4404 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4406 ipfw_obj_ntlv *ntlv;
4410 pa = (uintptr_t)tlvs;
4413 for (; pa < pe; pa += l) {
4414 ntlv = (ipfw_obj_ntlv *)pa;
4415 l = ntlv->head.length;
4417 if (l != sizeof(*ntlv))
4420 if (ntlv->idx != uidx)
4423 * When userland has specified zero TLV type, do
4424 * not compare it with eltv. In some cases userland
4425 * doesn't know what type should it have. Use only
4426 * uidx and name for search named_object.
4428 if (ntlv->head.type != 0 &&
4429 ntlv->head.type != (uint16_t)etlv)
4432 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4442 * Finds object config based on either legacy index
4444 * Note @ti structure contains unchecked data from userland.
4446 * Returns 0 in success and fills in @pno with found config
4449 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4450 uint32_t etlv, struct named_object **pno)
4453 ipfw_obj_ntlv *ntlv;
4456 if (ti->tlvs == NULL)
4459 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4465 * Use set provided by @ti instead of @ntlv one.
4466 * This is needed due to different sets behavior
4467 * controlled by V_fw_tables_sets.
4470 *pno = ipfw_objhash_lookup_name(ni, set, name);
4477 * Find named object by name, considering also its TLV type.
4479 struct named_object *
4480 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4481 uint32_t type, const char *name)
4483 struct named_object *no;
4486 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4488 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4489 if (ni->cmp_f(no, name, set) == 0 &&
4490 no->etlv == (uint16_t)type)
4497 struct named_object *
4498 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4500 struct named_object *no;
4503 hash = objhash_hash_idx(ni, kidx);
4505 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4506 if (no->kidx == kidx)
4514 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4515 struct named_object *b)
4518 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4525 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4529 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4530 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4532 hash = objhash_hash_idx(ni, no->kidx);
4533 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4539 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4543 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4544 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4546 hash = objhash_hash_idx(ni, no->kidx);
4547 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4553 ipfw_objhash_count(struct namedobj_instance *ni)
4560 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4562 struct named_object *no;
4567 for (i = 0; i < ni->nn_size; i++) {
4568 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4569 if (no->etlv == type)
4577 * Runs @func for each found named object.
4578 * It is safe to delete objects from callback
4581 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4583 struct named_object *no, *no_tmp;
4586 for (i = 0; i < ni->nn_size; i++) {
4587 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4588 ret = f(ni, no, arg);
4597 * Runs @f for each found named object with type @type.
4598 * It is safe to delete objects from callback
4601 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4602 void *arg, uint16_t type)
4604 struct named_object *no, *no_tmp;
4607 for (i = 0; i < ni->nn_size; i++) {
4608 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4609 if (no->etlv != type)
4611 ret = f(ni, no, arg);
4620 * Removes index from given set.
4621 * Returns 0 on success.
4624 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4629 i = idx / BLOCK_ITEMS;
4630 v = idx % BLOCK_ITEMS;
4632 if (i >= ni->max_blocks)
4635 mask = &ni->idx_mask[i];
4637 if ((*mask & ((u_long)1 << v)) != 0)
4641 *mask |= (u_long)1 << v;
4643 /* Update free offset */
4644 if (ni->free_off[0] > i)
4645 ni->free_off[0] = i;
4651 * Allocate new index in given instance and stores in in @pidx.
4652 * Returns 0 on success.
4655 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4657 struct namedobj_instance *ni;
4661 ni = (struct namedobj_instance *)n;
4663 off = ni->free_off[0];
4664 mask = &ni->idx_mask[off];
4666 for (i = off; i < ni->max_blocks; i++, mask++) {
4667 if ((v = ffsl(*mask)) == 0)
4671 *mask &= ~ ((u_long)1 << (v - 1));
4673 ni->free_off[0] = i;
4675 v = BLOCK_ITEMS * i + v - 1;