xref: /freebsd-13-stable/sys/netpfil/ipfw/ip_fw_sockopt.c (revision f1929835f76d587804c417f19188f41b77e8e7c6)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5  * Copyright (c) 2014 Yandex LLC
6  * Copyright (c) 2014 Alexander V. Chernikov
7  *
8  * Supported by: Valeria Paoli
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 /*
34  * Control socket and rule management routines for ipfw.
35  * Control is currently implemented via IP_FW3 setsockopt() code.
36  */
37 
38 #include "opt_ipfw.h"
39 #include "opt_inet.h"
40 #ifndef INET
41 #error IPFIREWALL requires INET.
42 #endif /* INET */
43 #include "opt_inet6.h"
44 
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>
50 #include <sys/lock.h>
51 #include <sys/priv.h>
52 #include <sys/proc.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>
60 #include <net/if.h>
61 #include <net/route.h>
62 #include <net/vnet.h>
63 #include <vm/vm.h>
64 #include <vm/vm_extern.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/ip_var.h> /* hooks */
68 #include <netinet/ip_fw.h>
69 
70 #include <netpfil/ipfw/ip_fw_private.h>
71 #include <netpfil/ipfw/ip_fw_table.h>
72 
73 #ifdef MAC
74 #include <security/mac/mac_framework.h>
75 #endif
76 
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);
84 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
85     struct rule_check_info *ci);
86 
87 #define	NAMEDOBJ_HASH_SIZE	32
88 
89 struct namedobj_instance {
90 	struct namedobjects_head	*names;
91 	struct namedobjects_head	*values;
92 	uint32_t nn_size;		/* names hash size */
93 	uint32_t nv_size;		/* number hash size */
94 	u_long *idx_mask;		/* used items bitmask */
95 	uint32_t max_blocks;		/* number of "long" blocks in bitmask */
96 	uint32_t count;			/* number of items */
97 	uint16_t free_off[IPFW_MAX_SETS];	/* first possible free offset */
98 	objhash_hash_f	*hash_f;
99 	objhash_cmp_f	*cmp_f;
100 };
101 #define	BLOCK_ITEMS	(8 * sizeof(u_long))	/* Number of items for ffsl() */
102 
103 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
104     const void *key, uint32_t kopt);
105 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
106 static int objhash_cmp_name(struct named_object *no, const void *name,
107     uint32_t set);
108 
109 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
110 
111 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
112     struct sockopt_data *sd);
113 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
114     struct sockopt_data *sd);
115 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
116     struct sockopt_data *sd);
117 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
118     struct sockopt_data *sd);
119 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
120     struct sockopt_data *sd);
121 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
122     struct sockopt_data *sd);
123 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
124     struct sockopt_data *sd);
125 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
126     struct sockopt_data *sd);
127 
128 /* ctl3 handler data */
129 struct mtx ctl3_lock;
130 #define	CTL3_LOCK_INIT()	mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
131 #define	CTL3_LOCK_DESTROY()	mtx_destroy(&ctl3_lock)
132 #define	CTL3_LOCK()		mtx_lock(&ctl3_lock)
133 #define	CTL3_UNLOCK()		mtx_unlock(&ctl3_lock)
134 
135 static struct ipfw_sopt_handler *ctl3_handlers;
136 static size_t ctl3_hsize;
137 static uint64_t ctl3_refct, ctl3_gencnt;
138 #define	CTL3_SMALLBUF	4096			/* small page-size write buffer */
139 #define	CTL3_LARGEBUF	16 * 1024 * 1024	/* handle large rulesets */
140 
141 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
142 
143 static struct ipfw_sopt_handler	scodes[] = {
144 	{ IP_FW_XGET,		0,	HDIR_GET,	dump_config },
145 	{ IP_FW_XADD,		0,	HDIR_BOTH,	add_rules },
146 	{ IP_FW_XDEL,		0,	HDIR_BOTH,	del_rules },
147 	{ IP_FW_XZERO,		0,	HDIR_SET,	clear_rules },
148 	{ IP_FW_XRESETLOG,	0,	HDIR_SET,	clear_rules },
149 	{ IP_FW_XMOVE,		0,	HDIR_SET,	move_rules },
150 	{ IP_FW_SET_SWAP,	0,	HDIR_SET,	manage_sets },
151 	{ IP_FW_SET_MOVE,	0,	HDIR_SET,	manage_sets },
152 	{ IP_FW_SET_ENABLE,	0,	HDIR_SET,	manage_sets },
153 	{ IP_FW_DUMP_SOPTCODES,	0,	HDIR_GET,	dump_soptcodes },
154 	{ IP_FW_DUMP_SRVOBJECTS,0,	HDIR_GET,	dump_srvobjects },
155 };
156 
157 static int
158 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
159 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
160     uint16_t *puidx, uint8_t *ptype);
161 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
162     struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
163 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
164     struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
165 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
166 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
167     struct obj_idx *oib, struct obj_idx *end);
168 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
169     struct sockopt_data *sd);
170 
171 /*
172  * Opcode object rewriter variables
173  */
174 struct opcode_obj_rewrite *ctl3_rewriters;
175 static size_t ctl3_rsize;
176 
177 /*
178  * static variables followed by global ones
179  */
180 
181 VNET_DEFINE_STATIC(uma_zone_t, ipfw_cntr_zone);
182 #define	V_ipfw_cntr_zone		VNET(ipfw_cntr_zone)
183 
184 void
ipfw_init_counters(void)185 ipfw_init_counters(void)
186 {
187 
188 	V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
189 	    IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
190 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
191 }
192 
193 void
ipfw_destroy_counters(void)194 ipfw_destroy_counters(void)
195 {
196 
197 	uma_zdestroy(V_ipfw_cntr_zone);
198 }
199 
200 struct ip_fw *
ipfw_alloc_rule(struct ip_fw_chain * chain,size_t rulesize)201 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
202 {
203 	struct ip_fw *rule;
204 
205 	rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
206 	rule->cntr = uma_zalloc_pcpu(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
207 	rule->refcnt = 1;
208 
209 	return (rule);
210 }
211 
212 void
ipfw_free_rule(struct ip_fw * rule)213 ipfw_free_rule(struct ip_fw *rule)
214 {
215 
216 	/*
217 	 * We don't release refcnt here, since this function
218 	 * can be called without any locks held. The caller
219 	 * must release reference under IPFW_UH_WLOCK, and then
220 	 * call this function if refcount becomes 1.
221 	 */
222 	if (rule->refcnt > 1)
223 		return;
224 	uma_zfree_pcpu(V_ipfw_cntr_zone, rule->cntr);
225 	free(rule, M_IPFW);
226 }
227 
228 /*
229  * Find the smallest rule >= key, id.
230  * We could use bsearch but it is so simple that we code it directly
231  */
232 int
ipfw_find_rule(struct ip_fw_chain * chain,uint32_t key,uint32_t id)233 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
234 {
235 	int i, lo, hi;
236 	struct ip_fw *r;
237 
238   	for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
239 		i = (lo + hi) / 2;
240 		r = chain->map[i];
241 		if (r->rulenum < key)
242 			lo = i + 1;	/* continue from the next one */
243 		else if (r->rulenum > key)
244 			hi = i;		/* this might be good */
245 		else if (r->id < id)
246 			lo = i + 1;	/* continue from the next one */
247 		else /* r->id >= id */
248 			hi = i;		/* this might be good */
249 	}
250 	return hi;
251 }
252 
253 /*
254  * Builds skipto cache on rule set @map.
255  */
256 static void
update_skipto_cache(struct ip_fw_chain * chain,struct ip_fw ** map)257 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
258 {
259 	int *smap, rulenum;
260 	int i, mi;
261 
262 	IPFW_UH_WLOCK_ASSERT(chain);
263 
264 	mi = 0;
265 	rulenum = map[mi]->rulenum;
266 	smap = chain->idxmap_back;
267 
268 	if (smap == NULL)
269 		return;
270 
271 	for (i = 0; i < 65536; i++) {
272 		smap[i] = mi;
273 		/* Use the same rule index until i < rulenum */
274 		if (i != rulenum || i == 65535)
275 			continue;
276 		/* Find next rule with num > i */
277 		rulenum = map[++mi]->rulenum;
278 		while (rulenum == i)
279 			rulenum = map[++mi]->rulenum;
280 	}
281 }
282 
283 /*
284  * Swaps prepared (backup) index with current one.
285  */
286 static void
swap_skipto_cache(struct ip_fw_chain * chain)287 swap_skipto_cache(struct ip_fw_chain *chain)
288 {
289 	int *map;
290 
291 	IPFW_UH_WLOCK_ASSERT(chain);
292 	IPFW_WLOCK_ASSERT(chain);
293 
294 	map = chain->idxmap;
295 	chain->idxmap = chain->idxmap_back;
296 	chain->idxmap_back = map;
297 }
298 
299 /*
300  * Allocate and initialize skipto cache.
301  */
302 void
ipfw_init_skipto_cache(struct ip_fw_chain * chain)303 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
304 {
305 	int *idxmap, *idxmap_back;
306 
307 	idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
308 	idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
309 
310 	/*
311 	 * Note we may be called at any time after initialization,
312 	 * for example, on first skipto rule, so we need to
313 	 * provide valid chain->idxmap on return
314 	 */
315 
316 	IPFW_UH_WLOCK(chain);
317 	if (chain->idxmap != NULL) {
318 		IPFW_UH_WUNLOCK(chain);
319 		free(idxmap, M_IPFW);
320 		free(idxmap_back, M_IPFW);
321 		return;
322 	}
323 
324 	/* Set backup pointer first to permit building cache */
325 	chain->idxmap_back = idxmap_back;
326 	update_skipto_cache(chain, chain->map);
327 	IPFW_WLOCK(chain);
328 	/* It is now safe to set chain->idxmap ptr */
329 	chain->idxmap = idxmap;
330 	swap_skipto_cache(chain);
331 	IPFW_WUNLOCK(chain);
332 	IPFW_UH_WUNLOCK(chain);
333 }
334 
335 /*
336  * Destroys skipto cache.
337  */
338 void
ipfw_destroy_skipto_cache(struct ip_fw_chain * chain)339 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
340 {
341 
342 	if (chain->idxmap != NULL)
343 		free(chain->idxmap, M_IPFW);
344 	if (chain->idxmap != NULL)
345 		free(chain->idxmap_back, M_IPFW);
346 }
347 
348 /*
349  * allocate a new map, returns the chain locked. extra is the number
350  * of entries to add or delete.
351  */
352 static struct ip_fw **
get_map(struct ip_fw_chain * chain,int extra,int locked)353 get_map(struct ip_fw_chain *chain, int extra, int locked)
354 {
355 
356 	for (;;) {
357 		struct ip_fw **map;
358 		u_int i, mflags;
359 
360 		mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
361 
362 		i = chain->n_rules + extra;
363 		map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
364 		if (map == NULL) {
365 			printf("%s: cannot allocate map\n", __FUNCTION__);
366 			return NULL;
367 		}
368 		if (!locked)
369 			IPFW_UH_WLOCK(chain);
370 		if (i >= chain->n_rules + extra) /* good */
371 			return map;
372 		/* otherwise we lost the race, free and retry */
373 		if (!locked)
374 			IPFW_UH_WUNLOCK(chain);
375 		free(map, M_IPFW);
376 	}
377 }
378 
379 /*
380  * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
381  */
382 static struct ip_fw **
swap_map(struct ip_fw_chain * chain,struct ip_fw ** new_map,int new_len)383 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
384 {
385 	struct ip_fw **old_map;
386 
387 	IPFW_WLOCK(chain);
388 	chain->id++;
389 	chain->n_rules = new_len;
390 	old_map = chain->map;
391 	chain->map = new_map;
392 	swap_skipto_cache(chain);
393 	IPFW_WUNLOCK(chain);
394 	return old_map;
395 }
396 
397 static void
export_cntr1_base(struct ip_fw * krule,struct ip_fw_bcounter * cntr)398 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
399 {
400 	struct timeval boottime;
401 
402 	cntr->size = sizeof(*cntr);
403 
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;
408 	}
409 	if (cntr->timestamp > 0) {
410 		getboottime(&boottime);
411 		cntr->timestamp += boottime.tv_sec;
412 	}
413 }
414 
415 static void
export_cntr0_base(struct ip_fw * krule,struct ip_fw_bcounter0 * cntr)416 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
417 {
418 	struct timeval boottime;
419 
420 	if (krule->cntr != NULL) {
421 		cntr->pcnt = counter_u64_fetch(krule->cntr);
422 		cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
423 		cntr->timestamp = krule->timestamp;
424 	}
425 	if (cntr->timestamp > 0) {
426 		getboottime(&boottime);
427 		cntr->timestamp += boottime.tv_sec;
428 	}
429 }
430 
431 /*
432  * Copies rule @urule from v1 userland format (current).
433  * to kernel @krule.
434  * Assume @krule is zeroed.
435  */
436 static void
import_rule1(struct rule_check_info * ci)437 import_rule1(struct rule_check_info *ci)
438 {
439 	struct ip_fw_rule *urule;
440 	struct ip_fw *krule;
441 
442 	urule = (struct ip_fw_rule *)ci->urule;
443 	krule = (struct ip_fw *)ci->krule;
444 
445 	/* copy header */
446 	krule->act_ofs = urule->act_ofs;
447 	krule->cmd_len = urule->cmd_len;
448 	krule->rulenum = urule->rulenum;
449 	krule->set = urule->set;
450 	krule->flags = urule->flags;
451 
452 	/* Save rulenum offset */
453 	ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
454 
455 	/* Copy opcodes */
456 	memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
457 }
458 
459 /*
460  * Export rule into v1 format (Current).
461  * Layout:
462  * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
463  *     [ ip_fw_rule ] OR
464  *     [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
465  * ]
466  * Assume @data is zeroed.
467  */
468 static void
export_rule1(struct ip_fw * krule,caddr_t data,int len,int rcntrs)469 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
470 {
471 	struct ip_fw_bcounter *cntr;
472 	struct ip_fw_rule *urule;
473 	ipfw_obj_tlv *tlv;
474 
475 	/* Fill in TLV header */
476 	tlv = (ipfw_obj_tlv *)data;
477 	tlv->type = IPFW_TLV_RULE_ENT;
478 	tlv->length = len;
479 
480 	if (rcntrs != 0) {
481 		/* Copy counters */
482 		cntr = (struct ip_fw_bcounter *)(tlv + 1);
483 		urule = (struct ip_fw_rule *)(cntr + 1);
484 		export_cntr1_base(krule, cntr);
485 	} else
486 		urule = (struct ip_fw_rule *)(tlv + 1);
487 
488 	/* copy header */
489 	urule->act_ofs = krule->act_ofs;
490 	urule->cmd_len = krule->cmd_len;
491 	urule->rulenum = krule->rulenum;
492 	urule->set = krule->set;
493 	urule->flags = krule->flags;
494 	urule->id = krule->id;
495 
496 	/* Copy opcodes */
497 	memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
498 }
499 
500 /*
501  * Copies rule @urule from FreeBSD8 userland format (v0)
502  * to kernel @krule.
503  * Assume @krule is zeroed.
504  */
505 static void
import_rule0(struct rule_check_info * ci)506 import_rule0(struct rule_check_info *ci)
507 {
508 	struct ip_fw_rule0 *urule;
509 	struct ip_fw *krule;
510 	int cmdlen, l;
511 	ipfw_insn *cmd;
512 	ipfw_insn_limit *lcmd;
513 	ipfw_insn_if *cmdif;
514 
515 	urule = (struct ip_fw_rule0 *)ci->urule;
516 	krule = (struct ip_fw *)ci->krule;
517 
518 	/* copy header */
519 	krule->act_ofs = urule->act_ofs;
520 	krule->cmd_len = urule->cmd_len;
521 	krule->rulenum = urule->rulenum;
522 	krule->set = urule->set;
523 	if ((urule->_pad & 1) != 0)
524 		krule->flags |= IPFW_RULE_NOOPT;
525 
526 	/* Save rulenum offset */
527 	ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
528 
529 	/* Copy opcodes */
530 	memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
531 
532 	/*
533 	 * Alter opcodes:
534 	 * 1) convert tablearg value from 65535 to 0
535 	 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
536 	 *    for targ).
537 	 * 3) convert table number in iface opcodes to u16
538 	 * 4) convert old `nat global` into new 65535
539 	 */
540 	l = krule->cmd_len;
541 	cmd = krule->cmd;
542 	cmdlen = 0;
543 
544 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
545 		cmdlen = F_LEN(cmd);
546 
547 		switch (cmd->opcode) {
548 		/* Opcodes supporting tablearg */
549 		case O_TAG:
550 		case O_TAGGED:
551 		case O_PIPE:
552 		case O_QUEUE:
553 		case O_DIVERT:
554 		case O_TEE:
555 		case O_SKIPTO:
556 		case O_CALLRETURN:
557 		case O_NETGRAPH:
558 		case O_NGTEE:
559 		case O_NAT:
560 			if (cmd->arg1 == IP_FW_TABLEARG)
561 				cmd->arg1 = IP_FW_TARG;
562 			else if (cmd->arg1 == 0)
563 				cmd->arg1 = IP_FW_NAT44_GLOBAL;
564 			break;
565 		case O_SETFIB:
566 		case O_SETDSCP:
567 			if (cmd->arg1 == IP_FW_TABLEARG)
568 				cmd->arg1 = IP_FW_TARG;
569 			else
570 				cmd->arg1 |= 0x8000;
571 			break;
572 		case O_LIMIT:
573 			lcmd = (ipfw_insn_limit *)cmd;
574 			if (lcmd->conn_limit == IP_FW_TABLEARG)
575 				lcmd->conn_limit = IP_FW_TARG;
576 			break;
577 		/* Interface tables */
578 		case O_XMIT:
579 		case O_RECV:
580 		case O_VIA:
581 			/* Interface table, possibly */
582 			cmdif = (ipfw_insn_if *)cmd;
583 			if (cmdif->name[0] != '\1')
584 				break;
585 
586 			cmdif->p.kidx = (uint16_t)cmdif->p.glob;
587 			break;
588 		}
589 	}
590 }
591 
592 /*
593  * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
594  */
595 static void
export_rule0(struct ip_fw * krule,struct ip_fw_rule0 * urule,int len)596 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
597 {
598 	int cmdlen, l;
599 	ipfw_insn *cmd;
600 	ipfw_insn_limit *lcmd;
601 	ipfw_insn_if *cmdif;
602 
603 	/* copy header */
604 	memset(urule, 0, len);
605 	urule->act_ofs = krule->act_ofs;
606 	urule->cmd_len = krule->cmd_len;
607 	urule->rulenum = krule->rulenum;
608 	urule->set = krule->set;
609 	if ((krule->flags & IPFW_RULE_NOOPT) != 0)
610 		urule->_pad |= 1;
611 
612 	/* Copy opcodes */
613 	memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
614 
615 	/* Export counters */
616 	export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
617 
618 	/*
619 	 * Alter opcodes:
620 	 * 1) convert tablearg value from 0 to 65535
621 	 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
622 	 * 3) convert table number in iface opcodes to int
623 	 */
624 	l = urule->cmd_len;
625 	cmd = urule->cmd;
626 	cmdlen = 0;
627 
628 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
629 		cmdlen = F_LEN(cmd);
630 
631 		switch (cmd->opcode) {
632 		/* Opcodes supporting tablearg */
633 		case O_TAG:
634 		case O_TAGGED:
635 		case O_PIPE:
636 		case O_QUEUE:
637 		case O_DIVERT:
638 		case O_TEE:
639 		case O_SKIPTO:
640 		case O_CALLRETURN:
641 		case O_NETGRAPH:
642 		case O_NGTEE:
643 		case O_NAT:
644 			if (cmd->arg1 == IP_FW_TARG)
645 				cmd->arg1 = IP_FW_TABLEARG;
646 			else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
647 				cmd->arg1 = 0;
648 			break;
649 		case O_SETFIB:
650 		case O_SETDSCP:
651 			if (cmd->arg1 == IP_FW_TARG)
652 				cmd->arg1 = IP_FW_TABLEARG;
653 			else
654 				cmd->arg1 &= ~0x8000;
655 			break;
656 		case O_LIMIT:
657 			lcmd = (ipfw_insn_limit *)cmd;
658 			if (lcmd->conn_limit == IP_FW_TARG)
659 				lcmd->conn_limit = IP_FW_TABLEARG;
660 			break;
661 		/* Interface tables */
662 		case O_XMIT:
663 		case O_RECV:
664 		case O_VIA:
665 			/* Interface table, possibly */
666 			cmdif = (ipfw_insn_if *)cmd;
667 			if (cmdif->name[0] != '\1')
668 				break;
669 
670 			cmdif->p.glob = cmdif->p.kidx;
671 			break;
672 		}
673 	}
674 }
675 
676 /*
677  * Add new rule(s) to the list possibly creating rule number for each.
678  * Update the rule_number in the input struct so the caller knows it as well.
679  * Must be called without IPFW_UH held
680  */
681 static int
commit_rules(struct ip_fw_chain * chain,struct rule_check_info * rci,int count)682 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
683 {
684 	int error, i, insert_before, tcount;
685 	uint16_t rulenum, *pnum;
686 	struct rule_check_info *ci;
687 	struct ip_fw *krule;
688 	struct ip_fw **map;	/* the new array of pointers */
689 
690 	/* Check if we need to do table/obj index remap */
691 	tcount = 0;
692 	for (ci = rci, i = 0; i < count; ci++, i++) {
693 		if (ci->object_opcodes == 0)
694 			continue;
695 
696 		/*
697 		 * Rule has some object opcodes.
698 		 * We need to find (and create non-existing)
699 		 * kernel objects, and reference existing ones.
700 		 */
701 		error = rewrite_rule_uidx(chain, ci);
702 		if (error != 0) {
703 			/*
704 			 * rewrite failed, state for current rule
705 			 * has been reverted. Check if we need to
706 			 * revert more.
707 			 */
708 			if (tcount > 0) {
709 				/*
710 				 * We have some more table rules
711 				 * we need to rollback.
712 				 */
713 
714 				IPFW_UH_WLOCK(chain);
715 				while (ci != rci) {
716 					ci--;
717 					if (ci->object_opcodes == 0)
718 						continue;
719 					unref_rule_objects(chain,ci->krule);
720 				}
721 				IPFW_UH_WUNLOCK(chain);
722 			}
723 
724 			return (error);
725 		}
726 
727 		tcount++;
728 	}
729 
730 	/* get_map returns with IPFW_UH_WLOCK if successful */
731 	map = get_map(chain, count, 0 /* not locked */);
732 	if (map == NULL) {
733 		if (tcount > 0) {
734 			/* Unbind tables */
735 			IPFW_UH_WLOCK(chain);
736 			for (ci = rci, i = 0; i < count; ci++, i++) {
737 				if (ci->object_opcodes == 0)
738 					continue;
739 
740 				unref_rule_objects(chain, ci->krule);
741 			}
742 			IPFW_UH_WUNLOCK(chain);
743 		}
744 
745 		return (ENOSPC);
746 	}
747 
748 	if (V_autoinc_step < 1)
749 		V_autoinc_step = 1;
750 	else if (V_autoinc_step > 1000)
751 		V_autoinc_step = 1000;
752 
753 	/* FIXME: Handle count > 1 */
754 	ci = rci;
755 	krule = ci->krule;
756 	rulenum = krule->rulenum;
757 
758 	/* find the insertion point, we will insert before */
759 	insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
760 	i = ipfw_find_rule(chain, insert_before, 0);
761 	/* duplicate first part */
762 	if (i > 0)
763 		bcopy(chain->map, map, i * sizeof(struct ip_fw *));
764 	map[i] = krule;
765 	/* duplicate remaining part, we always have the default rule */
766 	bcopy(chain->map + i, map + i + 1,
767 		sizeof(struct ip_fw *) *(chain->n_rules - i));
768 	if (rulenum == 0) {
769 		/* Compute rule number and write it back */
770 		rulenum = i > 0 ? map[i-1]->rulenum : 0;
771 		if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
772 			rulenum += V_autoinc_step;
773 		krule->rulenum = rulenum;
774 		/* Save number to userland rule */
775 		pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
776 		*pnum = rulenum;
777 	}
778 
779 	krule->id = chain->id + 1;
780 	update_skipto_cache(chain, map);
781 	map = swap_map(chain, map, chain->n_rules + 1);
782 	chain->static_len += RULEUSIZE0(krule);
783 	IPFW_UH_WUNLOCK(chain);
784 	if (map)
785 		free(map, M_IPFW);
786 	return (0);
787 }
788 
789 int
ipfw_add_protected_rule(struct ip_fw_chain * chain,struct ip_fw * rule,int locked)790 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
791     int locked)
792 {
793 	struct ip_fw **map;
794 
795 	map = get_map(chain, 1, locked);
796 	if (map == NULL)
797 		return (ENOMEM);
798 	if (chain->n_rules > 0)
799 		bcopy(chain->map, map,
800 		    chain->n_rules * sizeof(struct ip_fw *));
801 	map[chain->n_rules] = rule;
802 	rule->rulenum = IPFW_DEFAULT_RULE;
803 	rule->set = RESVD_SET;
804 	rule->id = chain->id + 1;
805 	/* We add rule in the end of chain, no need to update skipto cache */
806 	map = swap_map(chain, map, chain->n_rules + 1);
807 	chain->static_len += RULEUSIZE0(rule);
808 	IPFW_UH_WUNLOCK(chain);
809 	free(map, M_IPFW);
810 	return (0);
811 }
812 
813 /*
814  * Adds @rule to the list of rules to reap
815  */
816 void
ipfw_reap_add(struct ip_fw_chain * chain,struct ip_fw ** head,struct ip_fw * rule)817 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
818     struct ip_fw *rule)
819 {
820 
821 	IPFW_UH_WLOCK_ASSERT(chain);
822 
823 	/* Unlink rule from everywhere */
824 	unref_rule_objects(chain, rule);
825 
826 	rule->next = *head;
827 	*head = rule;
828 }
829 
830 /*
831  * Reclaim storage associated with a list of rules.  This is
832  * typically the list created using remove_rule.
833  * A NULL pointer on input is handled correctly.
834  */
835 void
ipfw_reap_rules(struct ip_fw * head)836 ipfw_reap_rules(struct ip_fw *head)
837 {
838 	struct ip_fw *rule;
839 
840 	while ((rule = head) != NULL) {
841 		head = head->next;
842 		ipfw_free_rule(rule);
843 	}
844 }
845 
846 /*
847  * Rules to keep are
848  *	(default || reserved || !match_set || !match_number)
849  * where
850  *   default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
851  *	// the default rule is always protected
852  *
853  *   reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
854  *	// RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
855  *
856  *   match_set ::= (cmd == 0 || rule->set == set)
857  *	// set number is ignored for cmd == 0
858  *
859  *   match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
860  *	// number is ignored for cmd == 1 or n == 0
861  *
862  */
863 int
ipfw_match_range(struct ip_fw * rule,ipfw_range_tlv * rt)864 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
865 {
866 
867 	/* Don't match default rule for modification queries */
868 	if (rule->rulenum == IPFW_DEFAULT_RULE &&
869 	    (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
870 		return (0);
871 
872 	/* Don't match rules in reserved set for flush requests */
873 	if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
874 		return (0);
875 
876 	/* If we're filtering by set, don't match other sets */
877 	if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
878 		return (0);
879 
880 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
881 	    (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
882 		return (0);
883 
884 	return (1);
885 }
886 
887 struct manage_sets_args {
888 	uint16_t	set;
889 	uint8_t		new_set;
890 };
891 
892 static int
swap_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)893 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
894     void *arg)
895 {
896 	struct manage_sets_args *args;
897 
898 	args = (struct manage_sets_args *)arg;
899 	if (no->set == (uint8_t)args->set)
900 		no->set = args->new_set;
901 	else if (no->set == args->new_set)
902 		no->set = (uint8_t)args->set;
903 	return (0);
904 }
905 
906 static int
move_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)907 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
908     void *arg)
909 {
910 	struct manage_sets_args *args;
911 
912 	args = (struct manage_sets_args *)arg;
913 	if (no->set == (uint8_t)args->set)
914 		no->set = args->new_set;
915 	return (0);
916 }
917 
918 static int
test_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)919 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
920     void *arg)
921 {
922 	struct manage_sets_args *args;
923 
924 	args = (struct manage_sets_args *)arg;
925 	if (no->set != (uint8_t)args->set)
926 		return (0);
927 	if (ipfw_objhash_lookup_name_type(ni, args->new_set,
928 	    no->etlv, no->name) != NULL)
929 		return (EEXIST);
930 	return (0);
931 }
932 
933 /*
934  * Generic function to handler moving and swapping sets.
935  */
936 int
ipfw_obj_manage_sets(struct namedobj_instance * ni,uint16_t type,uint16_t set,uint8_t new_set,enum ipfw_sets_cmd cmd)937 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
938     uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
939 {
940 	struct manage_sets_args args;
941 	struct named_object *no;
942 
943 	args.set = set;
944 	args.new_set = new_set;
945 	switch (cmd) {
946 	case SWAP_ALL:
947 		return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
948 		    &args, type));
949 	case TEST_ALL:
950 		return (ipfw_objhash_foreach_type(ni, test_sets_cb,
951 		    &args, type));
952 	case MOVE_ALL:
953 		return (ipfw_objhash_foreach_type(ni, move_sets_cb,
954 		    &args, type));
955 	case COUNT_ONE:
956 		/*
957 		 * @set used to pass kidx.
958 		 * When @new_set is zero - reset object counter,
959 		 * otherwise increment it.
960 		 */
961 		no = ipfw_objhash_lookup_kidx(ni, set);
962 		if (new_set != 0)
963 			no->ocnt++;
964 		else
965 			no->ocnt = 0;
966 		return (0);
967 	case TEST_ONE:
968 		/* @set used to pass kidx */
969 		no = ipfw_objhash_lookup_kidx(ni, set);
970 		/*
971 		 * First check number of references:
972 		 * when it differs, this mean other rules are holding
973 		 * reference to given object, so it is not possible to
974 		 * change its set. Note that refcnt may account references
975 		 * to some going-to-be-added rules. Since we don't know
976 		 * their numbers (and even if they will be added) it is
977 		 * perfectly OK to return error here.
978 		 */
979 		if (no->ocnt != no->refcnt)
980 			return (EBUSY);
981 		if (ipfw_objhash_lookup_name_type(ni, new_set, type,
982 		    no->name) != NULL)
983 			return (EEXIST);
984 		return (0);
985 	case MOVE_ONE:
986 		/* @set used to pass kidx */
987 		no = ipfw_objhash_lookup_kidx(ni, set);
988 		no->set = new_set;
989 		return (0);
990 	}
991 	return (EINVAL);
992 }
993 
994 /*
995  * Delete rules matching range @rt.
996  * Saves number of deleted rules in @ndel.
997  *
998  * Returns 0 on success.
999  */
1000 static int
delete_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int * ndel)1001 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1002 {
1003 	struct ip_fw *reap, *rule, **map;
1004 	int end, start;
1005 	int i, n, ndyn, ofs;
1006 
1007 	reap = NULL;
1008 	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
1009 
1010 	/*
1011 	 * Stage 1: Determine range to inspect.
1012 	 * Range is half-inclusive, e.g [start, end).
1013 	 */
1014 	start = 0;
1015 	end = chain->n_rules - 1;
1016 
1017 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1018 		start = ipfw_find_rule(chain, rt->start_rule, 0);
1019 
1020 		if (rt->end_rule >= IPFW_DEFAULT_RULE)
1021 			rt->end_rule = IPFW_DEFAULT_RULE - 1;
1022 		end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1023 	}
1024 
1025 	if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1026 		/*
1027 		 * Requested deleting only for dynamic states.
1028 		 */
1029 		*ndel = 0;
1030 		ipfw_expire_dyn_states(chain, rt);
1031 		IPFW_UH_WUNLOCK(chain);
1032 		return (0);
1033 	}
1034 
1035 	/* Allocate new map of the same size */
1036 	map = get_map(chain, 0, 1 /* locked */);
1037 	if (map == NULL) {
1038 		IPFW_UH_WUNLOCK(chain);
1039 		return (ENOMEM);
1040 	}
1041 
1042 	n = 0;
1043 	ndyn = 0;
1044 	ofs = start;
1045 	/* 1. bcopy the initial part of the map */
1046 	if (start > 0)
1047 		bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1048 	/* 2. copy active rules between start and end */
1049 	for (i = start; i < end; i++) {
1050 		rule = chain->map[i];
1051 		if (ipfw_match_range(rule, rt) == 0) {
1052 			map[ofs++] = rule;
1053 			continue;
1054 		}
1055 
1056 		n++;
1057 		if (ipfw_is_dyn_rule(rule) != 0)
1058 			ndyn++;
1059 	}
1060 	/* 3. copy the final part of the map */
1061 	bcopy(chain->map + end, map + ofs,
1062 		(chain->n_rules - end) * sizeof(struct ip_fw *));
1063 	/* 4. recalculate skipto cache */
1064 	update_skipto_cache(chain, map);
1065 	/* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1066 	map = swap_map(chain, map, chain->n_rules - n);
1067 	/* 6. Remove all dynamic states originated by deleted rules */
1068 	if (ndyn > 0)
1069 		ipfw_expire_dyn_states(chain, rt);
1070 	/* 7. now remove the rules deleted from the old map */
1071 	for (i = start; i < end; i++) {
1072 		rule = map[i];
1073 		if (ipfw_match_range(rule, rt) == 0)
1074 			continue;
1075 		chain->static_len -= RULEUSIZE0(rule);
1076 		ipfw_reap_add(chain, &reap, rule);
1077 	}
1078 	IPFW_UH_WUNLOCK(chain);
1079 
1080 	ipfw_reap_rules(reap);
1081 	if (map != NULL)
1082 		free(map, M_IPFW);
1083 	*ndel = n;
1084 	return (0);
1085 }
1086 
1087 static int
move_objects(struct ip_fw_chain * ch,ipfw_range_tlv * rt)1088 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1089 {
1090 	struct opcode_obj_rewrite *rw;
1091 	struct ip_fw *rule;
1092 	ipfw_insn *cmd;
1093 	int cmdlen, i, l, c;
1094 	uint16_t kidx;
1095 
1096 	IPFW_UH_WLOCK_ASSERT(ch);
1097 
1098 	/* Stage 1: count number of references by given rules */
1099 	for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1100 		rule = ch->map[i];
1101 		if (ipfw_match_range(rule, rt) == 0)
1102 			continue;
1103 		if (rule->set == rt->new_set) /* nothing to do */
1104 			continue;
1105 		/* Search opcodes with named objects */
1106 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1107 		    l > 0; l -= cmdlen, cmd += cmdlen) {
1108 			cmdlen = F_LEN(cmd);
1109 			rw = find_op_rw(cmd, &kidx, NULL);
1110 			if (rw == NULL || rw->manage_sets == NULL)
1111 				continue;
1112 			/*
1113 			 * When manage_sets() returns non-zero value to
1114 			 * COUNT_ONE command, consider this as an object
1115 			 * doesn't support sets (e.g. disabled with sysctl).
1116 			 * So, skip checks for this object.
1117 			 */
1118 			if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1119 				continue;
1120 			c++;
1121 		}
1122 	}
1123 	if (c == 0) /* No objects found */
1124 		return (0);
1125 	/* Stage 2: verify "ownership" */
1126 	for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1127 		rule = ch->map[i];
1128 		if (ipfw_match_range(rule, rt) == 0)
1129 			continue;
1130 		if (rule->set == rt->new_set) /* nothing to do */
1131 			continue;
1132 		/* Search opcodes with named objects */
1133 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1134 		    l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1135 			cmdlen = F_LEN(cmd);
1136 			rw = find_op_rw(cmd, &kidx, NULL);
1137 			if (rw == NULL || rw->manage_sets == NULL)
1138 				continue;
1139 			/* Test for ownership and conflicting names */
1140 			c = rw->manage_sets(ch, kidx,
1141 			    (uint8_t)rt->new_set, TEST_ONE);
1142 		}
1143 	}
1144 	/* Stage 3: change set and cleanup */
1145 	for (i = 0; i < ch->n_rules - 1; i++) {
1146 		rule = ch->map[i];
1147 		if (ipfw_match_range(rule, rt) == 0)
1148 			continue;
1149 		if (rule->set == rt->new_set) /* nothing to do */
1150 			continue;
1151 		/* Search opcodes with named objects */
1152 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1153 		    l > 0; l -= cmdlen, cmd += cmdlen) {
1154 			cmdlen = F_LEN(cmd);
1155 			rw = find_op_rw(cmd, &kidx, NULL);
1156 			if (rw == NULL || rw->manage_sets == NULL)
1157 				continue;
1158 			/* cleanup object counter */
1159 			rw->manage_sets(ch, kidx,
1160 			    0 /* reset counter */, COUNT_ONE);
1161 			if (c != 0)
1162 				continue;
1163 			/* change set */
1164 			rw->manage_sets(ch, kidx,
1165 			    (uint8_t)rt->new_set, MOVE_ONE);
1166 		}
1167 	}
1168 	return (c);
1169 }
1170 
1171 /*
1172  * Changes set of given rule rannge @rt
1173  * with each other.
1174  *
1175  * Returns 0 on success.
1176  */
1177 static int
move_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt)1178 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1179 {
1180 	struct ip_fw *rule;
1181 	int i;
1182 
1183 	IPFW_UH_WLOCK(chain);
1184 
1185 	/*
1186 	 * Move rules with matching paramenerts to a new set.
1187 	 * This one is much more complex. We have to ensure
1188 	 * that all referenced tables (if any) are referenced
1189 	 * by given rule subset only. Otherwise, we can't move
1190 	 * them to new set and have to return error.
1191 	 */
1192 	if ((i = move_objects(chain, rt)) != 0) {
1193 		IPFW_UH_WUNLOCK(chain);
1194 		return (i);
1195 	}
1196 
1197 	/* XXX: We have to do swap holding WLOCK */
1198 	for (i = 0; i < chain->n_rules; i++) {
1199 		rule = chain->map[i];
1200 		if (ipfw_match_range(rule, rt) == 0)
1201 			continue;
1202 		rule->set = rt->new_set;
1203 	}
1204 
1205 	IPFW_UH_WUNLOCK(chain);
1206 
1207 	return (0);
1208 }
1209 
1210 /*
1211  * Returns pointer to action instruction, skips all possible rule
1212  * modifiers like O_LOG, O_TAG, O_ALTQ.
1213  */
1214 ipfw_insn *
ipfw_get_action(struct ip_fw * rule)1215 ipfw_get_action(struct ip_fw *rule)
1216 {
1217 	ipfw_insn *cmd;
1218 	int l, cmdlen;
1219 
1220 	cmd = ACTION_PTR(rule);
1221 	l = rule->cmd_len - rule->act_ofs;
1222 	while (l > 0) {
1223 		switch (cmd->opcode) {
1224 		case O_ALTQ:
1225 		case O_LOG:
1226 		case O_TAG:
1227 			break;
1228 		default:
1229 			return (cmd);
1230 		}
1231 		cmdlen = F_LEN(cmd);
1232 		l -= cmdlen;
1233 		cmd += cmdlen;
1234 	}
1235 	panic("%s: rule (%p) has not action opcode", __func__, rule);
1236 	return (NULL);
1237 }
1238 
1239 /*
1240  * Clear counters for a specific rule.
1241  * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1242  * so we only care that rules do not disappear.
1243  */
1244 static void
clear_counters(struct ip_fw * rule,int log_only)1245 clear_counters(struct ip_fw *rule, int log_only)
1246 {
1247 	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1248 
1249 	if (log_only == 0)
1250 		IPFW_ZERO_RULE_COUNTER(rule);
1251 	if (l->o.opcode == O_LOG)
1252 		l->log_left = l->max_log;
1253 }
1254 
1255 /*
1256  * Flushes rules counters and/or log values on matching range.
1257  *
1258  * Returns number of items cleared.
1259  */
1260 static int
clear_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int log_only)1261 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1262 {
1263 	struct ip_fw *rule;
1264 	int num;
1265 	int i;
1266 
1267 	num = 0;
1268 	rt->flags |= IPFW_RCFLAG_DEFAULT;
1269 
1270 	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
1271 	for (i = 0; i < chain->n_rules; i++) {
1272 		rule = chain->map[i];
1273 		if (ipfw_match_range(rule, rt) == 0)
1274 			continue;
1275 		clear_counters(rule, log_only);
1276 		num++;
1277 	}
1278 	IPFW_UH_WUNLOCK(chain);
1279 
1280 	return (num);
1281 }
1282 
1283 static int
check_range_tlv(ipfw_range_tlv * rt)1284 check_range_tlv(ipfw_range_tlv *rt)
1285 {
1286 
1287 	if (rt->head.length != sizeof(*rt))
1288 		return (1);
1289 	if (rt->start_rule > rt->end_rule)
1290 		return (1);
1291 	if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1292 		return (1);
1293 
1294 	if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1295 		return (1);
1296 
1297 	return (0);
1298 }
1299 
1300 /*
1301  * Delete rules matching specified parameters
1302  * Data layout (v0)(current):
1303  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1304  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1305  *
1306  * Saves number of deleted rules in ipfw_range_tlv->new_set.
1307  *
1308  * Returns 0 on success.
1309  */
1310 static int
del_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1311 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1312     struct sockopt_data *sd)
1313 {
1314 	ipfw_range_header *rh;
1315 	int error, ndel;
1316 
1317 	if (sd->valsize != sizeof(*rh))
1318 		return (EINVAL);
1319 
1320 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1321 
1322 	if (check_range_tlv(&rh->range) != 0)
1323 		return (EINVAL);
1324 
1325 	ndel = 0;
1326 	if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1327 		return (error);
1328 
1329 	/* Save number of rules deleted */
1330 	rh->range.new_set = ndel;
1331 	return (0);
1332 }
1333 
1334 /*
1335  * Move rules/sets matching specified parameters
1336  * Data layout (v0)(current):
1337  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1338  *
1339  * Returns 0 on success.
1340  */
1341 static int
move_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1342 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1343     struct sockopt_data *sd)
1344 {
1345 	ipfw_range_header *rh;
1346 
1347 	if (sd->valsize != sizeof(*rh))
1348 		return (EINVAL);
1349 
1350 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1351 
1352 	if (check_range_tlv(&rh->range) != 0)
1353 		return (EINVAL);
1354 
1355 	return (move_range(chain, &rh->range));
1356 }
1357 
1358 /*
1359  * Clear rule accounting data matching specified parameters
1360  * Data layout (v0)(current):
1361  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1362  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1363  *
1364  * Saves number of cleared rules in ipfw_range_tlv->new_set.
1365  *
1366  * Returns 0 on success.
1367  */
1368 static int
clear_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1369 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1370     struct sockopt_data *sd)
1371 {
1372 	ipfw_range_header *rh;
1373 	int log_only, num;
1374 	char *msg;
1375 
1376 	if (sd->valsize != sizeof(*rh))
1377 		return (EINVAL);
1378 
1379 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1380 
1381 	if (check_range_tlv(&rh->range) != 0)
1382 		return (EINVAL);
1383 
1384 	log_only = (op3->opcode == IP_FW_XRESETLOG);
1385 
1386 	num = clear_range(chain, &rh->range, log_only);
1387 
1388 	if (rh->range.flags & IPFW_RCFLAG_ALL)
1389 		msg = log_only ? "All logging counts reset" :
1390 		    "Accounting cleared";
1391 	else
1392 		msg = log_only ? "logging count reset" : "cleared";
1393 
1394 	if (V_fw_verbose) {
1395 		int lev = LOG_SECURITY | LOG_NOTICE;
1396 		log(lev, "ipfw: %s.\n", msg);
1397 	}
1398 
1399 	/* Save number of rules cleared */
1400 	rh->range.new_set = num;
1401 	return (0);
1402 }
1403 
1404 static void
enable_sets(struct ip_fw_chain * chain,ipfw_range_tlv * rt)1405 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1406 {
1407 	uint32_t v_set;
1408 
1409 	IPFW_UH_WLOCK_ASSERT(chain);
1410 
1411 	/* Change enabled/disabled sets mask */
1412 	v_set = (V_set_disable | rt->set) & ~rt->new_set;
1413 	v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1414 	IPFW_WLOCK(chain);
1415 	V_set_disable = v_set;
1416 	IPFW_WUNLOCK(chain);
1417 }
1418 
1419 static int
swap_sets(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int mv)1420 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1421 {
1422 	struct opcode_obj_rewrite *rw;
1423 	struct ip_fw *rule;
1424 	int i;
1425 
1426 	IPFW_UH_WLOCK_ASSERT(chain);
1427 
1428 	if (rt->set == rt->new_set) /* nothing to do */
1429 		return (0);
1430 
1431 	if (mv != 0) {
1432 		/*
1433 		 * Berfore moving the rules we need to check that
1434 		 * there aren't any conflicting named objects.
1435 		 */
1436 		for (rw = ctl3_rewriters;
1437 		    rw < ctl3_rewriters + ctl3_rsize; rw++) {
1438 			if (rw->manage_sets == NULL)
1439 				continue;
1440 			i = rw->manage_sets(chain, (uint8_t)rt->set,
1441 			    (uint8_t)rt->new_set, TEST_ALL);
1442 			if (i != 0)
1443 				return (EEXIST);
1444 		}
1445 	}
1446 	/* Swap or move two sets */
1447 	for (i = 0; i < chain->n_rules - 1; i++) {
1448 		rule = chain->map[i];
1449 		if (rule->set == (uint8_t)rt->set)
1450 			rule->set = (uint8_t)rt->new_set;
1451 		else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1452 			rule->set = (uint8_t)rt->set;
1453 	}
1454 	for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1455 		if (rw->manage_sets == NULL)
1456 			continue;
1457 		rw->manage_sets(chain, (uint8_t)rt->set,
1458 		    (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1459 	}
1460 	return (0);
1461 }
1462 
1463 /*
1464  * Swaps or moves set
1465  * Data layout (v0)(current):
1466  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1467  *
1468  * Returns 0 on success.
1469  */
1470 static int
manage_sets(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1471 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1472     struct sockopt_data *sd)
1473 {
1474 	ipfw_range_header *rh;
1475 	int ret;
1476 
1477 	if (sd->valsize != sizeof(*rh))
1478 		return (EINVAL);
1479 
1480 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1481 
1482 	if (rh->range.head.length != sizeof(ipfw_range_tlv))
1483 		return (1);
1484 	/* enable_sets() expects bitmasks. */
1485 	if (op3->opcode != IP_FW_SET_ENABLE &&
1486 	    (rh->range.set >= IPFW_MAX_SETS ||
1487 	    rh->range.new_set >= IPFW_MAX_SETS))
1488 		return (EINVAL);
1489 
1490 	ret = 0;
1491 	IPFW_UH_WLOCK(chain);
1492 	switch (op3->opcode) {
1493 	case IP_FW_SET_SWAP:
1494 	case IP_FW_SET_MOVE:
1495 		ret = swap_sets(chain, &rh->range,
1496 		    op3->opcode == IP_FW_SET_MOVE);
1497 		break;
1498 	case IP_FW_SET_ENABLE:
1499 		enable_sets(chain, &rh->range);
1500 		break;
1501 	}
1502 	IPFW_UH_WUNLOCK(chain);
1503 
1504 	return (ret);
1505 }
1506 
1507 /**
1508  * Remove all rules with given number, or do set manipulation.
1509  * Assumes chain != NULL && *chain != NULL.
1510  *
1511  * The argument is an uint32_t. The low 16 bit are the rule or set number;
1512  * the next 8 bits are the new set; the top 8 bits indicate the command:
1513  *
1514  *	0	delete rules numbered "rulenum"
1515  *	1	delete rules in set "rulenum"
1516  *	2	move rules "rulenum" to set "new_set"
1517  *	3	move rules from set "rulenum" to set "new_set"
1518  *	4	swap sets "rulenum" and "new_set"
1519  *	5	delete rules "rulenum" and set "new_set"
1520  */
1521 static int
del_entry(struct ip_fw_chain * chain,uint32_t arg)1522 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1523 {
1524 	uint32_t num;	/* rule number or old_set */
1525 	uint8_t cmd, new_set;
1526 	int do_del, ndel;
1527 	int error = 0;
1528 	ipfw_range_tlv rt;
1529 
1530 	num = arg & 0xffff;
1531 	cmd = (arg >> 24) & 0xff;
1532 	new_set = (arg >> 16) & 0xff;
1533 
1534 	if (cmd > 5 || new_set > RESVD_SET)
1535 		return EINVAL;
1536 	if (cmd == 0 || cmd == 2 || cmd == 5) {
1537 		if (num >= IPFW_DEFAULT_RULE)
1538 			return EINVAL;
1539 	} else {
1540 		if (num > RESVD_SET)	/* old_set */
1541 			return EINVAL;
1542 	}
1543 
1544 	/* Convert old requests into new representation */
1545 	memset(&rt, 0, sizeof(rt));
1546 	rt.start_rule = num;
1547 	rt.end_rule = num;
1548 	rt.set = num;
1549 	rt.new_set = new_set;
1550 	do_del = 0;
1551 
1552 	switch (cmd) {
1553 	case 0: /* delete rules numbered "rulenum" */
1554 		if (num == 0)
1555 			rt.flags |= IPFW_RCFLAG_ALL;
1556 		else
1557 			rt.flags |= IPFW_RCFLAG_RANGE;
1558 		do_del = 1;
1559 		break;
1560 	case 1: /* delete rules in set "rulenum" */
1561 		rt.flags |= IPFW_RCFLAG_SET;
1562 		do_del = 1;
1563 		break;
1564 	case 5: /* delete rules "rulenum" and set "new_set" */
1565 		rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1566 		rt.set = new_set;
1567 		rt.new_set = 0;
1568 		do_del = 1;
1569 		break;
1570 	case 2: /* move rules "rulenum" to set "new_set" */
1571 		rt.flags |= IPFW_RCFLAG_RANGE;
1572 		break;
1573 	case 3: /* move rules from set "rulenum" to set "new_set" */
1574 		IPFW_UH_WLOCK(chain);
1575 		error = swap_sets(chain, &rt, 1);
1576 		IPFW_UH_WUNLOCK(chain);
1577 		return (error);
1578 	case 4: /* swap sets "rulenum" and "new_set" */
1579 		IPFW_UH_WLOCK(chain);
1580 		error = swap_sets(chain, &rt, 0);
1581 		IPFW_UH_WUNLOCK(chain);
1582 		return (error);
1583 	default:
1584 		return (ENOTSUP);
1585 	}
1586 
1587 	if (do_del != 0) {
1588 		if ((error = delete_range(chain, &rt, &ndel)) != 0)
1589 			return (error);
1590 
1591 		if (ndel == 0 && (cmd != 1 && num != 0))
1592 			return (EINVAL);
1593 
1594 		return (0);
1595 	}
1596 
1597 	return (move_range(chain, &rt));
1598 }
1599 
1600 /**
1601  * Reset some or all counters on firewall rules.
1602  * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1603  * the next 8 bits are the set number, the top 8 bits are the command:
1604  *	0	work with rules from all set's;
1605  *	1	work with rules only from specified set.
1606  * Specified rule number is zero if we want to clear all entries.
1607  * log_only is 1 if we only want to reset logs, zero otherwise.
1608  */
1609 static int
zero_entry(struct ip_fw_chain * chain,u_int32_t arg,int log_only)1610 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1611 {
1612 	struct ip_fw *rule;
1613 	char *msg;
1614 	int i;
1615 
1616 	uint16_t rulenum = arg & 0xffff;
1617 	uint8_t set = (arg >> 16) & 0xff;
1618 	uint8_t cmd = (arg >> 24) & 0xff;
1619 
1620 	if (cmd > 1)
1621 		return (EINVAL);
1622 	if (cmd == 1 && set > RESVD_SET)
1623 		return (EINVAL);
1624 
1625 	IPFW_UH_RLOCK(chain);
1626 	if (rulenum == 0) {
1627 		V_norule_counter = 0;
1628 		for (i = 0; i < chain->n_rules; i++) {
1629 			rule = chain->map[i];
1630 			/* Skip rules not in our set. */
1631 			if (cmd == 1 && rule->set != set)
1632 				continue;
1633 			clear_counters(rule, log_only);
1634 		}
1635 		msg = log_only ? "All logging counts reset" :
1636 		    "Accounting cleared";
1637 	} else {
1638 		int cleared = 0;
1639 		for (i = 0; i < chain->n_rules; i++) {
1640 			rule = chain->map[i];
1641 			if (rule->rulenum == rulenum) {
1642 				if (cmd == 0 || rule->set == set)
1643 					clear_counters(rule, log_only);
1644 				cleared = 1;
1645 			}
1646 			if (rule->rulenum > rulenum)
1647 				break;
1648 		}
1649 		if (!cleared) {	/* we did not find any matching rules */
1650 			IPFW_UH_RUNLOCK(chain);
1651 			return (EINVAL);
1652 		}
1653 		msg = log_only ? "logging count reset" : "cleared";
1654 	}
1655 	IPFW_UH_RUNLOCK(chain);
1656 
1657 	if (V_fw_verbose) {
1658 		int lev = LOG_SECURITY | LOG_NOTICE;
1659 
1660 		if (rulenum)
1661 			log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1662 		else
1663 			log(lev, "ipfw: %s.\n", msg);
1664 	}
1665 	return (0);
1666 }
1667 
1668 /*
1669  * Check rule head in FreeBSD11 format
1670  *
1671  */
1672 static int
check_ipfw_rule1(struct ip_fw_rule * rule,int size,struct rule_check_info * ci)1673 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1674     struct rule_check_info *ci)
1675 {
1676 	int l;
1677 
1678 	if (size < sizeof(*rule)) {
1679 		printf("ipfw: rule too short\n");
1680 		return (EINVAL);
1681 	}
1682 
1683 	/* Check for valid cmd_len */
1684 	l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1685 	if (l != size) {
1686 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1687 		return (EINVAL);
1688 	}
1689 	if (rule->act_ofs >= rule->cmd_len) {
1690 		printf("ipfw: bogus action offset (%u > %u)\n",
1691 		    rule->act_ofs, rule->cmd_len - 1);
1692 		return (EINVAL);
1693 	}
1694 
1695 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1696 		return (EINVAL);
1697 
1698 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1699 }
1700 
1701 /*
1702  * Check rule head in FreeBSD8 format
1703  *
1704  */
1705 static int
check_ipfw_rule0(struct ip_fw_rule0 * rule,int size,struct rule_check_info * ci)1706 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1707     struct rule_check_info *ci)
1708 {
1709 	int l;
1710 
1711 	if (size < sizeof(*rule)) {
1712 		printf("ipfw: rule too short\n");
1713 		return (EINVAL);
1714 	}
1715 
1716 	/* Check for valid cmd_len */
1717 	l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1718 	if (l != size) {
1719 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1720 		return (EINVAL);
1721 	}
1722 	if (rule->act_ofs >= rule->cmd_len) {
1723 		printf("ipfw: bogus action offset (%u > %u)\n",
1724 		    rule->act_ofs, rule->cmd_len - 1);
1725 		return (EINVAL);
1726 	}
1727 
1728 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1729 		return (EINVAL);
1730 
1731 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1732 }
1733 
1734 static int
check_ipfw_rule_body(ipfw_insn * cmd,int cmd_len,struct rule_check_info * ci)1735 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1736 {
1737 	int cmdlen, l;
1738 	int have_action;
1739 
1740 	have_action = 0;
1741 
1742 	/*
1743 	 * Now go for the individual checks. Very simple ones, basically only
1744 	 * instruction sizes.
1745 	 */
1746 	for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1747 		cmdlen = F_LEN(cmd);
1748 		if (cmdlen > l) {
1749 			printf("ipfw: opcode %d size truncated\n",
1750 			    cmd->opcode);
1751 			return EINVAL;
1752 		}
1753 		switch (cmd->opcode) {
1754 		case O_PROBE_STATE:
1755 		case O_KEEP_STATE:
1756 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1757 				goto bad_size;
1758 			ci->object_opcodes++;
1759 			break;
1760 		case O_PROTO:
1761 		case O_IP_SRC_ME:
1762 		case O_IP_DST_ME:
1763 		case O_LAYER2:
1764 		case O_IN:
1765 		case O_FRAG:
1766 		case O_DIVERTED:
1767 		case O_IPOPT:
1768 		case O_IPTOS:
1769 		case O_IPPRECEDENCE:
1770 		case O_IPVER:
1771 		case O_SOCKARG:
1772 		case O_TCPFLAGS:
1773 		case O_TCPOPTS:
1774 		case O_ESTAB:
1775 		case O_VERREVPATH:
1776 		case O_VERSRCREACH:
1777 		case O_ANTISPOOF:
1778 		case O_IPSEC:
1779 #ifdef INET6
1780 		case O_IP6_SRC_ME:
1781 		case O_IP6_DST_ME:
1782 		case O_EXT_HDR:
1783 		case O_IP6:
1784 #endif
1785 		case O_IP4:
1786 		case O_TAG:
1787 		case O_SKIP_ACTION:
1788 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1789 				goto bad_size;
1790 			break;
1791 
1792 		case O_EXTERNAL_ACTION:
1793 			if (cmd->arg1 == 0 ||
1794 			    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1795 				printf("ipfw: invalid external "
1796 				    "action opcode\n");
1797 				return (EINVAL);
1798 			}
1799 			ci->object_opcodes++;
1800 			/*
1801 			 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1802 			 * opcode?
1803 			 */
1804 			if (l != cmdlen) {
1805 				l -= cmdlen;
1806 				cmd += cmdlen;
1807 				cmdlen = F_LEN(cmd);
1808 				if (cmd->opcode == O_EXTERNAL_DATA)
1809 					goto check_action;
1810 				if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1811 					printf("ipfw: invalid opcode "
1812 					    "next to external action %u\n",
1813 					    cmd->opcode);
1814 					return (EINVAL);
1815 				}
1816 				if (cmd->arg1 == 0 ||
1817 				    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1818 					printf("ipfw: invalid external "
1819 					    "action instance opcode\n");
1820 					return (EINVAL);
1821 				}
1822 				ci->object_opcodes++;
1823 			}
1824 			goto check_action;
1825 
1826 		case O_FIB:
1827 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1828 				goto bad_size;
1829 			if (cmd->arg1 >= rt_numfibs) {
1830 				printf("ipfw: invalid fib number %d\n",
1831 					cmd->arg1);
1832 				return EINVAL;
1833 			}
1834 			break;
1835 
1836 		case O_SETFIB:
1837 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1838 				goto bad_size;
1839 			if ((cmd->arg1 != IP_FW_TARG) &&
1840 			    ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1841 				printf("ipfw: invalid fib number %d\n",
1842 					cmd->arg1 & 0x7FFF);
1843 				return EINVAL;
1844 			}
1845 			goto check_action;
1846 
1847 		case O_UID:
1848 		case O_GID:
1849 		case O_JAIL:
1850 		case O_IP_SRC:
1851 		case O_IP_DST:
1852 		case O_TCPSEQ:
1853 		case O_TCPACK:
1854 		case O_PROB:
1855 		case O_ICMPTYPE:
1856 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1857 				goto bad_size;
1858 			break;
1859 
1860 		case O_LIMIT:
1861 			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1862 				goto bad_size;
1863 			ci->object_opcodes++;
1864 			break;
1865 
1866 		case O_LOG:
1867 			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1868 				goto bad_size;
1869 
1870 			((ipfw_insn_log *)cmd)->log_left =
1871 			    ((ipfw_insn_log *)cmd)->max_log;
1872 
1873 			break;
1874 
1875 		case O_IP_SRC_MASK:
1876 		case O_IP_DST_MASK:
1877 			/* only odd command lengths */
1878 			if ((cmdlen & 1) == 0)
1879 				goto bad_size;
1880 			break;
1881 
1882 		case O_IP_SRC_SET:
1883 		case O_IP_DST_SET:
1884 			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1885 				printf("ipfw: invalid set size %d\n",
1886 					cmd->arg1);
1887 				return EINVAL;
1888 			}
1889 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1890 			    (cmd->arg1+31)/32 )
1891 				goto bad_size;
1892 			break;
1893 
1894 		case O_IP_SRC_LOOKUP:
1895 			if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1896 				goto bad_size;
1897 		case O_IP_DST_LOOKUP:
1898 			if (cmd->arg1 >= V_fw_tables_max) {
1899 				printf("ipfw: invalid table number %d\n",
1900 				    cmd->arg1);
1901 				return (EINVAL);
1902 			}
1903 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1904 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1905 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1906 				goto bad_size;
1907 			ci->object_opcodes++;
1908 			break;
1909 		case O_IP_FLOW_LOOKUP:
1910 		case O_MAC_DST_LOOKUP:
1911 		case O_MAC_SRC_LOOKUP:
1912 			if (cmd->arg1 >= V_fw_tables_max) {
1913 				printf("ipfw: invalid table number %d\n",
1914 				    cmd->arg1);
1915 				return (EINVAL);
1916 			}
1917 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1918 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1919 				goto bad_size;
1920 			ci->object_opcodes++;
1921 			break;
1922 		case O_MACADDR2:
1923 			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1924 				goto bad_size;
1925 			break;
1926 
1927 		case O_NOP:
1928 		case O_IPID:
1929 		case O_IPTTL:
1930 		case O_IPLEN:
1931 		case O_TCPDATALEN:
1932 		case O_TCPMSS:
1933 		case O_TCPWIN:
1934 		case O_TAGGED:
1935 			if (cmdlen < 1 || cmdlen > 31)
1936 				goto bad_size;
1937 			break;
1938 
1939 		case O_DSCP:
1940 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1941 				goto bad_size;
1942 			break;
1943 
1944 		case O_MAC_TYPE:
1945 		case O_IP_SRCPORT:
1946 		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1947 			if (cmdlen < 2 || cmdlen > 31)
1948 				goto bad_size;
1949 			break;
1950 
1951 		case O_RECV:
1952 		case O_XMIT:
1953 		case O_VIA:
1954 			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1955 				goto bad_size;
1956 			ci->object_opcodes++;
1957 			break;
1958 
1959 		case O_ALTQ:
1960 			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1961 				goto bad_size;
1962 			break;
1963 
1964 		case O_PIPE:
1965 		case O_QUEUE:
1966 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1967 				goto bad_size;
1968 			goto check_action;
1969 
1970 		case O_FORWARD_IP:
1971 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1972 				goto bad_size;
1973 			goto check_action;
1974 #ifdef INET6
1975 		case O_FORWARD_IP6:
1976 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1977 				goto bad_size;
1978 			goto check_action;
1979 #endif /* INET6 */
1980 
1981 		case O_DIVERT:
1982 		case O_TEE:
1983 			if (ip_divert_ptr == NULL)
1984 				return EINVAL;
1985 			else
1986 				goto check_size;
1987 		case O_NETGRAPH:
1988 		case O_NGTEE:
1989 			if (ng_ipfw_input_p == NULL)
1990 				return EINVAL;
1991 			else
1992 				goto check_size;
1993 		case O_NAT:
1994 			if (!IPFW_NAT_LOADED)
1995 				return EINVAL;
1996 			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1997  				goto bad_size;
1998  			goto check_action;
1999 		case O_CHECK_STATE:
2000 			ci->object_opcodes++;
2001 			/* FALLTHROUGH */
2002 		case O_FORWARD_MAC: /* XXX not implemented yet */
2003 		case O_COUNT:
2004 		case O_ACCEPT:
2005 		case O_DENY:
2006 		case O_REJECT:
2007 		case O_SETDSCP:
2008 #ifdef INET6
2009 		case O_UNREACH6:
2010 #endif
2011 		case O_SKIPTO:
2012 		case O_REASS:
2013 		case O_CALLRETURN:
2014 check_size:
2015 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2016 				goto bad_size;
2017 check_action:
2018 			if (have_action) {
2019 				printf("ipfw: opcode %d, multiple actions"
2020 					" not allowed\n",
2021 					cmd->opcode);
2022 				return (EINVAL);
2023 			}
2024 			have_action = 1;
2025 			if (l != cmdlen) {
2026 				printf("ipfw: opcode %d, action must be"
2027 					" last opcode\n",
2028 					cmd->opcode);
2029 				return (EINVAL);
2030 			}
2031 			break;
2032 #ifdef INET6
2033 		case O_IP6_SRC:
2034 		case O_IP6_DST:
2035 			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2036 			    F_INSN_SIZE(ipfw_insn))
2037 				goto bad_size;
2038 			break;
2039 
2040 		case O_FLOW6ID:
2041 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2042 			    ((ipfw_insn_u32 *)cmd)->o.arg1)
2043 				goto bad_size;
2044 			break;
2045 
2046 		case O_IP6_SRC_MASK:
2047 		case O_IP6_DST_MASK:
2048 			if ( !(cmdlen & 1) || cmdlen > 127)
2049 				goto bad_size;
2050 			break;
2051 		case O_ICMP6TYPE:
2052 			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2053 				goto bad_size;
2054 			break;
2055 #endif
2056 
2057 		default:
2058 			switch (cmd->opcode) {
2059 #ifndef INET6
2060 			case O_IP6_SRC_ME:
2061 			case O_IP6_DST_ME:
2062 			case O_EXT_HDR:
2063 			case O_IP6:
2064 			case O_UNREACH6:
2065 			case O_IP6_SRC:
2066 			case O_IP6_DST:
2067 			case O_FLOW6ID:
2068 			case O_IP6_SRC_MASK:
2069 			case O_IP6_DST_MASK:
2070 			case O_ICMP6TYPE:
2071 				printf("ipfw: no IPv6 support in kernel\n");
2072 				return (EPROTONOSUPPORT);
2073 #endif
2074 			default:
2075 				printf("ipfw: opcode %d, unknown opcode\n",
2076 					cmd->opcode);
2077 				return (EINVAL);
2078 			}
2079 		}
2080 	}
2081 	if (have_action == 0) {
2082 		printf("ipfw: missing action\n");
2083 		return (EINVAL);
2084 	}
2085 	return 0;
2086 
2087 bad_size:
2088 	printf("ipfw: opcode %d size %d wrong\n",
2089 		cmd->opcode, cmdlen);
2090 	return (EINVAL);
2091 }
2092 
2093 /*
2094  * Translation of requests for compatibility with FreeBSD 7.2/8.
2095  * a static variable tells us if we have an old client from userland,
2096  * and if necessary we translate requests and responses between the
2097  * two formats.
2098  */
2099 static int is7 = 0;
2100 
2101 struct ip_fw7 {
2102 	struct ip_fw7	*next;		/* linked list of rules     */
2103 	struct ip_fw7	*next_rule;	/* ptr to next [skipto] rule    */
2104 	/* 'next_rule' is used to pass up 'set_disable' status      */
2105 
2106 	uint16_t	act_ofs;	/* offset of action in 32-bit units */
2107 	uint16_t	cmd_len;	/* # of 32-bit words in cmd */
2108 	uint16_t	rulenum;	/* rule number          */
2109 	uint8_t		set;		/* rule set (0..31)     */
2110 	// #define RESVD_SET   31  /* set for default and persistent rules */
2111 	uint8_t		_pad;		/* padding          */
2112 	// uint32_t        id;             /* rule id, only in v.8 */
2113 	/* These fields are present in all rules.           */
2114 	uint64_t	pcnt;		/* Packet counter       */
2115 	uint64_t	bcnt;		/* Byte counter         */
2116 	uint32_t	timestamp;	/* tv_sec of last match     */
2117 
2118 	ipfw_insn	cmd[1];		/* storage for commands     */
2119 };
2120 
2121 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2122 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2123 
2124 #ifndef RULESIZE7
2125 #define RULESIZE7(rule)  (sizeof(struct ip_fw7) + \
2126 	((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2127 #endif
2128 
2129 /*
2130  * Copy the static and dynamic rules to the supplied buffer
2131  * and return the amount of space actually used.
2132  * Must be run under IPFW_UH_RLOCK
2133  */
2134 static size_t
ipfw_getrules(struct ip_fw_chain * chain,void * buf,size_t space)2135 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2136 {
2137 	char *bp = buf;
2138 	char *ep = bp + space;
2139 	struct ip_fw *rule;
2140 	struct ip_fw_rule0 *dst;
2141 	struct timeval boottime;
2142 	int error, i, l, warnflag;
2143 	time_t	boot_seconds;
2144 
2145 	warnflag = 0;
2146 
2147 	getboottime(&boottime);
2148         boot_seconds = boottime.tv_sec;
2149 	for (i = 0; i < chain->n_rules; i++) {
2150 		rule = chain->map[i];
2151 
2152 		if (is7) {
2153 		    /* Convert rule to FreeBSd 7.2 format */
2154 		    l = RULESIZE7(rule);
2155 		    if (bp + l + sizeof(uint32_t) <= ep) {
2156 			bcopy(rule, bp, l + sizeof(uint32_t));
2157 			error = set_legacy_obj_kidx(chain,
2158 			    (struct ip_fw_rule0 *)bp);
2159 			if (error != 0)
2160 				return (0);
2161 			error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2162 			if (error)
2163 				return 0; /*XXX correct? */
2164 			/*
2165 			 * XXX HACK. Store the disable mask in the "next"
2166 			 * pointer in a wild attempt to keep the ABI the same.
2167 			 * Why do we do this on EVERY rule?
2168 			 */
2169 			bcopy(&V_set_disable,
2170 				&(((struct ip_fw7 *)bp)->next_rule),
2171 				sizeof(V_set_disable));
2172 			if (((struct ip_fw7 *)bp)->timestamp)
2173 			    ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2174 			bp += l;
2175 		    }
2176 		    continue; /* go to next rule */
2177 		}
2178 
2179 		l = RULEUSIZE0(rule);
2180 		if (bp + l > ep) { /* should not happen */
2181 			printf("overflow dumping static rules\n");
2182 			break;
2183 		}
2184 		dst = (struct ip_fw_rule0 *)bp;
2185 		export_rule0(rule, dst, l);
2186 		error = set_legacy_obj_kidx(chain, dst);
2187 
2188 		/*
2189 		 * XXX HACK. Store the disable mask in the "next"
2190 		 * pointer in a wild attempt to keep the ABI the same.
2191 		 * Why do we do this on EVERY rule?
2192 		 *
2193 		 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2194 		 * so we need to fail _after_ saving at least one mask.
2195 		 */
2196 		bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2197 		if (dst->timestamp)
2198 			dst->timestamp += boot_seconds;
2199 		bp += l;
2200 
2201 		if (error != 0) {
2202 			if (error == 2) {
2203 				/* Non-fatal table rewrite error. */
2204 				warnflag = 1;
2205 				continue;
2206 			}
2207 			printf("Stop on rule %d. Fail to convert table\n",
2208 			    rule->rulenum);
2209 			break;
2210 		}
2211 	}
2212 	if (warnflag != 0)
2213 		printf("ipfw: process %s is using legacy interfaces,"
2214 		    " consider rebuilding\n", "");
2215 	ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2216 	return (bp - (char *)buf);
2217 }
2218 
2219 struct dump_args {
2220 	uint32_t	b;	/* start rule */
2221 	uint32_t	e;	/* end rule */
2222 	uint32_t	rcount;	/* number of rules */
2223 	uint32_t	rsize;	/* rules size */
2224 	uint32_t	tcount;	/* number of tables */
2225 	int		rcounters;	/* counters */
2226 	uint32_t	*bmask;	/* index bitmask of used named objects */
2227 };
2228 
2229 void
ipfw_export_obj_ntlv(struct named_object * no,ipfw_obj_ntlv * ntlv)2230 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2231 {
2232 
2233 	ntlv->head.type = no->etlv;
2234 	ntlv->head.length = sizeof(*ntlv);
2235 	ntlv->idx = no->kidx;
2236 	strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2237 }
2238 
2239 /*
2240  * Export named object info in instance @ni, identified by @kidx
2241  * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2242  *
2243  * Returns 0 on success.
2244  */
2245 static int
export_objhash_ntlv(struct namedobj_instance * ni,uint16_t kidx,struct sockopt_data * sd)2246 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2247     struct sockopt_data *sd)
2248 {
2249 	struct named_object *no;
2250 	ipfw_obj_ntlv *ntlv;
2251 
2252 	no = ipfw_objhash_lookup_kidx(ni, kidx);
2253 	KASSERT(no != NULL, ("invalid object kernel index passed"));
2254 
2255 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2256 	if (ntlv == NULL)
2257 		return (ENOMEM);
2258 
2259 	ipfw_export_obj_ntlv(no, ntlv);
2260 	return (0);
2261 }
2262 
2263 static int
export_named_objects(struct namedobj_instance * ni,struct dump_args * da,struct sockopt_data * sd)2264 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2265     struct sockopt_data *sd)
2266 {
2267 	int error, i;
2268 
2269 	for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2270 		if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2271 			continue;
2272 		if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2273 			return (error);
2274 		da->tcount--;
2275 	}
2276 	return (0);
2277 }
2278 
2279 static int
dump_named_objects(struct ip_fw_chain * ch,struct dump_args * da,struct sockopt_data * sd)2280 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2281     struct sockopt_data *sd)
2282 {
2283 	ipfw_obj_ctlv *ctlv;
2284 	int error;
2285 
2286 	MPASS(da->tcount > 0);
2287 	/* Header first */
2288 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2289 	if (ctlv == NULL)
2290 		return (ENOMEM);
2291 	ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2292 	ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2293 	    sizeof(*ctlv);
2294 	ctlv->count = da->tcount;
2295 	ctlv->objsize = sizeof(ipfw_obj_ntlv);
2296 
2297 	/* Dump table names first (if any) */
2298 	error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2299 	if (error != 0)
2300 		return (error);
2301 	/* Then dump another named objects */
2302 	da->bmask += IPFW_TABLES_MAX / 32;
2303 	return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2304 }
2305 
2306 /*
2307  * Dumps static rules with table TLVs in buffer @sd.
2308  *
2309  * Returns 0 on success.
2310  */
2311 static int
dump_static_rules(struct ip_fw_chain * chain,struct dump_args * da,struct sockopt_data * sd)2312 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2313     struct sockopt_data *sd)
2314 {
2315 	ipfw_obj_ctlv *ctlv;
2316 	struct ip_fw *krule;
2317 	caddr_t dst;
2318 	int i, l;
2319 
2320 	/* Dump rules */
2321 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2322 	if (ctlv == NULL)
2323 		return (ENOMEM);
2324 	ctlv->head.type = IPFW_TLV_RULE_LIST;
2325 	ctlv->head.length = da->rsize + sizeof(*ctlv);
2326 	ctlv->count = da->rcount;
2327 
2328 	for (i = da->b; i < da->e; i++) {
2329 		krule = chain->map[i];
2330 
2331 		l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2332 		if (da->rcounters != 0)
2333 			l += sizeof(struct ip_fw_bcounter);
2334 		dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2335 		if (dst == NULL)
2336 			return (ENOMEM);
2337 
2338 		export_rule1(krule, dst, l, da->rcounters);
2339 	}
2340 
2341 	return (0);
2342 }
2343 
2344 int
ipfw_mark_object_kidx(uint32_t * bmask,uint16_t etlv,uint16_t kidx)2345 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2346 {
2347 	uint32_t bidx;
2348 
2349 	/*
2350 	 * Maintain separate bitmasks for table and non-table objects.
2351 	 */
2352 	bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2353 	bidx += kidx / 32;
2354 	if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2355 		return (0);
2356 
2357 	bmask[bidx] |= 1 << (kidx % 32);
2358 	return (1);
2359 }
2360 
2361 /*
2362  * Marks every object index used in @rule with bit in @bmask.
2363  * Used to generate bitmask of referenced tables/objects for given ruleset
2364  * or its part.
2365  */
2366 static void
mark_rule_objects(struct ip_fw_chain * ch,struct ip_fw * rule,struct dump_args * da)2367 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2368     struct dump_args *da)
2369 {
2370 	struct opcode_obj_rewrite *rw;
2371 	ipfw_insn *cmd;
2372 	int cmdlen, l;
2373 	uint16_t kidx;
2374 	uint8_t subtype;
2375 
2376 	l = rule->cmd_len;
2377 	cmd = rule->cmd;
2378 	cmdlen = 0;
2379 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2380 		cmdlen = F_LEN(cmd);
2381 
2382 		rw = find_op_rw(cmd, &kidx, &subtype);
2383 		if (rw == NULL)
2384 			continue;
2385 
2386 		if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2387 			da->tcount++;
2388 	}
2389 }
2390 
2391 /*
2392  * Dumps requested objects data
2393  * Data layout (version 0)(current):
2394  * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2395  *   size = ipfw_cfg_lheader.size
2396  * Reply: [ ipfw_cfg_lheader
2397  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2398  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2399  *     ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2400  *   ] (optional)
2401  *   [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2402  * ]
2403  * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2404  * The rest (size, count) are set to zero and needs to be ignored.
2405  *
2406  * Returns 0 on success.
2407  */
2408 static int
dump_config(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2409 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2410     struct sockopt_data *sd)
2411 {
2412 	struct dump_args da;
2413 	ipfw_cfg_lheader *hdr;
2414 	struct ip_fw *rule;
2415 	size_t sz, rnum;
2416 	uint32_t hdr_flags, *bmask;
2417 	int error, i;
2418 
2419 	hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2420 	if (hdr == NULL)
2421 		return (EINVAL);
2422 
2423 	error = 0;
2424 	bmask = NULL;
2425 	memset(&da, 0, sizeof(da));
2426 	/*
2427 	 * Allocate needed state.
2428 	 * Note we allocate 2xspace mask, for table & srv
2429 	 */
2430 	if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2431 		da.bmask = bmask = malloc(
2432 		    sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2433 		    M_WAITOK | M_ZERO);
2434 	IPFW_UH_RLOCK(chain);
2435 
2436 	/*
2437 	 * STAGE 1: Determine size/count for objects in range.
2438 	 * Prepare used tables bitmask.
2439 	 */
2440 	sz = sizeof(ipfw_cfg_lheader);
2441 	da.e = chain->n_rules;
2442 
2443 	if (hdr->end_rule != 0) {
2444 		/* Handle custom range */
2445 		if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2446 			rnum = IPFW_DEFAULT_RULE;
2447 		da.b = ipfw_find_rule(chain, rnum, 0);
2448 		rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2449 		    hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2450 		da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2451 	}
2452 
2453 	if (hdr->flags & IPFW_CFG_GET_STATIC) {
2454 		for (i = da.b; i < da.e; i++) {
2455 			rule = chain->map[i];
2456 			da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2457 			da.rcount++;
2458 			/* Update bitmask of used objects for given range */
2459 			mark_rule_objects(chain, rule, &da);
2460 		}
2461 		/* Add counters if requested */
2462 		if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2463 			da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2464 			da.rcounters = 1;
2465 		}
2466 		sz += da.rsize + sizeof(ipfw_obj_ctlv);
2467 	}
2468 
2469 	if (hdr->flags & IPFW_CFG_GET_STATES) {
2470 		sz += sizeof(ipfw_obj_ctlv) +
2471 		    ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2472 		da.tcount += i;
2473 	}
2474 
2475 	if (da.tcount > 0)
2476 		sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2477 		    sizeof(ipfw_obj_ctlv);
2478 
2479 	/*
2480 	 * Fill header anyway.
2481 	 * Note we have to save header fields to stable storage
2482 	 * buffer inside @sd can be flushed after dumping rules
2483 	 */
2484 	hdr->size = sz;
2485 	hdr->set_mask = ~V_set_disable;
2486 	hdr_flags = hdr->flags;
2487 	hdr = NULL;
2488 
2489 	if (sd->valsize < sz) {
2490 		error = ENOMEM;
2491 		goto cleanup;
2492 	}
2493 
2494 	/* STAGE2: Store actual data */
2495 	if (da.tcount > 0) {
2496 		error = dump_named_objects(chain, &da, sd);
2497 		if (error != 0)
2498 			goto cleanup;
2499 	}
2500 
2501 	if (hdr_flags & IPFW_CFG_GET_STATIC) {
2502 		error = dump_static_rules(chain, &da, sd);
2503 		if (error != 0)
2504 			goto cleanup;
2505 	}
2506 
2507 	if (hdr_flags & IPFW_CFG_GET_STATES)
2508 		error = ipfw_dump_states(chain, sd);
2509 
2510 cleanup:
2511 	IPFW_UH_RUNLOCK(chain);
2512 
2513 	if (bmask != NULL)
2514 		free(bmask, M_TEMP);
2515 
2516 	return (error);
2517 }
2518 
2519 int
ipfw_check_object_name_generic(const char * name)2520 ipfw_check_object_name_generic(const char *name)
2521 {
2522 	int nsize;
2523 
2524 	nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2525 	if (strnlen(name, nsize) == nsize)
2526 		return (EINVAL);
2527 	if (name[0] == '\0')
2528 		return (EINVAL);
2529 	return (0);
2530 }
2531 
2532 /*
2533  * Creates non-existent objects referenced by rule.
2534  *
2535  * Return 0 on success.
2536  */
2537 int
create_objects_compat(struct ip_fw_chain * ch,ipfw_insn * cmd,struct obj_idx * oib,struct obj_idx * pidx,struct tid_info * ti)2538 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2539     struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2540 {
2541 	struct opcode_obj_rewrite *rw;
2542 	struct obj_idx *p;
2543 	uint16_t kidx;
2544 	int error;
2545 
2546 	/*
2547 	 * Compatibility stuff: do actual creation for non-existing,
2548 	 * but referenced objects.
2549 	 */
2550 	for (p = oib; p < pidx; p++) {
2551 		if (p->kidx != 0)
2552 			continue;
2553 
2554 		ti->uidx = p->uidx;
2555 		ti->type = p->type;
2556 		ti->atype = 0;
2557 
2558 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2559 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2560 		    (cmd + p->off)->opcode));
2561 
2562 		if (rw->create_object == NULL)
2563 			error = EOPNOTSUPP;
2564 		else
2565 			error = rw->create_object(ch, ti, &kidx);
2566 		if (error == 0) {
2567 			p->kidx = kidx;
2568 			continue;
2569 		}
2570 
2571 		/*
2572 		 * Error happened. We have to rollback everything.
2573 		 * Drop all already acquired references.
2574 		 */
2575 		IPFW_UH_WLOCK(ch);
2576 		unref_oib_objects(ch, cmd, oib, pidx);
2577 		IPFW_UH_WUNLOCK(ch);
2578 
2579 		return (error);
2580 	}
2581 
2582 	return (0);
2583 }
2584 
2585 /*
2586  * Compatibility function for old ipfw(8) binaries.
2587  * Rewrites table/nat kernel indices with userland ones.
2588  * Convert tables matching '/^\d+$/' to their atoi() value.
2589  * Use number 65535 for other tables.
2590  *
2591  * Returns 0 on success.
2592  */
2593 static int
set_legacy_obj_kidx(struct ip_fw_chain * ch,struct ip_fw_rule0 * rule)2594 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2595 {
2596 	struct opcode_obj_rewrite *rw;
2597 	struct named_object *no;
2598 	ipfw_insn *cmd;
2599 	char *end;
2600 	long val;
2601 	int cmdlen, error, l;
2602 	uint16_t kidx, uidx;
2603 	uint8_t subtype;
2604 
2605 	error = 0;
2606 
2607 	l = rule->cmd_len;
2608 	cmd = rule->cmd;
2609 	cmdlen = 0;
2610 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2611 		cmdlen = F_LEN(cmd);
2612 
2613 		/* Check if is index in given opcode */
2614 		rw = find_op_rw(cmd, &kidx, &subtype);
2615 		if (rw == NULL)
2616 			continue;
2617 
2618 		/* Try to find referenced kernel object */
2619 		no = rw->find_bykidx(ch, kidx);
2620 		if (no == NULL)
2621 			continue;
2622 
2623 		val = strtol(no->name, &end, 10);
2624 		if (*end == '\0' && val < 65535) {
2625 			uidx = val;
2626 		} else {
2627 			/*
2628 			 * We are called via legacy opcode.
2629 			 * Save error and show table as fake number
2630 			 * not to make ipfw(8) hang.
2631 			 */
2632 			uidx = 65535;
2633 			error = 2;
2634 		}
2635 
2636 		rw->update(cmd, uidx);
2637 	}
2638 
2639 	return (error);
2640 }
2641 
2642 /*
2643  * Unreferences all already-referenced objects in given @cmd rule,
2644  * using information in @oib.
2645  *
2646  * Used to rollback partially converted rule on error.
2647  */
2648 static void
unref_oib_objects(struct ip_fw_chain * ch,ipfw_insn * cmd,struct obj_idx * oib,struct obj_idx * end)2649 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2650     struct obj_idx *end)
2651 {
2652 	struct opcode_obj_rewrite *rw;
2653 	struct named_object *no;
2654 	struct obj_idx *p;
2655 
2656 	IPFW_UH_WLOCK_ASSERT(ch);
2657 
2658 	for (p = oib; p < end; p++) {
2659 		if (p->kidx == 0)
2660 			continue;
2661 
2662 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2663 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2664 		    (cmd + p->off)->opcode));
2665 
2666 		/* Find & unref by existing idx */
2667 		no = rw->find_bykidx(ch, p->kidx);
2668 		KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2669 		no->refcnt--;
2670 	}
2671 }
2672 
2673 /*
2674  * Remove references from every object used in @rule.
2675  * Used at rule removal code.
2676  */
2677 static void
unref_rule_objects(struct ip_fw_chain * ch,struct ip_fw * rule)2678 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2679 {
2680 	struct opcode_obj_rewrite *rw;
2681 	struct named_object *no;
2682 	ipfw_insn *cmd;
2683 	int cmdlen, l;
2684 	uint16_t kidx;
2685 	uint8_t subtype;
2686 
2687 	IPFW_UH_WLOCK_ASSERT(ch);
2688 
2689 	l = rule->cmd_len;
2690 	cmd = rule->cmd;
2691 	cmdlen = 0;
2692 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2693 		cmdlen = F_LEN(cmd);
2694 
2695 		rw = find_op_rw(cmd, &kidx, &subtype);
2696 		if (rw == NULL)
2697 			continue;
2698 		no = rw->find_bykidx(ch, kidx);
2699 
2700 		KASSERT(no != NULL, ("object id %d not found", kidx));
2701 		KASSERT(no->subtype == subtype,
2702 		    ("wrong type %d (%d) for object id %d",
2703 		    no->subtype, subtype, kidx));
2704 		KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2705 		    kidx, no->refcnt));
2706 
2707 		if (no->refcnt == 1 && rw->destroy_object != NULL)
2708 			rw->destroy_object(ch, no);
2709 		else
2710 			no->refcnt--;
2711 	}
2712 }
2713 
2714 /*
2715  * Find and reference object (if any) stored in instruction @cmd.
2716  *
2717  * Saves object info in @pidx, sets
2718  *  - @unresolved to 1 if object should exists but not found
2719  *
2720  * Returns non-zero value in case of error.
2721  */
2722 static int
ref_opcode_object(struct ip_fw_chain * ch,ipfw_insn * cmd,struct tid_info * ti,struct obj_idx * pidx,int * unresolved)2723 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2724     struct obj_idx *pidx, int *unresolved)
2725 {
2726 	struct named_object *no;
2727 	struct opcode_obj_rewrite *rw;
2728 	int error;
2729 
2730 	/* Check if this opcode is candidate for rewrite */
2731 	rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2732 	if (rw == NULL)
2733 		return (0);
2734 
2735 	/* Need to rewrite. Save necessary fields */
2736 	pidx->uidx = ti->uidx;
2737 	pidx->type = ti->type;
2738 
2739 	/* Try to find referenced kernel object */
2740 	error = rw->find_byname(ch, ti, &no);
2741 	if (error != 0)
2742 		return (error);
2743 	if (no == NULL) {
2744 		/*
2745 		 * Report about unresolved object for automaic
2746 		 * creation.
2747 		 */
2748 		*unresolved = 1;
2749 		return (0);
2750 	}
2751 
2752 	/*
2753 	 * Object is already exist.
2754 	 * Its subtype should match with expected value.
2755 	 */
2756 	if (ti->type != no->subtype)
2757 		return (EINVAL);
2758 
2759 	/* Bump refcount and update kidx. */
2760 	no->refcnt++;
2761 	rw->update(cmd, no->kidx);
2762 	return (0);
2763 }
2764 
2765 /*
2766  * Finds and bumps refcount for objects referenced by given @rule.
2767  * Auto-creates non-existing tables.
2768  * Fills in @oib array with userland/kernel indexes.
2769  *
2770  * Returns 0 on success.
2771  */
2772 static int
ref_rule_objects(struct ip_fw_chain * ch,struct ip_fw * rule,struct rule_check_info * ci,struct obj_idx * oib,struct tid_info * ti)2773 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2774     struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2775 {
2776 	struct obj_idx *pidx;
2777 	ipfw_insn *cmd;
2778 	int cmdlen, error, l, unresolved;
2779 
2780 	pidx = oib;
2781 	l = rule->cmd_len;
2782 	cmd = rule->cmd;
2783 	cmdlen = 0;
2784 	error = 0;
2785 
2786 	IPFW_UH_WLOCK(ch);
2787 
2788 	/* Increase refcount on each existing referenced table. */
2789 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2790 		cmdlen = F_LEN(cmd);
2791 		unresolved = 0;
2792 
2793 		error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2794 		if (error != 0)
2795 			break;
2796 		/*
2797 		 * Compatibility stuff for old clients:
2798 		 * prepare to automaitcally create non-existing objects.
2799 		 */
2800 		if (unresolved != 0) {
2801 			pidx->off = rule->cmd_len - l;
2802 			pidx++;
2803 		}
2804 	}
2805 
2806 	if (error != 0) {
2807 		/* Unref everything we have already done */
2808 		unref_oib_objects(ch, rule->cmd, oib, pidx);
2809 		IPFW_UH_WUNLOCK(ch);
2810 		return (error);
2811 	}
2812 	IPFW_UH_WUNLOCK(ch);
2813 
2814 	/* Perform auto-creation for non-existing objects */
2815 	if (pidx != oib)
2816 		error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2817 
2818 	/* Calculate real number of dynamic objects */
2819 	ci->object_opcodes = (uint16_t)(pidx - oib);
2820 
2821 	return (error);
2822 }
2823 
2824 /*
2825  * Checks is opcode is referencing table of appropriate type.
2826  * Adds reference count for found table if true.
2827  * Rewrites user-supplied opcode values with kernel ones.
2828  *
2829  * Returns 0 on success and appropriate error code otherwise.
2830  */
2831 static int
rewrite_rule_uidx(struct ip_fw_chain * chain,struct rule_check_info * ci)2832 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2833 {
2834 	int error;
2835 	ipfw_insn *cmd;
2836 	uint8_t type;
2837 	struct obj_idx *p, *pidx_first, *pidx_last;
2838 	struct tid_info ti;
2839 
2840 	/*
2841 	 * Prepare an array for storing opcode indices.
2842 	 * Use stack allocation by default.
2843 	 */
2844 	if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2845 		/* Stack */
2846 		pidx_first = ci->obuf;
2847 	} else
2848 		pidx_first = malloc(
2849 		    ci->object_opcodes * sizeof(struct obj_idx),
2850 		    M_IPFW, M_WAITOK | M_ZERO);
2851 
2852 	error = 0;
2853 	type = 0;
2854 	memset(&ti, 0, sizeof(ti));
2855 
2856 	/* Use set rule is assigned to. */
2857 	ti.set = ci->krule->set;
2858 	if (ci->ctlv != NULL) {
2859 		ti.tlvs = (void *)(ci->ctlv + 1);
2860 		ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2861 	}
2862 
2863 	/* Reference all used tables and other objects */
2864 	error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2865 	if (error != 0)
2866 		goto free;
2867 	/*
2868 	 * Note that ref_rule_objects() might have updated ci->object_opcodes
2869 	 * to reflect actual number of object opcodes.
2870 	 */
2871 
2872 	/* Perform rewrite of remaining opcodes */
2873 	p = pidx_first;
2874 	pidx_last = pidx_first + ci->object_opcodes;
2875 	for (p = pidx_first; p < pidx_last; p++) {
2876 		cmd = ci->krule->cmd + p->off;
2877 		update_opcode_kidx(cmd, p->kidx);
2878 	}
2879 
2880 free:
2881 	if (pidx_first != ci->obuf)
2882 		free(pidx_first, M_IPFW);
2883 
2884 	return (error);
2885 }
2886 
2887 /*
2888  * Adds one or more rules to ipfw @chain.
2889  * Data layout (version 0)(current):
2890  * Request:
2891  * [
2892  *   ip_fw3_opheader
2893  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2894  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2895  * ]
2896  * Reply:
2897  * [
2898  *   ip_fw3_opheader
2899  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2900  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2901  * ]
2902  *
2903  * Rules in reply are modified to store their actual ruleset number.
2904  *
2905  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2906  * according to their idx field and there has to be no duplicates.
2907  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2908  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2909  *
2910  * Returns 0 on success.
2911  */
2912 static int
add_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2913 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2914     struct sockopt_data *sd)
2915 {
2916 	ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2917 	ipfw_obj_ntlv *ntlv;
2918 	int clen, error, idx;
2919 	uint32_t count, read;
2920 	struct ip_fw_rule *r;
2921 	struct rule_check_info rci, *ci, *cbuf;
2922 	int i, rsize;
2923 
2924 	op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2925 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2926 
2927 	read = sizeof(ip_fw3_opheader);
2928 	rtlv = NULL;
2929 	tstate = NULL;
2930 	cbuf = NULL;
2931 	memset(&rci, 0, sizeof(struct rule_check_info));
2932 
2933 	if (read + sizeof(*ctlv) > sd->valsize)
2934 		return (EINVAL);
2935 
2936 	if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2937 		clen = ctlv->head.length;
2938 		/* Check size and alignment */
2939 		if (clen > sd->valsize || clen < sizeof(*ctlv))
2940 			return (EINVAL);
2941 		if ((clen % sizeof(uint64_t)) != 0)
2942 			return (EINVAL);
2943 
2944 		/*
2945 		 * Some table names or other named objects.
2946 		 * Check for validness.
2947 		 */
2948 		count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2949 		if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2950 			return (EINVAL);
2951 
2952 		/*
2953 		 * Check each TLV.
2954 		 * Ensure TLVs are sorted ascending and
2955 		 * there are no duplicates.
2956 		 */
2957 		idx = -1;
2958 		ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2959 		while (count > 0) {
2960 			if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2961 				return (EINVAL);
2962 
2963 			error = ipfw_check_object_name_generic(ntlv->name);
2964 			if (error != 0)
2965 				return (error);
2966 
2967 			if (ntlv->idx <= idx)
2968 				return (EINVAL);
2969 
2970 			idx = ntlv->idx;
2971 			count--;
2972 			ntlv++;
2973 		}
2974 
2975 		tstate = ctlv;
2976 		read += ctlv->head.length;
2977 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2978 	}
2979 
2980 	if (read + sizeof(*ctlv) > sd->valsize)
2981 		return (EINVAL);
2982 
2983 	if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2984 		clen = ctlv->head.length;
2985 		if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2986 			return (EINVAL);
2987 		if ((clen % sizeof(uint64_t)) != 0)
2988 			return (EINVAL);
2989 
2990 		/*
2991 		 * TODO: Permit adding multiple rules at once
2992 		 */
2993 		if (ctlv->count != 1)
2994 			return (ENOTSUP);
2995 
2996 		clen -= sizeof(*ctlv);
2997 
2998 		if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2999 			return (EINVAL);
3000 
3001 		/* Allocate state for each rule or use stack */
3002 		if (ctlv->count == 1) {
3003 			memset(&rci, 0, sizeof(struct rule_check_info));
3004 			cbuf = &rci;
3005 		} else
3006 			cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
3007 			    M_WAITOK | M_ZERO);
3008 		ci = cbuf;
3009 
3010 		/*
3011 		 * Check each rule for validness.
3012 		 * Ensure numbered rules are sorted ascending
3013 		 * and properly aligned
3014 		 */
3015 		idx = 0;
3016 		r = (struct ip_fw_rule *)(ctlv + 1);
3017 		count = 0;
3018 		error = 0;
3019 		while (clen > 0) {
3020 			rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3021 			if (rsize > clen || ctlv->count <= count) {
3022 				error = EINVAL;
3023 				break;
3024 			}
3025 
3026 			ci->ctlv = tstate;
3027 			error = check_ipfw_rule1(r, rsize, ci);
3028 			if (error != 0)
3029 				break;
3030 
3031 			/* Check sorting */
3032 			if (r->rulenum != 0 && r->rulenum < idx) {
3033 				printf("rulenum %d idx %d\n", r->rulenum, idx);
3034 				error = EINVAL;
3035 				break;
3036 			}
3037 			idx = r->rulenum;
3038 
3039 			ci->urule = (caddr_t)r;
3040 
3041 			rsize = roundup2(rsize, sizeof(uint64_t));
3042 			clen -= rsize;
3043 			r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3044 			count++;
3045 			ci++;
3046 		}
3047 
3048 		if (ctlv->count != count || error != 0) {
3049 			if (cbuf != &rci)
3050 				free(cbuf, M_TEMP);
3051 			return (EINVAL);
3052 		}
3053 
3054 		rtlv = ctlv;
3055 		read += ctlv->head.length;
3056 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3057 	}
3058 
3059 	if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3060 		if (cbuf != NULL && cbuf != &rci)
3061 			free(cbuf, M_TEMP);
3062 		return (EINVAL);
3063 	}
3064 
3065 	/*
3066 	 * Passed rules seems to be valid.
3067 	 * Allocate storage and try to add them to chain.
3068 	 */
3069 	for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3070 		clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3071 		ci->krule = ipfw_alloc_rule(chain, clen);
3072 		import_rule1(ci);
3073 	}
3074 
3075 	if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3076 		/* Free allocate krules */
3077 		for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3078 			ipfw_free_rule(ci->krule);
3079 	}
3080 
3081 	if (cbuf != NULL && cbuf != &rci)
3082 		free(cbuf, M_TEMP);
3083 
3084 	return (error);
3085 }
3086 
3087 /*
3088  * Lists all sopts currently registered.
3089  * Data layout (v0)(current):
3090  * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3091  * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3092  *
3093  * Returns 0 on success
3094  */
3095 static int
dump_soptcodes(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)3096 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3097     struct sockopt_data *sd)
3098 {
3099 	struct _ipfw_obj_lheader *olh;
3100 	ipfw_sopt_info *i;
3101 	struct ipfw_sopt_handler *sh;
3102 	uint32_t count, n, size;
3103 
3104 	olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3105 	if (olh == NULL)
3106 		return (EINVAL);
3107 	if (sd->valsize < olh->size)
3108 		return (EINVAL);
3109 
3110 	CTL3_LOCK();
3111 	count = ctl3_hsize;
3112 	size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3113 
3114 	/* Fill in header regadless of buffer size */
3115 	olh->count = count;
3116 	olh->objsize = sizeof(ipfw_sopt_info);
3117 
3118 	if (size > olh->size) {
3119 		olh->size = size;
3120 		CTL3_UNLOCK();
3121 		return (ENOMEM);
3122 	}
3123 	olh->size = size;
3124 
3125 	for (n = 0; n < count; n++) {
3126 		i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3127 		KASSERT(i != NULL, ("previously checked buffer is not enough"));
3128 		sh = &ctl3_handlers[n];
3129 		i->opcode = sh->opcode;
3130 		i->version = sh->version;
3131 		i->refcnt = sh->refcnt;
3132 	}
3133 	CTL3_UNLOCK();
3134 
3135 	return (0);
3136 }
3137 
3138 /*
3139  * Compares two opcodes.
3140  * Used both in qsort() and bsearch().
3141  *
3142  * Returns 0 if match is found.
3143  */
3144 static int
compare_opcodes(const void * _a,const void * _b)3145 compare_opcodes(const void *_a, const void *_b)
3146 {
3147 	const struct opcode_obj_rewrite *a, *b;
3148 
3149 	a = (const struct opcode_obj_rewrite *)_a;
3150 	b = (const struct opcode_obj_rewrite *)_b;
3151 
3152 	if (a->opcode < b->opcode)
3153 		return (-1);
3154 	else if (a->opcode > b->opcode)
3155 		return (1);
3156 
3157 	return (0);
3158 }
3159 
3160 /*
3161  * XXX: Rewrite bsearch()
3162  */
3163 static int
find_op_rw_range(uint16_t op,struct opcode_obj_rewrite ** plo,struct opcode_obj_rewrite ** phi)3164 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3165     struct opcode_obj_rewrite **phi)
3166 {
3167 	struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3168 
3169 	memset(&h, 0, sizeof(h));
3170 	h.opcode = op;
3171 
3172 	rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3173 	    ctl3_rsize, sizeof(h), compare_opcodes);
3174 	if (rw == NULL)
3175 		return (1);
3176 
3177 	/* Find the first element matching the same opcode */
3178 	lo = rw;
3179 	for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3180 		;
3181 
3182 	/* Find the last element matching the same opcode */
3183 	hi = rw;
3184 	ctl3_max = ctl3_rewriters + ctl3_rsize;
3185 	for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3186 		;
3187 
3188 	*plo = lo;
3189 	*phi = hi;
3190 
3191 	return (0);
3192 }
3193 
3194 /*
3195  * Finds opcode object rewriter based on @code.
3196  *
3197  * Returns pointer to handler or NULL.
3198  */
3199 static struct opcode_obj_rewrite *
find_op_rw(ipfw_insn * cmd,uint16_t * puidx,uint8_t * ptype)3200 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3201 {
3202 	struct opcode_obj_rewrite *rw, *lo, *hi;
3203 	uint16_t uidx;
3204 	uint8_t subtype;
3205 
3206 	if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3207 		return (NULL);
3208 
3209 	for (rw = lo; rw <= hi; rw++) {
3210 		if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3211 			if (puidx != NULL)
3212 				*puidx = uidx;
3213 			if (ptype != NULL)
3214 				*ptype = subtype;
3215 			return (rw);
3216 		}
3217 	}
3218 
3219 	return (NULL);
3220 }
3221 int
classify_opcode_kidx(ipfw_insn * cmd,uint16_t * puidx)3222 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3223 {
3224 
3225 	if (find_op_rw(cmd, puidx, NULL) == NULL)
3226 		return (1);
3227 	return (0);
3228 }
3229 
3230 void
update_opcode_kidx(ipfw_insn * cmd,uint16_t idx)3231 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3232 {
3233 	struct opcode_obj_rewrite *rw;
3234 
3235 	rw = find_op_rw(cmd, NULL, NULL);
3236 	KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3237 	rw->update(cmd, idx);
3238 }
3239 
3240 void
ipfw_init_obj_rewriter(void)3241 ipfw_init_obj_rewriter(void)
3242 {
3243 
3244 	ctl3_rewriters = NULL;
3245 	ctl3_rsize = 0;
3246 }
3247 
3248 void
ipfw_destroy_obj_rewriter(void)3249 ipfw_destroy_obj_rewriter(void)
3250 {
3251 
3252 	if (ctl3_rewriters != NULL)
3253 		free(ctl3_rewriters, M_IPFW);
3254 	ctl3_rewriters = NULL;
3255 	ctl3_rsize = 0;
3256 }
3257 
3258 /*
3259  * Adds one or more opcode object rewrite handlers to the global array.
3260  * Function may sleep.
3261  */
3262 void
ipfw_add_obj_rewriter(struct opcode_obj_rewrite * rw,size_t count)3263 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3264 {
3265 	size_t sz;
3266 	struct opcode_obj_rewrite *tmp;
3267 
3268 	CTL3_LOCK();
3269 
3270 	for (;;) {
3271 		sz = ctl3_rsize + count;
3272 		CTL3_UNLOCK();
3273 		tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3274 		CTL3_LOCK();
3275 		if (ctl3_rsize + count <= sz)
3276 			break;
3277 
3278 		/* Retry */
3279 		free(tmp, M_IPFW);
3280 	}
3281 
3282 	/* Merge old & new arrays */
3283 	sz = ctl3_rsize + count;
3284 	memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3285 	memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3286 	qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3287 	/* Switch new and free old */
3288 	if (ctl3_rewriters != NULL)
3289 		free(ctl3_rewriters, M_IPFW);
3290 	ctl3_rewriters = tmp;
3291 	ctl3_rsize = sz;
3292 
3293 	CTL3_UNLOCK();
3294 }
3295 
3296 /*
3297  * Removes one or more object rewrite handlers from the global array.
3298  */
3299 int
ipfw_del_obj_rewriter(struct opcode_obj_rewrite * rw,size_t count)3300 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3301 {
3302 	size_t sz;
3303 	struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3304 	int i;
3305 
3306 	CTL3_LOCK();
3307 
3308 	for (i = 0; i < count; i++) {
3309 		if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3310 			continue;
3311 
3312 		for (ktmp = lo; ktmp <= hi; ktmp++) {
3313 			if (ktmp->classifier != rw[i].classifier)
3314 				continue;
3315 
3316 			ctl3_max = ctl3_rewriters + ctl3_rsize;
3317 			sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3318 			memmove(ktmp, ktmp + 1, sz);
3319 			ctl3_rsize--;
3320 			break;
3321 		}
3322 	}
3323 
3324 	if (ctl3_rsize == 0) {
3325 		if (ctl3_rewriters != NULL)
3326 			free(ctl3_rewriters, M_IPFW);
3327 		ctl3_rewriters = NULL;
3328 	}
3329 
3330 	CTL3_UNLOCK();
3331 
3332 	return (0);
3333 }
3334 
3335 static int
export_objhash_ntlv_internal(struct namedobj_instance * ni,struct named_object * no,void * arg)3336 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3337     struct named_object *no, void *arg)
3338 {
3339 	struct sockopt_data *sd;
3340 	ipfw_obj_ntlv *ntlv;
3341 
3342 	sd = (struct sockopt_data *)arg;
3343 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3344 	if (ntlv == NULL)
3345 		return (ENOMEM);
3346 	ipfw_export_obj_ntlv(no, ntlv);
3347 	return (0);
3348 }
3349 
3350 /*
3351  * Lists all service objects.
3352  * Data layout (v0)(current):
3353  * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3354  * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3355  * Returns 0 on success
3356  */
3357 static int
dump_srvobjects(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)3358 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3359     struct sockopt_data *sd)
3360 {
3361 	ipfw_obj_lheader *hdr;
3362 	int count;
3363 
3364 	hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3365 	if (hdr == NULL)
3366 		return (EINVAL);
3367 
3368 	IPFW_UH_RLOCK(chain);
3369 	count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3370 	hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3371 	if (sd->valsize < hdr->size) {
3372 		IPFW_UH_RUNLOCK(chain);
3373 		return (ENOMEM);
3374 	}
3375 	hdr->count = count;
3376 	hdr->objsize = sizeof(ipfw_obj_ntlv);
3377 	if (count > 0)
3378 		ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3379 		    export_objhash_ntlv_internal, sd);
3380 	IPFW_UH_RUNLOCK(chain);
3381 	return (0);
3382 }
3383 
3384 /*
3385  * Compares two sopt handlers (code, version and handler ptr).
3386  * Used both as qsort() and bsearch().
3387  * Does not compare handler for latter case.
3388  *
3389  * Returns 0 if match is found.
3390  */
3391 static int
compare_sh(const void * _a,const void * _b)3392 compare_sh(const void *_a, const void *_b)
3393 {
3394 	const struct ipfw_sopt_handler *a, *b;
3395 
3396 	a = (const struct ipfw_sopt_handler *)_a;
3397 	b = (const struct ipfw_sopt_handler *)_b;
3398 
3399 	if (a->opcode < b->opcode)
3400 		return (-1);
3401 	else if (a->opcode > b->opcode)
3402 		return (1);
3403 
3404 	if (a->version < b->version)
3405 		return (-1);
3406 	else if (a->version > b->version)
3407 		return (1);
3408 
3409 	/* bsearch helper */
3410 	if (a->handler == NULL)
3411 		return (0);
3412 
3413 	if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3414 		return (-1);
3415 	else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3416 		return (1);
3417 
3418 	return (0);
3419 }
3420 
3421 /*
3422  * Finds sopt handler based on @code and @version.
3423  *
3424  * Returns pointer to handler or NULL.
3425  */
3426 static struct ipfw_sopt_handler *
find_sh(uint16_t code,uint8_t version,sopt_handler_f * handler)3427 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3428 {
3429 	struct ipfw_sopt_handler *sh, h;
3430 
3431 	memset(&h, 0, sizeof(h));
3432 	h.opcode = code;
3433 	h.version = version;
3434 	h.handler = handler;
3435 
3436 	sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3437 	    ctl3_hsize, sizeof(h), compare_sh);
3438 
3439 	return (sh);
3440 }
3441 
3442 static int
find_ref_sh(uint16_t opcode,uint8_t version,struct ipfw_sopt_handler * psh)3443 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3444 {
3445 	struct ipfw_sopt_handler *sh;
3446 
3447 	CTL3_LOCK();
3448 	if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3449 		CTL3_UNLOCK();
3450 		printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3451 		    opcode, version);
3452 		return (EINVAL);
3453 	}
3454 	sh->refcnt++;
3455 	ctl3_refct++;
3456 	/* Copy handler data to requested buffer */
3457 	*psh = *sh;
3458 	CTL3_UNLOCK();
3459 
3460 	return (0);
3461 }
3462 
3463 static void
find_unref_sh(struct ipfw_sopt_handler * psh)3464 find_unref_sh(struct ipfw_sopt_handler *psh)
3465 {
3466 	struct ipfw_sopt_handler *sh;
3467 
3468 	CTL3_LOCK();
3469 	sh = find_sh(psh->opcode, psh->version, NULL);
3470 	KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3471 	sh->refcnt--;
3472 	ctl3_refct--;
3473 	CTL3_UNLOCK();
3474 }
3475 
3476 void
ipfw_init_sopt_handler(void)3477 ipfw_init_sopt_handler(void)
3478 {
3479 
3480 	CTL3_LOCK_INIT();
3481 	IPFW_ADD_SOPT_HANDLER(1, scodes);
3482 }
3483 
3484 void
ipfw_destroy_sopt_handler(void)3485 ipfw_destroy_sopt_handler(void)
3486 {
3487 
3488 	IPFW_DEL_SOPT_HANDLER(1, scodes);
3489 	CTL3_LOCK_DESTROY();
3490 }
3491 
3492 /*
3493  * Adds one or more sockopt handlers to the global array.
3494  * Function may sleep.
3495  */
3496 void
ipfw_add_sopt_handler(struct ipfw_sopt_handler * sh,size_t count)3497 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3498 {
3499 	size_t sz;
3500 	struct ipfw_sopt_handler *tmp;
3501 
3502 	CTL3_LOCK();
3503 
3504 	for (;;) {
3505 		sz = ctl3_hsize + count;
3506 		CTL3_UNLOCK();
3507 		tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3508 		CTL3_LOCK();
3509 		if (ctl3_hsize + count <= sz)
3510 			break;
3511 
3512 		/* Retry */
3513 		free(tmp, M_IPFW);
3514 	}
3515 
3516 	/* Merge old & new arrays */
3517 	sz = ctl3_hsize + count;
3518 	memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3519 	memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3520 	qsort(tmp, sz, sizeof(*sh), compare_sh);
3521 	/* Switch new and free old */
3522 	if (ctl3_handlers != NULL)
3523 		free(ctl3_handlers, M_IPFW);
3524 	ctl3_handlers = tmp;
3525 	ctl3_hsize = sz;
3526 	ctl3_gencnt++;
3527 
3528 	CTL3_UNLOCK();
3529 }
3530 
3531 /*
3532  * Removes one or more sockopt handlers from the global array.
3533  */
3534 int
ipfw_del_sopt_handler(struct ipfw_sopt_handler * sh,size_t count)3535 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3536 {
3537 	size_t sz;
3538 	struct ipfw_sopt_handler *tmp, *h;
3539 	int i;
3540 
3541 	CTL3_LOCK();
3542 
3543 	for (i = 0; i < count; i++) {
3544 		tmp = &sh[i];
3545 		h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3546 		if (h == NULL)
3547 			continue;
3548 
3549 		sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3550 		memmove(h, h + 1, sz);
3551 		ctl3_hsize--;
3552 	}
3553 
3554 	if (ctl3_hsize == 0) {
3555 		if (ctl3_handlers != NULL)
3556 			free(ctl3_handlers, M_IPFW);
3557 		ctl3_handlers = NULL;
3558 	}
3559 
3560 	ctl3_gencnt++;
3561 
3562 	CTL3_UNLOCK();
3563 
3564 	return (0);
3565 }
3566 
3567 /*
3568  * Writes data accumulated in @sd to sockopt buffer.
3569  * Zeroes internal @sd buffer.
3570  */
3571 static int
ipfw_flush_sopt_data(struct sockopt_data * sd)3572 ipfw_flush_sopt_data(struct sockopt_data *sd)
3573 {
3574 	struct sockopt *sopt;
3575 	int error;
3576 	size_t sz;
3577 
3578 	sz = sd->koff;
3579 	if (sz == 0)
3580 		return (0);
3581 
3582 	sopt = sd->sopt;
3583 
3584 	if (sopt->sopt_dir == SOPT_GET) {
3585 		error = copyout(sd->kbuf, sopt->sopt_val, sz);
3586 		if (error != 0)
3587 			return (error);
3588 	}
3589 
3590 	memset(sd->kbuf, 0, sd->ksize);
3591 	sd->ktotal += sz;
3592 	sd->koff = 0;
3593 	if (sd->ktotal + sd->ksize < sd->valsize)
3594 		sd->kavail = sd->ksize;
3595 	else
3596 		sd->kavail = sd->valsize - sd->ktotal;
3597 
3598 	/* Update sopt buffer data */
3599 	sopt->sopt_valsize = sd->ktotal;
3600 	sopt->sopt_val = sd->sopt_val + sd->ktotal;
3601 
3602 	return (0);
3603 }
3604 
3605 /*
3606  * Ensures that @sd buffer has contiguous @neeeded number of
3607  * bytes.
3608  *
3609  * Returns pointer to requested space or NULL.
3610  */
3611 caddr_t
ipfw_get_sopt_space(struct sockopt_data * sd,size_t needed)3612 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3613 {
3614 	int error;
3615 	caddr_t addr;
3616 
3617 	if (sd->kavail < needed) {
3618 		/*
3619 		 * Flush data and try another time.
3620 		 */
3621 		error = ipfw_flush_sopt_data(sd);
3622 
3623 		if (sd->kavail < needed || error != 0)
3624 			return (NULL);
3625 	}
3626 
3627 	addr = sd->kbuf + sd->koff;
3628 	sd->koff += needed;
3629 	sd->kavail -= needed;
3630 	return (addr);
3631 }
3632 
3633 /*
3634  * Requests @needed contiguous bytes from @sd buffer.
3635  * Function is used to notify subsystem that we are
3636  * interesed in first @needed bytes (request header)
3637  * and the rest buffer can be safely zeroed.
3638  *
3639  * Returns pointer to requested space or NULL.
3640  */
3641 caddr_t
ipfw_get_sopt_header(struct sockopt_data * sd,size_t needed)3642 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3643 {
3644 	caddr_t addr;
3645 
3646 	if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3647 		return (NULL);
3648 
3649 	if (sd->kavail > 0)
3650 		memset(sd->kbuf + sd->koff, 0, sd->kavail);
3651 
3652 	return (addr);
3653 }
3654 
3655 /*
3656  * New sockopt handler.
3657  */
3658 int
ipfw_ctl3(struct sockopt * sopt)3659 ipfw_ctl3(struct sockopt *sopt)
3660 {
3661 	int error, locked;
3662 	size_t size, valsize;
3663 	struct ip_fw_chain *chain;
3664 	char xbuf[256];
3665 	struct sockopt_data sdata;
3666 	struct ipfw_sopt_handler h;
3667 	ip_fw3_opheader *op3 = NULL;
3668 
3669 	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3670 	if (error != 0)
3671 		return (error);
3672 
3673 	if (sopt->sopt_name != IP_FW3)
3674 		return (ipfw_ctl(sopt));
3675 
3676 	chain = &V_layer3_chain;
3677 	error = 0;
3678 
3679 	/* Save original valsize before it is altered via sooptcopyin() */
3680 	valsize = sopt->sopt_valsize;
3681 	memset(&sdata, 0, sizeof(sdata));
3682 	/* Read op3 header first to determine actual operation */
3683 	op3 = (ip_fw3_opheader *)xbuf;
3684 	error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3685 	if (error != 0)
3686 		return (error);
3687 	sopt->sopt_valsize = valsize;
3688 
3689 	/*
3690 	 * Find and reference command.
3691 	 */
3692 	error = find_ref_sh(op3->opcode, op3->version, &h);
3693 	if (error != 0)
3694 		return (error);
3695 
3696 	/*
3697 	 * Disallow modifications in really-really secure mode, but still allow
3698 	 * the logging counters to be reset.
3699 	 */
3700 	if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3701 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3702 		if (error != 0) {
3703 			find_unref_sh(&h);
3704 			return (error);
3705 		}
3706 	}
3707 
3708 	/*
3709 	 * Fill in sockopt_data structure that may be useful for
3710 	 * IP_FW3 get requests.
3711 	 */
3712 	locked = 0;
3713 	if (valsize <= sizeof(xbuf)) {
3714 		/* use on-stack buffer */
3715 		sdata.kbuf = xbuf;
3716 		sdata.ksize = sizeof(xbuf);
3717 		sdata.kavail = valsize;
3718 	} else {
3719 		/*
3720 		 * Determine opcode type/buffer size:
3721 		 * allocate sliding-window buf for data export or
3722 		 * contiguous buffer for special ops.
3723 		 */
3724 		if ((h.dir & HDIR_SET) != 0) {
3725 			/* Set request. Allocate contigous buffer. */
3726 			if (valsize > CTL3_LARGEBUF) {
3727 				find_unref_sh(&h);
3728 				return (EFBIG);
3729 			}
3730 
3731 			size = valsize;
3732 		} else {
3733 			/* Get request. Allocate sliding window buffer */
3734 			size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3735 
3736 			if (size < valsize) {
3737 				/* We have to wire user buffer */
3738 				error = vslock(sopt->sopt_val, valsize);
3739 				if (error != 0)
3740 					return (error);
3741 				locked = 1;
3742 			}
3743 		}
3744 
3745 		sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3746 		sdata.ksize = size;
3747 		sdata.kavail = size;
3748 	}
3749 
3750 	sdata.sopt = sopt;
3751 	sdata.sopt_val = sopt->sopt_val;
3752 	sdata.valsize = valsize;
3753 
3754 	/*
3755 	 * Copy either all request (if valsize < bsize_max)
3756 	 * or first bsize_max bytes to guarantee most consumers
3757 	 * that all necessary data has been copied).
3758 	 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3759 	 */
3760 	if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3761 	    sizeof(ip_fw3_opheader))) != 0)
3762 		return (error);
3763 	op3 = (ip_fw3_opheader *)sdata.kbuf;
3764 
3765 	/* Finally, run handler */
3766 	error = h.handler(chain, op3, &sdata);
3767 	find_unref_sh(&h);
3768 
3769 	/* Flush state and free buffers */
3770 	if (error == 0)
3771 		error = ipfw_flush_sopt_data(&sdata);
3772 	else
3773 		ipfw_flush_sopt_data(&sdata);
3774 
3775 	if (locked != 0)
3776 		vsunlock(sdata.sopt_val, valsize);
3777 
3778 	/* Restore original pointer and set number of bytes written */
3779 	sopt->sopt_val = sdata.sopt_val;
3780 	sopt->sopt_valsize = sdata.ktotal;
3781 	if (sdata.kbuf != xbuf)
3782 		free(sdata.kbuf, M_TEMP);
3783 
3784 	return (error);
3785 }
3786 
3787 /**
3788  * {set|get}sockopt parser.
3789  */
3790 int
ipfw_ctl(struct sockopt * sopt)3791 ipfw_ctl(struct sockopt *sopt)
3792 {
3793 #define	RULE_MAXSIZE	(512*sizeof(u_int32_t))
3794 	int error;
3795 	size_t size, valsize;
3796 	struct ip_fw *buf;
3797 	struct ip_fw_rule0 *rule;
3798 	struct ip_fw_chain *chain;
3799 	u_int32_t rulenum[2];
3800 	uint32_t opt;
3801 	struct rule_check_info ci;
3802 	IPFW_RLOCK_TRACKER;
3803 
3804 	chain = &V_layer3_chain;
3805 	error = 0;
3806 
3807 	/* Save original valsize before it is altered via sooptcopyin() */
3808 	valsize = sopt->sopt_valsize;
3809 	opt = sopt->sopt_name;
3810 
3811 	/*
3812 	 * Disallow modifications in really-really secure mode, but still allow
3813 	 * the logging counters to be reset.
3814 	 */
3815 	if (opt == IP_FW_ADD ||
3816 	    (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3817 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3818 		if (error != 0)
3819 			return (error);
3820 	}
3821 
3822 	switch (opt) {
3823 	case IP_FW_GET:
3824 		/*
3825 		 * pass up a copy of the current rules. Static rules
3826 		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3827 		 * followed by a possibly empty list of dynamic rule.
3828 		 * The last dynamic rule has NULL in the "next" field.
3829 		 *
3830 		 * Note that the calculated size is used to bound the
3831 		 * amount of data returned to the user.  The rule set may
3832 		 * change between calculating the size and returning the
3833 		 * data in which case we'll just return what fits.
3834 		 */
3835 		for (;;) {
3836 			int len = 0, want;
3837 
3838 			size = chain->static_len;
3839 			size += ipfw_dyn_len();
3840 			if (size >= sopt->sopt_valsize)
3841 				break;
3842 			buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3843 			IPFW_UH_RLOCK(chain);
3844 			/* check again how much space we need */
3845 			want = chain->static_len + ipfw_dyn_len();
3846 			if (size >= want)
3847 				len = ipfw_getrules(chain, buf, size);
3848 			IPFW_UH_RUNLOCK(chain);
3849 			if (size >= want)
3850 				error = sooptcopyout(sopt, buf, len);
3851 			free(buf, M_TEMP);
3852 			if (size >= want)
3853 				break;
3854 		}
3855 		break;
3856 
3857 	case IP_FW_FLUSH:
3858 		/* locking is done within del_entry() */
3859 		error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3860 		break;
3861 
3862 	case IP_FW_ADD:
3863 		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3864 		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3865 			sizeof(struct ip_fw7) );
3866 
3867 		memset(&ci, 0, sizeof(struct rule_check_info));
3868 
3869 		/*
3870 		 * If the size of commands equals RULESIZE7 then we assume
3871 		 * a FreeBSD7.2 binary is talking to us (set is7=1).
3872 		 * is7 is persistent so the next 'ipfw list' command
3873 		 * will use this format.
3874 		 * NOTE: If wrong version is guessed (this can happen if
3875 		 *       the first ipfw command is 'ipfw [pipe] list')
3876 		 *       the ipfw binary may crash or loop infinitly...
3877 		 */
3878 		size = sopt->sopt_valsize;
3879 		if (size == RULESIZE7(rule)) {
3880 		    is7 = 1;
3881 		    error = convert_rule_to_8(rule);
3882 		    if (error) {
3883 			free(rule, M_TEMP);
3884 			return error;
3885 		    }
3886 		    size = RULESIZE(rule);
3887 		} else
3888 		    is7 = 0;
3889 		if (error == 0)
3890 			error = check_ipfw_rule0(rule, size, &ci);
3891 		if (error == 0) {
3892 			/* locking is done within add_rule() */
3893 			struct ip_fw *krule;
3894 			krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3895 			ci.urule = (caddr_t)rule;
3896 			ci.krule = krule;
3897 			import_rule0(&ci);
3898 			error = commit_rules(chain, &ci, 1);
3899 			if (error != 0)
3900 				ipfw_free_rule(ci.krule);
3901 			else if (sopt->sopt_dir == SOPT_GET) {
3902 				if (is7) {
3903 					error = convert_rule_to_7(rule);
3904 					size = RULESIZE7(rule);
3905 					if (error) {
3906 						free(rule, M_TEMP);
3907 						return error;
3908 					}
3909 				}
3910 				error = sooptcopyout(sopt, rule, size);
3911 			}
3912 		}
3913 		free(rule, M_TEMP);
3914 		break;
3915 
3916 	case IP_FW_DEL:
3917 		/*
3918 		 * IP_FW_DEL is used for deleting single rules or sets,
3919 		 * and (ab)used to atomically manipulate sets. Argument size
3920 		 * is used to distinguish between the two:
3921 		 *    sizeof(u_int32_t)
3922 		 *	delete single rule or set of rules,
3923 		 *	or reassign rules (or sets) to a different set.
3924 		 *    2*sizeof(u_int32_t)
3925 		 *	atomic disable/enable sets.
3926 		 *	first u_int32_t contains sets to be disabled,
3927 		 *	second u_int32_t contains sets to be enabled.
3928 		 */
3929 		error = sooptcopyin(sopt, rulenum,
3930 			2*sizeof(u_int32_t), sizeof(u_int32_t));
3931 		if (error)
3932 			break;
3933 		size = sopt->sopt_valsize;
3934 		if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3935 			/* delete or reassign, locking done in del_entry() */
3936 			error = del_entry(chain, rulenum[0]);
3937 		} else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3938 			IPFW_UH_WLOCK(chain);
3939 			V_set_disable =
3940 			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
3941 			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3942 			IPFW_UH_WUNLOCK(chain);
3943 		} else
3944 			error = EINVAL;
3945 		break;
3946 
3947 	case IP_FW_ZERO:
3948 	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3949 		rulenum[0] = 0;
3950 		if (sopt->sopt_val != 0) {
3951 		    error = sooptcopyin(sopt, rulenum,
3952 			    sizeof(u_int32_t), sizeof(u_int32_t));
3953 		    if (error)
3954 			break;
3955 		}
3956 		error = zero_entry(chain, rulenum[0],
3957 			sopt->sopt_name == IP_FW_RESETLOG);
3958 		break;
3959 
3960 	/*--- TABLE opcodes ---*/
3961 	case IP_FW_TABLE_ADD:
3962 	case IP_FW_TABLE_DEL:
3963 		{
3964 			ipfw_table_entry ent;
3965 			struct tentry_info tei;
3966 			struct tid_info ti;
3967 			struct table_value v;
3968 
3969 			error = sooptcopyin(sopt, &ent,
3970 			    sizeof(ent), sizeof(ent));
3971 			if (error)
3972 				break;
3973 
3974 			memset(&tei, 0, sizeof(tei));
3975 			tei.paddr = &ent.addr;
3976 			tei.subtype = AF_INET;
3977 			tei.masklen = ent.masklen;
3978 			ipfw_import_table_value_legacy(ent.value, &v);
3979 			tei.pvalue = &v;
3980 			memset(&ti, 0, sizeof(ti));
3981 			ti.uidx = ent.tbl;
3982 			ti.type = IPFW_TABLE_CIDR;
3983 
3984 			error = (opt == IP_FW_TABLE_ADD) ?
3985 			    add_table_entry(chain, &ti, &tei, 0, 1) :
3986 			    del_table_entry(chain, &ti, &tei, 0, 1);
3987 		}
3988 		break;
3989 
3990 	case IP_FW_TABLE_FLUSH:
3991 		{
3992 			u_int16_t tbl;
3993 			struct tid_info ti;
3994 
3995 			error = sooptcopyin(sopt, &tbl,
3996 			    sizeof(tbl), sizeof(tbl));
3997 			if (error)
3998 				break;
3999 			memset(&ti, 0, sizeof(ti));
4000 			ti.uidx = tbl;
4001 			error = flush_table(chain, &ti);
4002 		}
4003 		break;
4004 
4005 	case IP_FW_TABLE_GETSIZE:
4006 		{
4007 			u_int32_t tbl, cnt;
4008 			struct tid_info ti;
4009 
4010 			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4011 			    sizeof(tbl))))
4012 				break;
4013 			memset(&ti, 0, sizeof(ti));
4014 			ti.uidx = tbl;
4015 			IPFW_RLOCK(chain);
4016 			error = ipfw_count_table(chain, &ti, &cnt);
4017 			IPFW_RUNLOCK(chain);
4018 			if (error)
4019 				break;
4020 			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4021 		}
4022 		break;
4023 
4024 	case IP_FW_TABLE_LIST:
4025 		{
4026 			ipfw_table *tbl;
4027 			struct tid_info ti;
4028 
4029 			if (sopt->sopt_valsize < sizeof(*tbl)) {
4030 				error = EINVAL;
4031 				break;
4032 			}
4033 			size = sopt->sopt_valsize;
4034 			tbl = malloc(size, M_TEMP, M_WAITOK);
4035 			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4036 			if (error) {
4037 				free(tbl, M_TEMP);
4038 				break;
4039 			}
4040 			tbl->size = (size - sizeof(*tbl)) /
4041 			    sizeof(ipfw_table_entry);
4042 			memset(&ti, 0, sizeof(ti));
4043 			ti.uidx = tbl->tbl;
4044 			IPFW_RLOCK(chain);
4045 			error = ipfw_dump_table_legacy(chain, &ti, tbl);
4046 			IPFW_RUNLOCK(chain);
4047 			if (error) {
4048 				free(tbl, M_TEMP);
4049 				break;
4050 			}
4051 			error = sooptcopyout(sopt, tbl, size);
4052 			free(tbl, M_TEMP);
4053 		}
4054 		break;
4055 
4056 	/*--- NAT operations are protected by the IPFW_LOCK ---*/
4057 	case IP_FW_NAT_CFG:
4058 		if (IPFW_NAT_LOADED)
4059 			error = ipfw_nat_cfg_ptr(sopt);
4060 		else {
4061 			printf("IP_FW_NAT_CFG: %s\n",
4062 			    "ipfw_nat not present, please load it");
4063 			error = EINVAL;
4064 		}
4065 		break;
4066 
4067 	case IP_FW_NAT_DEL:
4068 		if (IPFW_NAT_LOADED)
4069 			error = ipfw_nat_del_ptr(sopt);
4070 		else {
4071 			printf("IP_FW_NAT_DEL: %s\n",
4072 			    "ipfw_nat not present, please load it");
4073 			error = EINVAL;
4074 		}
4075 		break;
4076 
4077 	case IP_FW_NAT_GET_CONFIG:
4078 		if (IPFW_NAT_LOADED)
4079 			error = ipfw_nat_get_cfg_ptr(sopt);
4080 		else {
4081 			printf("IP_FW_NAT_GET_CFG: %s\n",
4082 			    "ipfw_nat not present, please load it");
4083 			error = EINVAL;
4084 		}
4085 		break;
4086 
4087 	case IP_FW_NAT_GET_LOG:
4088 		if (IPFW_NAT_LOADED)
4089 			error = ipfw_nat_get_log_ptr(sopt);
4090 		else {
4091 			printf("IP_FW_NAT_GET_LOG: %s\n",
4092 			    "ipfw_nat not present, please load it");
4093 			error = EINVAL;
4094 		}
4095 		break;
4096 
4097 	default:
4098 		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4099 		error = EINVAL;
4100 	}
4101 
4102 	return (error);
4103 #undef RULE_MAXSIZE
4104 }
4105 #define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
4106 
4107 /* Functions to convert rules 7.2 <==> 8.0 */
4108 static int
convert_rule_to_7(struct ip_fw_rule0 * rule)4109 convert_rule_to_7(struct ip_fw_rule0 *rule)
4110 {
4111 	/* Used to modify original rule */
4112 	struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4113 	/* copy of original rule, version 8 */
4114 	struct ip_fw_rule0 *tmp;
4115 
4116 	/* Used to copy commands */
4117 	ipfw_insn *ccmd, *dst;
4118 	int ll = 0, ccmdlen = 0;
4119 
4120 	tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4121 	if (tmp == NULL) {
4122 		return 1; //XXX error
4123 	}
4124 	bcopy(rule, tmp, RULE_MAXSIZE);
4125 
4126 	/* Copy fields */
4127 	//rule7->_pad = tmp->_pad;
4128 	rule7->set = tmp->set;
4129 	rule7->rulenum = tmp->rulenum;
4130 	rule7->cmd_len = tmp->cmd_len;
4131 	rule7->act_ofs = tmp->act_ofs;
4132 	rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4133 	rule7->cmd_len = tmp->cmd_len;
4134 	rule7->pcnt = tmp->pcnt;
4135 	rule7->bcnt = tmp->bcnt;
4136 	rule7->timestamp = tmp->timestamp;
4137 
4138 	/* Copy commands */
4139 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4140 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4141 		ccmdlen = F_LEN(ccmd);
4142 
4143 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4144 
4145 		if (dst->opcode > O_NAT)
4146 			/* O_REASS doesn't exists in 7.2 version, so
4147 			 * decrement opcode if it is after O_REASS
4148 			 */
4149 			dst->opcode--;
4150 
4151 		if (ccmdlen > ll) {
4152 			printf("ipfw: opcode %d size truncated\n",
4153 				ccmd->opcode);
4154 			return EINVAL;
4155 		}
4156 	}
4157 	free(tmp, M_TEMP);
4158 
4159 	return 0;
4160 }
4161 
4162 static int
convert_rule_to_8(struct ip_fw_rule0 * rule)4163 convert_rule_to_8(struct ip_fw_rule0 *rule)
4164 {
4165 	/* Used to modify original rule */
4166 	struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4167 
4168 	/* Used to copy commands */
4169 	ipfw_insn *ccmd, *dst;
4170 	int ll = 0, ccmdlen = 0;
4171 
4172 	/* Copy of original rule */
4173 	struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4174 	if (tmp == NULL) {
4175 		return 1; //XXX error
4176 	}
4177 
4178 	bcopy(rule7, tmp, RULE_MAXSIZE);
4179 
4180 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4181 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4182 		ccmdlen = F_LEN(ccmd);
4183 
4184 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4185 
4186 		if (dst->opcode > O_NAT)
4187 			/* O_REASS doesn't exists in 7.2 version, so
4188 			 * increment opcode if it is after O_REASS
4189 			 */
4190 			dst->opcode++;
4191 
4192 		if (ccmdlen > ll) {
4193 			printf("ipfw: opcode %d size truncated\n",
4194 			    ccmd->opcode);
4195 			return EINVAL;
4196 		}
4197 	}
4198 
4199 	rule->_pad = tmp->_pad;
4200 	rule->set = tmp->set;
4201 	rule->rulenum = tmp->rulenum;
4202 	rule->cmd_len = tmp->cmd_len;
4203 	rule->act_ofs = tmp->act_ofs;
4204 	rule->next_rule = (struct ip_fw *)tmp->next_rule;
4205 	rule->cmd_len = tmp->cmd_len;
4206 	rule->id = 0; /* XXX see if is ok = 0 */
4207 	rule->pcnt = tmp->pcnt;
4208 	rule->bcnt = tmp->bcnt;
4209 	rule->timestamp = tmp->timestamp;
4210 
4211 	free (tmp, M_TEMP);
4212 	return 0;
4213 }
4214 
4215 /*
4216  * Named object api
4217  *
4218  */
4219 
4220 void
ipfw_init_srv(struct ip_fw_chain * ch)4221 ipfw_init_srv(struct ip_fw_chain *ch)
4222 {
4223 
4224 	ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4225 	ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4226 	    M_IPFW, M_WAITOK | M_ZERO);
4227 }
4228 
4229 void
ipfw_destroy_srv(struct ip_fw_chain * ch)4230 ipfw_destroy_srv(struct ip_fw_chain *ch)
4231 {
4232 
4233 	free(ch->srvstate, M_IPFW);
4234 	ipfw_objhash_destroy(ch->srvmap);
4235 }
4236 
4237 /*
4238  * Allocate new bitmask which can be used to enlarge/shrink
4239  * named instance index.
4240  */
4241 void
ipfw_objhash_bitmap_alloc(uint32_t items,void ** idx,int * pblocks)4242 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4243 {
4244 	size_t size;
4245 	int max_blocks;
4246 	u_long *idx_mask;
4247 
4248 	KASSERT((items % BLOCK_ITEMS) == 0,
4249 	   ("bitmask size needs to power of 2 and greater or equal to %zu",
4250 	    BLOCK_ITEMS));
4251 
4252 	max_blocks = items / BLOCK_ITEMS;
4253 	size = items / 8;
4254 	idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4255 	/* Mark all as free */
4256 	memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4257 	*idx_mask &= ~(u_long)1; /* Skip index 0 */
4258 
4259 	*idx = idx_mask;
4260 	*pblocks = max_blocks;
4261 }
4262 
4263 /*
4264  * Copy current bitmask index to new one.
4265  */
4266 void
ipfw_objhash_bitmap_merge(struct namedobj_instance * ni,void ** idx,int * blocks)4267 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4268 {
4269 	int old_blocks, new_blocks;
4270 	u_long *old_idx, *new_idx;
4271 	int i;
4272 
4273 	old_idx = ni->idx_mask;
4274 	old_blocks = ni->max_blocks;
4275 	new_idx = *idx;
4276 	new_blocks = *blocks;
4277 
4278 	for (i = 0; i < IPFW_MAX_SETS; i++) {
4279 		memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4280 		    old_blocks * sizeof(u_long));
4281 	}
4282 }
4283 
4284 /*
4285  * Swaps current @ni index with new one.
4286  */
4287 void
ipfw_objhash_bitmap_swap(struct namedobj_instance * ni,void ** idx,int * blocks)4288 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4289 {
4290 	int old_blocks;
4291 	u_long *old_idx;
4292 
4293 	old_idx = ni->idx_mask;
4294 	old_blocks = ni->max_blocks;
4295 
4296 	ni->idx_mask = *idx;
4297 	ni->max_blocks = *blocks;
4298 
4299 	/* Save old values */
4300 	*idx = old_idx;
4301 	*blocks = old_blocks;
4302 }
4303 
4304 void
ipfw_objhash_bitmap_free(void * idx,int blocks)4305 ipfw_objhash_bitmap_free(void *idx, int blocks)
4306 {
4307 
4308 	free(idx, M_IPFW);
4309 }
4310 
4311 /*
4312  * Creates named hash instance.
4313  * Must be called without holding any locks.
4314  * Return pointer to new instance.
4315  */
4316 struct namedobj_instance *
ipfw_objhash_create(uint32_t items)4317 ipfw_objhash_create(uint32_t items)
4318 {
4319 	struct namedobj_instance *ni;
4320 	int i;
4321 	size_t size;
4322 
4323 	size = sizeof(struct namedobj_instance) +
4324 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4325 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4326 
4327 	ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4328 	ni->nn_size = NAMEDOBJ_HASH_SIZE;
4329 	ni->nv_size = NAMEDOBJ_HASH_SIZE;
4330 
4331 	ni->names = (struct namedobjects_head *)(ni +1);
4332 	ni->values = &ni->names[ni->nn_size];
4333 
4334 	for (i = 0; i < ni->nn_size; i++)
4335 		TAILQ_INIT(&ni->names[i]);
4336 
4337 	for (i = 0; i < ni->nv_size; i++)
4338 		TAILQ_INIT(&ni->values[i]);
4339 
4340 	/* Set default hashing/comparison functions */
4341 	ni->hash_f = objhash_hash_name;
4342 	ni->cmp_f = objhash_cmp_name;
4343 
4344 	/* Allocate bitmask separately due to possible resize */
4345 	ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4346 
4347 	return (ni);
4348 }
4349 
4350 void
ipfw_objhash_destroy(struct namedobj_instance * ni)4351 ipfw_objhash_destroy(struct namedobj_instance *ni)
4352 {
4353 
4354 	free(ni->idx_mask, M_IPFW);
4355 	free(ni, M_IPFW);
4356 }
4357 
4358 void
ipfw_objhash_set_funcs(struct namedobj_instance * ni,objhash_hash_f * hash_f,objhash_cmp_f * cmp_f)4359 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4360     objhash_cmp_f *cmp_f)
4361 {
4362 
4363 	ni->hash_f = hash_f;
4364 	ni->cmp_f = cmp_f;
4365 }
4366 
4367 static uint32_t
objhash_hash_name(struct namedobj_instance * ni,const void * name,uint32_t set)4368 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4369 {
4370 
4371 	return (fnv_32_str((const char *)name, FNV1_32_INIT));
4372 }
4373 
4374 static int
objhash_cmp_name(struct named_object * no,const void * name,uint32_t set)4375 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4376 {
4377 
4378 	if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4379 		return (0);
4380 
4381 	return (1);
4382 }
4383 
4384 static uint32_t
objhash_hash_idx(struct namedobj_instance * ni,uint32_t val)4385 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4386 {
4387 	uint32_t v;
4388 
4389 	v = val % (ni->nv_size - 1);
4390 
4391 	return (v);
4392 }
4393 
4394 struct named_object *
ipfw_objhash_lookup_name(struct namedobj_instance * ni,uint32_t set,char * name)4395 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4396 {
4397 	struct named_object *no;
4398 	uint32_t hash;
4399 
4400 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4401 
4402 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4403 		if (ni->cmp_f(no, name, set) == 0)
4404 			return (no);
4405 	}
4406 
4407 	return (NULL);
4408 }
4409 
4410 /*
4411  * Find named object by @uid.
4412  * Check @tlvs for valid data inside.
4413  *
4414  * Returns pointer to found TLV or NULL.
4415  */
4416 ipfw_obj_ntlv *
ipfw_find_name_tlv_type(void * tlvs,int len,uint16_t uidx,uint32_t etlv)4417 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4418 {
4419 	ipfw_obj_ntlv *ntlv;
4420 	uintptr_t pa, pe;
4421 	int l;
4422 
4423 	pa = (uintptr_t)tlvs;
4424 	pe = pa + len;
4425 	l = 0;
4426 	for (; pa < pe; pa += l) {
4427 		ntlv = (ipfw_obj_ntlv *)pa;
4428 		l = ntlv->head.length;
4429 
4430 		if (l != sizeof(*ntlv))
4431 			return (NULL);
4432 
4433 		if (ntlv->idx != uidx)
4434 			continue;
4435 		/*
4436 		 * When userland has specified zero TLV type, do
4437 		 * not compare it with eltv. In some cases userland
4438 		 * doesn't know what type should it have. Use only
4439 		 * uidx and name for search named_object.
4440 		 */
4441 		if (ntlv->head.type != 0 &&
4442 		    ntlv->head.type != (uint16_t)etlv)
4443 			continue;
4444 
4445 		if (ipfw_check_object_name_generic(ntlv->name) != 0)
4446 			return (NULL);
4447 
4448 		return (ntlv);
4449 	}
4450 
4451 	return (NULL);
4452 }
4453 
4454 /*
4455  * Finds object config based on either legacy index
4456  * or name in ntlv.
4457  * Note @ti structure contains unchecked data from userland.
4458  *
4459  * Returns 0 in success and fills in @pno with found config
4460  */
4461 int
ipfw_objhash_find_type(struct namedobj_instance * ni,struct tid_info * ti,uint32_t etlv,struct named_object ** pno)4462 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4463     uint32_t etlv, struct named_object **pno)
4464 {
4465 	char *name;
4466 	ipfw_obj_ntlv *ntlv;
4467 	uint32_t set;
4468 
4469 	if (ti->tlvs == NULL)
4470 		return (EINVAL);
4471 
4472 	ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4473 	if (ntlv == NULL)
4474 		return (EINVAL);
4475 	name = ntlv->name;
4476 
4477 	/*
4478 	 * Use set provided by @ti instead of @ntlv one.
4479 	 * This is needed due to different sets behavior
4480 	 * controlled by V_fw_tables_sets.
4481 	 */
4482 	set = ti->set;
4483 	*pno = ipfw_objhash_lookup_name(ni, set, name);
4484 	if (*pno == NULL)
4485 		return (ESRCH);
4486 	return (0);
4487 }
4488 
4489 /*
4490  * Find named object by name, considering also its TLV type.
4491  */
4492 struct named_object *
ipfw_objhash_lookup_name_type(struct namedobj_instance * ni,uint32_t set,uint32_t type,const char * name)4493 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4494     uint32_t type, const char *name)
4495 {
4496 	struct named_object *no;
4497 	uint32_t hash;
4498 
4499 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4500 
4501 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4502 		if (ni->cmp_f(no, name, set) == 0 &&
4503 		    no->etlv == (uint16_t)type)
4504 			return (no);
4505 	}
4506 
4507 	return (NULL);
4508 }
4509 
4510 struct named_object *
ipfw_objhash_lookup_kidx(struct namedobj_instance * ni,uint16_t kidx)4511 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4512 {
4513 	struct named_object *no;
4514 	uint32_t hash;
4515 
4516 	hash = objhash_hash_idx(ni, kidx);
4517 
4518 	TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4519 		if (no->kidx == kidx)
4520 			return (no);
4521 	}
4522 
4523 	return (NULL);
4524 }
4525 
4526 int
ipfw_objhash_same_name(struct namedobj_instance * ni,struct named_object * a,struct named_object * b)4527 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4528     struct named_object *b)
4529 {
4530 
4531 	if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4532 		return (1);
4533 
4534 	return (0);
4535 }
4536 
4537 void
ipfw_objhash_add(struct namedobj_instance * ni,struct named_object * no)4538 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4539 {
4540 	uint32_t hash;
4541 
4542 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4543 	TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4544 
4545 	hash = objhash_hash_idx(ni, no->kidx);
4546 	TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4547 
4548 	ni->count++;
4549 }
4550 
4551 void
ipfw_objhash_del(struct namedobj_instance * ni,struct named_object * no)4552 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4553 {
4554 	uint32_t hash;
4555 
4556 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4557 	TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4558 
4559 	hash = objhash_hash_idx(ni, no->kidx);
4560 	TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4561 
4562 	ni->count--;
4563 }
4564 
4565 uint32_t
ipfw_objhash_count(struct namedobj_instance * ni)4566 ipfw_objhash_count(struct namedobj_instance *ni)
4567 {
4568 
4569 	return (ni->count);
4570 }
4571 
4572 uint32_t
ipfw_objhash_count_type(struct namedobj_instance * ni,uint16_t type)4573 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4574 {
4575 	struct named_object *no;
4576 	uint32_t count;
4577 	int i;
4578 
4579 	count = 0;
4580 	for (i = 0; i < ni->nn_size; i++) {
4581 		TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4582 			if (no->etlv == type)
4583 				count++;
4584 		}
4585 	}
4586 	return (count);
4587 }
4588 
4589 /*
4590  * Runs @func for each found named object.
4591  * It is safe to delete objects from callback
4592  */
4593 int
ipfw_objhash_foreach(struct namedobj_instance * ni,objhash_cb_t * f,void * arg)4594 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4595 {
4596 	struct named_object *no, *no_tmp;
4597 	int i, ret;
4598 
4599 	for (i = 0; i < ni->nn_size; i++) {
4600 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4601 			ret = f(ni, no, arg);
4602 			if (ret != 0)
4603 				return (ret);
4604 		}
4605 	}
4606 	return (0);
4607 }
4608 
4609 /*
4610  * Runs @f for each found named object with type @type.
4611  * It is safe to delete objects from callback
4612  */
4613 int
ipfw_objhash_foreach_type(struct namedobj_instance * ni,objhash_cb_t * f,void * arg,uint16_t type)4614 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4615     void *arg, uint16_t type)
4616 {
4617 	struct named_object *no, *no_tmp;
4618 	int i, ret;
4619 
4620 	for (i = 0; i < ni->nn_size; i++) {
4621 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4622 			if (no->etlv != type)
4623 				continue;
4624 			ret = f(ni, no, arg);
4625 			if (ret != 0)
4626 				return (ret);
4627 		}
4628 	}
4629 	return (0);
4630 }
4631 
4632 /*
4633  * Removes index from given set.
4634  * Returns 0 on success.
4635  */
4636 int
ipfw_objhash_free_idx(struct namedobj_instance * ni,uint16_t idx)4637 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4638 {
4639 	u_long *mask;
4640 	int i, v;
4641 
4642 	i = idx / BLOCK_ITEMS;
4643 	v = idx % BLOCK_ITEMS;
4644 
4645 	if (i >= ni->max_blocks)
4646 		return (1);
4647 
4648 	mask = &ni->idx_mask[i];
4649 
4650 	if ((*mask & ((u_long)1 << v)) != 0)
4651 		return (1);
4652 
4653 	/* Mark as free */
4654 	*mask |= (u_long)1 << v;
4655 
4656 	/* Update free offset */
4657 	if (ni->free_off[0] > i)
4658 		ni->free_off[0] = i;
4659 
4660 	return (0);
4661 }
4662 
4663 /*
4664  * Allocate new index in given instance and stores in in @pidx.
4665  * Returns 0 on success.
4666  */
4667 int
ipfw_objhash_alloc_idx(void * n,uint16_t * pidx)4668 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4669 {
4670 	struct namedobj_instance *ni;
4671 	u_long *mask;
4672 	int i, off, v;
4673 
4674 	ni = (struct namedobj_instance *)n;
4675 
4676 	off = ni->free_off[0];
4677 	mask = &ni->idx_mask[off];
4678 
4679 	for (i = off; i < ni->max_blocks; i++, mask++) {
4680 		if ((v = ffsl(*mask)) == 0)
4681 			continue;
4682 
4683 		/* Mark as busy */
4684 		*mask &= ~ ((u_long)1 << (v - 1));
4685 
4686 		ni->free_off[0] = i;
4687 
4688 		v = BLOCK_ITEMS * i + v - 1;
4689 
4690 		*pidx = v;
4691 		return (0);
4692 	}
4693 
4694 	return (1);
4695 }
4696 
4697 /* end of file */
4698