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 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
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 static VNET_DEFINE(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(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
215 free_rule(struct ip_fw *rule)
218 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
224 * Find the smallest rule >= key, id.
225 * We could use bsearch but it is so simple that we code it directly
228 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
233 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
236 if (r->rulenum < key)
237 lo = i + 1; /* continue from the next one */
238 else if (r->rulenum > key)
239 hi = i; /* this might be good */
241 lo = i + 1; /* continue from the next one */
242 else /* r->id >= id */
243 hi = i; /* this might be good */
249 * Builds skipto cache on rule set @map.
252 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
257 IPFW_UH_WLOCK_ASSERT(chain);
260 rulenum = map[mi]->rulenum;
261 smap = chain->idxmap_back;
266 for (i = 0; i < 65536; i++) {
268 /* Use the same rule index until i < rulenum */
269 if (i != rulenum || i == 65535)
271 /* Find next rule with num > i */
272 rulenum = map[++mi]->rulenum;
274 rulenum = map[++mi]->rulenum;
279 * Swaps prepared (backup) index with current one.
282 swap_skipto_cache(struct ip_fw_chain *chain)
286 IPFW_UH_WLOCK_ASSERT(chain);
287 IPFW_WLOCK_ASSERT(chain);
290 chain->idxmap = chain->idxmap_back;
291 chain->idxmap_back = map;
295 * Allocate and initialize skipto cache.
298 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
300 int *idxmap, *idxmap_back;
302 idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
303 idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
306 * Note we may be called at any time after initialization,
307 * for example, on first skipto rule, so we need to
308 * provide valid chain->idxmap on return
311 IPFW_UH_WLOCK(chain);
312 if (chain->idxmap != NULL) {
313 IPFW_UH_WUNLOCK(chain);
314 free(idxmap, M_IPFW);
315 free(idxmap_back, M_IPFW);
319 /* Set backup pointer first to permit building cache */
320 chain->idxmap_back = idxmap_back;
321 update_skipto_cache(chain, chain->map);
323 /* It is now safe to set chain->idxmap ptr */
324 chain->idxmap = idxmap;
325 swap_skipto_cache(chain);
327 IPFW_UH_WUNLOCK(chain);
331 * Destroys skipto cache.
334 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
337 if (chain->idxmap != NULL)
338 free(chain->idxmap, M_IPFW);
339 if (chain->idxmap != NULL)
340 free(chain->idxmap_back, M_IPFW);
345 * allocate a new map, returns the chain locked. extra is the number
346 * of entries to add or delete.
348 static struct ip_fw **
349 get_map(struct ip_fw_chain *chain, int extra, int locked)
356 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
358 i = chain->n_rules + extra;
359 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
361 printf("%s: cannot allocate map\n", __FUNCTION__);
365 IPFW_UH_WLOCK(chain);
366 if (i >= chain->n_rules + extra) /* good */
368 /* otherwise we lost the race, free and retry */
370 IPFW_UH_WUNLOCK(chain);
376 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
378 static struct ip_fw **
379 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
381 struct ip_fw **old_map;
385 chain->n_rules = new_len;
386 old_map = chain->map;
387 chain->map = new_map;
388 swap_skipto_cache(chain);
395 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
397 struct timeval boottime;
399 cntr->size = sizeof(*cntr);
401 if (krule->cntr != NULL) {
402 cntr->pcnt = counter_u64_fetch(krule->cntr);
403 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
404 cntr->timestamp = krule->timestamp;
406 if (cntr->timestamp > 0) {
407 getboottime(&boottime);
408 cntr->timestamp += boottime.tv_sec;
413 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
415 struct timeval boottime;
417 if (krule->cntr != NULL) {
418 cntr->pcnt = counter_u64_fetch(krule->cntr);
419 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
420 cntr->timestamp = krule->timestamp;
422 if (cntr->timestamp > 0) {
423 getboottime(&boottime);
424 cntr->timestamp += boottime.tv_sec;
429 * Copies rule @urule from v1 userland format (current).
431 * Assume @krule is zeroed.
434 import_rule1(struct rule_check_info *ci)
436 struct ip_fw_rule *urule;
439 urule = (struct ip_fw_rule *)ci->urule;
440 krule = (struct ip_fw *)ci->krule;
443 krule->act_ofs = urule->act_ofs;
444 krule->cmd_len = urule->cmd_len;
445 krule->rulenum = urule->rulenum;
446 krule->set = urule->set;
447 krule->flags = urule->flags;
449 /* Save rulenum offset */
450 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
453 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
457 * Export rule into v1 format (Current).
459 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
461 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
463 * Assume @data is zeroed.
466 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
468 struct ip_fw_bcounter *cntr;
469 struct ip_fw_rule *urule;
472 /* Fill in TLV header */
473 tlv = (ipfw_obj_tlv *)data;
474 tlv->type = IPFW_TLV_RULE_ENT;
479 cntr = (struct ip_fw_bcounter *)(tlv + 1);
480 urule = (struct ip_fw_rule *)(cntr + 1);
481 export_cntr1_base(krule, cntr);
483 urule = (struct ip_fw_rule *)(tlv + 1);
486 urule->act_ofs = krule->act_ofs;
487 urule->cmd_len = krule->cmd_len;
488 urule->rulenum = krule->rulenum;
489 urule->set = krule->set;
490 urule->flags = krule->flags;
491 urule->id = krule->id;
494 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
499 * Copies rule @urule from FreeBSD8 userland format (v0)
501 * Assume @krule is zeroed.
504 import_rule0(struct rule_check_info *ci)
506 struct ip_fw_rule0 *urule;
510 ipfw_insn_limit *lcmd;
513 urule = (struct ip_fw_rule0 *)ci->urule;
514 krule = (struct ip_fw *)ci->krule;
517 krule->act_ofs = urule->act_ofs;
518 krule->cmd_len = urule->cmd_len;
519 krule->rulenum = urule->rulenum;
520 krule->set = urule->set;
521 if ((urule->_pad & 1) != 0)
522 krule->flags |= IPFW_RULE_NOOPT;
524 /* Save rulenum offset */
525 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
528 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
532 * 1) convert tablearg value from 65535 to 0
533 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
535 * 3) convert table number in iface opcodes to u16
536 * 4) convert old `nat global` into new 65535
542 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
545 switch (cmd->opcode) {
546 /* Opcodes supporting tablearg */
558 if (cmd->arg1 == IP_FW_TABLEARG)
559 cmd->arg1 = IP_FW_TARG;
560 else if (cmd->arg1 == 0)
561 cmd->arg1 = IP_FW_NAT44_GLOBAL;
565 if (cmd->arg1 == IP_FW_TABLEARG)
566 cmd->arg1 = IP_FW_TARG;
571 lcmd = (ipfw_insn_limit *)cmd;
572 if (lcmd->conn_limit == IP_FW_TABLEARG)
573 lcmd->conn_limit = IP_FW_TARG;
575 /* Interface tables */
579 /* Interface table, possibly */
580 cmdif = (ipfw_insn_if *)cmd;
581 if (cmdif->name[0] != '\1')
584 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
591 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
594 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
598 ipfw_insn_limit *lcmd;
602 memset(urule, 0, len);
603 urule->act_ofs = krule->act_ofs;
604 urule->cmd_len = krule->cmd_len;
605 urule->rulenum = krule->rulenum;
606 urule->set = krule->set;
607 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
611 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
613 /* Export counters */
614 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
618 * 1) convert tablearg value from 0 to 65535
619 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
620 * 3) convert table number in iface opcodes to int
626 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
629 switch (cmd->opcode) {
630 /* Opcodes supporting tablearg */
642 if (cmd->arg1 == IP_FW_TARG)
643 cmd->arg1 = IP_FW_TABLEARG;
644 else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
649 if (cmd->arg1 == IP_FW_TARG)
650 cmd->arg1 = IP_FW_TABLEARG;
652 cmd->arg1 &= ~0x8000;
655 lcmd = (ipfw_insn_limit *)cmd;
656 if (lcmd->conn_limit == IP_FW_TARG)
657 lcmd->conn_limit = IP_FW_TABLEARG;
659 /* Interface tables */
663 /* Interface table, possibly */
664 cmdif = (ipfw_insn_if *)cmd;
665 if (cmdif->name[0] != '\1')
668 cmdif->p.glob = cmdif->p.kidx;
675 * Add new rule(s) to the list possibly creating rule number for each.
676 * Update the rule_number in the input struct so the caller knows it as well.
677 * Must be called without IPFW_UH held
680 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
682 int error, i, insert_before, tcount;
683 uint16_t rulenum, *pnum;
684 struct rule_check_info *ci;
686 struct ip_fw **map; /* the new array of pointers */
688 /* Check if we need to do table/obj index remap */
690 for (ci = rci, i = 0; i < count; ci++, i++) {
691 if (ci->object_opcodes == 0)
695 * Rule has some object opcodes.
696 * We need to find (and create non-existing)
697 * kernel objects, and reference existing ones.
699 error = rewrite_rule_uidx(chain, ci);
703 * rewrite failed, state for current rule
704 * has been reverted. Check if we need to
710 * We have some more table rules
711 * we need to rollback.
714 IPFW_UH_WLOCK(chain);
717 if (ci->object_opcodes == 0)
719 unref_rule_objects(chain,ci->krule);
722 IPFW_UH_WUNLOCK(chain);
732 /* get_map returns with IPFW_UH_WLOCK if successful */
733 map = get_map(chain, count, 0 /* not locked */);
737 IPFW_UH_WLOCK(chain);
738 for (ci = rci, i = 0; i < count; ci++, i++) {
739 if (ci->object_opcodes == 0)
742 unref_rule_objects(chain, ci->krule);
744 IPFW_UH_WUNLOCK(chain);
750 if (V_autoinc_step < 1)
752 else if (V_autoinc_step > 1000)
753 V_autoinc_step = 1000;
755 /* FIXME: Handle count > 1 */
758 rulenum = krule->rulenum;
760 /* find the insertion point, we will insert before */
761 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
762 i = ipfw_find_rule(chain, insert_before, 0);
763 /* duplicate first part */
765 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
767 /* duplicate remaining part, we always have the default rule */
768 bcopy(chain->map + i, map + i + 1,
769 sizeof(struct ip_fw *) *(chain->n_rules - i));
771 /* Compute rule number and write it back */
772 rulenum = i > 0 ? map[i-1]->rulenum : 0;
773 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
774 rulenum += V_autoinc_step;
775 krule->rulenum = rulenum;
776 /* Save number to userland rule */
777 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
781 krule->id = chain->id + 1;
782 update_skipto_cache(chain, map);
783 map = swap_map(chain, map, chain->n_rules + 1);
784 chain->static_len += RULEUSIZE0(krule);
785 IPFW_UH_WUNLOCK(chain);
792 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
797 map = get_map(chain, 1, locked);
800 if (chain->n_rules > 0)
801 bcopy(chain->map, map,
802 chain->n_rules * sizeof(struct ip_fw *));
803 map[chain->n_rules] = rule;
804 rule->rulenum = IPFW_DEFAULT_RULE;
805 rule->set = RESVD_SET;
806 rule->id = chain->id + 1;
807 /* We add rule in the end of chain, no need to update skipto cache */
808 map = swap_map(chain, map, chain->n_rules + 1);
809 chain->static_len += RULEUSIZE0(rule);
810 IPFW_UH_WUNLOCK(chain);
816 * Adds @rule to the list of rules to reap
819 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
823 IPFW_UH_WLOCK_ASSERT(chain);
825 /* Unlink rule from everywhere */
826 unref_rule_objects(chain, rule);
828 *((struct ip_fw **)rule) = *head;
833 * Reclaim storage associated with a list of rules. This is
834 * typically the list created using remove_rule.
835 * A NULL pointer on input is handled correctly.
838 ipfw_reap_rules(struct ip_fw *head)
842 while ((rule = head) != NULL) {
843 head = *((struct ip_fw **)head);
850 * (default || reserved || !match_set || !match_number)
852 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
853 * // the default rule is always protected
855 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
856 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
858 * match_set ::= (cmd == 0 || rule->set == set)
859 * // set number is ignored for cmd == 0
861 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
862 * // number is ignored for cmd == 1 or n == 0
866 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
869 /* Don't match default rule for modification queries */
870 if (rule->rulenum == IPFW_DEFAULT_RULE &&
871 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
874 /* Don't match rules in reserved set for flush requests */
875 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
878 /* If we're filtering by set, don't match other sets */
879 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
882 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
883 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
889 struct manage_sets_args {
895 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
898 struct manage_sets_args *args;
900 args = (struct manage_sets_args *)arg;
901 if (no->set == (uint8_t)args->set)
902 no->set = args->new_set;
903 else if (no->set == args->new_set)
904 no->set = (uint8_t)args->set;
909 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
912 struct manage_sets_args *args;
914 args = (struct manage_sets_args *)arg;
915 if (no->set == (uint8_t)args->set)
916 no->set = args->new_set;
921 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
924 struct manage_sets_args *args;
926 args = (struct manage_sets_args *)arg;
927 if (no->set != (uint8_t)args->set)
929 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
930 no->etlv, no->name) != NULL)
936 * Generic function to handler moving and swapping sets.
939 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
940 uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
942 struct manage_sets_args args;
943 struct named_object *no;
946 args.new_set = new_set;
949 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
952 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
955 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
959 * @set used to pass kidx.
960 * When @new_set is zero - reset object counter,
961 * otherwise increment it.
963 no = ipfw_objhash_lookup_kidx(ni, set);
970 /* @set used to pass kidx */
971 no = ipfw_objhash_lookup_kidx(ni, set);
973 * First check number of references:
974 * when it differs, this mean other rules are holding
975 * reference to given object, so it is not possible to
976 * change its set. Note that refcnt may account references
977 * to some going-to-be-added rules. Since we don't know
978 * their numbers (and even if they will be added) it is
979 * perfectly OK to return error here.
981 if (no->ocnt != no->refcnt)
983 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
988 /* @set used to pass kidx */
989 no = ipfw_objhash_lookup_kidx(ni, set);
997 * Delete rules matching range @rt.
998 * Saves number of deleted rules in @ndel.
1000 * Returns 0 on success.
1003 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1005 struct ip_fw *reap, *rule, **map;
1007 int i, n, ndyn, ofs;
1010 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1013 * Stage 1: Determine range to inspect.
1014 * Range is half-inclusive, e.g [start, end).
1017 end = chain->n_rules - 1;
1019 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1020 start = ipfw_find_rule(chain, rt->start_rule, 0);
1022 if (rt->end_rule >= IPFW_DEFAULT_RULE)
1023 rt->end_rule = IPFW_DEFAULT_RULE - 1;
1024 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1027 /* Allocate new map of the same size */
1028 map = get_map(chain, 0, 1 /* locked */);
1030 IPFW_UH_WUNLOCK(chain);
1037 /* 1. bcopy the initial part of the map */
1039 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1040 /* 2. copy active rules between start and end */
1041 for (i = start; i < end; i++) {
1042 rule = chain->map[i];
1043 if (ipfw_match_range(rule, rt) == 0) {
1049 if (ipfw_is_dyn_rule(rule) != 0)
1052 /* 3. copy the final part of the map */
1053 bcopy(chain->map + end, map + ofs,
1054 (chain->n_rules - end) * sizeof(struct ip_fw *));
1055 /* 4. recalculate skipto cache */
1056 update_skipto_cache(chain, map);
1057 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1058 map = swap_map(chain, map, chain->n_rules - n);
1059 /* 6. Remove all dynamic states originated by deleted rules */
1061 ipfw_expire_dyn_states(chain, rt);
1062 /* 7. now remove the rules deleted from the old map */
1063 for (i = start; i < end; i++) {
1065 if (ipfw_match_range(rule, rt) == 0)
1067 chain->static_len -= RULEUSIZE0(rule);
1068 ipfw_reap_add(chain, &reap, rule);
1070 IPFW_UH_WUNLOCK(chain);
1072 ipfw_reap_rules(reap);
1080 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1082 struct opcode_obj_rewrite *rw;
1085 int cmdlen, i, l, c;
1088 IPFW_UH_WLOCK_ASSERT(ch);
1090 /* Stage 1: count number of references by given rules */
1091 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1093 if (ipfw_match_range(rule, rt) == 0)
1095 if (rule->set == rt->new_set) /* nothing to do */
1097 /* Search opcodes with named objects */
1098 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1099 l > 0; l -= cmdlen, cmd += cmdlen) {
1100 cmdlen = F_LEN(cmd);
1101 rw = find_op_rw(cmd, &kidx, NULL);
1102 if (rw == NULL || rw->manage_sets == NULL)
1105 * When manage_sets() returns non-zero value to
1106 * COUNT_ONE command, consider this as an object
1107 * doesn't support sets (e.g. disabled with sysctl).
1108 * So, skip checks for this object.
1110 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1115 if (c == 0) /* No objects found */
1117 /* Stage 2: verify "ownership" */
1118 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1120 if (ipfw_match_range(rule, rt) == 0)
1122 if (rule->set == rt->new_set) /* nothing to do */
1124 /* Search opcodes with named objects */
1125 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1126 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1127 cmdlen = F_LEN(cmd);
1128 rw = find_op_rw(cmd, &kidx, NULL);
1129 if (rw == NULL || rw->manage_sets == NULL)
1131 /* Test for ownership and conflicting names */
1132 c = rw->manage_sets(ch, kidx,
1133 (uint8_t)rt->new_set, TEST_ONE);
1136 /* Stage 3: change set and cleanup */
1137 for (i = 0; i < ch->n_rules - 1; 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; 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 /* cleanup object counter */
1151 rw->manage_sets(ch, kidx,
1152 0 /* reset counter */, COUNT_ONE);
1156 rw->manage_sets(ch, kidx,
1157 (uint8_t)rt->new_set, MOVE_ONE);
1162 * Changes set of given rule rannge @rt
1165 * Returns 0 on success.
1168 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1173 IPFW_UH_WLOCK(chain);
1176 * Move rules with matching paramenerts to a new set.
1177 * This one is much more complex. We have to ensure
1178 * that all referenced tables (if any) are referenced
1179 * by given rule subset only. Otherwise, we can't move
1180 * them to new set and have to return error.
1182 if ((i = move_objects(chain, rt)) != 0) {
1183 IPFW_UH_WUNLOCK(chain);
1187 /* XXX: We have to do swap holding WLOCK */
1188 for (i = 0; i < chain->n_rules; i++) {
1189 rule = chain->map[i];
1190 if (ipfw_match_range(rule, rt) == 0)
1192 rule->set = rt->new_set;
1195 IPFW_UH_WUNLOCK(chain);
1201 * Clear counters for a specific rule.
1202 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1203 * so we only care that rules do not disappear.
1206 clear_counters(struct ip_fw *rule, int log_only)
1208 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1211 IPFW_ZERO_RULE_COUNTER(rule);
1212 if (l->o.opcode == O_LOG)
1213 l->log_left = l->max_log;
1217 * Flushes rules counters and/or log values on matching range.
1219 * Returns number of items cleared.
1222 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1229 rt->flags |= IPFW_RCFLAG_DEFAULT;
1231 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1232 for (i = 0; i < chain->n_rules; i++) {
1233 rule = chain->map[i];
1234 if (ipfw_match_range(rule, rt) == 0)
1236 clear_counters(rule, log_only);
1239 IPFW_UH_WUNLOCK(chain);
1245 check_range_tlv(ipfw_range_tlv *rt)
1248 if (rt->head.length != sizeof(*rt))
1250 if (rt->start_rule > rt->end_rule)
1252 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1255 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1262 * Delete rules matching specified parameters
1263 * Data layout (v0)(current):
1264 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1265 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1267 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1269 * Returns 0 on success.
1272 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1273 struct sockopt_data *sd)
1275 ipfw_range_header *rh;
1278 if (sd->valsize != sizeof(*rh))
1281 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1283 if (check_range_tlv(&rh->range) != 0)
1287 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1290 /* Save number of rules deleted */
1291 rh->range.new_set = ndel;
1296 * Move rules/sets matching specified parameters
1297 * Data layout (v0)(current):
1298 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1300 * Returns 0 on success.
1303 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1304 struct sockopt_data *sd)
1306 ipfw_range_header *rh;
1308 if (sd->valsize != sizeof(*rh))
1311 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1313 if (check_range_tlv(&rh->range) != 0)
1316 return (move_range(chain, &rh->range));
1320 * Clear rule accounting data matching specified parameters
1321 * Data layout (v0)(current):
1322 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1323 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1325 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1327 * Returns 0 on success.
1330 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1331 struct sockopt_data *sd)
1333 ipfw_range_header *rh;
1337 if (sd->valsize != sizeof(*rh))
1340 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1342 if (check_range_tlv(&rh->range) != 0)
1345 log_only = (op3->opcode == IP_FW_XRESETLOG);
1347 num = clear_range(chain, &rh->range, log_only);
1349 if (rh->range.flags & IPFW_RCFLAG_ALL)
1350 msg = log_only ? "All logging counts reset" :
1351 "Accounting cleared";
1353 msg = log_only ? "logging count reset" : "cleared";
1356 int lev = LOG_SECURITY | LOG_NOTICE;
1357 log(lev, "ipfw: %s.\n", msg);
1360 /* Save number of rules cleared */
1361 rh->range.new_set = num;
1366 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1370 IPFW_UH_WLOCK_ASSERT(chain);
1372 /* Change enabled/disabled sets mask */
1373 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1374 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1376 V_set_disable = v_set;
1377 IPFW_WUNLOCK(chain);
1381 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1383 struct opcode_obj_rewrite *rw;
1387 IPFW_UH_WLOCK_ASSERT(chain);
1389 if (rt->set == rt->new_set) /* nothing to do */
1394 * Berfore moving the rules we need to check that
1395 * there aren't any conflicting named objects.
1397 for (rw = ctl3_rewriters;
1398 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1399 if (rw->manage_sets == NULL)
1401 i = rw->manage_sets(chain, (uint8_t)rt->set,
1402 (uint8_t)rt->new_set, TEST_ALL);
1407 /* Swap or move two sets */
1408 for (i = 0; i < chain->n_rules - 1; i++) {
1409 rule = chain->map[i];
1410 if (rule->set == (uint8_t)rt->set)
1411 rule->set = (uint8_t)rt->new_set;
1412 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1413 rule->set = (uint8_t)rt->set;
1415 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1416 if (rw->manage_sets == NULL)
1418 rw->manage_sets(chain, (uint8_t)rt->set,
1419 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1425 * Swaps or moves set
1426 * Data layout (v0)(current):
1427 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1429 * Returns 0 on success.
1432 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1433 struct sockopt_data *sd)
1435 ipfw_range_header *rh;
1438 if (sd->valsize != sizeof(*rh))
1441 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1443 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1445 /* enable_sets() expects bitmasks. */
1446 if (op3->opcode != IP_FW_SET_ENABLE &&
1447 (rh->range.set >= IPFW_MAX_SETS ||
1448 rh->range.new_set >= IPFW_MAX_SETS))
1452 IPFW_UH_WLOCK(chain);
1453 switch (op3->opcode) {
1454 case IP_FW_SET_SWAP:
1455 case IP_FW_SET_MOVE:
1456 ret = swap_sets(chain, &rh->range,
1457 op3->opcode == IP_FW_SET_MOVE);
1459 case IP_FW_SET_ENABLE:
1460 enable_sets(chain, &rh->range);
1463 IPFW_UH_WUNLOCK(chain);
1469 * Remove all rules with given number, or do set manipulation.
1470 * Assumes chain != NULL && *chain != NULL.
1472 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1473 * the next 8 bits are the new set; the top 8 bits indicate the command:
1475 * 0 delete rules numbered "rulenum"
1476 * 1 delete rules in set "rulenum"
1477 * 2 move rules "rulenum" to set "new_set"
1478 * 3 move rules from set "rulenum" to set "new_set"
1479 * 4 swap sets "rulenum" and "new_set"
1480 * 5 delete rules "rulenum" and set "new_set"
1483 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1485 uint32_t num; /* rule number or old_set */
1486 uint8_t cmd, new_set;
1492 cmd = (arg >> 24) & 0xff;
1493 new_set = (arg >> 16) & 0xff;
1495 if (cmd > 5 || new_set > RESVD_SET)
1497 if (cmd == 0 || cmd == 2 || cmd == 5) {
1498 if (num >= IPFW_DEFAULT_RULE)
1501 if (num > RESVD_SET) /* old_set */
1505 /* Convert old requests into new representation */
1506 memset(&rt, 0, sizeof(rt));
1507 rt.start_rule = num;
1510 rt.new_set = new_set;
1514 case 0: /* delete rules numbered "rulenum" */
1516 rt.flags |= IPFW_RCFLAG_ALL;
1518 rt.flags |= IPFW_RCFLAG_RANGE;
1521 case 1: /* delete rules in set "rulenum" */
1522 rt.flags |= IPFW_RCFLAG_SET;
1525 case 5: /* delete rules "rulenum" and set "new_set" */
1526 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1531 case 2: /* move rules "rulenum" to set "new_set" */
1532 rt.flags |= IPFW_RCFLAG_RANGE;
1534 case 3: /* move rules from set "rulenum" to set "new_set" */
1535 IPFW_UH_WLOCK(chain);
1536 error = swap_sets(chain, &rt, 1);
1537 IPFW_UH_WUNLOCK(chain);
1539 case 4: /* swap sets "rulenum" and "new_set" */
1540 IPFW_UH_WLOCK(chain);
1541 error = swap_sets(chain, &rt, 0);
1542 IPFW_UH_WUNLOCK(chain);
1549 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1552 if (ndel == 0 && (cmd != 1 && num != 0))
1558 return (move_range(chain, &rt));
1562 * Reset some or all counters on firewall rules.
1563 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1564 * the next 8 bits are the set number, the top 8 bits are the command:
1565 * 0 work with rules from all set's;
1566 * 1 work with rules only from specified set.
1567 * Specified rule number is zero if we want to clear all entries.
1568 * log_only is 1 if we only want to reset logs, zero otherwise.
1571 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1577 uint16_t rulenum = arg & 0xffff;
1578 uint8_t set = (arg >> 16) & 0xff;
1579 uint8_t cmd = (arg >> 24) & 0xff;
1583 if (cmd == 1 && set > RESVD_SET)
1586 IPFW_UH_RLOCK(chain);
1588 V_norule_counter = 0;
1589 for (i = 0; i < chain->n_rules; i++) {
1590 rule = chain->map[i];
1591 /* Skip rules not in our set. */
1592 if (cmd == 1 && rule->set != set)
1594 clear_counters(rule, log_only);
1596 msg = log_only ? "All logging counts reset" :
1597 "Accounting cleared";
1600 for (i = 0; i < chain->n_rules; i++) {
1601 rule = chain->map[i];
1602 if (rule->rulenum == rulenum) {
1603 if (cmd == 0 || rule->set == set)
1604 clear_counters(rule, log_only);
1607 if (rule->rulenum > rulenum)
1610 if (!cleared) { /* we did not find any matching rules */
1611 IPFW_UH_RUNLOCK(chain);
1614 msg = log_only ? "logging count reset" : "cleared";
1616 IPFW_UH_RUNLOCK(chain);
1619 int lev = LOG_SECURITY | LOG_NOTICE;
1622 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1624 log(lev, "ipfw: %s.\n", msg);
1631 * Check rule head in FreeBSD11 format
1635 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1636 struct rule_check_info *ci)
1640 if (size < sizeof(*rule)) {
1641 printf("ipfw: rule too short\n");
1645 /* Check for valid cmd_len */
1646 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1648 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1651 if (rule->act_ofs >= rule->cmd_len) {
1652 printf("ipfw: bogus action offset (%u > %u)\n",
1653 rule->act_ofs, rule->cmd_len - 1);
1657 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1660 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1664 * Check rule head in FreeBSD8 format
1668 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1669 struct rule_check_info *ci)
1673 if (size < sizeof(*rule)) {
1674 printf("ipfw: rule too short\n");
1678 /* Check for valid cmd_len */
1679 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1681 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1684 if (rule->act_ofs >= rule->cmd_len) {
1685 printf("ipfw: bogus action offset (%u > %u)\n",
1686 rule->act_ofs, rule->cmd_len - 1);
1690 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1693 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1697 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1705 * Now go for the individual checks. Very simple ones, basically only
1706 * instruction sizes.
1708 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1709 cmdlen = F_LEN(cmd);
1711 printf("ipfw: opcode %d size truncated\n",
1715 switch (cmd->opcode) {
1718 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1720 ci->object_opcodes++;
1731 case O_IPPRECEDENCE:
1750 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1754 case O_EXTERNAL_ACTION:
1755 if (cmd->arg1 == 0 ||
1756 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1757 printf("ipfw: invalid external "
1761 ci->object_opcodes++;
1763 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1769 cmdlen = F_LEN(cmd);
1770 if (cmd->opcode == O_EXTERNAL_DATA)
1772 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1773 printf("ipfw: invalid opcode "
1774 "next to external action %u\n",
1778 if (cmd->arg1 == 0 ||
1779 cmdlen != F_INSN_SIZE(ipfw_insn)) {
1780 printf("ipfw: invalid external "
1781 "action instance opcode\n");
1784 ci->object_opcodes++;
1789 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1791 if (cmd->arg1 >= rt_numfibs) {
1792 printf("ipfw: invalid fib number %d\n",
1799 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1801 if ((cmd->arg1 != IP_FW_TARG) &&
1802 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1803 printf("ipfw: invalid fib number %d\n",
1804 cmd->arg1 & 0x7FFF);
1818 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1823 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1825 ci->object_opcodes++;
1829 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1832 ((ipfw_insn_log *)cmd)->log_left =
1833 ((ipfw_insn_log *)cmd)->max_log;
1839 /* only odd command lengths */
1840 if ((cmdlen & 1) == 0)
1846 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1847 printf("ipfw: invalid set size %d\n",
1851 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1856 case O_IP_SRC_LOOKUP:
1857 if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1859 case O_IP_DST_LOOKUP:
1860 if (cmd->arg1 >= V_fw_tables_max) {
1861 printf("ipfw: invalid table number %d\n",
1865 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1866 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1867 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1869 ci->object_opcodes++;
1871 case O_IP_FLOW_LOOKUP:
1872 if (cmd->arg1 >= V_fw_tables_max) {
1873 printf("ipfw: invalid table number %d\n",
1877 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1878 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1880 ci->object_opcodes++;
1883 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1894 if (cmdlen < 1 || cmdlen > 31)
1899 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1905 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1906 if (cmdlen < 2 || cmdlen > 31)
1913 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1915 ci->object_opcodes++;
1919 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1925 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1930 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1935 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1942 if (ip_divert_ptr == NULL)
1948 if (ng_ipfw_input_p == NULL)
1953 if (!IPFW_NAT_LOADED)
1955 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1959 ci->object_opcodes++;
1961 case O_FORWARD_MAC: /* XXX not implemented yet */
1974 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1978 printf("ipfw: opcode %d, multiple actions"
1985 printf("ipfw: opcode %d, action must be"
1994 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1995 F_INSN_SIZE(ipfw_insn))
2000 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2001 ((ipfw_insn_u32 *)cmd)->o.arg1)
2005 case O_IP6_SRC_MASK:
2006 case O_IP6_DST_MASK:
2007 if ( !(cmdlen & 1) || cmdlen > 127)
2011 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2017 switch (cmd->opcode) {
2027 case O_IP6_SRC_MASK:
2028 case O_IP6_DST_MASK:
2030 printf("ipfw: no IPv6 support in kernel\n");
2031 return (EPROTONOSUPPORT);
2034 printf("ipfw: opcode %d, unknown opcode\n",
2040 if (have_action == 0) {
2041 printf("ipfw: missing action\n");
2047 printf("ipfw: opcode %d size %d wrong\n",
2048 cmd->opcode, cmdlen);
2054 * Translation of requests for compatibility with FreeBSD 7.2/8.
2055 * a static variable tells us if we have an old client from userland,
2056 * and if necessary we translate requests and responses between the
2062 struct ip_fw7 *next; /* linked list of rules */
2063 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
2064 /* 'next_rule' is used to pass up 'set_disable' status */
2066 uint16_t act_ofs; /* offset of action in 32-bit units */
2067 uint16_t cmd_len; /* # of 32-bit words in cmd */
2068 uint16_t rulenum; /* rule number */
2069 uint8_t set; /* rule set (0..31) */
2070 // #define RESVD_SET 31 /* set for default and persistent rules */
2071 uint8_t _pad; /* padding */
2072 // uint32_t id; /* rule id, only in v.8 */
2073 /* These fields are present in all rules. */
2074 uint64_t pcnt; /* Packet counter */
2075 uint64_t bcnt; /* Byte counter */
2076 uint32_t timestamp; /* tv_sec of last match */
2078 ipfw_insn cmd[1]; /* storage for commands */
2081 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2082 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2085 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
2086 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2091 * Copy the static and dynamic rules to the supplied buffer
2092 * and return the amount of space actually used.
2093 * Must be run under IPFW_UH_RLOCK
2096 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2099 char *ep = bp + space;
2101 struct ip_fw_rule0 *dst;
2102 struct timeval boottime;
2103 int error, i, l, warnflag;
2104 time_t boot_seconds;
2108 getboottime(&boottime);
2109 boot_seconds = boottime.tv_sec;
2110 for (i = 0; i < chain->n_rules; i++) {
2111 rule = chain->map[i];
2114 /* Convert rule to FreeBSd 7.2 format */
2115 l = RULESIZE7(rule);
2116 if (bp + l + sizeof(uint32_t) <= ep) {
2117 bcopy(rule, bp, l + sizeof(uint32_t));
2118 error = set_legacy_obj_kidx(chain,
2119 (struct ip_fw_rule0 *)bp);
2122 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2124 return 0; /*XXX correct? */
2126 * XXX HACK. Store the disable mask in the "next"
2127 * pointer in a wild attempt to keep the ABI the same.
2128 * Why do we do this on EVERY rule?
2130 bcopy(&V_set_disable,
2131 &(((struct ip_fw7 *)bp)->next_rule),
2132 sizeof(V_set_disable));
2133 if (((struct ip_fw7 *)bp)->timestamp)
2134 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2137 continue; /* go to next rule */
2140 l = RULEUSIZE0(rule);
2141 if (bp + l > ep) { /* should not happen */
2142 printf("overflow dumping static rules\n");
2145 dst = (struct ip_fw_rule0 *)bp;
2146 export_rule0(rule, dst, l);
2147 error = set_legacy_obj_kidx(chain, dst);
2150 * XXX HACK. Store the disable mask in the "next"
2151 * pointer in a wild attempt to keep the ABI the same.
2152 * Why do we do this on EVERY rule?
2154 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2155 * so we need to fail _after_ saving at least one mask.
2157 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2159 dst->timestamp += boot_seconds;
2164 /* Non-fatal table rewrite error. */
2168 printf("Stop on rule %d. Fail to convert table\n",
2174 printf("ipfw: process %s is using legacy interfaces,"
2175 " consider rebuilding\n", "");
2176 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2177 return (bp - (char *)buf);
2182 uint32_t b; /* start rule */
2183 uint32_t e; /* end rule */
2184 uint32_t rcount; /* number of rules */
2185 uint32_t rsize; /* rules size */
2186 uint32_t tcount; /* number of tables */
2187 int rcounters; /* counters */
2191 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2194 ntlv->head.type = no->etlv;
2195 ntlv->head.length = sizeof(*ntlv);
2196 ntlv->idx = no->kidx;
2197 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2201 * Export named object info in instance @ni, identified by @kidx
2202 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2204 * Returns 0 on success.
2207 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2208 struct sockopt_data *sd)
2210 struct named_object *no;
2211 ipfw_obj_ntlv *ntlv;
2213 no = ipfw_objhash_lookup_kidx(ni, kidx);
2214 KASSERT(no != NULL, ("invalid object kernel index passed"));
2216 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2220 ipfw_export_obj_ntlv(no, ntlv);
2225 * Dumps static rules with table TLVs in buffer @sd.
2227 * Returns 0 on success.
2230 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2231 uint32_t *bmask, struct sockopt_data *sd)
2236 ipfw_obj_ctlv *ctlv;
2237 struct ip_fw *krule;
2238 struct namedobj_instance *ni;
2241 /* Dump table names first (if any) */
2242 if (da->tcount > 0) {
2244 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2247 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2248 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2250 ctlv->count = da->tcount;
2251 ctlv->objsize = sizeof(ipfw_obj_ntlv);
2255 tcount = da->tcount;
2256 ni = ipfw_get_table_objhash(chain);
2257 while (tcount > 0) {
2258 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
2263 /* Jump to shared named object bitmask */
2264 if (i >= IPFW_TABLES_MAX) {
2265 ni = CHAIN_TO_SRV(chain);
2266 i -= IPFW_TABLES_MAX;
2267 bmask += IPFW_TABLES_MAX / 32;
2270 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2278 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2281 ctlv->head.type = IPFW_TLV_RULE_LIST;
2282 ctlv->head.length = da->rsize + sizeof(*ctlv);
2283 ctlv->count = da->rcount;
2285 for (i = da->b; i < da->e; i++) {
2286 krule = chain->map[i];
2288 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2289 if (da->rcounters != 0)
2290 l += sizeof(struct ip_fw_bcounter);
2291 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2295 export_rule1(krule, dst, l, da->rcounters);
2302 * Marks every object index used in @rule with bit in @bmask.
2303 * Used to generate bitmask of referenced tables/objects for given ruleset
2306 * Returns number of newly-referenced objects.
2309 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
2312 struct opcode_obj_rewrite *rw;
2314 int bidx, cmdlen, l, count;
2322 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2323 cmdlen = F_LEN(cmd);
2325 rw = find_op_rw(cmd, &kidx, &subtype);
2331 * Maintain separate bitmasks for table and
2332 * non-table objects.
2334 if (rw->etlv != IPFW_TLV_TBL_NAME)
2335 bidx += IPFW_TABLES_MAX / 32;
2337 if ((bmask[bidx] & (1 << (kidx % 32))) == 0)
2340 bmask[bidx] |= 1 << (kidx % 32);
2347 * Dumps requested objects data
2348 * Data layout (version 0)(current):
2349 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2350 * size = ipfw_cfg_lheader.size
2351 * Reply: [ ipfw_cfg_lheader
2352 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2353 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2354 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2356 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2358 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2359 * The rest (size, count) are set to zero and needs to be ignored.
2361 * Returns 0 on success.
2364 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2365 struct sockopt_data *sd)
2367 ipfw_cfg_lheader *hdr;
2372 struct dump_args da;
2375 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2381 /* Allocate needed state. Note we allocate 2xspace mask, for table&srv */
2382 if (hdr->flags & IPFW_CFG_GET_STATIC)
2383 bmask = malloc(IPFW_TABLES_MAX / 4, M_TEMP, M_WAITOK | M_ZERO);
2385 IPFW_UH_RLOCK(chain);
2388 * STAGE 1: Determine size/count for objects in range.
2389 * Prepare used tables bitmask.
2391 sz = sizeof(ipfw_cfg_lheader);
2392 memset(&da, 0, sizeof(da));
2395 da.e = chain->n_rules;
2397 if (hdr->end_rule != 0) {
2398 /* Handle custom range */
2399 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2400 rnum = IPFW_DEFAULT_RULE;
2401 da.b = ipfw_find_rule(chain, rnum, 0);
2402 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2403 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2404 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2407 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2408 for (i = da.b; i < da.e; i++) {
2409 rule = chain->map[i];
2410 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2412 /* Update bitmask of used objects for given range */
2413 da.tcount += mark_object_kidx(chain, rule, bmask);
2415 /* Add counters if requested */
2416 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2417 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2422 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2423 sizeof(ipfw_obj_ctlv);
2424 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2427 if (hdr->flags & IPFW_CFG_GET_STATES)
2428 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2429 sizeof(ipfw_obj_ctlv);
2433 * Fill header anyway.
2434 * Note we have to save header fields to stable storage
2435 * buffer inside @sd can be flushed after dumping rules
2438 hdr->set_mask = ~V_set_disable;
2439 hdr_flags = hdr->flags;
2442 if (sd->valsize < sz) {
2447 /* STAGE2: Store actual data */
2448 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2449 error = dump_static_rules(chain, &da, bmask, sd);
2454 if (hdr_flags & IPFW_CFG_GET_STATES)
2455 error = ipfw_dump_states(chain, sd);
2458 IPFW_UH_RUNLOCK(chain);
2461 free(bmask, M_TEMP);
2467 ipfw_check_object_name_generic(const char *name)
2471 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2472 if (strnlen(name, nsize) == nsize)
2474 if (name[0] == '\0')
2480 * Creates non-existent objects referenced by rule.
2482 * Return 0 on success.
2485 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2486 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2488 struct opcode_obj_rewrite *rw;
2494 * Compatibility stuff: do actual creation for non-existing,
2495 * but referenced objects.
2497 for (p = oib; p < pidx; p++) {
2505 rw = find_op_rw(cmd + p->off, NULL, NULL);
2506 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2507 (cmd + p->off)->opcode));
2509 if (rw->create_object == NULL)
2512 error = rw->create_object(ch, ti, &kidx);
2519 * Error happened. We have to rollback everything.
2520 * Drop all already acquired references.
2523 unref_oib_objects(ch, cmd, oib, pidx);
2524 IPFW_UH_WUNLOCK(ch);
2533 * Compatibility function for old ipfw(8) binaries.
2534 * Rewrites table/nat kernel indices with userland ones.
2535 * Convert tables matching '/^\d+$/' to their atoi() value.
2536 * Use number 65535 for other tables.
2538 * Returns 0 on success.
2541 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2543 struct opcode_obj_rewrite *rw;
2544 struct named_object *no;
2548 int cmdlen, error, l;
2549 uint16_t kidx, uidx;
2557 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2558 cmdlen = F_LEN(cmd);
2560 /* Check if is index in given opcode */
2561 rw = find_op_rw(cmd, &kidx, &subtype);
2565 /* Try to find referenced kernel object */
2566 no = rw->find_bykidx(ch, kidx);
2570 val = strtol(no->name, &end, 10);
2571 if (*end == '\0' && val < 65535) {
2576 * We are called via legacy opcode.
2577 * Save error and show table as fake number
2578 * not to make ipfw(8) hang.
2584 rw->update(cmd, uidx);
2592 * Unreferences all already-referenced objects in given @cmd rule,
2593 * using information in @oib.
2595 * Used to rollback partially converted rule on error.
2598 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2599 struct obj_idx *end)
2601 struct opcode_obj_rewrite *rw;
2602 struct named_object *no;
2605 IPFW_UH_WLOCK_ASSERT(ch);
2607 for (p = oib; p < end; p++) {
2611 rw = find_op_rw(cmd + p->off, NULL, NULL);
2612 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2613 (cmd + p->off)->opcode));
2615 /* Find & unref by existing idx */
2616 no = rw->find_bykidx(ch, p->kidx);
2617 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2623 * Remove references from every object used in @rule.
2624 * Used at rule removal code.
2627 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2629 struct opcode_obj_rewrite *rw;
2630 struct named_object *no;
2636 IPFW_UH_WLOCK_ASSERT(ch);
2641 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2642 cmdlen = F_LEN(cmd);
2644 rw = find_op_rw(cmd, &kidx, &subtype);
2647 no = rw->find_bykidx(ch, kidx);
2649 KASSERT(no != NULL, ("object id %d not found", kidx));
2650 KASSERT(no->subtype == subtype,
2651 ("wrong type %d (%d) for object id %d",
2652 no->subtype, subtype, kidx));
2653 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2656 if (no->refcnt == 1 && rw->destroy_object != NULL)
2657 rw->destroy_object(ch, no);
2665 * Find and reference object (if any) stored in instruction @cmd.
2667 * Saves object info in @pidx, sets
2668 * - @unresolved to 1 if object should exists but not found
2670 * Returns non-zero value in case of error.
2673 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2674 struct obj_idx *pidx, int *unresolved)
2676 struct named_object *no;
2677 struct opcode_obj_rewrite *rw;
2680 /* Check if this opcode is candidate for rewrite */
2681 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2685 /* Need to rewrite. Save necessary fields */
2686 pidx->uidx = ti->uidx;
2687 pidx->type = ti->type;
2689 /* Try to find referenced kernel object */
2690 error = rw->find_byname(ch, ti, &no);
2695 * Report about unresolved object for automaic
2703 * Object is already exist.
2704 * Its subtype should match with expected value.
2706 if (ti->type != no->subtype)
2709 /* Bump refcount and update kidx. */
2711 rw->update(cmd, no->kidx);
2716 * Finds and bumps refcount for objects referenced by given @rule.
2717 * Auto-creates non-existing tables.
2718 * Fills in @oib array with userland/kernel indexes.
2720 * Returns 0 on success.
2723 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2724 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2726 struct obj_idx *pidx;
2728 int cmdlen, error, l, unresolved;
2738 /* Increase refcount on each existing referenced table. */
2739 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2740 cmdlen = F_LEN(cmd);
2743 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2747 * Compatibility stuff for old clients:
2748 * prepare to automaitcally create non-existing objects.
2750 if (unresolved != 0) {
2751 pidx->off = rule->cmd_len - l;
2757 /* Unref everything we have already done */
2758 unref_oib_objects(ch, rule->cmd, oib, pidx);
2759 IPFW_UH_WUNLOCK(ch);
2762 IPFW_UH_WUNLOCK(ch);
2764 /* Perform auto-creation for non-existing objects */
2766 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2768 /* Calculate real number of dynamic objects */
2769 ci->object_opcodes = (uint16_t)(pidx - oib);
2775 * Checks is opcode is referencing table of appropriate type.
2776 * Adds reference count for found table if true.
2777 * Rewrites user-supplied opcode values with kernel ones.
2779 * Returns 0 on success and appropriate error code otherwise.
2782 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2787 struct obj_idx *p, *pidx_first, *pidx_last;
2791 * Prepare an array for storing opcode indices.
2792 * Use stack allocation by default.
2794 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2796 pidx_first = ci->obuf;
2798 pidx_first = malloc(
2799 ci->object_opcodes * sizeof(struct obj_idx),
2800 M_IPFW, M_WAITOK | M_ZERO);
2804 memset(&ti, 0, sizeof(ti));
2806 /* Use set rule is assigned to. */
2807 ti.set = ci->krule->set;
2808 if (ci->ctlv != NULL) {
2809 ti.tlvs = (void *)(ci->ctlv + 1);
2810 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2813 /* Reference all used tables and other objects */
2814 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2818 * Note that ref_rule_objects() might have updated ci->object_opcodes
2819 * to reflect actual number of object opcodes.
2822 /* Perform rewrite of remaining opcodes */
2824 pidx_last = pidx_first + ci->object_opcodes;
2825 for (p = pidx_first; p < pidx_last; p++) {
2826 cmd = ci->krule->cmd + p->off;
2827 update_opcode_kidx(cmd, p->kidx);
2831 if (pidx_first != ci->obuf)
2832 free(pidx_first, M_IPFW);
2838 * Adds one or more rules to ipfw @chain.
2839 * Data layout (version 0)(current):
2843 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2844 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2849 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2850 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2853 * Rules in reply are modified to store their actual ruleset number.
2855 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2856 * according to their idx field and there has to be no duplicates.
2857 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2858 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2860 * Returns 0 on success.
2863 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2864 struct sockopt_data *sd)
2866 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2867 ipfw_obj_ntlv *ntlv;
2868 int clen, error, idx;
2869 uint32_t count, read;
2870 struct ip_fw_rule *r;
2871 struct rule_check_info rci, *ci, *cbuf;
2874 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2875 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2877 read = sizeof(ip_fw3_opheader);
2881 memset(&rci, 0, sizeof(struct rule_check_info));
2883 if (read + sizeof(*ctlv) > sd->valsize)
2886 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2887 clen = ctlv->head.length;
2888 /* Check size and alignment */
2889 if (clen > sd->valsize || clen < sizeof(*ctlv))
2891 if ((clen % sizeof(uint64_t)) != 0)
2895 * Some table names or other named objects.
2896 * Check for validness.
2898 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2899 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2904 * Ensure TLVs are sorted ascending and
2905 * there are no duplicates.
2908 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2910 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2913 error = ipfw_check_object_name_generic(ntlv->name);
2917 if (ntlv->idx <= idx)
2926 read += ctlv->head.length;
2927 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2930 if (read + sizeof(*ctlv) > sd->valsize)
2933 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2934 clen = ctlv->head.length;
2935 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2937 if ((clen % sizeof(uint64_t)) != 0)
2941 * TODO: Permit adding multiple rules at once
2943 if (ctlv->count != 1)
2946 clen -= sizeof(*ctlv);
2948 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2951 /* Allocate state for each rule or use stack */
2952 if (ctlv->count == 1) {
2953 memset(&rci, 0, sizeof(struct rule_check_info));
2956 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2961 * Check each rule for validness.
2962 * Ensure numbered rules are sorted ascending
2963 * and properly aligned
2966 r = (struct ip_fw_rule *)(ctlv + 1);
2970 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2971 if (rsize > clen || ctlv->count <= count) {
2977 error = check_ipfw_rule1(r, rsize, ci);
2982 if (r->rulenum != 0 && r->rulenum < idx) {
2983 printf("rulenum %d idx %d\n", r->rulenum, idx);
2989 ci->urule = (caddr_t)r;
2991 rsize = roundup2(rsize, sizeof(uint64_t));
2993 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2998 if (ctlv->count != count || error != 0) {
3005 read += ctlv->head.length;
3006 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3009 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3010 if (cbuf != NULL && cbuf != &rci)
3016 * Passed rules seems to be valid.
3017 * Allocate storage and try to add them to chain.
3019 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3020 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3021 ci->krule = ipfw_alloc_rule(chain, clen);
3025 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3026 /* Free allocate krules */
3027 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3028 free_rule(ci->krule);
3031 if (cbuf != NULL && cbuf != &rci)
3038 * Lists all sopts currently registered.
3039 * Data layout (v0)(current):
3040 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3041 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3043 * Returns 0 on success
3046 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3047 struct sockopt_data *sd)
3049 struct _ipfw_obj_lheader *olh;
3051 struct ipfw_sopt_handler *sh;
3052 uint32_t count, n, size;
3054 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3057 if (sd->valsize < olh->size)
3062 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3064 /* Fill in header regadless of buffer size */
3066 olh->objsize = sizeof(ipfw_sopt_info);
3068 if (size > olh->size) {
3075 for (n = 1; n <= count; n++) {
3076 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3077 KASSERT(i != NULL, ("previously checked buffer is not enough"));
3078 sh = &ctl3_handlers[n];
3079 i->opcode = sh->opcode;
3080 i->version = sh->version;
3081 i->refcnt = sh->refcnt;
3089 * Compares two opcodes.
3090 * Used both in qsort() and bsearch().
3092 * Returns 0 if match is found.
3095 compare_opcodes(const void *_a, const void *_b)
3097 const struct opcode_obj_rewrite *a, *b;
3099 a = (const struct opcode_obj_rewrite *)_a;
3100 b = (const struct opcode_obj_rewrite *)_b;
3102 if (a->opcode < b->opcode)
3104 else if (a->opcode > b->opcode)
3111 * XXX: Rewrite bsearch()
3114 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3115 struct opcode_obj_rewrite **phi)
3117 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3119 memset(&h, 0, sizeof(h));
3122 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3123 ctl3_rsize, sizeof(h), compare_opcodes);
3127 /* Find the first element matching the same opcode */
3129 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3132 /* Find the last element matching the same opcode */
3134 ctl3_max = ctl3_rewriters + ctl3_rsize;
3135 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3145 * Finds opcode object rewriter based on @code.
3147 * Returns pointer to handler or NULL.
3149 static struct opcode_obj_rewrite *
3150 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3152 struct opcode_obj_rewrite *rw, *lo, *hi;
3156 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3159 for (rw = lo; rw <= hi; rw++) {
3160 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3172 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3175 if (find_op_rw(cmd, puidx, NULL) == NULL)
3181 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3183 struct opcode_obj_rewrite *rw;
3185 rw = find_op_rw(cmd, NULL, NULL);
3186 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3187 rw->update(cmd, idx);
3191 ipfw_init_obj_rewriter()
3194 ctl3_rewriters = NULL;
3199 ipfw_destroy_obj_rewriter()
3202 if (ctl3_rewriters != NULL)
3203 free(ctl3_rewriters, M_IPFW);
3204 ctl3_rewriters = NULL;
3209 * Adds one or more opcode object rewrite handlers to the global array.
3210 * Function may sleep.
3213 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3216 struct opcode_obj_rewrite *tmp;
3221 sz = ctl3_rsize + count;
3223 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3225 if (ctl3_rsize + count <= sz)
3232 /* Merge old & new arrays */
3233 sz = ctl3_rsize + count;
3234 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3235 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3236 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3237 /* Switch new and free old */
3238 if (ctl3_rewriters != NULL)
3239 free(ctl3_rewriters, M_IPFW);
3240 ctl3_rewriters = tmp;
3247 * Removes one or more object rewrite handlers from the global array.
3250 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3253 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3258 for (i = 0; i < count; i++) {
3259 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3262 for (ktmp = lo; ktmp <= hi; ktmp++) {
3263 if (ktmp->classifier != rw[i].classifier)
3266 ctl3_max = ctl3_rewriters + ctl3_rsize;
3267 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3268 memmove(ktmp, ktmp + 1, sz);
3275 if (ctl3_rsize == 0) {
3276 if (ctl3_rewriters != NULL)
3277 free(ctl3_rewriters, M_IPFW);
3278 ctl3_rewriters = NULL;
3287 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3288 struct named_object *no, void *arg)
3290 struct sockopt_data *sd;
3291 ipfw_obj_ntlv *ntlv;
3293 sd = (struct sockopt_data *)arg;
3294 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3297 ipfw_export_obj_ntlv(no, ntlv);
3302 * Lists all service objects.
3303 * Data layout (v0)(current):
3304 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3305 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3306 * Returns 0 on success
3309 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3310 struct sockopt_data *sd)
3312 ipfw_obj_lheader *hdr;
3315 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3319 IPFW_UH_RLOCK(chain);
3320 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3321 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3322 if (sd->valsize < hdr->size) {
3323 IPFW_UH_RUNLOCK(chain);
3327 hdr->objsize = sizeof(ipfw_obj_ntlv);
3329 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3330 export_objhash_ntlv_internal, sd);
3331 IPFW_UH_RUNLOCK(chain);
3336 * Compares two sopt handlers (code, version and handler ptr).
3337 * Used both as qsort() and bsearch().
3338 * Does not compare handler for latter case.
3340 * Returns 0 if match is found.
3343 compare_sh(const void *_a, const void *_b)
3345 const struct ipfw_sopt_handler *a, *b;
3347 a = (const struct ipfw_sopt_handler *)_a;
3348 b = (const struct ipfw_sopt_handler *)_b;
3350 if (a->opcode < b->opcode)
3352 else if (a->opcode > b->opcode)
3355 if (a->version < b->version)
3357 else if (a->version > b->version)
3360 /* bsearch helper */
3361 if (a->handler == NULL)
3364 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3366 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3373 * Finds sopt handler based on @code and @version.
3375 * Returns pointer to handler or NULL.
3377 static struct ipfw_sopt_handler *
3378 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3380 struct ipfw_sopt_handler *sh, h;
3382 memset(&h, 0, sizeof(h));
3384 h.version = version;
3385 h.handler = handler;
3387 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3388 ctl3_hsize, sizeof(h), compare_sh);
3394 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3396 struct ipfw_sopt_handler *sh;
3399 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3401 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3407 /* Copy handler data to requested buffer */
3415 find_unref_sh(struct ipfw_sopt_handler *psh)
3417 struct ipfw_sopt_handler *sh;
3420 sh = find_sh(psh->opcode, psh->version, NULL);
3421 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3428 ipfw_init_sopt_handler()
3432 IPFW_ADD_SOPT_HANDLER(1, scodes);
3436 ipfw_destroy_sopt_handler()
3439 IPFW_DEL_SOPT_HANDLER(1, scodes);
3440 CTL3_LOCK_DESTROY();
3444 * Adds one or more sockopt handlers to the global array.
3445 * Function may sleep.
3448 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3451 struct ipfw_sopt_handler *tmp;
3456 sz = ctl3_hsize + count;
3458 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3460 if (ctl3_hsize + count <= sz)
3467 /* Merge old & new arrays */
3468 sz = ctl3_hsize + count;
3469 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3470 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3471 qsort(tmp, sz, sizeof(*sh), compare_sh);
3472 /* Switch new and free old */
3473 if (ctl3_handlers != NULL)
3474 free(ctl3_handlers, M_IPFW);
3475 ctl3_handlers = tmp;
3483 * Removes one or more sockopt handlers from the global array.
3486 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3489 struct ipfw_sopt_handler *tmp, *h;
3494 for (i = 0; i < count; i++) {
3496 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3500 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3501 memmove(h, h + 1, sz);
3505 if (ctl3_hsize == 0) {
3506 if (ctl3_handlers != NULL)
3507 free(ctl3_handlers, M_IPFW);
3508 ctl3_handlers = NULL;
3519 * Writes data accumulated in @sd to sockopt buffer.
3520 * Zeroes internal @sd buffer.
3523 ipfw_flush_sopt_data(struct sockopt_data *sd)
3525 struct sockopt *sopt;
3535 if (sopt->sopt_dir == SOPT_GET) {
3536 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3541 memset(sd->kbuf, 0, sd->ksize);
3544 if (sd->ktotal + sd->ksize < sd->valsize)
3545 sd->kavail = sd->ksize;
3547 sd->kavail = sd->valsize - sd->ktotal;
3549 /* Update sopt buffer data */
3550 sopt->sopt_valsize = sd->ktotal;
3551 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3557 * Ensures that @sd buffer has contiguous @neeeded number of
3560 * Returns pointer to requested space or NULL.
3563 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3568 if (sd->kavail < needed) {
3570 * Flush data and try another time.
3572 error = ipfw_flush_sopt_data(sd);
3574 if (sd->kavail < needed || error != 0)
3578 addr = sd->kbuf + sd->koff;
3580 sd->kavail -= needed;
3585 * Requests @needed contiguous bytes from @sd buffer.
3586 * Function is used to notify subsystem that we are
3587 * interesed in first @needed bytes (request header)
3588 * and the rest buffer can be safely zeroed.
3590 * Returns pointer to requested space or NULL.
3593 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3597 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3601 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3607 * New sockopt handler.
3610 ipfw_ctl3(struct sockopt *sopt)
3613 size_t size, valsize;
3614 struct ip_fw_chain *chain;
3616 struct sockopt_data sdata;
3617 struct ipfw_sopt_handler h;
3618 ip_fw3_opheader *op3 = NULL;
3620 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3624 if (sopt->sopt_name != IP_FW3)
3625 return (ipfw_ctl(sopt));
3627 chain = &V_layer3_chain;
3630 /* Save original valsize before it is altered via sooptcopyin() */
3631 valsize = sopt->sopt_valsize;
3632 memset(&sdata, 0, sizeof(sdata));
3633 /* Read op3 header first to determine actual operation */
3634 op3 = (ip_fw3_opheader *)xbuf;
3635 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3638 sopt->sopt_valsize = valsize;
3641 * Find and reference command.
3643 error = find_ref_sh(op3->opcode, op3->version, &h);
3648 * Disallow modifications in really-really secure mode, but still allow
3649 * the logging counters to be reset.
3651 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3652 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3660 * Fill in sockopt_data structure that may be useful for
3661 * IP_FW3 get requests.
3664 if (valsize <= sizeof(xbuf)) {
3665 /* use on-stack buffer */
3667 sdata.ksize = sizeof(xbuf);
3668 sdata.kavail = valsize;
3672 * Determine opcode type/buffer size:
3673 * allocate sliding-window buf for data export or
3674 * contiguous buffer for special ops.
3676 if ((h.dir & HDIR_SET) != 0) {
3677 /* Set request. Allocate contigous buffer. */
3678 if (valsize > CTL3_LARGEBUF) {
3685 /* Get request. Allocate sliding window buffer */
3686 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3688 if (size < valsize) {
3689 /* We have to wire user buffer */
3690 error = vslock(sopt->sopt_val, valsize);
3697 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3699 sdata.kavail = size;
3703 sdata.sopt_val = sopt->sopt_val;
3704 sdata.valsize = valsize;
3707 * Copy either all request (if valsize < bsize_max)
3708 * or first bsize_max bytes to guarantee most consumers
3709 * that all necessary data has been copied).
3710 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3712 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3713 sizeof(ip_fw3_opheader))) != 0)
3715 op3 = (ip_fw3_opheader *)sdata.kbuf;
3717 /* Finally, run handler */
3718 error = h.handler(chain, op3, &sdata);
3721 /* Flush state and free buffers */
3723 error = ipfw_flush_sopt_data(&sdata);
3725 ipfw_flush_sopt_data(&sdata);
3728 vsunlock(sdata.sopt_val, valsize);
3730 /* Restore original pointer and set number of bytes written */
3731 sopt->sopt_val = sdata.sopt_val;
3732 sopt->sopt_valsize = sdata.ktotal;
3733 if (sdata.kbuf != xbuf)
3734 free(sdata.kbuf, M_TEMP);
3740 * {set|get}sockopt parser.
3743 ipfw_ctl(struct sockopt *sopt)
3745 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3747 size_t size, valsize;
3749 struct ip_fw_rule0 *rule;
3750 struct ip_fw_chain *chain;
3751 u_int32_t rulenum[2];
3753 struct rule_check_info ci;
3756 chain = &V_layer3_chain;
3759 /* Save original valsize before it is altered via sooptcopyin() */
3760 valsize = sopt->sopt_valsize;
3761 opt = sopt->sopt_name;
3764 * Disallow modifications in really-really secure mode, but still allow
3765 * the logging counters to be reset.
3767 if (opt == IP_FW_ADD ||
3768 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3769 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3777 * pass up a copy of the current rules. Static rules
3778 * come first (the last of which has number IPFW_DEFAULT_RULE),
3779 * followed by a possibly empty list of dynamic rule.
3780 * The last dynamic rule has NULL in the "next" field.
3782 * Note that the calculated size is used to bound the
3783 * amount of data returned to the user. The rule set may
3784 * change between calculating the size and returning the
3785 * data in which case we'll just return what fits.
3790 size = chain->static_len;
3791 size += ipfw_dyn_len();
3792 if (size >= sopt->sopt_valsize)
3794 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3795 IPFW_UH_RLOCK(chain);
3796 /* check again how much space we need */
3797 want = chain->static_len + ipfw_dyn_len();
3799 len = ipfw_getrules(chain, buf, size);
3800 IPFW_UH_RUNLOCK(chain);
3802 error = sooptcopyout(sopt, buf, len);
3810 /* locking is done within del_entry() */
3811 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3815 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3816 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3817 sizeof(struct ip_fw7) );
3819 memset(&ci, 0, sizeof(struct rule_check_info));
3822 * If the size of commands equals RULESIZE7 then we assume
3823 * a FreeBSD7.2 binary is talking to us (set is7=1).
3824 * is7 is persistent so the next 'ipfw list' command
3825 * will use this format.
3826 * NOTE: If wrong version is guessed (this can happen if
3827 * the first ipfw command is 'ipfw [pipe] list')
3828 * the ipfw binary may crash or loop infinitly...
3830 size = sopt->sopt_valsize;
3831 if (size == RULESIZE7(rule)) {
3833 error = convert_rule_to_8(rule);
3838 size = RULESIZE(rule);
3842 error = check_ipfw_rule0(rule, size, &ci);
3844 /* locking is done within add_rule() */
3845 struct ip_fw *krule;
3846 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3847 ci.urule = (caddr_t)rule;
3850 error = commit_rules(chain, &ci, 1);
3852 free_rule(ci.krule);
3853 else if (sopt->sopt_dir == SOPT_GET) {
3855 error = convert_rule_to_7(rule);
3856 size = RULESIZE7(rule);
3862 error = sooptcopyout(sopt, rule, size);
3870 * IP_FW_DEL is used for deleting single rules or sets,
3871 * and (ab)used to atomically manipulate sets. Argument size
3872 * is used to distinguish between the two:
3874 * delete single rule or set of rules,
3875 * or reassign rules (or sets) to a different set.
3876 * 2*sizeof(u_int32_t)
3877 * atomic disable/enable sets.
3878 * first u_int32_t contains sets to be disabled,
3879 * second u_int32_t contains sets to be enabled.
3881 error = sooptcopyin(sopt, rulenum,
3882 2*sizeof(u_int32_t), sizeof(u_int32_t));
3885 size = sopt->sopt_valsize;
3886 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3887 /* delete or reassign, locking done in del_entry() */
3888 error = del_entry(chain, rulenum[0]);
3889 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3890 IPFW_UH_WLOCK(chain);
3892 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3893 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3894 IPFW_UH_WUNLOCK(chain);
3900 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3902 if (sopt->sopt_val != 0) {
3903 error = sooptcopyin(sopt, rulenum,
3904 sizeof(u_int32_t), sizeof(u_int32_t));
3908 error = zero_entry(chain, rulenum[0],
3909 sopt->sopt_name == IP_FW_RESETLOG);
3912 /*--- TABLE opcodes ---*/
3913 case IP_FW_TABLE_ADD:
3914 case IP_FW_TABLE_DEL:
3916 ipfw_table_entry ent;
3917 struct tentry_info tei;
3919 struct table_value v;
3921 error = sooptcopyin(sopt, &ent,
3922 sizeof(ent), sizeof(ent));
3926 memset(&tei, 0, sizeof(tei));
3927 tei.paddr = &ent.addr;
3928 tei.subtype = AF_INET;
3929 tei.masklen = ent.masklen;
3930 ipfw_import_table_value_legacy(ent.value, &v);
3932 memset(&ti, 0, sizeof(ti));
3934 ti.type = IPFW_TABLE_CIDR;
3936 error = (opt == IP_FW_TABLE_ADD) ?
3937 add_table_entry(chain, &ti, &tei, 0, 1) :
3938 del_table_entry(chain, &ti, &tei, 0, 1);
3943 case IP_FW_TABLE_FLUSH:
3948 error = sooptcopyin(sopt, &tbl,
3949 sizeof(tbl), sizeof(tbl));
3952 memset(&ti, 0, sizeof(ti));
3954 error = flush_table(chain, &ti);
3958 case IP_FW_TABLE_GETSIZE:
3963 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3966 memset(&ti, 0, sizeof(ti));
3969 error = ipfw_count_table(chain, &ti, &cnt);
3970 IPFW_RUNLOCK(chain);
3973 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3977 case IP_FW_TABLE_LIST:
3982 if (sopt->sopt_valsize < sizeof(*tbl)) {
3986 size = sopt->sopt_valsize;
3987 tbl = malloc(size, M_TEMP, M_WAITOK);
3988 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3993 tbl->size = (size - sizeof(*tbl)) /
3994 sizeof(ipfw_table_entry);
3995 memset(&ti, 0, sizeof(ti));
3998 error = ipfw_dump_table_legacy(chain, &ti, tbl);
3999 IPFW_RUNLOCK(chain);
4004 error = sooptcopyout(sopt, tbl, size);
4009 /*--- NAT operations are protected by the IPFW_LOCK ---*/
4011 if (IPFW_NAT_LOADED)
4012 error = ipfw_nat_cfg_ptr(sopt);
4014 printf("IP_FW_NAT_CFG: %s\n",
4015 "ipfw_nat not present, please load it");
4021 if (IPFW_NAT_LOADED)
4022 error = ipfw_nat_del_ptr(sopt);
4024 printf("IP_FW_NAT_DEL: %s\n",
4025 "ipfw_nat not present, please load it");
4030 case IP_FW_NAT_GET_CONFIG:
4031 if (IPFW_NAT_LOADED)
4032 error = ipfw_nat_get_cfg_ptr(sopt);
4034 printf("IP_FW_NAT_GET_CFG: %s\n",
4035 "ipfw_nat not present, please load it");
4040 case IP_FW_NAT_GET_LOG:
4041 if (IPFW_NAT_LOADED)
4042 error = ipfw_nat_get_log_ptr(sopt);
4044 printf("IP_FW_NAT_GET_LOG: %s\n",
4045 "ipfw_nat not present, please load it");
4051 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4058 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
4060 /* Functions to convert rules 7.2 <==> 8.0 */
4062 convert_rule_to_7(struct ip_fw_rule0 *rule)
4064 /* Used to modify original rule */
4065 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4066 /* copy of original rule, version 8 */
4067 struct ip_fw_rule0 *tmp;
4069 /* Used to copy commands */
4070 ipfw_insn *ccmd, *dst;
4071 int ll = 0, ccmdlen = 0;
4073 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4075 return 1; //XXX error
4077 bcopy(rule, tmp, RULE_MAXSIZE);
4080 //rule7->_pad = tmp->_pad;
4081 rule7->set = tmp->set;
4082 rule7->rulenum = tmp->rulenum;
4083 rule7->cmd_len = tmp->cmd_len;
4084 rule7->act_ofs = tmp->act_ofs;
4085 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4086 rule7->cmd_len = tmp->cmd_len;
4087 rule7->pcnt = tmp->pcnt;
4088 rule7->bcnt = tmp->bcnt;
4089 rule7->timestamp = tmp->timestamp;
4092 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4093 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4094 ccmdlen = F_LEN(ccmd);
4096 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4098 if (dst->opcode > O_NAT)
4099 /* O_REASS doesn't exists in 7.2 version, so
4100 * decrement opcode if it is after O_REASS
4105 printf("ipfw: opcode %d size truncated\n",
4116 convert_rule_to_8(struct ip_fw_rule0 *rule)
4118 /* Used to modify original rule */
4119 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4121 /* Used to copy commands */
4122 ipfw_insn *ccmd, *dst;
4123 int ll = 0, ccmdlen = 0;
4125 /* Copy of original rule */
4126 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4128 return 1; //XXX error
4131 bcopy(rule7, tmp, RULE_MAXSIZE);
4133 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4134 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4135 ccmdlen = F_LEN(ccmd);
4137 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4139 if (dst->opcode > O_NAT)
4140 /* O_REASS doesn't exists in 7.2 version, so
4141 * increment opcode if it is after O_REASS
4146 printf("ipfw: opcode %d size truncated\n",
4152 rule->_pad = tmp->_pad;
4153 rule->set = tmp->set;
4154 rule->rulenum = tmp->rulenum;
4155 rule->cmd_len = tmp->cmd_len;
4156 rule->act_ofs = tmp->act_ofs;
4157 rule->next_rule = (struct ip_fw *)tmp->next_rule;
4158 rule->cmd_len = tmp->cmd_len;
4159 rule->id = 0; /* XXX see if is ok = 0 */
4160 rule->pcnt = tmp->pcnt;
4161 rule->bcnt = tmp->bcnt;
4162 rule->timestamp = tmp->timestamp;
4174 ipfw_init_srv(struct ip_fw_chain *ch)
4177 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4178 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4179 M_IPFW, M_WAITOK | M_ZERO);
4183 ipfw_destroy_srv(struct ip_fw_chain *ch)
4186 free(ch->srvstate, M_IPFW);
4187 ipfw_objhash_destroy(ch->srvmap);
4191 * Allocate new bitmask which can be used to enlarge/shrink
4192 * named instance index.
4195 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4201 KASSERT((items % BLOCK_ITEMS) == 0,
4202 ("bitmask size needs to power of 2 and greater or equal to %zu",
4205 max_blocks = items / BLOCK_ITEMS;
4207 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4208 /* Mark all as free */
4209 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4210 *idx_mask &= ~(u_long)1; /* Skip index 0 */
4213 *pblocks = max_blocks;
4217 * Copy current bitmask index to new one.
4220 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4222 int old_blocks, new_blocks;
4223 u_long *old_idx, *new_idx;
4226 old_idx = ni->idx_mask;
4227 old_blocks = ni->max_blocks;
4229 new_blocks = *blocks;
4231 for (i = 0; i < IPFW_MAX_SETS; i++) {
4232 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4233 old_blocks * sizeof(u_long));
4238 * Swaps current @ni index with new one.
4241 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4246 old_idx = ni->idx_mask;
4247 old_blocks = ni->max_blocks;
4249 ni->idx_mask = *idx;
4250 ni->max_blocks = *blocks;
4252 /* Save old values */
4254 *blocks = old_blocks;
4258 ipfw_objhash_bitmap_free(void *idx, int blocks)
4265 * Creates named hash instance.
4266 * Must be called without holding any locks.
4267 * Return pointer to new instance.
4269 struct namedobj_instance *
4270 ipfw_objhash_create(uint32_t items)
4272 struct namedobj_instance *ni;
4276 size = sizeof(struct namedobj_instance) +
4277 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4278 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4280 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4281 ni->nn_size = NAMEDOBJ_HASH_SIZE;
4282 ni->nv_size = NAMEDOBJ_HASH_SIZE;
4284 ni->names = (struct namedobjects_head *)(ni +1);
4285 ni->values = &ni->names[ni->nn_size];
4287 for (i = 0; i < ni->nn_size; i++)
4288 TAILQ_INIT(&ni->names[i]);
4290 for (i = 0; i < ni->nv_size; i++)
4291 TAILQ_INIT(&ni->values[i]);
4293 /* Set default hashing/comparison functions */
4294 ni->hash_f = objhash_hash_name;
4295 ni->cmp_f = objhash_cmp_name;
4297 /* Allocate bitmask separately due to possible resize */
4298 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4304 ipfw_objhash_destroy(struct namedobj_instance *ni)
4307 free(ni->idx_mask, M_IPFW);
4312 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4313 objhash_cmp_f *cmp_f)
4316 ni->hash_f = hash_f;
4321 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4324 return (fnv_32_str((const char *)name, FNV1_32_INIT));
4328 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4331 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4338 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4342 v = val % (ni->nv_size - 1);
4347 struct named_object *
4348 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4350 struct named_object *no;
4353 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4355 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4356 if (ni->cmp_f(no, name, set) == 0)
4364 * Find named object by @uid.
4365 * Check @tlvs for valid data inside.
4367 * Returns pointer to found TLV or NULL.
4370 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4372 ipfw_obj_ntlv *ntlv;
4376 pa = (uintptr_t)tlvs;
4379 for (; pa < pe; pa += l) {
4380 ntlv = (ipfw_obj_ntlv *)pa;
4381 l = ntlv->head.length;
4383 if (l != sizeof(*ntlv))
4386 if (ntlv->idx != uidx)
4389 * When userland has specified zero TLV type, do
4390 * not compare it with eltv. In some cases userland
4391 * doesn't know what type should it have. Use only
4392 * uidx and name for search named_object.
4394 if (ntlv->head.type != 0 &&
4395 ntlv->head.type != (uint16_t)etlv)
4398 if (ipfw_check_object_name_generic(ntlv->name) != 0)
4408 * Finds object config based on either legacy index
4410 * Note @ti structure contains unchecked data from userland.
4412 * Returns 0 in success and fills in @pno with found config
4415 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4416 uint32_t etlv, struct named_object **pno)
4419 ipfw_obj_ntlv *ntlv;
4422 if (ti->tlvs == NULL)
4425 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4431 * Use set provided by @ti instead of @ntlv one.
4432 * This is needed due to different sets behavior
4433 * controlled by V_fw_tables_sets.
4436 *pno = ipfw_objhash_lookup_name(ni, set, name);
4443 * Find named object by name, considering also its TLV type.
4445 struct named_object *
4446 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4447 uint32_t type, const char *name)
4449 struct named_object *no;
4452 hash = ni->hash_f(ni, name, set) % ni->nn_size;
4454 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4455 if (ni->cmp_f(no, name, set) == 0 &&
4456 no->etlv == (uint16_t)type)
4463 struct named_object *
4464 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4466 struct named_object *no;
4469 hash = objhash_hash_idx(ni, kidx);
4471 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4472 if (no->kidx == kidx)
4480 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4481 struct named_object *b)
4484 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4491 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4495 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4496 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4498 hash = objhash_hash_idx(ni, no->kidx);
4499 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4505 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4509 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4510 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4512 hash = objhash_hash_idx(ni, no->kidx);
4513 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4519 ipfw_objhash_count(struct namedobj_instance *ni)
4526 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4528 struct named_object *no;
4533 for (i = 0; i < ni->nn_size; i++) {
4534 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4535 if (no->etlv == type)
4543 * Runs @func for each found named object.
4544 * It is safe to delete objects from callback
4547 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4549 struct named_object *no, *no_tmp;
4552 for (i = 0; i < ni->nn_size; i++) {
4553 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4554 ret = f(ni, no, arg);
4563 * Runs @f for each found named object with type @type.
4564 * It is safe to delete objects from callback
4567 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4568 void *arg, uint16_t type)
4570 struct named_object *no, *no_tmp;
4573 for (i = 0; i < ni->nn_size; i++) {
4574 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4575 if (no->etlv != type)
4577 ret = f(ni, no, arg);
4586 * Removes index from given set.
4587 * Returns 0 on success.
4590 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4595 i = idx / BLOCK_ITEMS;
4596 v = idx % BLOCK_ITEMS;
4598 if (i >= ni->max_blocks)
4601 mask = &ni->idx_mask[i];
4603 if ((*mask & ((u_long)1 << v)) != 0)
4607 *mask |= (u_long)1 << v;
4609 /* Update free offset */
4610 if (ni->free_off[0] > i)
4611 ni->free_off[0] = i;
4617 * Allocate new index in given instance and stores in in @pidx.
4618 * Returns 0 on success.
4621 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4623 struct namedobj_instance *ni;
4627 ni = (struct namedobj_instance *)n;
4629 off = ni->free_off[0];
4630 mask = &ni->idx_mask[off];
4632 for (i = off; i < ni->max_blocks; i++, mask++) {
4633 if ((v = ffsl(*mask)) == 0)
4637 *mask &= ~ ((u_long)1 << (v - 1));
4639 ni->free_off[0] = i;
4641 v = BLOCK_ITEMS * i + v - 1;