2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 * Copyright (c) 2014 Yandex LLC
4 * Copyright (c) 2014 Alexander V. Chernikov
6 * Supported by: Valeria Paoli
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
34 * Control socket and rule management routines for ipfw.
35 * Control is currently implemented via IP_FW3 setsockopt() code.
41 #error IPFIREWALL requires INET.
43 #include "opt_inet6.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h> /* struct m_tag used by nested headers */
49 #include <sys/kernel.h>
53 #include <sys/rwlock.h>
54 #include <sys/rmlock.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/fnv_hash.h>
62 #include <net/route.h>
65 #include <vm/vm_extern.h>
67 #include <netinet/in.h>
68 #include <netinet/ip_var.h> /* hooks */
69 #include <netinet/ip_fw.h>
71 #include <netpfil/ipfw/ip_fw_private.h>
72 #include <netpfil/ipfw/ip_fw_table.h>
75 #include <security/mac/mac_framework.h>
78 static int ipfw_ctl(struct sockopt *sopt);
79 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
80 struct rule_check_info *ci);
81 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
82 struct rule_check_info *ci);
83 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
84 struct rule_check_info *ci);
85 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
86 struct rule_check_info *ci);
88 #define NAMEDOBJ_HASH_SIZE 32
90 struct namedobj_instance {
91 struct namedobjects_head *names;
92 struct namedobjects_head *values;
93 uint32_t nn_size; /* names hash size */
94 uint32_t nv_size; /* number hash size */
95 u_long *idx_mask; /* used items bitmask */
96 uint32_t max_blocks; /* number of "long" blocks in bitmask */
97 uint32_t count; /* number of items */
98 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
99 objhash_hash_f *hash_f;
100 objhash_cmp_f *cmp_f;
102 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
104 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
105 const void *key, uint32_t kopt);
106 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
107 static int objhash_cmp_name(struct named_object *no, const void *name,
110 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
112 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
113 struct sockopt_data *sd);
114 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
115 struct sockopt_data *sd);
116 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
117 struct sockopt_data *sd);
118 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
119 struct sockopt_data *sd);
120 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
121 struct sockopt_data *sd);
122 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
123 struct sockopt_data *sd);
124 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
125 struct sockopt_data *sd);
126 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
127 struct sockopt_data *sd);
129 /* ctl3 handler data */
130 struct mtx ctl3_lock;
131 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
132 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
133 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
134 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
136 static struct ipfw_sopt_handler *ctl3_handlers;
137 static size_t ctl3_hsize;
138 static uint64_t ctl3_refct, ctl3_gencnt;
139 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
140 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
142 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
144 static struct ipfw_sopt_handler scodes[] = {
145 { IP_FW_XGET, 0, HDIR_GET, dump_config },
146 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
147 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
148 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
149 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
150 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
151 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
152 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
153 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
154 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
155 { IP_FW_DUMP_SRVOBJECTS,0, HDIR_GET, dump_srvobjects },
159 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
160 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
161 uint16_t *puidx, uint8_t *ptype);
162 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
163 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
164 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
165 struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
166 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
167 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
168 struct obj_idx *oib, struct obj_idx *end);
169 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
170 struct sockopt_data *sd);
173 * Opcode object rewriter variables
175 struct opcode_obj_rewrite *ctl3_rewriters;
176 static size_t ctl3_rsize;
179 * static variables followed by global ones
182 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
183 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
189 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
190 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
191 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
195 ipfw_destroy_counters()
198 uma_zdestroy(V_ipfw_cntr_zone);
202 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
206 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
207 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
214 ipfw_free_rule(struct ip_fw *rule)
218 * We don't release refcnt here, since this function
219 * can be called without any locks held. The caller
220 * must release reference under IPFW_UH_WLOCK, and then
221 * call this function if refcount becomes 1.
223 if (rule->refcnt > 1)
225 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
231 * Find the smallest rule >= key, id.
232 * We could use bsearch but it is so simple that we code it directly
235 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
240 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
243 if (r->rulenum < key)
244 lo = i + 1; /* continue from the next one */
245 else if (r->rulenum > key)
246 hi = i; /* this might be good */
248 lo = i + 1; /* continue from the next one */
249 else /* r->id >= id */
250 hi = i; /* this might be good */
256 * Builds skipto cache on rule set @map.
259 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
264 IPFW_UH_WLOCK_ASSERT(chain);
267 rulenum = map[mi]->rulenum;
268 smap = chain->idxmap_back;
273 for (i = 0; i < 65536; i++) {
275 /* Use the same rule index until i < rulenum */
276 if (i != rulenum || i == 65535)
278 /* Find next rule with num > i */
279 rulenum = map[++mi]->rulenum;
281 rulenum = map[++mi]->rulenum;
286 * Swaps prepared (backup) index with current one.
289 swap_skipto_cache(struct ip_fw_chain *chain)
293 IPFW_UH_WLOCK_ASSERT(chain);
294 IPFW_WLOCK_ASSERT(chain);
297 chain->idxmap = chain->idxmap_back;
298 chain->idxmap_back = map;
302 * Allocate and initialize skipto cache.
305 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
307 int *idxmap, *idxmap_back;
309 idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
310 idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
313 * Note we may be called at any time after initialization,
314 * for example, on first skipto rule, so we need to
315 * provide valid chain->idxmap on return
318 IPFW_UH_WLOCK(chain);
319 if (chain->idxmap != NULL) {
320 IPFW_UH_WUNLOCK(chain);
321 free(idxmap, M_IPFW);
322 free(idxmap_back, M_IPFW);
326 /* Set backup pointer first to permit building cache */
327 chain->idxmap_back = idxmap_back;
328 update_skipto_cache(chain, chain->map);
330 /* It is now safe to set chain->idxmap ptr */
331 chain->idxmap = idxmap;
332 swap_skipto_cache(chain);
334 IPFW_UH_WUNLOCK(chain);
338 * Destroys skipto cache.
341 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
344 if (chain->idxmap != NULL)
345 free(chain->idxmap, M_IPFW);
346 if (chain->idxmap != NULL)
347 free(chain->idxmap_back, M_IPFW);
352 * allocate a new map, returns the chain locked. extra is the number
353 * of entries to add or delete.
355 static struct ip_fw **
356 get_map(struct ip_fw_chain *chain, int extra, int locked)
363 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
365 i = chain->n_rules + extra;
366 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
368 printf("%s: cannot allocate map\n", __FUNCTION__);
372 IPFW_UH_WLOCK(chain);
373 if (i >= chain->n_rules + extra) /* good */
375 /* otherwise we lost the race, free and retry */
377 IPFW_UH_WUNLOCK(chain);
383 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
385 static struct ip_fw **
386 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
388 struct ip_fw **old_map;
392 chain->n_rules = new_len;
393 old_map = chain->map;
394 chain->map = new_map;
395 swap_skipto_cache(chain);
402 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
404 struct timeval boottime;
406 cntr->size = sizeof(*cntr);
408 if (krule->cntr != NULL) {
409 cntr->pcnt = counter_u64_fetch(krule->cntr);
410 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
411 cntr->timestamp = krule->timestamp;
413 if (cntr->timestamp > 0) {
414 getboottime(&boottime);
415 cntr->timestamp += boottime.tv_sec;
420 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
422 struct timeval boottime;
424 if (krule->cntr != NULL) {
425 cntr->pcnt = counter_u64_fetch(krule->cntr);
426 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
427 cntr->timestamp = krule->timestamp;
429 if (cntr->timestamp > 0) {
430 getboottime(&boottime);
431 cntr->timestamp += boottime.tv_sec;
436 * Copies rule @urule from v1 userland format (current).
438 * Assume @krule is zeroed.
441 import_rule1(struct rule_check_info *ci)
443 struct ip_fw_rule *urule;
446 urule = (struct ip_fw_rule *)ci->urule;
447 krule = (struct ip_fw *)ci->krule;
450 krule->act_ofs = urule->act_ofs;
451 krule->cmd_len = urule->cmd_len;
452 krule->rulenum = urule->rulenum;
453 krule->set = urule->set;
454 krule->flags = urule->flags;
456 /* Save rulenum offset */
457 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
460 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
464 * Export rule into v1 format (Current).
466 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
468 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
470 * Assume @data is zeroed.
473 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
475 struct ip_fw_bcounter *cntr;
476 struct ip_fw_rule *urule;
479 /* Fill in TLV header */
480 tlv = (ipfw_obj_tlv *)data;
481 tlv->type = IPFW_TLV_RULE_ENT;
486 cntr = (struct ip_fw_bcounter *)(tlv + 1);
487 urule = (struct ip_fw_rule *)(cntr + 1);
488 export_cntr1_base(krule, cntr);
490 urule = (struct ip_fw_rule *)(tlv + 1);
493 urule->act_ofs = krule->act_ofs;
494 urule->cmd_len = krule->cmd_len;
495 urule->rulenum = krule->rulenum;
496 urule->set = krule->set;
497 urule->flags = krule->flags;
498 urule->id = krule->id;
501 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
506 * Copies rule @urule from FreeBSD8 userland format (v0)
508 * Assume @krule is zeroed.
511 import_rule0(struct rule_check_info *ci)
513 struct ip_fw_rule0 *urule;
517 ipfw_insn_limit *lcmd;
520 urule = (struct ip_fw_rule0 *)ci->urule;
521 krule = (struct ip_fw *)ci->krule;
524 krule->act_ofs = urule->act_ofs;
525 krule->cmd_len = urule->cmd_len;
526 krule->rulenum = urule->rulenum;
527 krule->set = urule->set;
528 if ((urule->_pad & 1) != 0)
529 krule->flags |= IPFW_RULE_NOOPT;
531 /* Save rulenum offset */
532 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
535 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
539 * 1) convert tablearg value from 65535 to 0
540 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
542 * 3) convert table number in iface opcodes to u16
543 * 4) convert old `nat global` into new 65535
549 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
552 switch (cmd->opcode) {
553 /* Opcodes supporting tablearg */
565 if (cmd->arg1 == IP_FW_TABLEARG)
566 cmd->arg1 = IP_FW_TARG;
567 else if (cmd->arg1 == 0)
568 cmd->arg1 = IP_FW_NAT44_GLOBAL;
572 if (cmd->arg1 == IP_FW_TABLEARG)
573 cmd->arg1 = IP_FW_TARG;
578 lcmd = (ipfw_insn_limit *)cmd;
579 if (lcmd->conn_limit == IP_FW_TABLEARG)
580 lcmd->conn_limit = IP_FW_TARG;
582 /* Interface tables */
586 /* Interface table, possibly */
587 cmdif = (ipfw_insn_if *)cmd;
588 if (cmdif->name[0] != '\1')
591 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
598 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
601 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
605 ipfw_insn_limit *lcmd;
609 memset(urule, 0, len);
610 urule->act_ofs = krule->act_ofs;
611 urule->cmd_len = krule->cmd_len;
612 urule->rulenum = krule->rulenum;
613 urule->set = krule->set;
614 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
618 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
620 /* Export counters */
621 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
625 * 1) convert tablearg value from 0 to 65535
626 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
627 * 3) convert table number in iface opcodes to int
633 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
636 switch (cmd->opcode) {
637 /* Opcodes supporting tablearg */
649 if (cmd->arg1 == IP_FW_TARG)
650 cmd->arg1 = IP_FW_TABLEARG;
651 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
656 if (cmd->arg1 == IP_FW_TARG)
657 cmd->arg1 = IP_FW_TABLEARG;
659 cmd->arg1 &= ~0x8000;
662 lcmd = (ipfw_insn_limit *)cmd;
663 if (lcmd->conn_limit == IP_FW_TARG)
664 lcmd->conn_limit = IP_FW_TABLEARG;
666 /* Interface tables */
670 /* Interface table, possibly */
671 cmdif = (ipfw_insn_if *)cmd;
672 if (cmdif->name[0] != '\1')
675 cmdif->p.glob = cmdif->p.kidx;
682 * Add new rule(s) to the list possibly creating rule number for each.
683 * Update the rule_number in the input struct so the caller knows it as well.
684 * Must be called without IPFW_UH held
687 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
689 int error, i, insert_before, tcount;
690 uint16_t rulenum, *pnum;
691 struct rule_check_info *ci;
693 struct ip_fw **map; /* the new array of pointers */
695 /* Check if we need to do table/obj index remap */
697 for (ci = rci, i = 0; i < count; ci++, i++) {
698 if (ci->object_opcodes == 0)
702 * Rule has some object opcodes.
703 * We need to find (and create non-existing)
704 * kernel objects, and reference existing ones.
706 error = rewrite_rule_uidx(chain, ci);
710 * rewrite failed, state for current rule
711 * has been reverted. Check if we need to
717 * We have some more table rules
718 * we need to rollback.
721 IPFW_UH_WLOCK(chain);
724 if (ci->object_opcodes == 0)
726 unref_rule_objects(chain,ci->krule);
729 IPFW_UH_WUNLOCK(chain);
739 /* get_map returns with IPFW_UH_WLOCK if successful */
740 map = get_map(chain, count, 0 /* not locked */);
744 IPFW_UH_WLOCK(chain);
745 for (ci = rci, i = 0; i < count; ci++, i++) {
746 if (ci->object_opcodes == 0)
749 unref_rule_objects(chain, ci->krule);
751 IPFW_UH_WUNLOCK(chain);
757 if (V_autoinc_step < 1)
759 else if (V_autoinc_step > 1000)
760 V_autoinc_step = 1000;
762 /* FIXME: Handle count > 1 */
765 rulenum = krule->rulenum;
767 /* find the insertion point, we will insert before */
768 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
769 i = ipfw_find_rule(chain, insert_before, 0);
770 /* duplicate first part */
772 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
774 /* duplicate remaining part, we always have the default rule */
775 bcopy(chain->map + i, map + i + 1,
776 sizeof(struct ip_fw *) *(chain->n_rules - i));
778 /* Compute rule number and write it back */
779 rulenum = i > 0 ? map[i-1]->rulenum : 0;
780 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
781 rulenum += V_autoinc_step;
782 krule->rulenum = rulenum;
783 /* Save number to userland rule */
784 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
788 krule->id = chain->id + 1;
789 update_skipto_cache(chain, map);
790 map = swap_map(chain, map, chain->n_rules + 1);
791 chain->static_len += RULEUSIZE0(krule);
792 IPFW_UH_WUNLOCK(chain);
799 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
804 map = get_map(chain, 1, locked);
807 if (chain->n_rules > 0)
808 bcopy(chain->map, map,
809 chain->n_rules * sizeof(struct ip_fw *));
810 map[chain->n_rules] = rule;
811 rule->rulenum = IPFW_DEFAULT_RULE;
812 rule->set = RESVD_SET;
813 rule->id = chain->id + 1;
814 /* We add rule in the end of chain, no need to update skipto cache */
815 map = swap_map(chain, map, chain->n_rules + 1);
816 chain->static_len += RULEUSIZE0(rule);
817 IPFW_UH_WUNLOCK(chain);
823 * Adds @rule to the list of rules to reap
826 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
830 IPFW_UH_WLOCK_ASSERT(chain);
832 /* Unlink rule from everywhere */
833 unref_rule_objects(chain, rule);
840 * Reclaim storage associated with a list of rules. This is
841 * typically the list created using remove_rule.
842 * A NULL pointer on input is handled correctly.
845 ipfw_reap_rules(struct ip_fw *head)
849 while ((rule = head) != NULL) {
851 ipfw_free_rule(rule);
857 * (default || reserved || !match_set || !match_number)
859 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
860 * // the default rule is always protected
862 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
863 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
865 * match_set ::= (cmd == 0 || rule->set == set)
866 * // set number is ignored for cmd == 0
868 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
869 * // number is ignored for cmd == 1 or n == 0
873 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
876 /* Don't match default rule for modification queries */
877 if (rule->rulenum == IPFW_DEFAULT_RULE &&
878 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
881 /* Don't match rules in reserved set for flush requests */
882 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
885 /* If we're filtering by set, don't match other sets */
886 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
889 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
890 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
896 struct manage_sets_args {
902 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
905 struct manage_sets_args *args;
907 args = (struct manage_sets_args *)arg;
908 if (no->set == (uint8_t)args->set)
909 no->set = args->new_set;
910 else if (no->set == args->new_set)
911 no->set = (uint8_t)args->set;
916 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
919 struct manage_sets_args *args;
921 args = (struct manage_sets_args *)arg;
922 if (no->set == (uint8_t)args->set)
923 no->set = args->new_set;
928 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
931 struct manage_sets_args *args;
933 args = (struct manage_sets_args *)arg;
934 if (no->set != (uint8_t)args->set)
936 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
937 no->etlv, no->name) != NULL)
943 * Generic function to handler moving and swapping sets.
946 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
947 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
949 struct manage_sets_args args;
950 struct named_object *no;
953 args.new_set = new_set;
956 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
959 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
962 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
966 * @set used to pass kidx.
967 * When @new_set is zero - reset object counter,
968 * otherwise increment it.
970 no = ipfw_objhash_lookup_kidx(ni, set);
977 /* @set used to pass kidx */
978 no = ipfw_objhash_lookup_kidx(ni, set);
980 * First check number of references:
981 * when it differs, this mean other rules are holding
982 * reference to given object, so it is not possible to
983 * change its set. Note that refcnt may account references
984 * to some going-to-be-added rules. Since we don't know
985 * their numbers (and even if they will be added) it is
986 * perfectly OK to return error here.
988 if (no->ocnt != no->refcnt)
990 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
995 /* @set used to pass kidx */
996 no = ipfw_objhash_lookup_kidx(ni, set);
1004 * Delete rules matching range @rt.
1005 * Saves number of deleted rules in @ndel.
1007 * Returns 0 on success.
1010 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1012 struct ip_fw *reap, *rule, **map;
1014 int i, n, ndyn, ofs;
1017 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1020 * Stage 1: Determine range to inspect.
1021 * Range is half-inclusive, e.g [start, end).
1024 end = chain->n_rules - 1;
1026 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1027 start = ipfw_find_rule(chain, rt->start_rule, 0);
1029 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1030 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1031 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1034 if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1036 * Requested deleting only for dynamic states.
1039 ipfw_expire_dyn_states(chain, rt);
1040 IPFW_UH_WUNLOCK(chain);
1044 /* Allocate new map of the same size */
1045 map = get_map(chain, 0, 1 /* locked */);
1047 IPFW_UH_WUNLOCK(chain);
1054 /* 1. bcopy the initial part of the map */
1056 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1057 /* 2. copy active rules between start and end */
1058 for (i = start; i < end; i++) {
1059 rule = chain->map[i];
1060 if (ipfw_match_range(rule, rt) == 0) {
1066 if (ipfw_is_dyn_rule(rule) != 0)
1069 /* 3. copy the final part of the map */
1070 bcopy(chain->map + end, map + ofs,
1071 (chain->n_rules - end) * sizeof(struct ip_fw *));
1072 /* 4. recalculate skipto cache */
1073 update_skipto_cache(chain, map);
1074 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1075 map = swap_map(chain, map, chain->n_rules - n);
1076 /* 6. Remove all dynamic states originated by deleted rules */
1078 ipfw_expire_dyn_states(chain, rt);
1079 /* 7. now remove the rules deleted from the old map */
1080 for (i = start; i < end; i++) {
1082 if (ipfw_match_range(rule, rt) == 0)
1084 chain->static_len -= RULEUSIZE0(rule);
1085 ipfw_reap_add(chain, &reap, rule);
1087 IPFW_UH_WUNLOCK(chain);
1089 ipfw_reap_rules(reap);
1097 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1099 struct opcode_obj_rewrite *rw;
1102 int cmdlen, i, l, c;
1105 IPFW_UH_WLOCK_ASSERT(ch);
1107 /* Stage 1: count number of references by given rules */
1108 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1110 if (ipfw_match_range(rule, rt) == 0)
1112 if (rule->set == rt->new_set) /* nothing to do */
1114 /* Search opcodes with named objects */
1115 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1116 l > 0; l -= cmdlen, cmd += cmdlen) {
1117 cmdlen = F_LEN(cmd);
1118 rw = find_op_rw(cmd, &kidx, NULL);
1119 if (rw == NULL || rw->manage_sets == NULL)
1122 * When manage_sets() returns non-zero value to
1123 * COUNT_ONE command, consider this as an object
1124 * doesn't support sets (e.g. disabled with sysctl).
1125 * So, skip checks for this object.
1127 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1132 if (c == 0) /* No objects found */
1134 /* Stage 2: verify "ownership" */
1135 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1137 if (ipfw_match_range(rule, rt) == 0)
1139 if (rule->set == rt->new_set) /* nothing to do */
1141 /* Search opcodes with named objects */
1142 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1143 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1144 cmdlen = F_LEN(cmd);
1145 rw = find_op_rw(cmd, &kidx, NULL);
1146 if (rw == NULL || rw->manage_sets == NULL)
1148 /* Test for ownership and conflicting names */
1149 c = rw->manage_sets(ch, kidx,
1150 (uint8_t)rt->new_set, TEST_ONE);
1153 /* Stage 3: change set and cleanup */
1154 for (i = 0; i < ch->n_rules - 1; i++) {
1156 if (ipfw_match_range(rule, rt) == 0)
1158 if (rule->set == rt->new_set) /* nothing to do */
1160 /* Search opcodes with named objects */
1161 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1162 l > 0; l -= cmdlen, cmd += cmdlen) {
1163 cmdlen = F_LEN(cmd);
1164 rw = find_op_rw(cmd, &kidx, NULL);
1165 if (rw == NULL || rw->manage_sets == NULL)
1167 /* cleanup object counter */
1168 rw->manage_sets(ch, kidx,
1169 0 /* reset counter */, COUNT_ONE);
1173 rw->manage_sets(ch, kidx,
1174 (uint8_t)rt->new_set, MOVE_ONE);
1179 * Changes set of given rule rannge @rt
1182 * Returns 0 on success.
1185 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1190 IPFW_UH_WLOCK(chain);
1193 * Move rules with matching paramenerts to a new set.
1194 * This one is much more complex. We have to ensure
1195 * that all referenced tables (if any) are referenced
1196 * by given rule subset only. Otherwise, we can't move
1197 * them to new set and have to return error.
1199 if ((i = move_objects(chain, rt)) != 0) {
1200 IPFW_UH_WUNLOCK(chain);
1204 /* XXX: We have to do swap holding WLOCK */
1205 for (i = 0; i < chain->n_rules; i++) {
1206 rule = chain->map[i];
1207 if (ipfw_match_range(rule, rt) == 0)
1209 rule->set = rt->new_set;
1212 IPFW_UH_WUNLOCK(chain);
1218 * Clear counters for a specific rule.
1219 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1220 * so we only care that rules do not disappear.
1223 clear_counters(struct ip_fw *rule, int log_only)
1225 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1228 IPFW_ZERO_RULE_COUNTER(rule);
1229 if (l->o.opcode == O_LOG)
1230 l->log_left = l->max_log;
1234 * Flushes rules counters and/or log values on matching range.
1236 * Returns number of items cleared.
1239 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1246 rt->flags |= IPFW_RCFLAG_DEFAULT;
1248 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1249 for (i = 0; i < chain->n_rules; i++) {
1250 rule = chain->map[i];
1251 if (ipfw_match_range(rule, rt) == 0)
1253 clear_counters(rule, log_only);
1256 IPFW_UH_WUNLOCK(chain);
1262 check_range_tlv(ipfw_range_tlv *rt)
1265 if (rt->head.length != sizeof(*rt))
1267 if (rt->start_rule > rt->end_rule)
1269 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1272 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1279 * Delete rules matching specified parameters
1280 * Data layout (v0)(current):
1281 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1282 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1284 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1286 * Returns 0 on success.
1289 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1290 struct sockopt_data *sd)
1292 ipfw_range_header *rh;
1295 if (sd->valsize != sizeof(*rh))
1298 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1300 if (check_range_tlv(&rh->range) != 0)
1304 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1307 /* Save number of rules deleted */
1308 rh->range.new_set = ndel;
1313 * Move rules/sets matching specified parameters
1314 * Data layout (v0)(current):
1315 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1317 * Returns 0 on success.
1320 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1321 struct sockopt_data *sd)
1323 ipfw_range_header *rh;
1325 if (sd->valsize != sizeof(*rh))
1328 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1330 if (check_range_tlv(&rh->range) != 0)
1333 return (move_range(chain, &rh->range));
1337 * Clear rule accounting data matching specified parameters
1338 * Data layout (v0)(current):
1339 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1340 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1342 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1344 * Returns 0 on success.
1347 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1348 struct sockopt_data *sd)
1350 ipfw_range_header *rh;
1354 if (sd->valsize != sizeof(*rh))
1357 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1359 if (check_range_tlv(&rh->range) != 0)
1362 log_only = (op3->opcode == IP_FW_XRESETLOG);
1364 num = clear_range(chain, &rh->range, log_only);
1366 if (rh->range.flags & IPFW_RCFLAG_ALL)
1367 msg = log_only ? "All logging counts reset" :
1368 "Accounting cleared";
1370 msg = log_only ? "logging count reset" : "cleared";
1373 int lev = LOG_SECURITY | LOG_NOTICE;
1374 log(lev, "ipfw: %s.\n", msg);
1377 /* Save number of rules cleared */
1378 rh->range.new_set = num;
1383 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1387 IPFW_UH_WLOCK_ASSERT(chain);
1389 /* Change enabled/disabled sets mask */
1390 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1391 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1393 V_set_disable = v_set;
1394 IPFW_WUNLOCK(chain);
1398 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1400 struct opcode_obj_rewrite *rw;
1404 IPFW_UH_WLOCK_ASSERT(chain);
1406 if (rt->set == rt->new_set) /* nothing to do */
1411 * Berfore moving the rules we need to check that
1412 * there aren't any conflicting named objects.
1414 for (rw = ctl3_rewriters;
1415 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1416 if (rw->manage_sets == NULL)
1418 i = rw->manage_sets(chain, (uint8_t)rt->set,
1419 (uint8_t)rt->new_set, TEST_ALL);
1424 /* Swap or move two sets */
1425 for (i = 0; i < chain->n_rules - 1; i++) {
1426 rule = chain->map[i];
1427 if (rule->set == (uint8_t)rt->set)
1428 rule->set = (uint8_t)rt->new_set;
1429 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1430 rule->set = (uint8_t)rt->set;
1432 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1433 if (rw->manage_sets == NULL)
1435 rw->manage_sets(chain, (uint8_t)rt->set,
1436 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1442 * Swaps or moves set
1443 * Data layout (v0)(current):
1444 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1446 * Returns 0 on success.
1449 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1450 struct sockopt_data *sd)
1452 ipfw_range_header *rh;
1455 if (sd->valsize != sizeof(*rh))
1458 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1460 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1462 /* enable_sets() expects bitmasks. */
1463 if (op3->opcode != IP_FW_SET_ENABLE &&
1464 (rh->range.set >= IPFW_MAX_SETS ||
1465 rh->range.new_set >= IPFW_MAX_SETS))
1469 IPFW_UH_WLOCK(chain);
1470 switch (op3->opcode) {
1471 case IP_FW_SET_SWAP:
1472 case IP_FW_SET_MOVE:
1473 ret = swap_sets(chain, &rh->range,
1474 op3->opcode == IP_FW_SET_MOVE);
1476 case IP_FW_SET_ENABLE:
1477 enable_sets(chain, &rh->range);
1480 IPFW_UH_WUNLOCK(chain);
1486 * Remove all rules with given number, or do set manipulation.
1487 * Assumes chain != NULL && *chain != NULL.
1489 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1490 * the next 8 bits are the new set; the top 8 bits indicate the command:
1492 * 0 delete rules numbered "rulenum"
1493 * 1 delete rules in set "rulenum"
1494 * 2 move rules "rulenum" to set "new_set"
1495 * 3 move rules from set "rulenum" to set "new_set"
1496 * 4 swap sets "rulenum" and "new_set"
1497 * 5 delete rules "rulenum" and set "new_set"
1500 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1502 uint32_t num; /* rule number or old_set */
1503 uint8_t cmd, new_set;
1509 cmd = (arg >> 24) & 0xff;
1510 new_set = (arg >> 16) & 0xff;
1512 if (cmd > 5 || new_set > RESVD_SET)
1514 if (cmd == 0 || cmd == 2 || cmd == 5) {
1515 if (num >= IPFW_DEFAULT_RULE)
1518 if (num > RESVD_SET) /* old_set */
1522 /* Convert old requests into new representation */
1523 memset(&rt, 0, sizeof(rt));
1524 rt.start_rule = num;
1527 rt.new_set = new_set;
1531 case 0: /* delete rules numbered "rulenum" */
1533 rt.flags |= IPFW_RCFLAG_ALL;
1535 rt.flags |= IPFW_RCFLAG_RANGE;
1538 case 1: /* delete rules in set "rulenum" */
1539 rt.flags |= IPFW_RCFLAG_SET;
1542 case 5: /* delete rules "rulenum" and set "new_set" */
1543 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1548 case 2: /* move rules "rulenum" to set "new_set" */
1549 rt.flags |= IPFW_RCFLAG_RANGE;
1551 case 3: /* move rules from set "rulenum" to set "new_set" */
1552 IPFW_UH_WLOCK(chain);
1553 error = swap_sets(chain, &rt, 1);
1554 IPFW_UH_WUNLOCK(chain);
1556 case 4: /* swap sets "rulenum" and "new_set" */
1557 IPFW_UH_WLOCK(chain);
1558 error = swap_sets(chain, &rt, 0);
1559 IPFW_UH_WUNLOCK(chain);
1566 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1569 if (ndel == 0 && (cmd != 1 && num != 0))
1575 return (move_range(chain, &rt));
1579 * Reset some or all counters on firewall rules.
1580 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1581 * the next 8 bits are the set number, the top 8 bits are the command:
1582 * 0 work with rules from all set's;
1583 * 1 work with rules only from specified set.
1584 * Specified rule number is zero if we want to clear all entries.
1585 * log_only is 1 if we only want to reset logs, zero otherwise.
1588 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1594 uint16_t rulenum = arg & 0xffff;
1595 uint8_t set = (arg >> 16) & 0xff;
1596 uint8_t cmd = (arg >> 24) & 0xff;
1600 if (cmd == 1 && set > RESVD_SET)
1603 IPFW_UH_RLOCK(chain);
1605 V_norule_counter = 0;
1606 for (i = 0; i < chain->n_rules; i++) {
1607 rule = chain->map[i];
1608 /* Skip rules not in our set. */
1609 if (cmd == 1 && rule->set != set)
1611 clear_counters(rule, log_only);
1613 msg = log_only ? "All logging counts reset" :
1614 "Accounting cleared";
1617 for (i = 0; i < chain->n_rules; i++) {
1618 rule = chain->map[i];
1619 if (rule->rulenum == rulenum) {
1620 if (cmd == 0 || rule->set == set)
1621 clear_counters(rule, log_only);
1624 if (rule->rulenum > rulenum)
1627 if (!cleared) { /* we did not find any matching rules */
1628 IPFW_UH_RUNLOCK(chain);
1631 msg = log_only ? "logging count reset" : "cleared";
1633 IPFW_UH_RUNLOCK(chain);
1636 int lev = LOG_SECURITY | LOG_NOTICE;
1639 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1641 log(lev, "ipfw: %s.\n", msg);
1648 * Check rule head in FreeBSD11 format
1652 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1653 struct rule_check_info *ci)
1657 if (size < sizeof(*rule)) {
1658 printf("ipfw: rule too short\n");
1662 /* Check for valid cmd_len */
1663 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1665 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1668 if (rule->act_ofs >= rule->cmd_len) {
1669 printf("ipfw: bogus action offset (%u > %u)\n",
1670 rule->act_ofs, rule->cmd_len - 1);
1674 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1677 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1681 * Check rule head in FreeBSD8 format
1685 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1686 struct rule_check_info *ci)
1690 if (size < sizeof(*rule)) {
1691 printf("ipfw: rule too short\n");
1695 /* Check for valid cmd_len */
1696 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1698 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1701 if (rule->act_ofs >= rule->cmd_len) {
1702 printf("ipfw: bogus action offset (%u > %u)\n",
1703 rule->act_ofs, rule->cmd_len - 1);
1707 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1710 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1714 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1722 * Now go for the individual checks. Very simple ones, basically only
1723 * instruction sizes.
1725 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1726 cmdlen = F_LEN(cmd);
1728 printf("ipfw: opcode %d size truncated\n",
1732 switch (cmd->opcode) {
1735 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1737 ci->object_opcodes++;
1748 case O_IPPRECEDENCE:
1767 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1771 case O_EXTERNAL_ACTION:
1772 if (cmd->arg1 == 0 ||
1773 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1774 printf("ipfw: invalid external "
1778 ci->object_opcodes++;
1780 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1786 cmdlen = F_LEN(cmd);
1787 if (cmd->opcode == O_EXTERNAL_DATA)
1789 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1790 printf("ipfw: invalid opcode "
1791 "next to external action %u\n",
1795 if (cmd->arg1 == 0 ||
1796 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1797 printf("ipfw: invalid external "
1798 "action instance opcode\n");
1801 ci->object_opcodes++;
1806 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1808 if (cmd->arg1 >= rt_numfibs) {
1809 printf("ipfw: invalid fib number %d\n",
1816 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1818 if ((cmd->arg1 != IP_FW_TARG) &&
1819 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1820 printf("ipfw: invalid fib number %d\n",
1821 cmd->arg1 & 0x7FFF);
1835 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1840 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1842 ci->object_opcodes++;
1846 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1849 ((ipfw_insn_log *)cmd)->log_left =
1850 ((ipfw_insn_log *)cmd)->max_log;
1856 /* only odd command lengths */
1857 if ((cmdlen & 1) == 0)
1863 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1864 printf("ipfw: invalid set size %d\n",
1868 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1873 case O_IP_SRC_LOOKUP:
1874 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1876 case O_IP_DST_LOOKUP:
1877 if (cmd->arg1 >= V_fw_tables_max) {
1878 printf("ipfw: invalid table number %d\n",
1882 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1883 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1884 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1886 ci->object_opcodes++;
1888 case O_IP_FLOW_LOOKUP:
1889 if (cmd->arg1 >= V_fw_tables_max) {
1890 printf("ipfw: invalid table number %d\n",
1894 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1895 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1897 ci->object_opcodes++;
1900 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1911 if (cmdlen < 1 || cmdlen > 31)
1916 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1922 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1923 if (cmdlen < 2 || cmdlen > 31)
1930 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1932 ci->object_opcodes++;
1936 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1942 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1947 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1952 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1959 if (ip_divert_ptr == NULL)
1965 if (ng_ipfw_input_p == NULL)
1970 if (!IPFW_NAT_LOADED)
1972 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1976 ci->object_opcodes++;
1978 case O_FORWARD_MAC: /* XXX not implemented yet */
1991 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1995 printf("ipfw: opcode %d, multiple actions"
2002 printf("ipfw: opcode %d, action must be"
2011 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2012 F_INSN_SIZE(ipfw_insn))
2017 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2018 ((ipfw_insn_u32 *)cmd)->o.arg1)
2022 case O_IP6_SRC_MASK:
2023 case O_IP6_DST_MASK:
2024 if ( !(cmdlen & 1) || cmdlen > 127)
2028 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2034 switch (cmd->opcode) {
2044 case O_IP6_SRC_MASK:
2045 case O_IP6_DST_MASK:
2047 printf("ipfw: no IPv6 support in kernel\n");
2048 return (EPROTONOSUPPORT);
2051 printf("ipfw: opcode %d, unknown opcode\n",
2057 if (have_action == 0) {
2058 printf("ipfw: missing action\n");
2064 printf("ipfw: opcode %d size %d wrong\n",
2065 cmd->opcode, cmdlen);
2071 * Translation of requests for compatibility with FreeBSD 7.2/8.
2072 * a static variable tells us if we have an old client from userland,
2073 * and if necessary we translate requests and responses between the
2079 struct ip_fw7 *next; /* linked list of rules */
2080 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2081 /* 'next_rule' is used to pass up 'set_disable' status */
2083 uint16_t act_ofs; /* offset of action in 32-bit units */
2084 uint16_t cmd_len; /* # of 32-bit words in cmd */
2085 uint16_t rulenum; /* rule number */
2086 uint8_t set; /* rule set (0..31) */
2087 // #define RESVD_SET 31 /* set for default and persistent rules */
2088 uint8_t _pad; /* padding */
2089 // uint32_t id; /* rule id, only in v.8 */
2090 /* These fields are present in all rules. */
2091 uint64_t pcnt; /* Packet counter */
2092 uint64_t bcnt; /* Byte counter */
2093 uint32_t timestamp; /* tv_sec of last match */
2095 ipfw_insn cmd[1]; /* storage for commands */
2098 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2099 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2102 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2103 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2108 * Copy the static and dynamic rules to the supplied buffer
2109 * and return the amount of space actually used.
2110 * Must be run under IPFW_UH_RLOCK
2113 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2116 char *ep = bp + space;
2118 struct ip_fw_rule0 *dst;
2119 struct timeval boottime;
2120 int error, i, l, warnflag;
2121 time_t boot_seconds;
2125 getboottime(&boottime);
2126 boot_seconds = boottime.tv_sec;
2127 for (i = 0; i < chain->n_rules; i++) {
2128 rule = chain->map[i];
2131 /* Convert rule to FreeBSd 7.2 format */
2132 l = RULESIZE7(rule);
2133 if (bp + l + sizeof(uint32_t) <= ep) {
2134 bcopy(rule, bp, l + sizeof(uint32_t));
2135 error = set_legacy_obj_kidx(chain,
2136 (struct ip_fw_rule0 *)bp);
2139 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2141 return 0; /*XXX correct? */
2143 * XXX HACK. Store the disable mask in the "next"
2144 * pointer in a wild attempt to keep the ABI the same.
2145 * Why do we do this on EVERY rule?
2147 bcopy(&V_set_disable,
2148 &(((struct ip_fw7 *)bp)->next_rule),
2149 sizeof(V_set_disable));
2150 if (((struct ip_fw7 *)bp)->timestamp)
2151 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2154 continue; /* go to next rule */
2157 l = RULEUSIZE0(rule);
2158 if (bp + l > ep) { /* should not happen */
2159 printf("overflow dumping static rules\n");
2162 dst = (struct ip_fw_rule0 *)bp;
2163 export_rule0(rule, dst, l);
2164 error = set_legacy_obj_kidx(chain, dst);
2167 * XXX HACK. Store the disable mask in the "next"
2168 * pointer in a wild attempt to keep the ABI the same.
2169 * Why do we do this on EVERY rule?
2171 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2172 * so we need to fail _after_ saving at least one mask.
2174 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2176 dst->timestamp += boot_seconds;
2181 /* Non-fatal table rewrite error. */
2185 printf("Stop on rule %d. Fail to convert table\n",
2191 printf("ipfw: process %s is using legacy interfaces,"
2192 " consider rebuilding\n", "");
2193 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2194 return (bp - (char *)buf);
2199 uint32_t b; /* start rule */
2200 uint32_t e; /* end rule */
2201 uint32_t rcount; /* number of rules */
2202 uint32_t rsize; /* rules size */
2203 uint32_t tcount; /* number of tables */
2204 int rcounters; /* counters */
2205 uint32_t *bmask; /* index bitmask of used named objects */
2209 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2212 ntlv->head.type = no->etlv;
2213 ntlv->head.length = sizeof(*ntlv);
2214 ntlv->idx = no->kidx;
2215 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2219 * Export named object info in instance @ni, identified by @kidx
2220 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2222 * Returns 0 on success.
2225 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2226 struct sockopt_data *sd)
2228 struct named_object *no;
2229 ipfw_obj_ntlv *ntlv;
2231 no = ipfw_objhash_lookup_kidx(ni, kidx);
2232 KASSERT(no != NULL, ("invalid object kernel index passed"));
2234 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2238 ipfw_export_obj_ntlv(no, ntlv);
2243 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2244 struct sockopt_data *sd)
2248 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2249 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2251 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2259 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2260 struct sockopt_data *sd)
2262 ipfw_obj_ctlv *ctlv;
2265 MPASS(da->tcount > 0);
2267 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2270 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2271 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2273 ctlv->count = da->tcount;
2274 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2276 /* Dump table names first (if any) */
2277 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2280 /* Then dump another named objects */
2281 da->bmask += IPFW_TABLES_MAX / 32;
2282 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2286 * Dumps static rules with table TLVs in buffer @sd.
2288 * Returns 0 on success.
2291 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2292 struct sockopt_data *sd)
2294 ipfw_obj_ctlv *ctlv;
2295 struct ip_fw *krule;
2300 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2303 ctlv->head.type = IPFW_TLV_RULE_LIST;
2304 ctlv->head.length = da->rsize + sizeof(*ctlv);
2305 ctlv->count = da->rcount;
2307 for (i = da->b; i < da->e; i++) {
2308 krule = chain->map[i];
2310 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2311 if (da->rcounters != 0)
2312 l += sizeof(struct ip_fw_bcounter);
2313 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2317 export_rule1(krule, dst, l, da->rcounters);
2324 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2329 * Maintain separate bitmasks for table and non-table objects.
2331 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2333 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2336 bmask[bidx] |= 1 << (kidx % 32);
2341 * Marks every object index used in @rule with bit in @bmask.
2342 * Used to generate bitmask of referenced tables/objects for given ruleset
2346 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2347 struct dump_args *da)
2349 struct opcode_obj_rewrite *rw;
2358 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2359 cmdlen = F_LEN(cmd);
2361 rw = find_op_rw(cmd, &kidx, &subtype);
2365 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2371 * Dumps requested objects data
2372 * Data layout (version 0)(current):
2373 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2374 * size = ipfw_cfg_lheader.size
2375 * Reply: [ ipfw_cfg_lheader
2376 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2377 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2378 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2380 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2382 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2383 * The rest (size, count) are set to zero and needs to be ignored.
2385 * Returns 0 on success.
2388 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2389 struct sockopt_data *sd)
2391 struct dump_args da;
2392 ipfw_cfg_lheader *hdr;
2395 uint32_t hdr_flags, *bmask;
2398 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2404 memset(&da, 0, sizeof(da));
2406 * Allocate needed state.
2407 * Note we allocate 2xspace mask, for table & srv
2409 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2410 da.bmask = bmask = malloc(
2411 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2413 IPFW_UH_RLOCK(chain);
2416 * STAGE 1: Determine size/count for objects in range.
2417 * Prepare used tables bitmask.
2419 sz = sizeof(ipfw_cfg_lheader);
2420 da.e = chain->n_rules;
2422 if (hdr->end_rule != 0) {
2423 /* Handle custom range */
2424 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2425 rnum = IPFW_DEFAULT_RULE;
2426 da.b = ipfw_find_rule(chain, rnum, 0);
2427 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2428 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2429 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2432 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2433 for (i = da.b; i < da.e; i++) {
2434 rule = chain->map[i];
2435 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2437 /* Update bitmask of used objects for given range */
2438 mark_rule_objects(chain, rule, &da);
2440 /* Add counters if requested */
2441 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2442 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2445 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2448 if (hdr->flags & IPFW_CFG_GET_STATES) {
2449 sz += sizeof(ipfw_obj_ctlv) +
2450 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2455 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2456 sizeof(ipfw_obj_ctlv);
2459 * Fill header anyway.
2460 * Note we have to save header fields to stable storage
2461 * buffer inside @sd can be flushed after dumping rules
2464 hdr->set_mask = ~V_set_disable;
2465 hdr_flags = hdr->flags;
2468 if (sd->valsize < sz) {
2473 /* STAGE2: Store actual data */
2474 if (da.tcount > 0) {
2475 error = dump_named_objects(chain, &da, sd);
2480 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2481 error = dump_static_rules(chain, &da, sd);
2486 if (hdr_flags & IPFW_CFG_GET_STATES)
2487 error = ipfw_dump_states(chain, sd);
2490 IPFW_UH_RUNLOCK(chain);
2493 free(bmask, M_TEMP);
2499 ipfw_check_object_name_generic(const char *name)
2503 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2504 if (strnlen(name, nsize) == nsize)
2506 if (name[0] == '\0')
2512 * Creates non-existent objects referenced by rule.
2514 * Return 0 on success.
2517 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2518 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2520 struct opcode_obj_rewrite *rw;
2526 * Compatibility stuff: do actual creation for non-existing,
2527 * but referenced objects.
2529 for (p = oib; p < pidx; p++) {
2537 rw = find_op_rw(cmd + p->off, NULL, NULL);
2538 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2539 (cmd + p->off)->opcode));
2541 if (rw->create_object == NULL)
2544 error = rw->create_object(ch, ti, &kidx);
2551 * Error happened. We have to rollback everything.
2552 * Drop all already acquired references.
2555 unref_oib_objects(ch, cmd, oib, pidx);
2556 IPFW_UH_WUNLOCK(ch);
2565 * Compatibility function for old ipfw(8) binaries.
2566 * Rewrites table/nat kernel indices with userland ones.
2567 * Convert tables matching '/^\d+$/' to their atoi() value.
2568 * Use number 65535 for other tables.
2570 * Returns 0 on success.
2573 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2575 struct opcode_obj_rewrite *rw;
2576 struct named_object *no;
2580 int cmdlen, error, l;
2581 uint16_t kidx, uidx;
2589 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2590 cmdlen = F_LEN(cmd);
2592 /* Check if is index in given opcode */
2593 rw = find_op_rw(cmd, &kidx, &subtype);
2597 /* Try to find referenced kernel object */
2598 no = rw->find_bykidx(ch, kidx);
2602 val = strtol(no->name, &end, 10);
2603 if (*end == '\0' && val < 65535) {
2608 * We are called via legacy opcode.
2609 * Save error and show table as fake number
2610 * not to make ipfw(8) hang.
2616 rw->update(cmd, uidx);
2624 * Unreferences all already-referenced objects in given @cmd rule,
2625 * using information in @oib.
2627 * Used to rollback partially converted rule on error.
2630 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2631 struct obj_idx *end)
2633 struct opcode_obj_rewrite *rw;
2634 struct named_object *no;
2637 IPFW_UH_WLOCK_ASSERT(ch);
2639 for (p = oib; p < end; p++) {
2643 rw = find_op_rw(cmd + p->off, NULL, NULL);
2644 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2645 (cmd + p->off)->opcode));
2647 /* Find & unref by existing idx */
2648 no = rw->find_bykidx(ch, p->kidx);
2649 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2655 * Remove references from every object used in @rule.
2656 * Used at rule removal code.
2659 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2661 struct opcode_obj_rewrite *rw;
2662 struct named_object *no;
2668 IPFW_UH_WLOCK_ASSERT(ch);
2673 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2674 cmdlen = F_LEN(cmd);
2676 rw = find_op_rw(cmd, &kidx, &subtype);
2679 no = rw->find_bykidx(ch, kidx);
2681 KASSERT(no != NULL, ("object id %d not found", kidx));
2682 KASSERT(no->subtype == subtype,
2683 ("wrong type %d (%d) for object id %d",
2684 no->subtype, subtype, kidx));
2685 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2688 if (no->refcnt == 1 && rw->destroy_object != NULL)
2689 rw->destroy_object(ch, no);
2697 * Find and reference object (if any) stored in instruction @cmd.
2699 * Saves object info in @pidx, sets
2700 * - @unresolved to 1 if object should exists but not found
2702 * Returns non-zero value in case of error.
2705 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2706 struct obj_idx *pidx, int *unresolved)
2708 struct named_object *no;
2709 struct opcode_obj_rewrite *rw;
2712 /* Check if this opcode is candidate for rewrite */
2713 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2717 /* Need to rewrite. Save necessary fields */
2718 pidx->uidx = ti->uidx;
2719 pidx->type = ti->type;
2721 /* Try to find referenced kernel object */
2722 error = rw->find_byname(ch, ti, &no);
2727 * Report about unresolved object for automaic
2735 * Object is already exist.
2736 * Its subtype should match with expected value.
2738 if (ti->type != no->subtype)
2741 /* Bump refcount and update kidx. */
2743 rw->update(cmd, no->kidx);
2748 * Finds and bumps refcount for objects referenced by given @rule.
2749 * Auto-creates non-existing tables.
2750 * Fills in @oib array with userland/kernel indexes.
2752 * Returns 0 on success.
2755 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2756 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2758 struct obj_idx *pidx;
2760 int cmdlen, error, l, unresolved;
2770 /* Increase refcount on each existing referenced table. */
2771 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2772 cmdlen = F_LEN(cmd);
2775 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2779 * Compatibility stuff for old clients:
2780 * prepare to automaitcally create non-existing objects.
2782 if (unresolved != 0) {
2783 pidx->off = rule->cmd_len - l;
2789 /* Unref everything we have already done */
2790 unref_oib_objects(ch, rule->cmd, oib, pidx);
2791 IPFW_UH_WUNLOCK(ch);
2794 IPFW_UH_WUNLOCK(ch);
2796 /* Perform auto-creation for non-existing objects */
2798 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2800 /* Calculate real number of dynamic objects */
2801 ci->object_opcodes = (uint16_t)(pidx - oib);
2807 * Checks is opcode is referencing table of appropriate type.
2808 * Adds reference count for found table if true.
2809 * Rewrites user-supplied opcode values with kernel ones.
2811 * Returns 0 on success and appropriate error code otherwise.
2814 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2819 struct obj_idx *p, *pidx_first, *pidx_last;
2823 * Prepare an array for storing opcode indices.
2824 * Use stack allocation by default.
2826 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2828 pidx_first = ci->obuf;
2830 pidx_first = malloc(
2831 ci->object_opcodes * sizeof(struct obj_idx),
2832 M_IPFW, M_WAITOK | M_ZERO);
2836 memset(&ti, 0, sizeof(ti));
2838 /* Use set rule is assigned to. */
2839 ti.set = ci->krule->set;
2840 if (ci->ctlv != NULL) {
2841 ti.tlvs = (void *)(ci->ctlv + 1);
2842 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2845 /* Reference all used tables and other objects */
2846 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2850 * Note that ref_rule_objects() might have updated ci->object_opcodes
2851 * to reflect actual number of object opcodes.
2854 /* Perform rewrite of remaining opcodes */
2856 pidx_last = pidx_first + ci->object_opcodes;
2857 for (p = pidx_first; p < pidx_last; p++) {
2858 cmd = ci->krule->cmd + p->off;
2859 update_opcode_kidx(cmd, p->kidx);
2863 if (pidx_first != ci->obuf)
2864 free(pidx_first, M_IPFW);
2870 * Adds one or more rules to ipfw @chain.
2871 * Data layout (version 0)(current):
2875 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2876 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2881 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2882 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2885 * Rules in reply are modified to store their actual ruleset number.
2887 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2888 * according to their idx field and there has to be no duplicates.
2889 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2890 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2892 * Returns 0 on success.
2895 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2896 struct sockopt_data *sd)
2898 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2899 ipfw_obj_ntlv *ntlv;
2900 int clen, error, idx;
2901 uint32_t count, read;
2902 struct ip_fw_rule *r;
2903 struct rule_check_info rci, *ci, *cbuf;
2906 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2907 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2909 read = sizeof(ip_fw3_opheader);
2913 memset(&rci, 0, sizeof(struct rule_check_info));
2915 if (read + sizeof(*ctlv) > sd->valsize)
2918 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2919 clen = ctlv->head.length;
2920 /* Check size and alignment */
2921 if (clen > sd->valsize || clen < sizeof(*ctlv))
2923 if ((clen % sizeof(uint64_t)) != 0)
2927 * Some table names or other named objects.
2928 * Check for validness.
2930 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2931 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2936 * Ensure TLVs are sorted ascending and
2937 * there are no duplicates.
2940 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2942 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2945 error = ipfw_check_object_name_generic(ntlv->name);
2949 if (ntlv->idx <= idx)
2958 read += ctlv->head.length;
2959 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2962 if (read + sizeof(*ctlv) > sd->valsize)
2965 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2966 clen = ctlv->head.length;
2967 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2969 if ((clen % sizeof(uint64_t)) != 0)
2973 * TODO: Permit adding multiple rules at once
2975 if (ctlv->count != 1)
2978 clen -= sizeof(*ctlv);
2980 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2983 /* Allocate state for each rule or use stack */
2984 if (ctlv->count == 1) {
2985 memset(&rci, 0, sizeof(struct rule_check_info));
2988 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2993 * Check each rule for validness.
2994 * Ensure numbered rules are sorted ascending
2995 * and properly aligned
2998 r = (struct ip_fw_rule *)(ctlv + 1);
3002 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3003 if (rsize > clen || ctlv->count <= count) {
3009 error = check_ipfw_rule1(r, rsize, ci);
3014 if (r->rulenum != 0 && r->rulenum < idx) {
3015 printf("rulenum %d idx %d\n", r->rulenum, idx);
3021 ci->urule = (caddr_t)r;
3023 rsize = roundup2(rsize, sizeof(uint64_t));
3025 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3030 if (ctlv->count != count || error != 0) {
3037 read += ctlv->head.length;
3038 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3041 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3042 if (cbuf != NULL && cbuf != &rci)
3048 * Passed rules seems to be valid.
3049 * Allocate storage and try to add them to chain.
3051 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3052 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3053 ci->krule = ipfw_alloc_rule(chain, clen);
3057 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3058 /* Free allocate krules */
3059 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3060 ipfw_free_rule(ci->krule);
3063 if (cbuf != NULL && cbuf != &rci)
3070 * Lists all sopts currently registered.
3071 * Data layout (v0)(current):
3072 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3073 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3075 * Returns 0 on success
3078 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3079 struct sockopt_data *sd)
3081 struct _ipfw_obj_lheader *olh;
3083 struct ipfw_sopt_handler *sh;
3084 uint32_t count, n, size;
3086 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3089 if (sd->valsize < olh->size)
3094 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3096 /* Fill in header regadless of buffer size */
3098 olh->objsize = sizeof(ipfw_sopt_info);
3100 if (size > olh->size) {
3107 for (n = 1; n <= count; n++) {
3108 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3109 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3110 sh = &ctl3_handlers[n];
3111 i->opcode = sh->opcode;
3112 i->version = sh->version;
3113 i->refcnt = sh->refcnt;
3121 * Compares two opcodes.
3122 * Used both in qsort() and bsearch().
3124 * Returns 0 if match is found.
3127 compare_opcodes(const void *_a, const void *_b)
3129 const struct opcode_obj_rewrite *a, *b;
3131 a = (const struct opcode_obj_rewrite *)_a;
3132 b = (const struct opcode_obj_rewrite *)_b;
3134 if (a->opcode < b->opcode)
3136 else if (a->opcode > b->opcode)
3143 * XXX: Rewrite bsearch()
3146 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3147 struct opcode_obj_rewrite **phi)
3149 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3151 memset(&h, 0, sizeof(h));
3154 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3155 ctl3_rsize, sizeof(h), compare_opcodes);
3159 /* Find the first element matching the same opcode */
3161 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3164 /* Find the last element matching the same opcode */
3166 ctl3_max = ctl3_rewriters + ctl3_rsize;
3167 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3177 * Finds opcode object rewriter based on @code.
3179 * Returns pointer to handler or NULL.
3181 static struct opcode_obj_rewrite *
3182 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3184 struct opcode_obj_rewrite *rw, *lo, *hi;
3188 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3191 for (rw = lo; rw <= hi; rw++) {
3192 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3204 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3207 if (find_op_rw(cmd, puidx, NULL) == NULL)
3213 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3215 struct opcode_obj_rewrite *rw;
3217 rw = find_op_rw(cmd, NULL, NULL);
3218 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3219 rw->update(cmd, idx);
3223 ipfw_init_obj_rewriter()
3226 ctl3_rewriters = NULL;
3231 ipfw_destroy_obj_rewriter()
3234 if (ctl3_rewriters != NULL)
3235 free(ctl3_rewriters, M_IPFW);
3236 ctl3_rewriters = NULL;
3241 * Adds one or more opcode object rewrite handlers to the global array.
3242 * Function may sleep.
3245 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3248 struct opcode_obj_rewrite *tmp;
3253 sz = ctl3_rsize + count;
3255 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3257 if (ctl3_rsize + count <= sz)
3264 /* Merge old & new arrays */
3265 sz = ctl3_rsize + count;
3266 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3267 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3268 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3269 /* Switch new and free old */
3270 if (ctl3_rewriters != NULL)
3271 free(ctl3_rewriters, M_IPFW);
3272 ctl3_rewriters = tmp;
3279 * Removes one or more object rewrite handlers from the global array.
3282 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3285 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3290 for (i = 0; i < count; i++) {
3291 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3294 for (ktmp = lo; ktmp <= hi; ktmp++) {
3295 if (ktmp->classifier != rw[i].classifier)
3298 ctl3_max = ctl3_rewriters + ctl3_rsize;
3299 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3300 memmove(ktmp, ktmp + 1, sz);
3307 if (ctl3_rsize == 0) {
3308 if (ctl3_rewriters != NULL)
3309 free(ctl3_rewriters, M_IPFW);
3310 ctl3_rewriters = NULL;
3319 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3320 struct named_object *no, void *arg)
3322 struct sockopt_data *sd;
3323 ipfw_obj_ntlv *ntlv;
3325 sd = (struct sockopt_data *)arg;
3326 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3329 ipfw_export_obj_ntlv(no, ntlv);
3334 * Lists all service objects.
3335 * Data layout (v0)(current):
3336 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3337 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3338 * Returns 0 on success
3341 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3342 struct sockopt_data *sd)
3344 ipfw_obj_lheader *hdr;
3347 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3351 IPFW_UH_RLOCK(chain);
3352 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3353 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3354 if (sd->valsize < hdr->size) {
3355 IPFW_UH_RUNLOCK(chain);
3359 hdr->objsize = sizeof(ipfw_obj_ntlv);
3361 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3362 export_objhash_ntlv_internal, sd);
3363 IPFW_UH_RUNLOCK(chain);
3368 * Compares two sopt handlers (code, version and handler ptr).
3369 * Used both as qsort() and bsearch().
3370 * Does not compare handler for latter case.
3372 * Returns 0 if match is found.
3375 compare_sh(const void *_a, const void *_b)
3377 const struct ipfw_sopt_handler *a, *b;
3379 a = (const struct ipfw_sopt_handler *)_a;
3380 b = (const struct ipfw_sopt_handler *)_b;
3382 if (a->opcode < b->opcode)
3384 else if (a->opcode > b->opcode)
3387 if (a->version < b->version)
3389 else if (a->version > b->version)
3392 /* bsearch helper */
3393 if (a->handler == NULL)
3396 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3398 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3405 * Finds sopt handler based on @code and @version.
3407 * Returns pointer to handler or NULL.
3409 static struct ipfw_sopt_handler *
3410 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3412 struct ipfw_sopt_handler *sh, h;
3414 memset(&h, 0, sizeof(h));
3416 h.version = version;
3417 h.handler = handler;
3419 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3420 ctl3_hsize, sizeof(h), compare_sh);
3426 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3428 struct ipfw_sopt_handler *sh;
3431 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3433 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3439 /* Copy handler data to requested buffer */
3447 find_unref_sh(struct ipfw_sopt_handler *psh)
3449 struct ipfw_sopt_handler *sh;
3452 sh = find_sh(psh->opcode, psh->version, NULL);
3453 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3460 ipfw_init_sopt_handler()
3464 IPFW_ADD_SOPT_HANDLER(1, scodes);
3468 ipfw_destroy_sopt_handler()
3471 IPFW_DEL_SOPT_HANDLER(1, scodes);
3472 CTL3_LOCK_DESTROY();
3476 * Adds one or more sockopt handlers to the global array.
3477 * Function may sleep.
3480 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3483 struct ipfw_sopt_handler *tmp;
3488 sz = ctl3_hsize + count;
3490 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3492 if (ctl3_hsize + count <= sz)
3499 /* Merge old & new arrays */
3500 sz = ctl3_hsize + count;
3501 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3502 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3503 qsort(tmp, sz, sizeof(*sh), compare_sh);
3504 /* Switch new and free old */
3505 if (ctl3_handlers != NULL)
3506 free(ctl3_handlers, M_IPFW);
3507 ctl3_handlers = tmp;
3515 * Removes one or more sockopt handlers from the global array.
3518 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3521 struct ipfw_sopt_handler *tmp, *h;
3526 for (i = 0; i < count; i++) {
3528 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3532 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3533 memmove(h, h + 1, sz);
3537 if (ctl3_hsize == 0) {
3538 if (ctl3_handlers != NULL)
3539 free(ctl3_handlers, M_IPFW);
3540 ctl3_handlers = NULL;
3551 * Writes data accumulated in @sd to sockopt buffer.
3552 * Zeroes internal @sd buffer.
3555 ipfw_flush_sopt_data(struct sockopt_data *sd)
3557 struct sockopt *sopt;
3567 if (sopt->sopt_dir == SOPT_GET) {
3568 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3573 memset(sd->kbuf, 0, sd->ksize);
3576 if (sd->ktotal + sd->ksize < sd->valsize)
3577 sd->kavail = sd->ksize;
3579 sd->kavail = sd->valsize - sd->ktotal;
3581 /* Update sopt buffer data */
3582 sopt->sopt_valsize = sd->ktotal;
3583 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3589 * Ensures that @sd buffer has contiguous @neeeded number of
3592 * Returns pointer to requested space or NULL.
3595 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3600 if (sd->kavail < needed) {
3602 * Flush data and try another time.
3604 error = ipfw_flush_sopt_data(sd);
3606 if (sd->kavail < needed || error != 0)
3610 addr = sd->kbuf + sd->koff;
3612 sd->kavail -= needed;
3617 * Requests @needed contiguous bytes from @sd buffer.
3618 * Function is used to notify subsystem that we are
3619 * interesed in first @needed bytes (request header)
3620 * and the rest buffer can be safely zeroed.
3622 * Returns pointer to requested space or NULL.
3625 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3629 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3633 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3639 * New sockopt handler.
3642 ipfw_ctl3(struct sockopt *sopt)
3645 size_t size, valsize;
3646 struct ip_fw_chain *chain;
3648 struct sockopt_data sdata;
3649 struct ipfw_sopt_handler h;
3650 ip_fw3_opheader *op3 = NULL;
3652 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3656 if (sopt->sopt_name != IP_FW3)
3657 return (ipfw_ctl(sopt));
3659 chain = &V_layer3_chain;
3662 /* Save original valsize before it is altered via sooptcopyin() */
3663 valsize = sopt->sopt_valsize;
3664 memset(&sdata, 0, sizeof(sdata));
3665 /* Read op3 header first to determine actual operation */
3666 op3 = (ip_fw3_opheader *)xbuf;
3667 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3670 sopt->sopt_valsize = valsize;
3673 * Find and reference command.
3675 error = find_ref_sh(op3->opcode, op3->version, &h);
3680 * Disallow modifications in really-really secure mode, but still allow
3681 * the logging counters to be reset.
3683 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3684 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3692 * Fill in sockopt_data structure that may be useful for
3693 * IP_FW3 get requests.
3696 if (valsize <= sizeof(xbuf)) {
3697 /* use on-stack buffer */
3699 sdata.ksize = sizeof(xbuf);
3700 sdata.kavail = valsize;
3704 * Determine opcode type/buffer size:
3705 * allocate sliding-window buf for data export or
3706 * contiguous buffer for special ops.
3708 if ((h.dir & HDIR_SET) != 0) {
3709 /* Set request. Allocate contigous buffer. */
3710 if (valsize > CTL3_LARGEBUF) {
3717 /* Get request. Allocate sliding window buffer */
3718 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3720 if (size < valsize) {
3721 /* We have to wire user buffer */
3722 error = vslock(sopt->sopt_val, valsize);
3729 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3731 sdata.kavail = size;
3735 sdata.sopt_val = sopt->sopt_val;
3736 sdata.valsize = valsize;
3739 * Copy either all request (if valsize < bsize_max)
3740 * or first bsize_max bytes to guarantee most consumers
3741 * that all necessary data has been copied).
3742 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3744 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3745 sizeof(ip_fw3_opheader))) != 0)
3747 op3 = (ip_fw3_opheader *)sdata.kbuf;
3749 /* Finally, run handler */
3750 error = h.handler(chain, op3, &sdata);
3753 /* Flush state and free buffers */
3755 error = ipfw_flush_sopt_data(&sdata);
3757 ipfw_flush_sopt_data(&sdata);
3760 vsunlock(sdata.sopt_val, valsize);
3762 /* Restore original pointer and set number of bytes written */
3763 sopt->sopt_val = sdata.sopt_val;
3764 sopt->sopt_valsize = sdata.ktotal;
3765 if (sdata.kbuf != xbuf)
3766 free(sdata.kbuf, M_TEMP);
3772 * {set|get}sockopt parser.
3775 ipfw_ctl(struct sockopt *sopt)
3777 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3779 size_t size, valsize;
3781 struct ip_fw_rule0 *rule;
3782 struct ip_fw_chain *chain;
3783 u_int32_t rulenum[2];
3785 struct rule_check_info ci;
3788 chain = &V_layer3_chain;
3791 /* Save original valsize before it is altered via sooptcopyin() */
3792 valsize = sopt->sopt_valsize;
3793 opt = sopt->sopt_name;
3796 * Disallow modifications in really-really secure mode, but still allow
3797 * the logging counters to be reset.
3799 if (opt == IP_FW_ADD ||
3800 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3801 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3809 * pass up a copy of the current rules. Static rules
3810 * come first (the last of which has number IPFW_DEFAULT_RULE),
3811 * followed by a possibly empty list of dynamic rule.
3812 * The last dynamic rule has NULL in the "next" field.
3814 * Note that the calculated size is used to bound the
3815 * amount of data returned to the user. The rule set may
3816 * change between calculating the size and returning the
3817 * data in which case we'll just return what fits.
3822 size = chain->static_len;
3823 size += ipfw_dyn_len();
3824 if (size >= sopt->sopt_valsize)
3826 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3827 IPFW_UH_RLOCK(chain);
3828 /* check again how much space we need */
3829 want = chain->static_len + ipfw_dyn_len();
3831 len = ipfw_getrules(chain, buf, size);
3832 IPFW_UH_RUNLOCK(chain);
3834 error = sooptcopyout(sopt, buf, len);
3842 /* locking is done within del_entry() */
3843 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3847 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3848 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3849 sizeof(struct ip_fw7) );
3851 memset(&ci, 0, sizeof(struct rule_check_info));
3854 * If the size of commands equals RULESIZE7 then we assume
3855 * a FreeBSD7.2 binary is talking to us (set is7=1).
3856 * is7 is persistent so the next 'ipfw list' command
3857 * will use this format.
3858 * NOTE: If wrong version is guessed (this can happen if
3859 * the first ipfw command is 'ipfw [pipe] list')
3860 * the ipfw binary may crash or loop infinitly...
3862 size = sopt->sopt_valsize;
3863 if (size == RULESIZE7(rule)) {
3865 error = convert_rule_to_8(rule);
3870 size = RULESIZE(rule);
3874 error = check_ipfw_rule0(rule, size, &ci);
3876 /* locking is done within add_rule() */
3877 struct ip_fw *krule;
3878 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3879 ci.urule = (caddr_t)rule;
3882 error = commit_rules(chain, &ci, 1);
3884 ipfw_free_rule(ci.krule);
3885 else if (sopt->sopt_dir == SOPT_GET) {
3887 error = convert_rule_to_7(rule);
3888 size = RULESIZE7(rule);
3894 error = sooptcopyout(sopt, rule, size);
3902 * IP_FW_DEL is used for deleting single rules or sets,
3903 * and (ab)used to atomically manipulate sets. Argument size
3904 * is used to distinguish between the two:
3906 * delete single rule or set of rules,
3907 * or reassign rules (or sets) to a different set.
3908 * 2*sizeof(u_int32_t)
3909 * atomic disable/enable sets.
3910 * first u_int32_t contains sets to be disabled,
3911 * second u_int32_t contains sets to be enabled.
3913 error = sooptcopyin(sopt, rulenum,
3914 2*sizeof(u_int32_t), sizeof(u_int32_t));
3917 size = sopt->sopt_valsize;
3918 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3919 /* delete or reassign, locking done in del_entry() */
3920 error = del_entry(chain, rulenum[0]);
3921 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3922 IPFW_UH_WLOCK(chain);
3924 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3925 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3926 IPFW_UH_WUNLOCK(chain);
3932 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3934 if (sopt->sopt_val != 0) {
3935 error = sooptcopyin(sopt, rulenum,
3936 sizeof(u_int32_t), sizeof(u_int32_t));
3940 error = zero_entry(chain, rulenum[0],
3941 sopt->sopt_name == IP_FW_RESETLOG);
3944 /*--- TABLE opcodes ---*/
3945 case IP_FW_TABLE_ADD:
3946 case IP_FW_TABLE_DEL:
3948 ipfw_table_entry ent;
3949 struct tentry_info tei;
3951 struct table_value v;
3953 error = sooptcopyin(sopt, &ent,
3954 sizeof(ent), sizeof(ent));
3958 memset(&tei, 0, sizeof(tei));
3959 tei.paddr = &ent.addr;
3960 tei.subtype = AF_INET;
3961 tei.masklen = ent.masklen;
3962 ipfw_import_table_value_legacy(ent.value, &v);
3964 memset(&ti, 0, sizeof(ti));
3966 ti.type = IPFW_TABLE_CIDR;
3968 error = (opt == IP_FW_TABLE_ADD) ?
3969 add_table_entry(chain, &ti, &tei, 0, 1) :
3970 del_table_entry(chain, &ti, &tei, 0, 1);
3975 case IP_FW_TABLE_FLUSH:
3980 error = sooptcopyin(sopt, &tbl,
3981 sizeof(tbl), sizeof(tbl));
3984 memset(&ti, 0, sizeof(ti));
3986 error = flush_table(chain, &ti);
3990 case IP_FW_TABLE_GETSIZE:
3995 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3998 memset(&ti, 0, sizeof(ti));
4001 error = ipfw_count_table(chain, &ti, &cnt);
4002 IPFW_RUNLOCK(chain);
4005 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4009 case IP_FW_TABLE_LIST:
4014 if (sopt->sopt_valsize < sizeof(*tbl)) {
4018 size = sopt->sopt_valsize;
4019 tbl = malloc(size, M_TEMP, M_WAITOK);
4020 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4025 tbl->size = (size - sizeof(*tbl)) /
4026 sizeof(ipfw_table_entry);
4027 memset(&ti, 0, sizeof(ti));
4030 error = ipfw_dump_table_legacy(chain, &ti, tbl);
4031 IPFW_RUNLOCK(chain);
4036 error = sooptcopyout(sopt, tbl, size);
4041 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4043 if (IPFW_NAT_LOADED)
4044 error = ipfw_nat_cfg_ptr(sopt);
4046 printf("IP_FW_NAT_CFG: %s\n",
4047 "ipfw_nat not present, please load it");
4053 if (IPFW_NAT_LOADED)
4054 error = ipfw_nat_del_ptr(sopt);
4056 printf("IP_FW_NAT_DEL: %s\n",
4057 "ipfw_nat not present, please load it");
4062 case IP_FW_NAT_GET_CONFIG:
4063 if (IPFW_NAT_LOADED)
4064 error = ipfw_nat_get_cfg_ptr(sopt);
4066 printf("IP_FW_NAT_GET_CFG: %s\n",
4067 "ipfw_nat not present, please load it");
4072 case IP_FW_NAT_GET_LOG:
4073 if (IPFW_NAT_LOADED)
4074 error = ipfw_nat_get_log_ptr(sopt);
4076 printf("IP_FW_NAT_GET_LOG: %s\n",
4077 "ipfw_nat not present, please load it");
4083 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4090 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4092 /* Functions to convert rules 7.2 <==> 8.0 */
4094 convert_rule_to_7(struct ip_fw_rule0 *rule)
4096 /* Used to modify original rule */
4097 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4098 /* copy of original rule, version 8 */
4099 struct ip_fw_rule0 *tmp;
4101 /* Used to copy commands */
4102 ipfw_insn *ccmd, *dst;
4103 int ll = 0, ccmdlen = 0;
4105 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4107 return 1; //XXX error
4109 bcopy(rule, tmp, RULE_MAXSIZE);
4112 //rule7->_pad = tmp->_pad;
4113 rule7->set = tmp->set;
4114 rule7->rulenum = tmp->rulenum;
4115 rule7->cmd_len = tmp->cmd_len;
4116 rule7->act_ofs = tmp->act_ofs;
4117 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4118 rule7->cmd_len = tmp->cmd_len;
4119 rule7->pcnt = tmp->pcnt;
4120 rule7->bcnt = tmp->bcnt;
4121 rule7->timestamp = tmp->timestamp;
4124 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4125 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4126 ccmdlen = F_LEN(ccmd);
4128 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4130 if (dst->opcode > O_NAT)
4131 /* O_REASS doesn't exists in 7.2 version, so
4132 * decrement opcode if it is after O_REASS
4137 printf("ipfw: opcode %d size truncated\n",
4148 convert_rule_to_8(struct ip_fw_rule0 *rule)
4150 /* Used to modify original rule */
4151 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4153 /* Used to copy commands */
4154 ipfw_insn *ccmd, *dst;
4155 int ll = 0, ccmdlen = 0;
4157 /* Copy of original rule */
4158 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4160 return 1; //XXX error
4163 bcopy(rule7, tmp, RULE_MAXSIZE);
4165 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4166 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4167 ccmdlen = F_LEN(ccmd);
4169 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4171 if (dst->opcode > O_NAT)
4172 /* O_REASS doesn't exists in 7.2 version, so
4173 * increment opcode if it is after O_REASS
4178 printf("ipfw: opcode %d size truncated\n",
4184 rule->_pad = tmp->_pad;
4185 rule->set = tmp->set;
4186 rule->rulenum = tmp->rulenum;
4187 rule->cmd_len = tmp->cmd_len;
4188 rule->act_ofs = tmp->act_ofs;
4189 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4190 rule->cmd_len = tmp->cmd_len;
4191 rule->id = 0; /* XXX see if is ok = 0 */
4192 rule->pcnt = tmp->pcnt;
4193 rule->bcnt = tmp->bcnt;
4194 rule->timestamp = tmp->timestamp;
4206 ipfw_init_srv(struct ip_fw_chain *ch)
4209 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4210 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4211 M_IPFW, M_WAITOK | M_ZERO);
4215 ipfw_destroy_srv(struct ip_fw_chain *ch)
4218 free(ch->srvstate, M_IPFW);
4219 ipfw_objhash_destroy(ch->srvmap);
4223 * Allocate new bitmask which can be used to enlarge/shrink
4224 * named instance index.
4227 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4233 KASSERT((items % BLOCK_ITEMS) == 0,
4234 ("bitmask size needs to power of 2 and greater or equal to %zu",
4237 max_blocks = items / BLOCK_ITEMS;
4239 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4240 /* Mark all as free */
4241 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4242 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4245 *pblocks = max_blocks;
4249 * Copy current bitmask index to new one.
4252 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4254 int old_blocks, new_blocks;
4255 u_long *old_idx, *new_idx;
4258 old_idx = ni->idx_mask;
4259 old_blocks = ni->max_blocks;
4261 new_blocks = *blocks;
4263 for (i = 0; i < IPFW_MAX_SETS; i++) {
4264 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4265 old_blocks * sizeof(u_long));
4270 * Swaps current @ni index with new one.
4273 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4278 old_idx = ni->idx_mask;
4279 old_blocks = ni->max_blocks;
4281 ni->idx_mask = *idx;
4282 ni->max_blocks = *blocks;
4284 /* Save old values */
4286 *blocks = old_blocks;
4290 ipfw_objhash_bitmap_free(void *idx, int blocks)
4297 * Creates named hash instance.
4298 * Must be called without holding any locks.
4299 * Return pointer to new instance.
4301 struct namedobj_instance *
4302 ipfw_objhash_create(uint32_t items)
4304 struct namedobj_instance *ni;
4308 size = sizeof(struct namedobj_instance) +
4309 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4310 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4312 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4313 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4314 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4316 ni->names = (struct namedobjects_head *)(ni +1);
4317 ni->values = &ni->names[ni->nn_size];
4319 for (i = 0; i < ni->nn_size; i++)
4320 TAILQ_INIT(&ni->names[i]);
4322 for (i = 0; i < ni->nv_size; i++)
4323 TAILQ_INIT(&ni->values[i]);
4325 /* Set default hashing/comparison functions */
4326 ni->hash_f = objhash_hash_name;
4327 ni->cmp_f = objhash_cmp_name;
4329 /* Allocate bitmask separately due to possible resize */
4330 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4336 ipfw_objhash_destroy(struct namedobj_instance *ni)
4339 free(ni->idx_mask, M_IPFW);
4344 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4345 objhash_cmp_f *cmp_f)
4348 ni->hash_f = hash_f;
4353 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4356 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4360 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4363 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4370 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4374 v = val % (ni->nv_size - 1);
4379 struct named_object *
4380 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4382 struct named_object *no;
4385 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4387 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4388 if (ni->cmp_f(no, name, set) == 0)
4396 * Find named object by @uid.
4397 * Check @tlvs for valid data inside.
4399 * Returns pointer to found TLV or NULL.
4402 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4404 ipfw_obj_ntlv *ntlv;
4408 pa = (uintptr_t)tlvs;
4411 for (; pa < pe; pa += l) {
4412 ntlv = (ipfw_obj_ntlv *)pa;
4413 l = ntlv->head.length;
4415 if (l != sizeof(*ntlv))
4418 if (ntlv->idx != uidx)
4421 * When userland has specified zero TLV type, do
4422 * not compare it with eltv. In some cases userland
4423 * doesn't know what type should it have. Use only
4424 * uidx and name for search named_object.
4426 if (ntlv->head.type != 0 &&
4427 ntlv->head.type != (uint16_t)etlv)
4430 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4440 * Finds object config based on either legacy index
4442 * Note @ti structure contains unchecked data from userland.
4444 * Returns 0 in success and fills in @pno with found config
4447 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4448 uint32_t etlv, struct named_object **pno)
4451 ipfw_obj_ntlv *ntlv;
4454 if (ti->tlvs == NULL)
4457 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4463 * Use set provided by @ti instead of @ntlv one.
4464 * This is needed due to different sets behavior
4465 * controlled by V_fw_tables_sets.
4468 *pno = ipfw_objhash_lookup_name(ni, set, name);
4475 * Find named object by name, considering also its TLV type.
4477 struct named_object *
4478 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4479 uint32_t type, const char *name)
4481 struct named_object *no;
4484 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4486 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4487 if (ni->cmp_f(no, name, set) == 0 &&
4488 no->etlv == (uint16_t)type)
4495 struct named_object *
4496 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4498 struct named_object *no;
4501 hash = objhash_hash_idx(ni, kidx);
4503 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4504 if (no->kidx == kidx)
4512 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4513 struct named_object *b)
4516 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4523 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4527 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4528 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4530 hash = objhash_hash_idx(ni, no->kidx);
4531 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4537 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4541 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4542 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4544 hash = objhash_hash_idx(ni, no->kidx);
4545 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4551 ipfw_objhash_count(struct namedobj_instance *ni)
4558 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4560 struct named_object *no;
4565 for (i = 0; i < ni->nn_size; i++) {
4566 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4567 if (no->etlv == type)
4575 * Runs @func for each found named object.
4576 * It is safe to delete objects from callback
4579 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4581 struct named_object *no, *no_tmp;
4584 for (i = 0; i < ni->nn_size; i++) {
4585 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4586 ret = f(ni, no, arg);
4595 * Runs @f for each found named object with type @type.
4596 * It is safe to delete objects from callback
4599 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4600 void *arg, uint16_t type)
4602 struct named_object *no, *no_tmp;
4605 for (i = 0; i < ni->nn_size; i++) {
4606 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4607 if (no->etlv != type)
4609 ret = f(ni, no, arg);
4618 * Removes index from given set.
4619 * Returns 0 on success.
4622 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4627 i = idx / BLOCK_ITEMS;
4628 v = idx % BLOCK_ITEMS;
4630 if (i >= ni->max_blocks)
4633 mask = &ni->idx_mask[i];
4635 if ((*mask & ((u_long)1 << v)) != 0)
4639 *mask |= (u_long)1 << v;
4641 /* Update free offset */
4642 if (ni->free_off[0] > i)
4643 ni->free_off[0] = i;
4649 * Allocate new index in given instance and stores in in @pidx.
4650 * Returns 0 on success.
4653 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4655 struct namedobj_instance *ni;
4659 ni = (struct namedobj_instance *)n;
4661 off = ni->free_off[0];
4662 mask = &ni->idx_mask[off];
4664 for (i = off; i < ni->max_blocks; i++, mask++) {
4665 if ((v = ffsl(*mask)) == 0)
4669 *mask &= ~ ((u_long)1 << (v - 1));
4671 ni->free_off[0] = i;
4673 v = BLOCK_ITEMS * i + v - 1;