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>
61 #include <net/route.h>
64 #include <vm/vm_extern.h>
66 #include <netinet/in.h>
67 #include <netinet/ip_var.h> /* hooks */
68 #include <netinet/ip_fw.h>
70 #include <netpfil/ipfw/ip_fw_private.h>
71 #include <netpfil/ipfw/ip_fw_table.h>
74 #include <security/mac/mac_framework.h>
77 static int ipfw_ctl(struct sockopt *sopt);
78 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
79 struct rule_check_info *ci);
80 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
81 struct rule_check_info *ci);
82 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
83 struct rule_check_info *ci);
85 #define NAMEDOBJ_HASH_SIZE 32
87 struct namedobj_instance {
88 struct namedobjects_head *names;
89 struct namedobjects_head *values;
90 uint32_t nn_size; /* names hash size */
91 uint32_t nv_size; /* number hash size */
92 u_long *idx_mask; /* used items bitmask */
93 uint32_t max_blocks; /* number of "long" blocks in bitmask */
94 uint32_t count; /* number of items */
95 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
96 objhash_hash_f *hash_f;
99 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
101 static uint32_t objhash_hash_name(struct namedobj_instance *ni, void *key,
103 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
104 static int objhash_cmp_name(struct named_object *no, void *name, uint32_t set);
106 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
108 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
109 struct sockopt_data *sd);
110 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
111 struct sockopt_data *sd);
112 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
113 struct sockopt_data *sd);
114 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
115 struct sockopt_data *sd);
116 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
117 struct sockopt_data *sd);
118 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
119 struct sockopt_data *sd);
120 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
121 struct sockopt_data *sd);
123 /* ctl3 handler data */
124 struct mtx ctl3_lock;
125 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
126 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
127 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
128 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
130 static struct ipfw_sopt_handler *ctl3_handlers;
131 static size_t ctl3_hsize;
132 static uint64_t ctl3_refct, ctl3_gencnt;
133 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
134 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
136 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
138 static struct ipfw_sopt_handler scodes[] = {
139 { IP_FW_XGET, 0, HDIR_GET, dump_config },
140 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
141 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
142 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
143 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
144 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
145 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
146 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
147 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
148 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
152 * static variables followed by global ones
157 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
158 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
164 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
165 sizeof(ip_fw_cntr), NULL, NULL, NULL, NULL,
166 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
170 ipfw_destroy_counters()
173 uma_zdestroy(V_ipfw_cntr_zone);
177 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
181 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
182 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
188 free_rule(struct ip_fw *rule)
191 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
201 ipfw_destroy_counters()
206 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
210 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
216 free_rule(struct ip_fw *rule)
226 * Find the smallest rule >= key, id.
227 * We could use bsearch but it is so simple that we code it directly
230 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
235 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
238 if (r->rulenum < key)
239 lo = i + 1; /* continue from the next one */
240 else if (r->rulenum > key)
241 hi = i; /* this might be good */
243 lo = i + 1; /* continue from the next one */
244 else /* r->id >= id */
245 hi = i; /* this might be good */
251 * Builds skipto cache on rule set @map.
254 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
259 IPFW_UH_WLOCK_ASSERT(chain);
262 rulenum = map[mi]->rulenum;
263 smap = chain->idxmap_back;
268 for (i = 0; i < 65536; i++) {
270 /* Use the same rule index until i < rulenum */
271 if (i != rulenum || i == 65535)
273 /* Find next rule with num > i */
274 rulenum = map[++mi]->rulenum;
276 rulenum = map[++mi]->rulenum;
281 * Swaps prepared (backup) index with current one.
284 swap_skipto_cache(struct ip_fw_chain *chain)
288 IPFW_UH_WLOCK_ASSERT(chain);
289 IPFW_WLOCK_ASSERT(chain);
292 chain->idxmap = chain->idxmap_back;
293 chain->idxmap_back = map;
297 * Allocate and initialize skipto cache.
300 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
302 int *idxmap, *idxmap_back;
304 idxmap = malloc(65536 * sizeof(uint32_t *), M_IPFW,
306 idxmap_back = malloc(65536 * sizeof(uint32_t *), M_IPFW,
310 * Note we may be called at any time after initialization,
311 * for example, on first skipto rule, so we need to
312 * provide valid chain->idxmap on return
315 IPFW_UH_WLOCK(chain);
316 if (chain->idxmap != NULL) {
317 IPFW_UH_WUNLOCK(chain);
318 free(idxmap, M_IPFW);
319 free(idxmap_back, M_IPFW);
323 /* Set backup pointer first to permit building cache */
324 chain->idxmap_back = idxmap_back;
325 update_skipto_cache(chain, chain->map);
327 /* It is now safe to set chain->idxmap ptr */
328 chain->idxmap = idxmap;
329 swap_skipto_cache(chain);
331 IPFW_UH_WUNLOCK(chain);
335 * Destroys skipto cache.
338 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
341 if (chain->idxmap != NULL)
342 free(chain->idxmap, M_IPFW);
343 if (chain->idxmap != NULL)
344 free(chain->idxmap_back, M_IPFW);
349 * allocate a new map, returns the chain locked. extra is the number
350 * of entries to add or delete.
352 static struct ip_fw **
353 get_map(struct ip_fw_chain *chain, int extra, int locked)
360 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
362 i = chain->n_rules + extra;
363 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
365 printf("%s: cannot allocate map\n", __FUNCTION__);
369 IPFW_UH_WLOCK(chain);
370 if (i >= chain->n_rules + extra) /* good */
372 /* otherwise we lost the race, free and retry */
374 IPFW_UH_WUNLOCK(chain);
380 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
382 static struct ip_fw **
383 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
385 struct ip_fw **old_map;
389 chain->n_rules = new_len;
390 old_map = chain->map;
391 chain->map = new_map;
392 swap_skipto_cache(chain);
399 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
402 cntr->size = sizeof(*cntr);
404 if (krule->cntr != NULL) {
405 cntr->pcnt = counter_u64_fetch(krule->cntr);
406 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
407 cntr->timestamp = krule->timestamp;
409 if (cntr->timestamp > 0)
410 cntr->timestamp += boottime.tv_sec;
414 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
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 cntr->timestamp += boottime.tv_sec;
427 * Copies rule @urule from v1 userland format (current).
429 * Assume @krule is zeroed.
432 import_rule1(struct rule_check_info *ci)
434 struct ip_fw_rule *urule;
437 urule = (struct ip_fw_rule *)ci->urule;
438 krule = (struct ip_fw *)ci->krule;
441 krule->act_ofs = urule->act_ofs;
442 krule->cmd_len = urule->cmd_len;
443 krule->rulenum = urule->rulenum;
444 krule->set = urule->set;
445 krule->flags = urule->flags;
447 /* Save rulenum offset */
448 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
451 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
455 * Export rule into v1 format (Current).
457 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
459 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
461 * Assume @data is zeroed.
464 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
466 struct ip_fw_bcounter *cntr;
467 struct ip_fw_rule *urule;
470 /* Fill in TLV header */
471 tlv = (ipfw_obj_tlv *)data;
472 tlv->type = IPFW_TLV_RULE_ENT;
477 cntr = (struct ip_fw_bcounter *)(tlv + 1);
478 urule = (struct ip_fw_rule *)(cntr + 1);
479 export_cntr1_base(krule, cntr);
481 urule = (struct ip_fw_rule *)(tlv + 1);
484 urule->act_ofs = krule->act_ofs;
485 urule->cmd_len = krule->cmd_len;
486 urule->rulenum = krule->rulenum;
487 urule->set = krule->set;
488 urule->flags = krule->flags;
489 urule->id = krule->id;
492 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
497 * Copies rule @urule from FreeBSD8 userland format (v0)
499 * Assume @krule is zeroed.
502 import_rule0(struct rule_check_info *ci)
504 struct ip_fw_rule0 *urule;
508 ipfw_insn_limit *lcmd;
511 urule = (struct ip_fw_rule0 *)ci->urule;
512 krule = (struct ip_fw *)ci->krule;
515 krule->act_ofs = urule->act_ofs;
516 krule->cmd_len = urule->cmd_len;
517 krule->rulenum = urule->rulenum;
518 krule->set = urule->set;
519 if ((urule->_pad & 1) != 0)
520 krule->flags |= IPFW_RULE_NOOPT;
522 /* Save rulenum offset */
523 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
526 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
530 * 1) convert tablearg value from 65335 to 0
531 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room for targ).
532 * 3) convert table number in iface opcodes to u16
538 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
541 switch (cmd->opcode) {
542 /* Opcodes supporting tablearg */
554 if (cmd->arg1 == 65535)
555 cmd->arg1 = IP_FW_TARG;
559 if (cmd->arg1 == 65535)
560 cmd->arg1 = IP_FW_TARG;
565 lcmd = (ipfw_insn_limit *)cmd;
566 if (lcmd->conn_limit == 65535)
567 lcmd->conn_limit = IP_FW_TARG;
569 /* Interface tables */
573 /* Interface table, possibly */
574 cmdif = (ipfw_insn_if *)cmd;
575 if (cmdif->name[0] != '\1')
578 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
585 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
588 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
592 ipfw_insn_limit *lcmd;
596 memset(urule, 0, len);
597 urule->act_ofs = krule->act_ofs;
598 urule->cmd_len = krule->cmd_len;
599 urule->rulenum = krule->rulenum;
600 urule->set = krule->set;
601 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
605 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
607 /* Export counters */
608 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
612 * 1) convert tablearg value from 0 to 65335
613 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
614 * 3) convert table number in iface opcodes to int
620 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
623 switch (cmd->opcode) {
624 /* Opcodes supporting tablearg */
636 if (cmd->arg1 == IP_FW_TARG)
641 if (cmd->arg1 == IP_FW_TARG)
644 cmd->arg1 &= ~0x8000;
647 lcmd = (ipfw_insn_limit *)cmd;
648 if (lcmd->conn_limit == IP_FW_TARG)
649 lcmd->conn_limit = 65535;
651 /* Interface tables */
655 /* Interface table, possibly */
656 cmdif = (ipfw_insn_if *)cmd;
657 if (cmdif->name[0] != '\1')
660 cmdif->p.glob = cmdif->p.kidx;
667 * Add new rule(s) to the list possibly creating rule number for each.
668 * Update the rule_number in the input struct so the caller knows it as well.
669 * Must be called without IPFW_UH held
672 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
674 int error, i, insert_before, tcount;
675 uint16_t rulenum, *pnum;
676 struct rule_check_info *ci;
678 struct ip_fw **map; /* the new array of pointers */
680 /* Check if we need to do table remap */
682 for (ci = rci, i = 0; i < count; ci++, i++) {
683 if (ci->table_opcodes == 0)
687 * Rule has some table opcodes.
688 * Reference & allocate needed tables/
690 error = ipfw_rewrite_table_uidx(chain, ci);
694 * rewrite failed, state for current rule
695 * has been reverted. Check if we need to
701 * We have some more table rules
702 * we need to rollback.
705 IPFW_UH_WLOCK(chain);
708 if (ci->table_opcodes == 0)
710 ipfw_unref_rule_tables(chain,ci->krule);
713 IPFW_UH_WUNLOCK(chain);
723 /* get_map returns with IPFW_UH_WLOCK if successful */
724 map = get_map(chain, count, 0 /* not locked */);
728 IPFW_UH_WLOCK(chain);
729 for (ci = rci, i = 0; i < count; ci++, i++) {
730 if (ci->table_opcodes == 0)
733 ipfw_unref_rule_tables(chain, ci->krule);
735 IPFW_UH_WUNLOCK(chain);
741 if (V_autoinc_step < 1)
743 else if (V_autoinc_step > 1000)
744 V_autoinc_step = 1000;
746 /* FIXME: Handle count > 1 */
749 rulenum = krule->rulenum;
751 /* find the insertion point, we will insert before */
752 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
753 i = ipfw_find_rule(chain, insert_before, 0);
754 /* duplicate first part */
756 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
758 /* duplicate remaining part, we always have the default rule */
759 bcopy(chain->map + i, map + i + 1,
760 sizeof(struct ip_fw *) *(chain->n_rules - i));
762 /* Compute rule number and write it back */
763 rulenum = i > 0 ? map[i-1]->rulenum : 0;
764 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
765 rulenum += V_autoinc_step;
766 krule->rulenum = rulenum;
767 /* Save number to userland rule */
768 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
772 krule->id = chain->id + 1;
773 update_skipto_cache(chain, map);
774 map = swap_map(chain, map, chain->n_rules + 1);
775 chain->static_len += RULEUSIZE0(krule);
776 IPFW_UH_WUNLOCK(chain);
783 * Adds @rule to the list of rules to reap
786 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
790 IPFW_UH_WLOCK_ASSERT(chain);
792 /* Unlink rule from everywhere */
793 ipfw_unref_rule_tables(chain, rule);
795 *((struct ip_fw **)rule) = *head;
800 * Reclaim storage associated with a list of rules. This is
801 * typically the list created using remove_rule.
802 * A NULL pointer on input is handled correctly.
805 ipfw_reap_rules(struct ip_fw *head)
809 while ((rule = head) != NULL) {
810 head = *((struct ip_fw **)head);
817 * (default || reserved || !match_set || !match_number)
819 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
820 * // the default rule is always protected
822 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
823 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
825 * match_set ::= (cmd == 0 || rule->set == set)
826 * // set number is ignored for cmd == 0
828 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
829 * // number is ignored for cmd == 1 or n == 0
833 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
836 /* Don't match default rule regardless of query */
837 if (rule->rulenum == IPFW_DEFAULT_RULE)
840 /* Don't match rules in reserved set for flush requests */
841 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
844 /* If we're filtering by set, don't match other sets */
845 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
848 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
849 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
856 * Delete rules matching range @rt.
857 * Saves number of deleted rules in @ndel.
859 * Returns 0 on success.
862 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
864 struct ip_fw *reap, *rule, **map;
869 IPFW_UH_WLOCK(chain); /* arbitrate writers */
872 * Stage 1: Determine range to inspect.
873 * Range is half-inclusive, e.g [start, end).
876 end = chain->n_rules - 1;
878 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
879 start = ipfw_find_rule(chain, rt->start_rule, 0);
881 end = ipfw_find_rule(chain, rt->end_rule, 0);
882 if (rt->end_rule != IPFW_DEFAULT_RULE)
883 while (chain->map[end]->rulenum == rt->end_rule)
887 /* Allocate new map of the same size */
888 map = get_map(chain, 0, 1 /* locked */);
890 IPFW_UH_WUNLOCK(chain);
897 /* 1. bcopy the initial part of the map */
899 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
900 /* 2. copy active rules between start and end */
901 for (i = start; i < end; i++) {
902 rule = chain->map[i];
903 if (ipfw_match_range(rule, rt) == 0) {
909 if (ipfw_is_dyn_rule(rule) != 0)
912 /* 3. copy the final part of the map */
913 bcopy(chain->map + end, map + ofs,
914 (chain->n_rules - end) * sizeof(struct ip_fw *));
915 /* 4. recalculate skipto cache */
916 update_skipto_cache(chain, map);
917 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
918 map = swap_map(chain, map, chain->n_rules - n);
919 /* 6. Remove all dynamic states originated by deleted rules */
921 ipfw_expire_dyn_rules(chain, rt);
922 /* 7. now remove the rules deleted from the old map */
923 for (i = start; i < end; i++) {
925 if (ipfw_match_range(rule, rt) == 0)
927 chain->static_len -= RULEUSIZE0(rule);
928 ipfw_reap_add(chain, &reap, rule);
930 IPFW_UH_WUNLOCK(chain);
932 ipfw_reap_rules(reap);
940 * Changes set of given rule rannge @rt
943 * Returns 0 on success.
946 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
951 IPFW_UH_WLOCK(chain);
954 * Move rules with matching paramenerts to a new set.
955 * This one is much more complex. We have to ensure
956 * that all referenced tables (if any) are referenced
957 * by given rule subset only. Otherwise, we can't move
958 * them to new set and have to return error.
960 if (V_fw_tables_sets != 0) {
961 if (ipfw_move_tables_sets(chain, rt, rt->new_set) != 0) {
962 IPFW_UH_WUNLOCK(chain);
967 /* XXX: We have to do swap holding WLOCK */
968 for (i = 0; i < chain->n_rules - 1; i++) {
969 rule = chain->map[i];
970 if (ipfw_match_range(rule, rt) == 0)
972 rule->set = rt->new_set;
975 IPFW_UH_WUNLOCK(chain);
981 * Clear counters for a specific rule.
982 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
983 * so we only care that rules do not disappear.
986 clear_counters(struct ip_fw *rule, int log_only)
988 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
991 IPFW_ZERO_RULE_COUNTER(rule);
992 if (l->o.opcode == O_LOG)
993 l->log_left = l->max_log;
997 * Flushes rules counters and/or log values on matching range.
999 * Returns number of items cleared.
1002 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1010 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1011 for (i = 0; i < chain->n_rules - 1; i++) {
1012 rule = chain->map[i];
1013 if (ipfw_match_range(rule, rt) == 0)
1015 clear_counters(rule, log_only);
1018 IPFW_UH_WUNLOCK(chain);
1024 check_range_tlv(ipfw_range_tlv *rt)
1027 if (rt->head.length != sizeof(*rt))
1029 if (rt->start_rule > rt->end_rule)
1031 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1038 * Delete rules matching specified parameters
1039 * Data layout (v0)(current):
1040 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1041 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1043 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1045 * Returns 0 on success.
1048 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1049 struct sockopt_data *sd)
1051 ipfw_range_header *rh;
1054 if (sd->valsize != sizeof(*rh))
1057 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1059 if (check_range_tlv(&rh->range) != 0)
1063 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1066 /* Save number of rules deleted */
1067 rh->range.new_set = ndel;
1072 * Move rules/sets matching specified parameters
1073 * Data layout (v0)(current):
1074 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1076 * Returns 0 on success.
1079 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1080 struct sockopt_data *sd)
1082 ipfw_range_header *rh;
1084 if (sd->valsize != sizeof(*rh))
1087 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1089 if (check_range_tlv(&rh->range) != 0)
1092 return (move_range(chain, &rh->range));
1096 * Clear rule accounting data matching specified parameters
1097 * Data layout (v0)(current):
1098 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1099 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1101 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1103 * Returns 0 on success.
1106 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1107 struct sockopt_data *sd)
1109 ipfw_range_header *rh;
1113 if (sd->valsize != sizeof(*rh))
1116 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1118 if (check_range_tlv(&rh->range) != 0)
1121 log_only = (op3->opcode == IP_FW_XRESETLOG);
1123 num = clear_range(chain, &rh->range, log_only);
1125 if (rh->range.flags & IPFW_RCFLAG_ALL)
1126 msg = log_only ? "All logging counts reset" :
1127 "Accounting cleared";
1129 msg = log_only ? "logging count reset" : "cleared";
1132 int lev = LOG_SECURITY | LOG_NOTICE;
1133 log(lev, "ipfw: %s.\n", msg);
1136 /* Save number of rules cleared */
1137 rh->range.new_set = num;
1142 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1146 IPFW_UH_WLOCK_ASSERT(chain);
1148 /* Change enabled/disabled sets mask */
1149 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1150 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1152 V_set_disable = v_set;
1153 IPFW_WUNLOCK(chain);
1157 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1162 IPFW_UH_WLOCK_ASSERT(chain);
1164 /* Swap or move two sets */
1165 for (i = 0; i < chain->n_rules - 1; i++) {
1166 rule = chain->map[i];
1167 if (rule->set == rt->set)
1168 rule->set = rt->new_set;
1169 else if (rule->set == rt->new_set && mv == 0)
1170 rule->set = rt->set;
1172 if (V_fw_tables_sets != 0)
1173 ipfw_swap_tables_sets(chain, rt->set, rt->new_set, mv);
1177 * Swaps or moves set
1178 * Data layout (v0)(current):
1179 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1181 * Returns 0 on success.
1184 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1185 struct sockopt_data *sd)
1187 ipfw_range_header *rh;
1189 if (sd->valsize != sizeof(*rh))
1192 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1194 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1197 IPFW_UH_WLOCK(chain);
1198 switch (op3->opcode) {
1199 case IP_FW_SET_SWAP:
1200 case IP_FW_SET_MOVE:
1201 swap_sets(chain, &rh->range, op3->opcode == IP_FW_SET_MOVE);
1203 case IP_FW_SET_ENABLE:
1204 enable_sets(chain, &rh->range);
1207 IPFW_UH_WUNLOCK(chain);
1213 * Remove all rules with given number, or do set manipulation.
1214 * Assumes chain != NULL && *chain != NULL.
1216 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1217 * the next 8 bits are the new set; the top 8 bits indicate the command:
1219 * 0 delete rules numbered "rulenum"
1220 * 1 delete rules in set "rulenum"
1221 * 2 move rules "rulenum" to set "new_set"
1222 * 3 move rules from set "rulenum" to set "new_set"
1223 * 4 swap sets "rulenum" and "new_set"
1224 * 5 delete rules "rulenum" and set "new_set"
1227 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1229 uint32_t num; /* rule number or old_set */
1230 uint8_t cmd, new_set;
1236 cmd = (arg >> 24) & 0xff;
1237 new_set = (arg >> 16) & 0xff;
1239 if (cmd > 5 || new_set > RESVD_SET)
1241 if (cmd == 0 || cmd == 2 || cmd == 5) {
1242 if (num >= IPFW_DEFAULT_RULE)
1245 if (num > RESVD_SET) /* old_set */
1249 /* Convert old requests into new representation */
1250 memset(&rt, 0, sizeof(rt));
1251 rt.start_rule = num;
1254 rt.new_set = new_set;
1258 case 0: /* delete rules numbered "rulenum" */
1260 rt.flags |= IPFW_RCFLAG_ALL;
1262 rt.flags |= IPFW_RCFLAG_RANGE;
1265 case 1: /* delete rules in set "rulenum" */
1266 rt.flags |= IPFW_RCFLAG_SET;
1269 case 5: /* delete rules "rulenum" and set "new_set" */
1270 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1275 case 2: /* move rules "rulenum" to set "new_set" */
1276 rt.flags |= IPFW_RCFLAG_RANGE;
1278 case 3: /* move rules from set "rulenum" to set "new_set" */
1279 IPFW_UH_WLOCK(chain);
1280 swap_sets(chain, &rt, 1);
1281 IPFW_UH_WUNLOCK(chain);
1283 case 4: /* swap sets "rulenum" and "new_set" */
1284 IPFW_UH_WLOCK(chain);
1285 swap_sets(chain, &rt, 0);
1286 IPFW_UH_WUNLOCK(chain);
1293 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1296 if (ndel == 0 && (cmd != 1 && num != 0))
1302 return (move_range(chain, &rt));
1306 * Reset some or all counters on firewall rules.
1307 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1308 * the next 8 bits are the set number, the top 8 bits are the command:
1309 * 0 work with rules from all set's;
1310 * 1 work with rules only from specified set.
1311 * Specified rule number is zero if we want to clear all entries.
1312 * log_only is 1 if we only want to reset logs, zero otherwise.
1315 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1321 uint16_t rulenum = arg & 0xffff;
1322 uint8_t set = (arg >> 16) & 0xff;
1323 uint8_t cmd = (arg >> 24) & 0xff;
1327 if (cmd == 1 && set > RESVD_SET)
1330 IPFW_UH_RLOCK(chain);
1332 V_norule_counter = 0;
1333 for (i = 0; i < chain->n_rules; i++) {
1334 rule = chain->map[i];
1335 /* Skip rules not in our set. */
1336 if (cmd == 1 && rule->set != set)
1338 clear_counters(rule, log_only);
1340 msg = log_only ? "All logging counts reset" :
1341 "Accounting cleared";
1344 for (i = 0; i < chain->n_rules; i++) {
1345 rule = chain->map[i];
1346 if (rule->rulenum == rulenum) {
1347 if (cmd == 0 || rule->set == set)
1348 clear_counters(rule, log_only);
1351 if (rule->rulenum > rulenum)
1354 if (!cleared) { /* we did not find any matching rules */
1355 IPFW_UH_RUNLOCK(chain);
1358 msg = log_only ? "logging count reset" : "cleared";
1360 IPFW_UH_RUNLOCK(chain);
1363 int lev = LOG_SECURITY | LOG_NOTICE;
1366 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1368 log(lev, "ipfw: %s.\n", msg);
1375 * Check rule head in FreeBSD11 format
1379 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1380 struct rule_check_info *ci)
1384 if (size < sizeof(*rule)) {
1385 printf("ipfw: rule too short\n");
1389 /* Check for valid cmd_len */
1390 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1392 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1395 if (rule->act_ofs >= rule->cmd_len) {
1396 printf("ipfw: bogus action offset (%u > %u)\n",
1397 rule->act_ofs, rule->cmd_len - 1);
1401 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1404 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1408 * Check rule head in FreeBSD8 format
1412 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1413 struct rule_check_info *ci)
1417 if (size < sizeof(*rule)) {
1418 printf("ipfw: rule too short\n");
1422 /* Check for valid cmd_len */
1423 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1425 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1428 if (rule->act_ofs >= rule->cmd_len) {
1429 printf("ipfw: bogus action offset (%u > %u)\n",
1430 rule->act_ofs, rule->cmd_len - 1);
1434 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1437 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1441 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1449 * Now go for the individual checks. Very simple ones, basically only
1450 * instruction sizes.
1452 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1453 cmdlen = F_LEN(cmd);
1455 printf("ipfw: opcode %d size truncated\n",
1459 switch (cmd->opcode) {
1471 case O_IPPRECEDENCE:
1489 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1494 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1496 if (cmd->arg1 >= rt_numfibs) {
1497 printf("ipfw: invalid fib number %d\n",
1504 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1506 if ((cmd->arg1 != IP_FW_TARG) &&
1507 ((cmd->arg1 & 0x7FFFF) >= rt_numfibs)) {
1508 printf("ipfw: invalid fib number %d\n",
1509 cmd->arg1 & 0x7FFFF);
1523 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1528 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1533 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1536 ((ipfw_insn_log *)cmd)->log_left =
1537 ((ipfw_insn_log *)cmd)->max_log;
1543 /* only odd command lengths */
1544 if ( !(cmdlen & 1) || cmdlen > 31)
1550 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1551 printf("ipfw: invalid set size %d\n",
1555 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1560 case O_IP_SRC_LOOKUP:
1561 case O_IP_DST_LOOKUP:
1562 if (cmd->arg1 >= V_fw_tables_max) {
1563 printf("ipfw: invalid table number %d\n",
1567 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1568 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1569 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1571 ci->table_opcodes++;
1573 case O_IP_FLOW_LOOKUP:
1574 if (cmd->arg1 >= V_fw_tables_max) {
1575 printf("ipfw: invalid table number %d\n",
1579 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1580 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1582 ci->table_opcodes++;
1585 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1596 if (cmdlen < 1 || cmdlen > 31)
1601 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1607 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1608 if (cmdlen < 2 || cmdlen > 31)
1615 if (((ipfw_insn_if *)cmd)->name[0] == '\1')
1616 ci->table_opcodes++;
1617 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1622 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1628 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1633 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1638 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1645 if (ip_divert_ptr == NULL)
1651 if (ng_ipfw_input_p == NULL)
1656 if (!IPFW_NAT_LOADED)
1658 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1661 case O_FORWARD_MAC: /* XXX not implemented yet */
1675 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1679 printf("ipfw: opcode %d, multiple actions"
1686 printf("ipfw: opcode %d, action must be"
1695 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1696 F_INSN_SIZE(ipfw_insn))
1701 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1702 ((ipfw_insn_u32 *)cmd)->o.arg1)
1706 case O_IP6_SRC_MASK:
1707 case O_IP6_DST_MASK:
1708 if ( !(cmdlen & 1) || cmdlen > 127)
1712 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
1718 switch (cmd->opcode) {
1728 case O_IP6_SRC_MASK:
1729 case O_IP6_DST_MASK:
1731 printf("ipfw: no IPv6 support in kernel\n");
1732 return (EPROTONOSUPPORT);
1735 printf("ipfw: opcode %d, unknown opcode\n",
1741 if (have_action == 0) {
1742 printf("ipfw: missing action\n");
1748 printf("ipfw: opcode %d size %d wrong\n",
1749 cmd->opcode, cmdlen);
1755 * Translation of requests for compatibility with FreeBSD 7.2/8.
1756 * a static variable tells us if we have an old client from userland,
1757 * and if necessary we translate requests and responses between the
1763 struct ip_fw7 *next; /* linked list of rules */
1764 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
1765 /* 'next_rule' is used to pass up 'set_disable' status */
1767 uint16_t act_ofs; /* offset of action in 32-bit units */
1768 uint16_t cmd_len; /* # of 32-bit words in cmd */
1769 uint16_t rulenum; /* rule number */
1770 uint8_t set; /* rule set (0..31) */
1771 // #define RESVD_SET 31 /* set for default and persistent rules */
1772 uint8_t _pad; /* padding */
1773 // uint32_t id; /* rule id, only in v.8 */
1774 /* These fields are present in all rules. */
1775 uint64_t pcnt; /* Packet counter */
1776 uint64_t bcnt; /* Byte counter */
1777 uint32_t timestamp; /* tv_sec of last match */
1779 ipfw_insn cmd[1]; /* storage for commands */
1782 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
1783 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
1786 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
1787 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
1792 * Copy the static and dynamic rules to the supplied buffer
1793 * and return the amount of space actually used.
1794 * Must be run under IPFW_UH_RLOCK
1797 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
1800 char *ep = bp + space;
1802 struct ip_fw_rule0 *dst;
1803 int error, i, l, warnflag;
1804 time_t boot_seconds;
1808 boot_seconds = boottime.tv_sec;
1809 for (i = 0; i < chain->n_rules; i++) {
1810 rule = chain->map[i];
1813 /* Convert rule to FreeBSd 7.2 format */
1814 l = RULESIZE7(rule);
1815 if (bp + l + sizeof(uint32_t) <= ep) {
1816 bcopy(rule, bp, l + sizeof(uint32_t));
1817 error = ipfw_rewrite_table_kidx(chain,
1818 (struct ip_fw_rule0 *)bp);
1821 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
1823 return 0; /*XXX correct? */
1825 * XXX HACK. Store the disable mask in the "next"
1826 * pointer in a wild attempt to keep the ABI the same.
1827 * Why do we do this on EVERY rule?
1829 bcopy(&V_set_disable,
1830 &(((struct ip_fw7 *)bp)->next_rule),
1831 sizeof(V_set_disable));
1832 if (((struct ip_fw7 *)bp)->timestamp)
1833 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
1836 continue; /* go to next rule */
1839 l = RULEUSIZE0(rule);
1840 if (bp + l > ep) { /* should not happen */
1841 printf("overflow dumping static rules\n");
1844 dst = (struct ip_fw_rule0 *)bp;
1845 export_rule0(rule, dst, l);
1846 error = ipfw_rewrite_table_kidx(chain, dst);
1849 * XXX HACK. Store the disable mask in the "next"
1850 * pointer in a wild attempt to keep the ABI the same.
1851 * Why do we do this on EVERY rule?
1853 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
1854 * so we need to fail _after_ saving at least one mask.
1856 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
1858 dst->timestamp += boot_seconds;
1863 /* Non-fatal table rewrite error. */
1867 printf("Stop on rule %d. Fail to convert table\n",
1873 printf("ipfw: process %s is using legacy interfaces,"
1874 " consider rebuilding\n", "");
1875 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
1876 return (bp - (char *)buf);
1881 uint32_t b; /* start rule */
1882 uint32_t e; /* end rule */
1883 uint32_t rcount; /* number of rules */
1884 uint32_t rsize; /* rules size */
1885 uint32_t tcount; /* number of tables */
1886 int rcounters; /* counters */
1890 * Dumps static rules with table TLVs in buffer @sd.
1892 * Returns 0 on success.
1895 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
1896 uint32_t *bmask, struct sockopt_data *sd)
1901 ipfw_obj_ctlv *ctlv;
1902 struct ip_fw *krule;
1905 /* Dump table names first (if any) */
1906 if (da->tcount > 0) {
1908 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1911 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
1912 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
1914 ctlv->count = da->tcount;
1915 ctlv->objsize = sizeof(ipfw_obj_ntlv);
1919 tcount = da->tcount;
1920 while (tcount > 0) {
1921 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
1926 if ((error = ipfw_export_table_ntlv(chain, i, sd)) != 0)
1934 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1937 ctlv->head.type = IPFW_TLV_RULE_LIST;
1938 ctlv->head.length = da->rsize + sizeof(*ctlv);
1939 ctlv->count = da->rcount;
1941 for (i = da->b; i < da->e; i++) {
1942 krule = chain->map[i];
1944 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
1945 if (da->rcounters != 0)
1946 l += sizeof(struct ip_fw_bcounter);
1947 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
1951 export_rule1(krule, dst, l, da->rcounters);
1958 * Dumps requested objects data
1959 * Data layout (version 0)(current):
1960 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
1961 * size = ipfw_cfg_lheader.size
1962 * Reply: [ ipfw_cfg_lheader
1963 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
1964 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
1965 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
1967 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
1969 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
1970 * The rest (size, count) are set to zero and needs to be ignored.
1972 * Returns 0 on success.
1975 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1976 struct sockopt_data *sd)
1978 ipfw_cfg_lheader *hdr;
1983 struct dump_args da;
1986 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
1992 /* Allocate needed state */
1993 if (hdr->flags & IPFW_CFG_GET_STATIC)
1994 bmask = malloc(IPFW_TABLES_MAX / 8, M_TEMP, M_WAITOK | M_ZERO);
1996 IPFW_UH_RLOCK(chain);
1999 * STAGE 1: Determine size/count for objects in range.
2000 * Prepare used tables bitmask.
2002 sz = sizeof(ipfw_cfg_lheader);
2003 memset(&da, 0, sizeof(da));
2006 da.e = chain->n_rules;
2008 if (hdr->end_rule != 0) {
2009 /* Handle custom range */
2010 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2011 rnum = IPFW_DEFAULT_RULE;
2012 da.b = ipfw_find_rule(chain, rnum, 0);
2013 rnum = hdr->end_rule;
2014 rnum = (rnum < IPFW_DEFAULT_RULE) ? rnum+1 : IPFW_DEFAULT_RULE;
2015 da.e = ipfw_find_rule(chain, rnum, 0);
2018 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2019 for (i = da.b; i < da.e; i++) {
2020 rule = chain->map[i];
2021 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2023 da.tcount += ipfw_mark_table_kidx(chain, rule, bmask);
2025 /* Add counters if requested */
2026 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2027 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2032 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2033 sizeof(ipfw_obj_ctlv);
2034 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2037 if (hdr->flags & IPFW_CFG_GET_STATES)
2038 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2039 sizeof(ipfw_obj_ctlv);
2043 * Fill header anyway.
2044 * Note we have to save header fields to stable storage
2045 * buffer inside @sd can be flushed after dumping rules
2048 hdr->set_mask = ~V_set_disable;
2049 hdr_flags = hdr->flags;
2052 if (sd->valsize < sz) {
2057 /* STAGE2: Store actual data */
2058 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2059 error = dump_static_rules(chain, &da, bmask, sd);
2064 if (hdr_flags & IPFW_CFG_GET_STATES)
2065 error = ipfw_dump_states(chain, sd);
2068 IPFW_UH_RUNLOCK(chain);
2071 free(bmask, M_TEMP);
2077 check_object_name(ipfw_obj_ntlv *ntlv)
2081 switch (ntlv->head.type) {
2082 case IPFW_TLV_TBL_NAME:
2083 error = ipfw_check_table_name(ntlv->name);
2093 * Adds one or more rules to ipfw @chain.
2094 * Data layout (version 0)(current):
2098 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2099 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2104 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2105 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2108 * Rules in reply are modified to store their actual ruleset number.
2110 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2111 * accoring to their idx field and there has to be no duplicates.
2112 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2113 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2115 * Returns 0 on success.
2118 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2119 struct sockopt_data *sd)
2121 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2122 ipfw_obj_ntlv *ntlv;
2123 int clen, error, idx;
2124 uint32_t count, read;
2125 struct ip_fw_rule *r;
2126 struct rule_check_info rci, *ci, *cbuf;
2129 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2130 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2132 read = sizeof(ip_fw3_opheader);
2136 memset(&rci, 0, sizeof(struct rule_check_info));
2138 if (read + sizeof(*ctlv) > sd->valsize)
2141 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2142 clen = ctlv->head.length;
2143 /* Check size and alignment */
2144 if (clen > sd->valsize || clen < sizeof(*ctlv))
2146 if ((clen % sizeof(uint64_t)) != 0)
2150 * Some table names or other named objects.
2151 * Check for validness.
2153 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2154 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2159 * Ensure TLVs are sorted ascending and
2160 * there are no duplicates.
2163 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2165 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2168 error = check_object_name(ntlv);
2172 if (ntlv->idx <= idx)
2181 read += ctlv->head.length;
2182 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2185 if (read + sizeof(*ctlv) > sd->valsize)
2188 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2189 clen = ctlv->head.length;
2190 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2192 if ((clen % sizeof(uint64_t)) != 0)
2196 * TODO: Permit adding multiple rules at once
2198 if (ctlv->count != 1)
2201 clen -= sizeof(*ctlv);
2203 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2206 /* Allocate state for each rule or use stack */
2207 if (ctlv->count == 1) {
2208 memset(&rci, 0, sizeof(struct rule_check_info));
2211 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2216 * Check each rule for validness.
2217 * Ensure numbered rules are sorted ascending
2218 * and properly aligned
2221 r = (struct ip_fw_rule *)(ctlv + 1);
2225 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2226 if (rsize > clen || ctlv->count <= count) {
2232 error = check_ipfw_rule1(r, rsize, ci);
2237 if (r->rulenum != 0 && r->rulenum < idx) {
2238 printf("rulenum %d idx %d\n", r->rulenum, idx);
2244 ci->urule = (caddr_t)r;
2246 rsize = roundup2(rsize, sizeof(uint64_t));
2248 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2253 if (ctlv->count != count || error != 0) {
2260 read += ctlv->head.length;
2261 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2264 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
2265 if (cbuf != NULL && cbuf != &rci)
2271 * Passed rules seems to be valid.
2272 * Allocate storage and try to add them to chain.
2274 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
2275 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
2276 ci->krule = ipfw_alloc_rule(chain, clen);
2280 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
2281 /* Free allocate krules */
2282 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
2283 free(ci->krule, M_IPFW);
2286 if (cbuf != NULL && cbuf != &rci)
2293 * Lists all sopts currently registered.
2294 * Data layout (v0)(current):
2295 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
2296 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
2298 * Returns 0 on success
2301 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2302 struct sockopt_data *sd)
2304 struct _ipfw_obj_lheader *olh;
2306 struct ipfw_sopt_handler *sh;
2307 uint32_t count, n, size;
2309 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
2312 if (sd->valsize < olh->size)
2317 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
2319 /* Fill in header regadless of buffer size */
2321 olh->objsize = sizeof(ipfw_sopt_info);
2323 if (size > olh->size) {
2330 for (n = 1; n <= count; n++) {
2331 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
2332 KASSERT(i != 0, ("previously checked buffer is not enough"));
2333 sh = &ctl3_handlers[n];
2334 i->opcode = sh->opcode;
2335 i->version = sh->version;
2336 i->refcnt = sh->refcnt;
2344 * Compares two sopt handlers (code, version and handler ptr).
2345 * Used both as qsort() and bsearch().
2346 * Does not compare handler for latter case.
2348 * Returns 0 if match is found.
2351 compare_sh(const void *_a, const void *_b)
2353 const struct ipfw_sopt_handler *a, *b;
2355 a = (const struct ipfw_sopt_handler *)_a;
2356 b = (const struct ipfw_sopt_handler *)_b;
2358 if (a->opcode < b->opcode)
2360 else if (a->opcode > b->opcode)
2363 if (a->version < b->version)
2365 else if (a->version > b->version)
2368 /* bsearch helper */
2369 if (a->handler == NULL)
2372 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
2374 else if ((uintptr_t)b->handler > (uintptr_t)b->handler)
2381 * Finds sopt handler based on @code and @version.
2383 * Returns pointer to handler or NULL.
2385 static struct ipfw_sopt_handler *
2386 find_sh(uint16_t code, uint8_t version, void *handler)
2388 struct ipfw_sopt_handler *sh, h;
2390 memset(&h, 0, sizeof(h));
2392 h.version = version;
2393 h.handler = handler;
2395 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
2396 ctl3_hsize, sizeof(h), compare_sh);
2402 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
2404 struct ipfw_sopt_handler *sh;
2407 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
2409 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
2415 /* Copy handler data to requested buffer */
2423 find_unref_sh(struct ipfw_sopt_handler *psh)
2425 struct ipfw_sopt_handler *sh;
2428 sh = find_sh(psh->opcode, psh->version, NULL);
2429 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
2436 ipfw_init_sopt_handler()
2440 IPFW_ADD_SOPT_HANDLER(1, scodes);
2444 ipfw_destroy_sopt_handler()
2447 IPFW_DEL_SOPT_HANDLER(1, scodes);
2448 CTL3_LOCK_DESTROY();
2452 * Adds one or more sockopt handlers to the global array.
2453 * Function may sleep.
2456 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
2459 struct ipfw_sopt_handler *tmp;
2464 sz = ctl3_hsize + count;
2466 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
2468 if (ctl3_hsize + count <= sz)
2475 /* Merge old & new arrays */
2476 sz = ctl3_hsize + count;
2477 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
2478 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
2479 qsort(tmp, sz, sizeof(*sh), compare_sh);
2480 /* Switch new and free old */
2481 if (ctl3_handlers != NULL)
2482 free(ctl3_handlers, M_IPFW);
2483 ctl3_handlers = tmp;
2491 * Removes one or more sockopt handlers from the global array.
2494 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
2497 struct ipfw_sopt_handler *tmp, *h;
2502 for (i = 0; i < count; i++) {
2504 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
2508 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
2509 memmove(h, h + 1, sz);
2513 if (ctl3_hsize == 0) {
2514 if (ctl3_handlers != NULL)
2515 free(ctl3_handlers, M_IPFW);
2516 ctl3_handlers = NULL;
2527 * Writes data accumulated in @sd to sockopt buffer.
2528 * Zeroes internal @sd buffer.
2531 ipfw_flush_sopt_data(struct sockopt_data *sd)
2533 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
2537 if ((sz = sd->koff) == 0)
2540 if (sd->sopt->sopt_dir == SOPT_GET) {
2541 error = sooptcopyout(sd->sopt, sd->kbuf, sz);
2546 memset(sd->kbuf, 0, sd->ksize);
2547 sd->ktotal += sd->koff;
2549 if (sd->ktotal + sd->ksize < sd->valsize)
2550 sd->kavail = sd->ksize;
2552 sd->kavail = sd->valsize - sd->ktotal;
2554 /* Update sopt buffer */
2555 sd->sopt->sopt_valsize = sd->ktotal;
2556 sd->sopt->sopt_val = sd->sopt_val + sd->ktotal;
2562 * Ensures that @sd buffer has contigious @neeeded number of
2565 * Returns pointer to requested space or NULL.
2568 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
2573 if (sd->kavail < needed) {
2575 * Flush data and try another time.
2577 error = ipfw_flush_sopt_data(sd);
2579 if (sd->kavail < needed || error != 0)
2583 addr = sd->kbuf + sd->koff;
2585 sd->kavail -= needed;
2590 * Requests @needed contigious bytes from @sd buffer.
2591 * Function is used to notify subsystem that we are
2592 * interesed in first @needed bytes (request header)
2593 * and the rest buffer can be safely zeroed.
2595 * Returns pointer to requested space or NULL.
2598 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
2602 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
2606 memset(sd->kbuf + sd->koff, 0, sd->kavail);
2612 * New sockopt handler.
2615 ipfw_ctl3(struct sockopt *sopt)
2618 size_t size, valsize;
2619 struct ip_fw_chain *chain;
2621 struct sockopt_data sdata;
2622 struct ipfw_sopt_handler h;
2623 ip_fw3_opheader *op3 = NULL;
2625 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
2629 if (sopt->sopt_name != IP_FW3)
2630 return (ipfw_ctl(sopt));
2632 chain = &V_layer3_chain;
2635 /* Save original valsize before it is altered via sooptcopyin() */
2636 valsize = sopt->sopt_valsize;
2637 memset(&sdata, 0, sizeof(sdata));
2638 /* Read op3 header first to determine actual operation */
2639 op3 = (ip_fw3_opheader *)xbuf;
2640 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
2643 sopt->sopt_valsize = valsize;
2646 * Find and reference command.
2648 error = find_ref_sh(op3->opcode, op3->version, &h);
2653 * Disallow modifications in really-really secure mode, but still allow
2654 * the logging counters to be reset.
2656 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
2657 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2665 * Fill in sockopt_data structure that may be useful for
2666 * IP_FW3 get requests.
2669 if (valsize <= sizeof(xbuf)) {
2670 /* use on-stack buffer */
2672 sdata.ksize = sizeof(xbuf);
2673 sdata.kavail = valsize;
2677 * Determine opcode type/buffer size:
2678 * allocate sliding-window buf for data export or
2679 * contigious buffer for special ops.
2681 if ((h.dir & HDIR_SET) != 0) {
2682 /* Set request. Allocate contigous buffer. */
2683 if (valsize > CTL3_LARGEBUF) {
2690 /* Get request. Allocate sliding window buffer */
2691 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
2693 if (size < valsize) {
2694 /* We have to wire user buffer */
2695 error = vslock(sopt->sopt_val, valsize);
2702 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
2704 sdata.kavail = size;
2708 sdata.sopt_val = sopt->sopt_val;
2709 sdata.valsize = valsize;
2712 * Copy either all request (if valsize < bsize_max)
2713 * or first bsize_max bytes to guarantee most consumers
2714 * that all necessary data has been copied).
2715 * Anyway, copy not less than sizeof(ip_fw3_opheader).
2717 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
2718 sizeof(ip_fw3_opheader))) != 0)
2720 op3 = (ip_fw3_opheader *)sdata.kbuf;
2722 /* Finally, run handler */
2723 error = h.handler(chain, op3, &sdata);
2726 /* Flush state and free buffers */
2728 error = ipfw_flush_sopt_data(&sdata);
2730 ipfw_flush_sopt_data(&sdata);
2733 vsunlock(sdata.sopt_val, valsize);
2735 /* Restore original pointer and set number of bytes written */
2736 sopt->sopt_val = sdata.sopt_val;
2737 sopt->sopt_valsize = sdata.ktotal;
2738 if (sdata.kbuf != xbuf)
2739 free(sdata.kbuf, M_TEMP);
2745 * {set|get}sockopt parser.
2748 ipfw_ctl(struct sockopt *sopt)
2750 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
2752 size_t size, valsize;
2754 struct ip_fw_rule0 *rule;
2755 struct ip_fw_chain *chain;
2756 u_int32_t rulenum[2];
2758 struct rule_check_info ci;
2761 chain = &V_layer3_chain;
2764 /* Save original valsize before it is altered via sooptcopyin() */
2765 valsize = sopt->sopt_valsize;
2766 opt = sopt->sopt_name;
2769 * Disallow modifications in really-really secure mode, but still allow
2770 * the logging counters to be reset.
2772 if (opt == IP_FW_ADD ||
2773 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
2774 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2782 * pass up a copy of the current rules. Static rules
2783 * come first (the last of which has number IPFW_DEFAULT_RULE),
2784 * followed by a possibly empty list of dynamic rule.
2785 * The last dynamic rule has NULL in the "next" field.
2787 * Note that the calculated size is used to bound the
2788 * amount of data returned to the user. The rule set may
2789 * change between calculating the size and returning the
2790 * data in which case we'll just return what fits.
2795 size = chain->static_len;
2796 size += ipfw_dyn_len();
2797 if (size >= sopt->sopt_valsize)
2799 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
2800 IPFW_UH_RLOCK(chain);
2801 /* check again how much space we need */
2802 want = chain->static_len + ipfw_dyn_len();
2804 len = ipfw_getrules(chain, buf, size);
2805 IPFW_UH_RUNLOCK(chain);
2807 error = sooptcopyout(sopt, buf, len);
2815 /* locking is done within del_entry() */
2816 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
2820 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
2821 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
2822 sizeof(struct ip_fw7) );
2824 memset(&ci, 0, sizeof(struct rule_check_info));
2827 * If the size of commands equals RULESIZE7 then we assume
2828 * a FreeBSD7.2 binary is talking to us (set is7=1).
2829 * is7 is persistent so the next 'ipfw list' command
2830 * will use this format.
2831 * NOTE: If wrong version is guessed (this can happen if
2832 * the first ipfw command is 'ipfw [pipe] list')
2833 * the ipfw binary may crash or loop infinitly...
2835 size = sopt->sopt_valsize;
2836 if (size == RULESIZE7(rule)) {
2838 error = convert_rule_to_8(rule);
2843 size = RULESIZE(rule);
2847 error = check_ipfw_rule0(rule, size, &ci);
2849 /* locking is done within add_rule() */
2850 struct ip_fw *krule;
2851 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
2852 ci.urule = (caddr_t)rule;
2855 error = commit_rules(chain, &ci, 1);
2856 if (!error && sopt->sopt_dir == SOPT_GET) {
2858 error = convert_rule_to_7(rule);
2859 size = RULESIZE7(rule);
2865 error = sooptcopyout(sopt, rule, size);
2873 * IP_FW_DEL is used for deleting single rules or sets,
2874 * and (ab)used to atomically manipulate sets. Argument size
2875 * is used to distinguish between the two:
2877 * delete single rule or set of rules,
2878 * or reassign rules (or sets) to a different set.
2879 * 2*sizeof(u_int32_t)
2880 * atomic disable/enable sets.
2881 * first u_int32_t contains sets to be disabled,
2882 * second u_int32_t contains sets to be enabled.
2884 error = sooptcopyin(sopt, rulenum,
2885 2*sizeof(u_int32_t), sizeof(u_int32_t));
2888 size = sopt->sopt_valsize;
2889 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
2890 /* delete or reassign, locking done in del_entry() */
2891 error = del_entry(chain, rulenum[0]);
2892 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
2893 IPFW_UH_WLOCK(chain);
2895 (V_set_disable | rulenum[0]) & ~rulenum[1] &
2896 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
2897 IPFW_UH_WUNLOCK(chain);
2903 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
2905 if (sopt->sopt_val != 0) {
2906 error = sooptcopyin(sopt, rulenum,
2907 sizeof(u_int32_t), sizeof(u_int32_t));
2911 error = zero_entry(chain, rulenum[0],
2912 sopt->sopt_name == IP_FW_RESETLOG);
2915 /*--- TABLE opcodes ---*/
2916 case IP_FW_TABLE_ADD:
2917 case IP_FW_TABLE_DEL:
2919 ipfw_table_entry ent;
2920 struct tentry_info tei;
2922 struct table_value v;
2924 error = sooptcopyin(sopt, &ent,
2925 sizeof(ent), sizeof(ent));
2929 memset(&tei, 0, sizeof(tei));
2930 tei.paddr = &ent.addr;
2931 tei.subtype = AF_INET;
2932 tei.masklen = ent.masklen;
2933 ipfw_import_table_value_legacy(ent.value, &v);
2935 memset(&ti, 0, sizeof(ti));
2937 ti.type = IPFW_TABLE_CIDR;
2939 error = (opt == IP_FW_TABLE_ADD) ?
2940 add_table_entry(chain, &ti, &tei, 0, 1) :
2941 del_table_entry(chain, &ti, &tei, 0, 1);
2946 case IP_FW_TABLE_FLUSH:
2951 error = sooptcopyin(sopt, &tbl,
2952 sizeof(tbl), sizeof(tbl));
2955 memset(&ti, 0, sizeof(ti));
2957 error = flush_table(chain, &ti);
2961 case IP_FW_TABLE_GETSIZE:
2966 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
2969 memset(&ti, 0, sizeof(ti));
2972 error = ipfw_count_table(chain, &ti, &cnt);
2973 IPFW_RUNLOCK(chain);
2976 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
2980 case IP_FW_TABLE_LIST:
2985 if (sopt->sopt_valsize < sizeof(*tbl)) {
2989 size = sopt->sopt_valsize;
2990 tbl = malloc(size, M_TEMP, M_WAITOK);
2991 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
2996 tbl->size = (size - sizeof(*tbl)) /
2997 sizeof(ipfw_table_entry);
2998 memset(&ti, 0, sizeof(ti));
3001 error = ipfw_dump_table_legacy(chain, &ti, tbl);
3002 IPFW_RUNLOCK(chain);
3007 error = sooptcopyout(sopt, tbl, size);
3012 /*--- NAT operations are protected by the IPFW_LOCK ---*/
3014 if (IPFW_NAT_LOADED)
3015 error = ipfw_nat_cfg_ptr(sopt);
3017 printf("IP_FW_NAT_CFG: %s\n",
3018 "ipfw_nat not present, please load it");
3024 if (IPFW_NAT_LOADED)
3025 error = ipfw_nat_del_ptr(sopt);
3027 printf("IP_FW_NAT_DEL: %s\n",
3028 "ipfw_nat not present, please load it");
3033 case IP_FW_NAT_GET_CONFIG:
3034 if (IPFW_NAT_LOADED)
3035 error = ipfw_nat_get_cfg_ptr(sopt);
3037 printf("IP_FW_NAT_GET_CFG: %s\n",
3038 "ipfw_nat not present, please load it");
3043 case IP_FW_NAT_GET_LOG:
3044 if (IPFW_NAT_LOADED)
3045 error = ipfw_nat_get_log_ptr(sopt);
3047 printf("IP_FW_NAT_GET_LOG: %s\n",
3048 "ipfw_nat not present, please load it");
3054 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3061 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3063 /* Functions to convert rules 7.2 <==> 8.0 */
3065 convert_rule_to_7(struct ip_fw_rule0 *rule)
3067 /* Used to modify original rule */
3068 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
3069 /* copy of original rule, version 8 */
3070 struct ip_fw_rule0 *tmp;
3072 /* Used to copy commands */
3073 ipfw_insn *ccmd, *dst;
3074 int ll = 0, ccmdlen = 0;
3076 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3078 return 1; //XXX error
3080 bcopy(rule, tmp, RULE_MAXSIZE);
3083 //rule7->_pad = tmp->_pad;
3084 rule7->set = tmp->set;
3085 rule7->rulenum = tmp->rulenum;
3086 rule7->cmd_len = tmp->cmd_len;
3087 rule7->act_ofs = tmp->act_ofs;
3088 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
3089 rule7->cmd_len = tmp->cmd_len;
3090 rule7->pcnt = tmp->pcnt;
3091 rule7->bcnt = tmp->bcnt;
3092 rule7->timestamp = tmp->timestamp;
3095 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
3096 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3097 ccmdlen = F_LEN(ccmd);
3099 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3101 if (dst->opcode > O_NAT)
3102 /* O_REASS doesn't exists in 7.2 version, so
3103 * decrement opcode if it is after O_REASS
3108 printf("ipfw: opcode %d size truncated\n",
3119 convert_rule_to_8(struct ip_fw_rule0 *rule)
3121 /* Used to modify original rule */
3122 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
3124 /* Used to copy commands */
3125 ipfw_insn *ccmd, *dst;
3126 int ll = 0, ccmdlen = 0;
3128 /* Copy of original rule */
3129 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3131 return 1; //XXX error
3134 bcopy(rule7, tmp, RULE_MAXSIZE);
3136 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
3137 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3138 ccmdlen = F_LEN(ccmd);
3140 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3142 if (dst->opcode > O_NAT)
3143 /* O_REASS doesn't exists in 7.2 version, so
3144 * increment opcode if it is after O_REASS
3149 printf("ipfw: opcode %d size truncated\n",
3155 rule->_pad = tmp->_pad;
3156 rule->set = tmp->set;
3157 rule->rulenum = tmp->rulenum;
3158 rule->cmd_len = tmp->cmd_len;
3159 rule->act_ofs = tmp->act_ofs;
3160 rule->next_rule = (struct ip_fw *)tmp->next_rule;
3161 rule->cmd_len = tmp->cmd_len;
3162 rule->id = 0; /* XXX see if is ok = 0 */
3163 rule->pcnt = tmp->pcnt;
3164 rule->bcnt = tmp->bcnt;
3165 rule->timestamp = tmp->timestamp;
3177 * Allocate new bitmask which can be used to enlarge/shrink
3178 * named instance index.
3181 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
3187 KASSERT((items % BLOCK_ITEMS) == 0,
3188 ("bitmask size needs to power of 2 and greater or equal to %lu",
3191 max_blocks = items / BLOCK_ITEMS;
3193 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
3194 /* Mark all as free */
3195 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
3196 *idx_mask &= ~(u_long)1; /* Skip index 0 */
3199 *pblocks = max_blocks;
3203 * Copy current bitmask index to new one.
3206 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
3208 int old_blocks, new_blocks;
3209 u_long *old_idx, *new_idx;
3212 old_idx = ni->idx_mask;
3213 old_blocks = ni->max_blocks;
3215 new_blocks = *blocks;
3217 for (i = 0; i < IPFW_MAX_SETS; i++) {
3218 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
3219 old_blocks * sizeof(u_long));
3224 * Swaps current @ni index with new one.
3227 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
3232 old_idx = ni->idx_mask;
3233 old_blocks = ni->max_blocks;
3235 ni->idx_mask = *idx;
3236 ni->max_blocks = *blocks;
3238 /* Save old values */
3240 *blocks = old_blocks;
3244 ipfw_objhash_bitmap_free(void *idx, int blocks)
3251 * Creates named hash instance.
3252 * Must be called without holding any locks.
3253 * Return pointer to new instance.
3255 struct namedobj_instance *
3256 ipfw_objhash_create(uint32_t items)
3258 struct namedobj_instance *ni;
3262 size = sizeof(struct namedobj_instance) +
3263 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
3264 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
3266 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
3267 ni->nn_size = NAMEDOBJ_HASH_SIZE;
3268 ni->nv_size = NAMEDOBJ_HASH_SIZE;
3270 ni->names = (struct namedobjects_head *)(ni +1);
3271 ni->values = &ni->names[ni->nn_size];
3273 for (i = 0; i < ni->nn_size; i++)
3274 TAILQ_INIT(&ni->names[i]);
3276 for (i = 0; i < ni->nv_size; i++)
3277 TAILQ_INIT(&ni->values[i]);
3279 /* Set default hashing/comparison functions */
3280 ni->hash_f = objhash_hash_name;
3281 ni->cmp_f = objhash_cmp_name;
3283 /* Allocate bitmask separately due to possible resize */
3284 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
3290 ipfw_objhash_destroy(struct namedobj_instance *ni)
3293 free(ni->idx_mask, M_IPFW);
3298 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
3299 objhash_cmp_f *cmp_f)
3302 ni->hash_f = hash_f;
3307 objhash_hash_name(struct namedobj_instance *ni, void *name, uint32_t set)
3310 return (fnv_32_str((char *)name, FNV1_32_INIT));
3314 objhash_cmp_name(struct named_object *no, void *name, uint32_t set)
3317 if ((strcmp(no->name, (char *)name) == 0) && (no->set == set))
3324 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
3328 v = val % (ni->nv_size - 1);
3333 struct named_object *
3334 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
3336 struct named_object *no;
3339 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3341 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3342 if (ni->cmp_f(no, name, set) == 0)
3349 struct named_object *
3350 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
3352 struct named_object *no;
3355 hash = objhash_hash_idx(ni, kidx);
3357 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
3358 if (no->kidx == kidx)
3366 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
3367 struct named_object *b)
3370 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
3377 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
3381 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3382 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
3384 hash = objhash_hash_idx(ni, no->kidx);
3385 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
3391 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
3395 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3396 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
3398 hash = objhash_hash_idx(ni, no->kidx);
3399 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
3405 ipfw_objhash_count(struct namedobj_instance *ni)
3412 * Runs @func for each found named object.
3413 * It is safe to delete objects from callback
3416 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
3418 struct named_object *no, *no_tmp;
3421 for (i = 0; i < ni->nn_size; i++) {
3422 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp)
3428 * Removes index from given set.
3429 * Returns 0 on success.
3432 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
3437 i = idx / BLOCK_ITEMS;
3438 v = idx % BLOCK_ITEMS;
3440 if (i >= ni->max_blocks)
3443 mask = &ni->idx_mask[i];
3445 if ((*mask & ((u_long)1 << v)) != 0)
3449 *mask |= (u_long)1 << v;
3451 /* Update free offset */
3452 if (ni->free_off[0] > i)
3453 ni->free_off[0] = i;
3459 * Allocate new index in given instance and stores in in @pidx.
3460 * Returns 0 on success.
3463 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
3465 struct namedobj_instance *ni;
3469 ni = (struct namedobj_instance *)n;
3471 off = ni->free_off[0];
3472 mask = &ni->idx_mask[off];
3474 for (i = off; i < ni->max_blocks; i++, mask++) {
3475 if ((v = ffsl(*mask)) == 0)
3479 *mask &= ~ ((u_long)1 << (v - 1));
3481 ni->free_off[0] = i;
3483 v = BLOCK_ITEMS * i + v - 1;