1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5 * Copyright (c) 2014-2025 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 enum ipfw_opcheck_result
check_opcode_compat_nop(ipfw_insn ** pcmd,int * plen,struct rule_check_info * ci)78 check_opcode_compat_nop(ipfw_insn **pcmd, int *plen,
79 struct rule_check_info *ci)
80 {
81 /* Compatibility code is not registered */
82 return (FAILED);
83 }
84
85 static ipfw_check_opcode_t check_opcode_f = check_opcode_compat_nop;
86
87 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
88 struct rule_check_info *ci);
89 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
90 struct rule_check_info *ci);
91
92 struct namedobj_instance {
93 struct namedobjects_head *names;
94 struct namedobjects_head *values;
95 uint32_t nn_size; /* names hash size */
96 uint32_t nv_size; /* number hash size */
97 u_long *idx_mask; /* used items bitmask */
98 uint32_t max_blocks; /* number of "long" blocks in bitmask */
99 uint32_t count; /* number of items */
100 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
101 objhash_hash_f *hash_f;
102 objhash_cmp_f *cmp_f;
103 };
104 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
105
106 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
107 const void *key, uint32_t kopt);
108 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
109 static int objhash_cmp_name(struct named_object *no, const void *name,
110 uint32_t set);
111
112 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
113
114 /* ctl3 handler data */
115 static struct mtx ctl3_lock;
116 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
117 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
118 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
119 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
120
121 static struct ipfw_sopt_handler *ctl3_handlers;
122 static size_t ctl3_hsize;
123 static uint64_t ctl3_refct, ctl3_gencnt;
124 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
125 #define CTL3_LARGEBUF (16 * 1024 * 1024) /* handle large rulesets */
126
127 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
128
129 static sopt_handler_f dump_config, add_rules, del_rules, clear_rules,
130 move_rules, manage_sets, dump_soptcodes, dump_srvobjects,
131 manage_skiptocache;
132
133 static struct ipfw_sopt_handler scodes[] = {
134 { IP_FW_XGET, IP_FW3_OPVER, HDIR_GET, dump_config },
135 { IP_FW_XADD, IP_FW3_OPVER, HDIR_BOTH, add_rules },
136 { IP_FW_XDEL, IP_FW3_OPVER, HDIR_BOTH, del_rules },
137 { IP_FW_XZERO, IP_FW3_OPVER, HDIR_SET, clear_rules },
138 { IP_FW_XRESETLOG, IP_FW3_OPVER, HDIR_SET, clear_rules },
139 { IP_FW_XMOVE, IP_FW3_OPVER, HDIR_SET, move_rules },
140 { IP_FW_SET_SWAP, IP_FW3_OPVER, HDIR_SET, manage_sets },
141 { IP_FW_SET_MOVE, IP_FW3_OPVER, HDIR_SET, manage_sets },
142 { IP_FW_SET_ENABLE, IP_FW3_OPVER, HDIR_SET, manage_sets },
143 { IP_FW_DUMP_SOPTCODES, IP_FW3_OPVER, HDIR_GET, dump_soptcodes },
144 { IP_FW_DUMP_SRVOBJECTS, IP_FW3_OPVER, HDIR_GET, dump_srvobjects },
145 { IP_FW_SKIPTO_CACHE, IP_FW3_OPVER, HDIR_BOTH, manage_skiptocache },
146 };
147
148 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
149 uint32_t *puidx, uint8_t *ptype);
150 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
151 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
152 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
153 struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
154 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
155 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
156 struct obj_idx *oib, struct obj_idx *end);
157 static int export_objhash_ntlv(struct namedobj_instance *ni, uint32_t kidx,
158 struct sockopt_data *sd);
159
160 /*
161 * Opcode object rewriter variables
162 */
163 struct opcode_obj_rewrite *ctl3_rewriters;
164 static size_t ctl3_rsize;
165
166 /*
167 * static variables followed by global ones
168 */
169
170 VNET_DEFINE_STATIC(uma_zone_t, ipfw_cntr_zone);
171 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
172
173 void
ipfw_init_counters(void)174 ipfw_init_counters(void)
175 {
176
177 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
178 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
179 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
180 }
181
182 void
ipfw_destroy_counters(void)183 ipfw_destroy_counters(void)
184 {
185
186 uma_zdestroy(V_ipfw_cntr_zone);
187 }
188
189 struct ip_fw *
ipfw_alloc_rule(struct ip_fw_chain * chain,size_t rulesize)190 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
191 {
192 struct ip_fw *rule;
193
194 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
195 rule->cntr = uma_zalloc_pcpu(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
196 rule->refcnt = 1;
197
198 return (rule);
199 }
200
201 void
ipfw_free_rule(struct ip_fw * rule)202 ipfw_free_rule(struct ip_fw *rule)
203 {
204
205 /*
206 * We don't release refcnt here, since this function
207 * can be called without any locks held. The caller
208 * must release reference under IPFW_UH_WLOCK, and then
209 * call this function if refcount becomes 1.
210 */
211 if (rule->refcnt > 1)
212 return;
213 if (ACTION_PTR(rule)->opcode == O_LOG)
214 ipfw_tap_free(rule->rulenum);
215 uma_zfree_pcpu(V_ipfw_cntr_zone, rule->cntr);
216 free(rule, M_IPFW);
217 }
218
219 /*
220 * Find the smallest rule >= key, id.
221 * We could use bsearch but it is so simple that we code it directly
222 */
223 int
ipfw_find_rule(struct ip_fw_chain * chain,uint32_t key,uint32_t id)224 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
225 {
226 int i, lo, hi;
227 struct ip_fw *r;
228
229 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
230 i = (lo + hi) / 2;
231 r = chain->map[i];
232 if (r->rulenum < key)
233 lo = i + 1; /* continue from the next one */
234 else if (r->rulenum > key)
235 hi = i; /* this might be good */
236 else if (r->id < id)
237 lo = i + 1; /* continue from the next one */
238 else /* r->id >= id */
239 hi = i; /* this might be good */
240 }
241 return hi;
242 }
243
244 /*
245 * Builds skipto cache on rule set @map.
246 */
247 static void
update_skipto_cache(struct ip_fw_chain * chain,struct ip_fw ** map)248 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
249 {
250 uint32_t *smap, rulenum;
251 int i, mi;
252
253 IPFW_UH_WLOCK_ASSERT(chain);
254
255 mi = 0;
256 rulenum = map[mi]->rulenum;
257 smap = chain->idxmap_back;
258
259 if (smap == NULL)
260 return;
261
262 for (i = 0; i <= IPFW_DEFAULT_RULE; i++) {
263 smap[i] = mi;
264 /* Use the same rule index until i < rulenum */
265 if (i != rulenum || i == IPFW_DEFAULT_RULE)
266 continue;
267 /* Find next rule with num > i */
268 rulenum = map[++mi]->rulenum;
269 while (rulenum == i)
270 rulenum = map[++mi]->rulenum;
271 }
272 }
273
274 /*
275 * Swaps prepared (backup) index with current one.
276 */
277 static void
swap_skipto_cache(struct ip_fw_chain * chain)278 swap_skipto_cache(struct ip_fw_chain *chain)
279 {
280 uint32_t *map;
281
282 IPFW_UH_WLOCK_ASSERT(chain);
283 IPFW_WLOCK_ASSERT(chain);
284
285 map = chain->idxmap;
286 chain->idxmap = chain->idxmap_back;
287 chain->idxmap_back = map;
288 }
289
290 /*
291 * Allocate and initialize skipto cache.
292 */
293 void
ipfw_init_skipto_cache(struct ip_fw_chain * chain)294 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
295 {
296 uint32_t *idxmap, *idxmap_back;
297
298 idxmap = malloc((IPFW_DEFAULT_RULE + 1) * sizeof(uint32_t),
299 M_IPFW, M_WAITOK | M_ZERO);
300 idxmap_back = malloc((IPFW_DEFAULT_RULE + 1) * sizeof(uint32_t),
301 M_IPFW, M_WAITOK | M_ZERO);
302
303 /*
304 * Note we may be called at any time after initialization,
305 * for example, on first skipto rule, so we need to
306 * provide valid chain->idxmap on return
307 */
308
309 IPFW_UH_WLOCK(chain);
310 if (chain->idxmap != NULL) {
311 IPFW_UH_WUNLOCK(chain);
312 free(idxmap, M_IPFW);
313 free(idxmap_back, M_IPFW);
314 return;
315 }
316
317 /* Set backup pointer first to permit building cache */
318 chain->idxmap_back = idxmap_back;
319 if (V_skipto_cache != 0)
320 update_skipto_cache(chain, chain->map);
321 IPFW_WLOCK(chain);
322 /* It is now safe to set chain->idxmap ptr */
323 chain->idxmap = idxmap;
324 swap_skipto_cache(chain);
325 IPFW_WUNLOCK(chain);
326 IPFW_UH_WUNLOCK(chain);
327 }
328
329 /*
330 * Destroys skipto cache.
331 */
332 void
ipfw_destroy_skipto_cache(struct ip_fw_chain * chain)333 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
334 {
335 free(chain->idxmap, M_IPFW);
336 free(chain->idxmap_back, M_IPFW);
337 }
338
339 /*
340 * allocate a new map, returns the chain locked. extra is the number
341 * of entries to add or delete.
342 */
343 static struct ip_fw **
get_map(struct ip_fw_chain * chain,int extra,int locked)344 get_map(struct ip_fw_chain *chain, int extra, int locked)
345 {
346
347 for (;;) {
348 struct ip_fw **map;
349 u_int i, mflags;
350
351 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
352
353 i = chain->n_rules + extra;
354 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
355 if (map == NULL) {
356 printf("%s: cannot allocate map\n", __FUNCTION__);
357 return NULL;
358 }
359 if (!locked)
360 IPFW_UH_WLOCK(chain);
361 if (i >= chain->n_rules + extra) /* good */
362 return map;
363 /* otherwise we lost the race, free and retry */
364 if (!locked)
365 IPFW_UH_WUNLOCK(chain);
366 free(map, M_IPFW);
367 }
368 }
369
370 /*
371 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
372 */
373 static struct ip_fw **
swap_map(struct ip_fw_chain * chain,struct ip_fw ** new_map,int new_len)374 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
375 {
376 struct ip_fw **old_map;
377
378 IPFW_WLOCK(chain);
379 chain->id++;
380 chain->n_rules = new_len;
381 old_map = chain->map;
382 chain->map = new_map;
383 swap_skipto_cache(chain);
384 IPFW_WUNLOCK(chain);
385 return old_map;
386 }
387
388 static void
export_cntr1_base(struct ip_fw * krule,struct ip_fw_bcounter * cntr)389 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
390 {
391 struct timeval boottime;
392
393 cntr->size = sizeof(*cntr);
394
395 if (krule->cntr != NULL) {
396 cntr->pcnt = counter_u64_fetch(krule->cntr);
397 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
398 cntr->timestamp = krule->timestamp;
399 }
400 if (cntr->timestamp > 0) {
401 getboottime(&boottime);
402 cntr->timestamp += boottime.tv_sec;
403 }
404 }
405
406 /*
407 * Export rule into v1 format (Current).
408 * Layout:
409 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
410 * [ ip_fw_rule ] OR
411 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
412 * ]
413 * Assume @data is zeroed.
414 */
415 static void
export_rule1(struct ip_fw * krule,caddr_t data,int len,int rcntrs)416 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
417 {
418 struct ip_fw_bcounter *cntr;
419 struct ip_fw_rule *urule;
420 ipfw_obj_tlv *tlv;
421
422 /* Fill in TLV header */
423 tlv = (ipfw_obj_tlv *)data;
424 tlv->type = IPFW_TLV_RULE_ENT;
425 tlv->length = len;
426
427 if (rcntrs != 0) {
428 /* Copy counters */
429 cntr = (struct ip_fw_bcounter *)(tlv + 1);
430 urule = (struct ip_fw_rule *)(cntr + 1);
431 export_cntr1_base(krule, cntr);
432 } else
433 urule = (struct ip_fw_rule *)(tlv + 1);
434
435 /* copy header */
436 urule->act_ofs = krule->act_ofs;
437 urule->cmd_len = krule->cmd_len;
438 urule->rulenum = krule->rulenum;
439 urule->set = krule->set;
440 urule->flags = krule->flags;
441 urule->id = krule->id;
442
443 /* Copy opcodes */
444 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
445 }
446
447 /*
448 * Add new rule(s) to the list possibly creating rule number for each.
449 * Update the rule_number in the input struct so the caller knows it as well.
450 * Must be called without IPFW_UH held
451 */
452 int
ipfw_commit_rules(struct ip_fw_chain * chain,struct rule_check_info * rci,int count)453 ipfw_commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci,
454 int count)
455 {
456 int error, i, insert_before, tcount, rule_idx, last_rule_idx;
457 uint32_t rulenum;
458 struct rule_check_info *ci;
459 struct ip_fw *krule;
460 struct ip_fw **map; /* the new array of pointers */
461
462 /* Check if we need to do table/obj index remap */
463 tcount = 0;
464 for (ci = rci, i = 0; i < count; ci++, i++) {
465 if (ci->object_opcodes == 0)
466 continue;
467
468 /*
469 * Rule has some object opcodes.
470 * We need to find (and create non-existing)
471 * kernel objects, and reference existing ones.
472 */
473 error = rewrite_rule_uidx(chain, ci);
474 if (error != 0) {
475
476 /*
477 * rewrite failed, state for current rule
478 * has been reverted. Check if we need to
479 * revert more.
480 */
481 if (tcount > 0) {
482
483 /*
484 * We have some more table rules
485 * we need to rollback.
486 */
487
488 IPFW_UH_WLOCK(chain);
489 while (ci != rci) {
490 ci--;
491 if (ci->object_opcodes == 0)
492 continue;
493 unref_rule_objects(chain,ci->krule);
494
495 }
496 IPFW_UH_WUNLOCK(chain);
497
498 }
499
500 return (error);
501 }
502
503 tcount++;
504 }
505
506 /* get_map returns with IPFW_UH_WLOCK if successful */
507 map = get_map(chain, count, 0 /* not locked */);
508 if (map == NULL) {
509 if (tcount > 0) {
510 /* Unbind tables */
511 IPFW_UH_WLOCK(chain);
512 for (ci = rci, i = 0; i < count; ci++, i++) {
513 if (ci->object_opcodes == 0)
514 continue;
515
516 unref_rule_objects(chain, ci->krule);
517 }
518 IPFW_UH_WUNLOCK(chain);
519 }
520
521 return (ENOSPC);
522 }
523
524 if (V_autoinc_step < 1)
525 V_autoinc_step = 1;
526 else if (V_autoinc_step > 1000)
527 V_autoinc_step = 1000;
528
529 last_rule_idx = 0;
530 for (ci = rci, i = 0; i < count; ci++, i++) {
531 krule = ci->krule;
532 rulenum = krule->rulenum;
533
534 krule->id = chain->id + 1;
535
536 /* find the insertion point, we will insert before */
537 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
538 rule_idx = ipfw_find_rule(chain, insert_before, 0);
539 /* duplicate the previous part */
540 if (last_rule_idx < rule_idx)
541 bcopy(chain->map + last_rule_idx, map + last_rule_idx + i,
542 (rule_idx - last_rule_idx) * sizeof(struct ip_fw *));
543 last_rule_idx = rule_idx;
544 map[rule_idx + i] = krule;
545 if (rulenum == 0) {
546 /* Compute rule number and write it back */
547 rulenum = rule_idx + i > 0 ? map[rule_idx + i - 1]->rulenum : 0;
548 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
549 rulenum += V_autoinc_step;
550 krule->rulenum = rulenum;
551 /* Save number to userland rule */
552 memcpy((char *)ci->urule + ci->urule_numoff, &rulenum,
553 sizeof(rulenum));
554 }
555 }
556
557 /* duplicate the remaining part, we always have the default rule */
558 bcopy(chain->map + last_rule_idx, map + last_rule_idx + count,
559 (chain->n_rules - last_rule_idx) * sizeof(struct ip_fw *));
560
561 if (V_skipto_cache != 0)
562 update_skipto_cache(chain, map);
563 map = swap_map(chain, map, chain->n_rules + count);
564 IPFW_UH_WUNLOCK(chain);
565 if (map)
566 free(map, M_IPFW);
567 return (0);
568 }
569
570 int
ipfw_add_protected_rule(struct ip_fw_chain * chain,struct ip_fw * rule,int locked)571 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
572 int locked)
573 {
574 struct ip_fw **map;
575
576 map = get_map(chain, 1, locked);
577 if (map == NULL)
578 return (ENOMEM);
579 if (chain->n_rules > 0)
580 bcopy(chain->map, map,
581 chain->n_rules * sizeof(struct ip_fw *));
582 map[chain->n_rules] = rule;
583 rule->rulenum = IPFW_DEFAULT_RULE;
584 rule->set = RESVD_SET;
585 rule->id = chain->id + 1;
586 /* We add rule in the end of chain, no need to update skipto cache */
587 map = swap_map(chain, map, chain->n_rules + 1);
588 IPFW_UH_WUNLOCK(chain);
589 free(map, M_IPFW);
590 return (0);
591 }
592
593 /*
594 * Adds @rule to the list of rules to reap
595 */
596 void
ipfw_reap_add(struct ip_fw_chain * chain,struct ip_fw ** head,struct ip_fw * rule)597 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
598 struct ip_fw *rule)
599 {
600
601 IPFW_UH_WLOCK_ASSERT(chain);
602
603 /* Unlink rule from everywhere */
604 unref_rule_objects(chain, rule);
605
606 rule->next = *head;
607 *head = rule;
608 }
609
610 /*
611 * Reclaim storage associated with a list of rules. This is
612 * typically the list created using remove_rule.
613 * A NULL pointer on input is handled correctly.
614 */
615 void
ipfw_reap_rules(struct ip_fw * head)616 ipfw_reap_rules(struct ip_fw *head)
617 {
618 struct ip_fw *rule;
619
620 while ((rule = head) != NULL) {
621 head = head->next;
622 ipfw_free_rule(rule);
623 }
624 }
625
626 /*
627 * Rules to keep are
628 * (default || reserved || !match_set || !match_number)
629 * where
630 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
631 * // the default rule is always protected
632 *
633 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
634 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
635 *
636 * match_set ::= (cmd == 0 || rule->set == set)
637 * // set number is ignored for cmd == 0
638 *
639 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
640 * // number is ignored for cmd == 1 or n == 0
641 *
642 */
643 int
ipfw_match_range(struct ip_fw * rule,ipfw_range_tlv * rt)644 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
645 {
646
647 /* Don't match default rule for modification queries */
648 if (rule->rulenum == IPFW_DEFAULT_RULE &&
649 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
650 return (0);
651
652 /* Don't match rules in reserved set for flush requests */
653 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
654 return (0);
655
656 /* If we're filtering by set, don't match other sets */
657 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
658 return (0);
659
660 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
661 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
662 return (0);
663
664 return (1);
665 }
666
667 struct manage_sets_args {
668 uint32_t set;
669 uint8_t new_set;
670 };
671
672 static int
swap_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)673 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
674 void *arg)
675 {
676 struct manage_sets_args *args;
677
678 args = (struct manage_sets_args *)arg;
679 if (no->set == (uint8_t)args->set)
680 no->set = args->new_set;
681 else if (no->set == args->new_set)
682 no->set = (uint8_t)args->set;
683 return (0);
684 }
685
686 static int
move_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)687 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
688 void *arg)
689 {
690 struct manage_sets_args *args;
691
692 args = (struct manage_sets_args *)arg;
693 if (no->set == (uint8_t)args->set)
694 no->set = args->new_set;
695 return (0);
696 }
697
698 static int
test_sets_cb(struct namedobj_instance * ni,struct named_object * no,void * arg)699 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
700 void *arg)
701 {
702 struct manage_sets_args *args;
703
704 args = (struct manage_sets_args *)arg;
705 if (no->set != (uint8_t)args->set)
706 return (0);
707 if (ipfw_objhash_lookup_name_type(ni, args->new_set,
708 no->etlv, no->name) != NULL)
709 return (EEXIST);
710 return (0);
711 }
712
713 /*
714 * Generic function to handler moving and swapping sets.
715 */
716 int
ipfw_obj_manage_sets(struct namedobj_instance * ni,uint16_t type,uint32_t set,uint8_t new_set,enum ipfw_sets_cmd cmd)717 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
718 uint32_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
719 {
720 struct manage_sets_args args;
721 struct named_object *no;
722
723 args.set = set;
724 args.new_set = new_set;
725 switch (cmd) {
726 case SWAP_ALL:
727 return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
728 &args, type));
729 case TEST_ALL:
730 return (ipfw_objhash_foreach_type(ni, test_sets_cb,
731 &args, type));
732 case MOVE_ALL:
733 return (ipfw_objhash_foreach_type(ni, move_sets_cb,
734 &args, type));
735 case COUNT_ONE:
736 /*
737 * @set used to pass kidx.
738 * When @new_set is zero - reset object counter,
739 * otherwise increment it.
740 */
741 no = ipfw_objhash_lookup_kidx(ni, set);
742 if (new_set != 0)
743 no->ocnt++;
744 else
745 no->ocnt = 0;
746 return (0);
747 case TEST_ONE:
748 /* @set used to pass kidx */
749 no = ipfw_objhash_lookup_kidx(ni, set);
750 /*
751 * First check number of references:
752 * when it differs, this mean other rules are holding
753 * reference to given object, so it is not possible to
754 * change its set. Note that refcnt may account references
755 * to some going-to-be-added rules. Since we don't know
756 * their numbers (and even if they will be added) it is
757 * perfectly OK to return error here.
758 */
759 if (no->ocnt != no->refcnt)
760 return (EBUSY);
761 if (ipfw_objhash_lookup_name_type(ni, new_set, type,
762 no->name) != NULL)
763 return (EEXIST);
764 return (0);
765 case MOVE_ONE:
766 /* @set used to pass kidx */
767 no = ipfw_objhash_lookup_kidx(ni, set);
768 no->set = new_set;
769 return (0);
770 }
771 return (EINVAL);
772 }
773
774 /*
775 * Delete rules matching range @rt.
776 * Saves number of deleted rules in @ndel.
777 *
778 * Returns 0 on success.
779 */
780 int
delete_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int * ndel)781 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
782 {
783 struct ip_fw *reap, *rule, **map;
784 uint32_t end, start;
785 int i, n, ndyn, ofs;
786
787 reap = NULL;
788 IPFW_UH_WLOCK(chain); /* arbitrate writers */
789
790 /*
791 * Stage 1: Determine range to inspect.
792 * Range is half-inclusive, e.g [start, end).
793 */
794 start = 0;
795 end = chain->n_rules - 1;
796
797 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
798 start = ipfw_find_rule(chain, rt->start_rule, 0);
799
800 if (rt->end_rule >= IPFW_DEFAULT_RULE)
801 rt->end_rule = IPFW_DEFAULT_RULE - 1;
802 end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
803 }
804
805 if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
806 /*
807 * Requested deleting only for dynamic states.
808 */
809 *ndel = 0;
810 ipfw_expire_dyn_states(chain, rt);
811 IPFW_UH_WUNLOCK(chain);
812 return (0);
813 }
814
815 /* Allocate new map of the same size */
816 map = get_map(chain, 0, 1 /* locked */);
817 if (map == NULL) {
818 IPFW_UH_WUNLOCK(chain);
819 return (ENOMEM);
820 }
821
822 n = 0;
823 ndyn = 0;
824 ofs = start;
825 /* 1. bcopy the initial part of the map */
826 if (start > 0)
827 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
828 /* 2. copy active rules between start and end */
829 for (i = start; i < end; i++) {
830 rule = chain->map[i];
831 if (ipfw_match_range(rule, rt) == 0) {
832 map[ofs++] = rule;
833 continue;
834 }
835
836 n++;
837 if (ipfw_is_dyn_rule(rule) != 0)
838 ndyn++;
839 }
840 /* 3. copy the final part of the map */
841 bcopy(chain->map + end, map + ofs,
842 (chain->n_rules - end) * sizeof(struct ip_fw *));
843 /* 4. recalculate skipto cache */
844 update_skipto_cache(chain, map);
845 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
846 map = swap_map(chain, map, chain->n_rules - n);
847 /* 6. Remove all dynamic states originated by deleted rules */
848 if (ndyn > 0)
849 ipfw_expire_dyn_states(chain, rt);
850 /* 7. now remove the rules deleted from the old map */
851 for (i = start; i < end; i++) {
852 rule = map[i];
853 if (ipfw_match_range(rule, rt) == 0)
854 continue;
855 ipfw_reap_add(chain, &reap, rule);
856 }
857 IPFW_UH_WUNLOCK(chain);
858
859 ipfw_reap_rules(reap);
860 if (map != NULL)
861 free(map, M_IPFW);
862 *ndel = n;
863 return (0);
864 }
865
866 static int
move_objects(struct ip_fw_chain * ch,ipfw_range_tlv * rt)867 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
868 {
869 struct opcode_obj_rewrite *rw;
870 struct ip_fw *rule;
871 ipfw_insn *cmd;
872 uint32_t kidx;
873 int cmdlen, i, l, c;
874
875 IPFW_UH_WLOCK_ASSERT(ch);
876
877 /* Stage 1: count number of references by given rules */
878 for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
879 rule = ch->map[i];
880 if (ipfw_match_range(rule, rt) == 0)
881 continue;
882 if (rule->set == rt->new_set) /* nothing to do */
883 continue;
884 /* Search opcodes with named objects */
885 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
886 l > 0; l -= cmdlen, cmd += cmdlen) {
887 cmdlen = F_LEN(cmd);
888 rw = find_op_rw(cmd, &kidx, NULL);
889 if (rw == NULL || rw->manage_sets == NULL)
890 continue;
891 /*
892 * When manage_sets() returns non-zero value to
893 * COUNT_ONE command, consider this as an object
894 * doesn't support sets (e.g. disabled with sysctl).
895 * So, skip checks for this object.
896 */
897 if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
898 continue;
899 c++;
900 }
901 }
902 if (c == 0) /* No objects found */
903 return (0);
904 /* Stage 2: verify "ownership" */
905 for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
906 rule = ch->map[i];
907 if (ipfw_match_range(rule, rt) == 0)
908 continue;
909 if (rule->set == rt->new_set) /* nothing to do */
910 continue;
911 /* Search opcodes with named objects */
912 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
913 l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
914 cmdlen = F_LEN(cmd);
915 rw = find_op_rw(cmd, &kidx, NULL);
916 if (rw == NULL || rw->manage_sets == NULL)
917 continue;
918 /* Test for ownership and conflicting names */
919 c = rw->manage_sets(ch, kidx,
920 (uint8_t)rt->new_set, TEST_ONE);
921 }
922 }
923 /* Stage 3: change set and cleanup */
924 for (i = 0; i < ch->n_rules - 1; i++) {
925 rule = ch->map[i];
926 if (ipfw_match_range(rule, rt) == 0)
927 continue;
928 if (rule->set == rt->new_set) /* nothing to do */
929 continue;
930 /* Search opcodes with named objects */
931 for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
932 l > 0; l -= cmdlen, cmd += cmdlen) {
933 cmdlen = F_LEN(cmd);
934 rw = find_op_rw(cmd, &kidx, NULL);
935 if (rw == NULL || rw->manage_sets == NULL)
936 continue;
937 /* cleanup object counter */
938 rw->manage_sets(ch, kidx,
939 0 /* reset counter */, COUNT_ONE);
940 if (c != 0)
941 continue;
942 /* change set */
943 rw->manage_sets(ch, kidx,
944 (uint8_t)rt->new_set, MOVE_ONE);
945 }
946 }
947 return (c);
948 }
949
950 /*
951 * Changes set of given rule rannge @rt
952 * with each other.
953 *
954 * Returns 0 on success.
955 */
956 static int
move_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt)957 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
958 {
959 struct ip_fw *rule;
960 int i;
961
962 IPFW_UH_WLOCK(chain);
963
964 /*
965 * Move rules with matching paramenerts to a new set.
966 * This one is much more complex. We have to ensure
967 * that all referenced tables (if any) are referenced
968 * by given rule subset only. Otherwise, we can't move
969 * them to new set and have to return error.
970 */
971 if ((i = move_objects(chain, rt)) != 0) {
972 IPFW_UH_WUNLOCK(chain);
973 return (i);
974 }
975
976 /* XXX: We have to do swap holding WLOCK */
977 for (i = 0; i < chain->n_rules; i++) {
978 rule = chain->map[i];
979 if (ipfw_match_range(rule, rt) == 0)
980 continue;
981 rule->set = rt->new_set;
982 }
983
984 IPFW_UH_WUNLOCK(chain);
985
986 return (0);
987 }
988
989 /*
990 * Returns pointer to action instruction, skips all possible rule
991 * modifiers like O_LOG, O_TAG, O_ALTQ.
992 */
993 ipfw_insn *
ipfw_get_action(struct ip_fw * rule)994 ipfw_get_action(struct ip_fw *rule)
995 {
996 ipfw_insn *cmd;
997 int l, cmdlen;
998
999 cmd = ACTION_PTR(rule);
1000 l = rule->cmd_len - rule->act_ofs;
1001 while (l > 0) {
1002 switch (cmd->opcode) {
1003 case O_ALTQ:
1004 case O_LOG:
1005 case O_TAG:
1006 break;
1007 default:
1008 return (cmd);
1009 }
1010 cmdlen = F_LEN(cmd);
1011 l -= cmdlen;
1012 cmd += cmdlen;
1013 }
1014 panic("%s: rule (%p) has not action opcode", __func__, rule);
1015 return (NULL);
1016 }
1017
1018 /*
1019 * Clear counters for a specific rule.
1020 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1021 * so we only care that rules do not disappear.
1022 */
1023 static void
clear_counters(struct ip_fw * rule,int log_only)1024 clear_counters(struct ip_fw *rule, int log_only)
1025 {
1026 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1027
1028 if (log_only == 0)
1029 IPFW_ZERO_RULE_COUNTER(rule);
1030 if (l->o.opcode == O_LOG)
1031 l->log_left = l->max_log;
1032 }
1033
1034 /*
1035 * Flushes rules counters and/or log values on matching range.
1036 *
1037 * Returns number of items cleared.
1038 */
1039 static int
clear_range(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int log_only)1040 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1041 {
1042 struct ip_fw *rule;
1043 int num;
1044 int i;
1045
1046 num = 0;
1047 rt->flags |= IPFW_RCFLAG_DEFAULT;
1048
1049 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1050 for (i = 0; i < chain->n_rules; i++) {
1051 rule = chain->map[i];
1052 if (ipfw_match_range(rule, rt) == 0)
1053 continue;
1054 clear_counters(rule, log_only);
1055 num++;
1056 }
1057 IPFW_UH_WUNLOCK(chain);
1058
1059 return (num);
1060 }
1061
1062 static int
check_range_tlv(ipfw_range_tlv * rt)1063 check_range_tlv(ipfw_range_tlv *rt)
1064 {
1065
1066 if (rt->head.length != sizeof(*rt))
1067 return (1);
1068 if (rt->start_rule > rt->end_rule)
1069 return (1);
1070 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1071 return (1);
1072
1073 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1074 return (1);
1075
1076 return (0);
1077 }
1078
1079 /*
1080 * Delete rules matching specified parameters
1081 * Data layout (v0)(current):
1082 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1083 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1084 *
1085 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1086 *
1087 * Returns 0 on success.
1088 */
1089 static int
del_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1090 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1091 struct sockopt_data *sd)
1092 {
1093 ipfw_range_header *rh;
1094 int error, ndel;
1095
1096 if (sd->valsize != sizeof(*rh))
1097 return (EINVAL);
1098
1099 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1100
1101 if (check_range_tlv(&rh->range) != 0)
1102 return (EINVAL);
1103
1104 ndel = 0;
1105 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1106 return (error);
1107
1108 /* Save number of rules deleted */
1109 rh->range.new_set = ndel;
1110 return (0);
1111 }
1112
1113 /*
1114 * Move rules/sets matching specified parameters
1115 * Data layout (v0)(current):
1116 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1117 *
1118 * Returns 0 on success.
1119 */
1120 static int
move_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1121 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1122 struct sockopt_data *sd)
1123 {
1124 ipfw_range_header *rh;
1125
1126 if (sd->valsize != sizeof(*rh))
1127 return (EINVAL);
1128
1129 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1130
1131 if (check_range_tlv(&rh->range) != 0)
1132 return (EINVAL);
1133
1134 return (move_range(chain, &rh->range));
1135 }
1136
1137 /*
1138 * Clear rule accounting data matching specified parameters
1139 * Data layout (v0)(current):
1140 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1141 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1142 *
1143 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1144 *
1145 * Returns 0 on success.
1146 */
1147 static int
clear_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1148 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1149 struct sockopt_data *sd)
1150 {
1151 ipfw_range_header *rh;
1152 int log_only, num;
1153 char *msg;
1154
1155 if (sd->valsize != sizeof(*rh))
1156 return (EINVAL);
1157
1158 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1159
1160 if (check_range_tlv(&rh->range) != 0)
1161 return (EINVAL);
1162
1163 log_only = (op3->opcode == IP_FW_XRESETLOG);
1164
1165 num = clear_range(chain, &rh->range, log_only);
1166
1167 if (rh->range.flags & IPFW_RCFLAG_ALL)
1168 msg = log_only ? "All logging counts reset" :
1169 "Accounting cleared";
1170 else
1171 msg = log_only ? "logging count reset" : "cleared";
1172
1173 if (V_fw_verbose) {
1174 int lev = LOG_SECURITY | LOG_NOTICE;
1175 log(lev, "ipfw: %s.\n", msg);
1176 }
1177
1178 /* Save number of rules cleared */
1179 rh->range.new_set = num;
1180 return (0);
1181 }
1182
1183 static void
enable_sets(struct ip_fw_chain * chain,ipfw_range_tlv * rt)1184 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1185 {
1186 uint32_t v_set;
1187
1188 IPFW_UH_WLOCK_ASSERT(chain);
1189
1190 /* Change enabled/disabled sets mask */
1191 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1192 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1193 IPFW_WLOCK(chain);
1194 V_set_disable = v_set;
1195 IPFW_WUNLOCK(chain);
1196 }
1197
1198 static int
swap_sets(struct ip_fw_chain * chain,ipfw_range_tlv * rt,int mv)1199 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1200 {
1201 struct opcode_obj_rewrite *rw;
1202 struct ip_fw *rule;
1203 int i;
1204
1205 IPFW_UH_WLOCK_ASSERT(chain);
1206
1207 if (rt->set == rt->new_set) /* nothing to do */
1208 return (0);
1209
1210 if (mv != 0) {
1211 /*
1212 * Berfore moving the rules we need to check that
1213 * there aren't any conflicting named objects.
1214 */
1215 for (rw = ctl3_rewriters;
1216 rw < ctl3_rewriters + ctl3_rsize; rw++) {
1217 if (rw->manage_sets == NULL)
1218 continue;
1219 i = rw->manage_sets(chain, (uint8_t)rt->set,
1220 (uint8_t)rt->new_set, TEST_ALL);
1221 if (i != 0)
1222 return (EEXIST);
1223 }
1224 }
1225 /* Swap or move two sets */
1226 for (i = 0; i < chain->n_rules - 1; i++) {
1227 rule = chain->map[i];
1228 if (rule->set == (uint8_t)rt->set)
1229 rule->set = (uint8_t)rt->new_set;
1230 else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1231 rule->set = (uint8_t)rt->set;
1232 }
1233 for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1234 if (rw->manage_sets == NULL)
1235 continue;
1236 rw->manage_sets(chain, (uint8_t)rt->set,
1237 (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1238 }
1239 return (0);
1240 }
1241
1242 /*
1243 * Swaps or moves set
1244 * Data layout (v0)(current):
1245 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1246 *
1247 * Returns 0 on success.
1248 */
1249 static int
manage_sets(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1250 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1251 struct sockopt_data *sd)
1252 {
1253 ipfw_range_header *rh;
1254 int ret;
1255
1256 if (sd->valsize != sizeof(*rh))
1257 return (EINVAL);
1258
1259 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1260
1261 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1262 return (1);
1263 /* enable_sets() expects bitmasks. */
1264 if (op3->opcode != IP_FW_SET_ENABLE &&
1265 (rh->range.set >= IPFW_MAX_SETS ||
1266 rh->range.new_set >= IPFW_MAX_SETS))
1267 return (EINVAL);
1268
1269 ret = 0;
1270 IPFW_UH_WLOCK(chain);
1271 switch (op3->opcode) {
1272 case IP_FW_SET_SWAP:
1273 case IP_FW_SET_MOVE:
1274 ret = swap_sets(chain, &rh->range,
1275 op3->opcode == IP_FW_SET_MOVE);
1276 break;
1277 case IP_FW_SET_ENABLE:
1278 enable_sets(chain, &rh->range);
1279 break;
1280 }
1281 IPFW_UH_WUNLOCK(chain);
1282
1283 return (ret);
1284 }
1285
1286 /* Check rule format */
1287 int
ipfw_check_rule(struct ip_fw_rule * rule,size_t size,struct rule_check_info * ci)1288 ipfw_check_rule(struct ip_fw_rule *rule, size_t size,
1289 struct rule_check_info *ci)
1290 {
1291 int l;
1292
1293 if (size < sizeof(*rule)) {
1294 printf("ipfw: rule too short\n");
1295 return (EINVAL);
1296 }
1297
1298 /* Check for valid cmd_len */
1299 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1300 if (l != size) {
1301 printf("ipfw: size mismatch (have %zu want %d)\n", size, l);
1302 return (EINVAL);
1303 }
1304 if (rule->act_ofs >= rule->cmd_len) {
1305 printf("ipfw: bogus action offset (%u > %u)\n",
1306 rule->act_ofs, rule->cmd_len - 1);
1307 return (EINVAL);
1308 }
1309
1310 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1311 return (EINVAL);
1312
1313 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1314 }
1315
1316 #define CHECK_TARG(a, c) \
1317 ((a) == IP_FW_TARG && ((c)->flags & IPFW_RCIFLAG_HAS_STATE))
1318
1319 enum ipfw_opcheck_result
ipfw_check_opcode(ipfw_insn ** pcmd,int * plen,struct rule_check_info * ci)1320 ipfw_check_opcode(ipfw_insn **pcmd, int *plen, struct rule_check_info *ci)
1321 {
1322 ipfw_insn *cmd;
1323 size_t cmdlen;
1324
1325 cmd = *pcmd;
1326 cmdlen = F_LEN(cmd);
1327
1328 switch (cmd->opcode) {
1329 case O_PROBE_STATE:
1330 case O_KEEP_STATE:
1331 if (cmdlen != F_INSN_SIZE(ipfw_insn_kidx))
1332 return (BAD_SIZE);
1333 ci->object_opcodes++;
1334 ci->flags |= IPFW_RCIFLAG_HAS_STATE;
1335 break;
1336 case O_PROTO:
1337 case O_IP_SRC_ME:
1338 case O_IP_DST_ME:
1339 case O_LAYER2:
1340 case O_IN:
1341 case O_FRAG:
1342 case O_DIVERTED:
1343 case O_IPOPT:
1344 case O_IPTOS:
1345 case O_IPPRECEDENCE:
1346 case O_IPVER:
1347 case O_SOCKARG:
1348 case O_TCPFLAGS:
1349 case O_TCPOPTS:
1350 case O_ESTAB:
1351 case O_VERREVPATH:
1352 case O_VERSRCREACH:
1353 case O_ANTISPOOF:
1354 case O_IPSEC:
1355 #ifdef INET6
1356 case O_IP6_SRC_ME:
1357 case O_IP6_DST_ME:
1358 case O_EXT_HDR:
1359 case O_IP6:
1360 #endif
1361 case O_IP4:
1362 case O_TAG:
1363 case O_SKIP_ACTION:
1364 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1365 return (BAD_SIZE);
1366 break;
1367
1368 case O_EXTERNAL_ACTION:
1369 if (cmdlen != F_INSN_SIZE(ipfw_insn_kidx))
1370 return (BAD_SIZE);
1371
1372 if (insntod(cmd, kidx)->kidx == 0)
1373 return (FAILED);
1374 ci->object_opcodes++;
1375 /*
1376 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1377 * opcode?
1378 */
1379 if (*plen != cmdlen) {
1380 *plen -= cmdlen;
1381 cmd += cmdlen;
1382 *pcmd = cmd;
1383 cmdlen = F_LEN(cmd);
1384 if (cmd->opcode == O_EXTERNAL_DATA)
1385 return (CHECK_ACTION);
1386 if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1387 printf("ipfw: invalid opcode "
1388 "next to external action %u\n",
1389 cmd->opcode);
1390 return (FAILED);
1391 }
1392 if (cmdlen != F_INSN_SIZE(ipfw_insn_kidx))
1393 return (BAD_SIZE);
1394 if (insntod(cmd, kidx)->kidx == 0)
1395 return (FAILED);
1396 ci->object_opcodes++;
1397 }
1398 return (CHECK_ACTION);
1399
1400 case O_FIB:
1401 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1402 return (BAD_SIZE);
1403 if (cmd->arg1 >= rt_numfibs) {
1404 printf("ipfw: invalid fib number %d\n",
1405 cmd->arg1);
1406 return (FAILED);
1407 }
1408 break;
1409
1410 case O_SETFIB:
1411 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1412 return (BAD_SIZE);
1413 if ((cmd->arg1 != IP_FW_TARG) &&
1414 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1415 printf("ipfw: invalid fib number %d\n",
1416 cmd->arg1 & 0x7FFF);
1417 return (FAILED);
1418 }
1419 if (CHECK_TARG(cmd->arg1, ci))
1420 goto bad_targ;
1421 return (CHECK_ACTION);
1422
1423 case O_UID:
1424 case O_GID:
1425 case O_JAIL:
1426 case O_IP_SRC:
1427 case O_IP_DST:
1428 case O_TCPSEQ:
1429 case O_TCPACK:
1430 case O_PROB:
1431 case O_ICMPTYPE:
1432 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1433 return (BAD_SIZE);
1434 break;
1435
1436 case O_LIMIT:
1437 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1438 return (BAD_SIZE);
1439 ci->object_opcodes++;
1440 break;
1441
1442 case O_LOG:
1443 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1444 return (BAD_SIZE);
1445 insntod(cmd, log)->log_left = insntod(cmd, log)->max_log;
1446 break;
1447
1448 case O_IP_SRC_MASK:
1449 case O_IP_DST_MASK:
1450 /* only odd command lengths */
1451 if ((cmdlen & 1) == 0)
1452 return (BAD_SIZE);
1453 break;
1454
1455 case O_IP_SRC_SET:
1456 case O_IP_DST_SET:
1457 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1458 printf("ipfw: invalid set size %d\n",
1459 cmd->arg1);
1460 return (FAILED);
1461 }
1462 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1463 (cmd->arg1+31)/32 )
1464 return (BAD_SIZE);
1465 break;
1466
1467 case O_IP_SRC_LOOKUP:
1468 case O_IP_DST_LOOKUP:
1469 case O_IP_FLOW_LOOKUP:
1470 case O_MAC_SRC_LOOKUP:
1471 case O_MAC_DST_LOOKUP:
1472 if (cmdlen != F_INSN_SIZE(ipfw_insn_kidx) &&
1473 cmdlen != F_INSN_SIZE(ipfw_insn_table))
1474 return (BAD_SIZE);
1475 if (insntod(cmd, kidx)->kidx >= V_fw_tables_max) {
1476 printf("ipfw: invalid table index %u\n",
1477 insntod(cmd, kidx)->kidx);
1478 return (FAILED);
1479 }
1480 ci->object_opcodes++;
1481 break;
1482 case O_MACADDR2:
1483 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1484 return (BAD_SIZE);
1485 break;
1486
1487 case O_NOP:
1488 case O_IPID:
1489 case O_IPTTL:
1490 case O_IPLEN:
1491 case O_TCPDATALEN:
1492 case O_TCPMSS:
1493 case O_TCPWIN:
1494 case O_TAGGED:
1495 if (cmdlen < 1 || cmdlen > 31)
1496 return (BAD_SIZE);
1497 break;
1498
1499 case O_DSCP:
1500 case O_MARK:
1501 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1502 return (BAD_SIZE);
1503 break;
1504
1505 case O_MAC_TYPE:
1506 case O_IP_SRCPORT:
1507 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1508 if (cmdlen < 2 || cmdlen > 31)
1509 return (BAD_SIZE);
1510 break;
1511
1512 case O_RECV:
1513 case O_XMIT:
1514 case O_VIA:
1515 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1516 return (BAD_SIZE);
1517 ci->object_opcodes++;
1518 break;
1519
1520 case O_ALTQ:
1521 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1522 return (BAD_SIZE);
1523 break;
1524
1525 case O_PIPE:
1526 case O_QUEUE:
1527 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1528 return (BAD_SIZE);
1529 if (CHECK_TARG(cmd->arg1, ci))
1530 goto bad_targ;
1531 return (CHECK_ACTION);
1532
1533 case O_FORWARD_IP:
1534 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1535 return (BAD_SIZE);
1536 if (insntoc(cmd, sa)->sa.sin_addr.s_addr == INADDR_ANY &&
1537 (ci->flags & IPFW_RCIFLAG_HAS_STATE))
1538 goto bad_targ;
1539 return (CHECK_ACTION);
1540 #ifdef INET6
1541 case O_FORWARD_IP6:
1542 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1543 return (BAD_SIZE);
1544 return (CHECK_ACTION);
1545 #endif /* INET6 */
1546
1547 case O_DIVERT:
1548 case O_TEE:
1549 if (ip_divert_ptr == NULL)
1550 return (FAILED);
1551 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1552 return (BAD_SIZE);
1553 if (CHECK_TARG(cmd->arg1, ci))
1554 goto bad_targ;
1555 return (CHECK_ACTION);
1556 case O_NETGRAPH:
1557 case O_NGTEE:
1558 if (ng_ipfw_input_p == NULL)
1559 return (FAILED);
1560 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1561 return (BAD_SIZE);
1562 if (CHECK_TARG(cmd->arg1, ci))
1563 goto bad_targ;
1564 return (CHECK_ACTION);
1565 case O_NAT:
1566 if (!IPFW_NAT_LOADED)
1567 return (FAILED);
1568 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1569 return (BAD_SIZE);
1570 if (CHECK_TARG(cmd->arg1, ci))
1571 goto bad_targ;
1572 return (CHECK_ACTION);
1573
1574 case O_SKIPTO:
1575 case O_CALLRETURN:
1576 case O_SETMARK:
1577 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1578 return (BAD_SIZE);
1579 /* O_CALLRETURN + F_NOT means 'return' opcode. */
1580 if (cmd->opcode != O_CALLRETURN || (cmd->len & F_NOT) == 0) {
1581 if (CHECK_TARG(insntoc(cmd, u32)->d[0], ci))
1582 goto bad_targ;
1583 }
1584 return (CHECK_ACTION);
1585
1586 case O_CHECK_STATE:
1587 if (cmdlen != F_INSN_SIZE(ipfw_insn_kidx))
1588 return (BAD_SIZE);
1589 ci->object_opcodes++;
1590 return (CHECK_ACTION);
1591
1592 case O_FORWARD_MAC: /* XXX not implemented yet */
1593 case O_COUNT:
1594 case O_ACCEPT:
1595 case O_DENY:
1596 case O_REJECT:
1597 case O_SETDSCP:
1598 #ifdef INET6
1599 case O_UNREACH6:
1600 #endif
1601 case O_REASS:
1602 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1603 return (BAD_SIZE);
1604 if (cmd->opcode == O_SETDSCP && CHECK_TARG(cmd->arg1, ci))
1605 goto bad_targ;
1606 return (CHECK_ACTION);
1607 #ifdef INET6
1608 case O_IP6_SRC:
1609 case O_IP6_DST:
1610 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1611 F_INSN_SIZE(ipfw_insn))
1612 return (BAD_SIZE);
1613 break;
1614
1615 case O_FLOW6ID:
1616 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1617 ((ipfw_insn_u32 *)cmd)->o.arg1)
1618 return (BAD_SIZE);
1619 break;
1620
1621 case O_IP6_SRC_MASK:
1622 case O_IP6_DST_MASK:
1623 if ( !(cmdlen & 1) || cmdlen > 127)
1624 return (BAD_SIZE);
1625 break;
1626 case O_ICMP6TYPE:
1627 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
1628 return (BAD_SIZE);
1629 break;
1630 #endif
1631
1632 default:
1633 switch (cmd->opcode) {
1634 #ifndef INET6
1635 case O_IP6_SRC_ME:
1636 case O_IP6_DST_ME:
1637 case O_EXT_HDR:
1638 case O_IP6:
1639 case O_UNREACH6:
1640 case O_IP6_SRC:
1641 case O_IP6_DST:
1642 case O_FLOW6ID:
1643 case O_IP6_SRC_MASK:
1644 case O_IP6_DST_MASK:
1645 case O_ICMP6TYPE:
1646 printf("ipfw: no IPv6 support in kernel\n");
1647 return (FAILED);
1648 #endif
1649 default:
1650 printf("ipfw: opcode %d: unknown opcode\n",
1651 cmd->opcode);
1652 return (FAILED);
1653 }
1654 }
1655 return (SUCCESS);
1656 bad_targ:
1657 /*
1658 * For dynamic states we can not correctly initialize tablearg value,
1659 * because we don't go through rule's opcodes except rule action.
1660 */
1661 printf("ipfw: tablearg is not allowed with dynamic states\n");
1662 return (FAILED);
1663 }
1664
1665 static __noinline int
check_ipfw_rule_body(ipfw_insn * cmd,int cmd_len,struct rule_check_info * ci)1666 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1667 {
1668 int cmdlen, l;
1669 int have_action, ret;
1670
1671 /*
1672 * Now go for the individual checks. Very simple ones, basically only
1673 * instruction sizes.
1674 */
1675 have_action = 0;
1676 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1677 cmdlen = F_LEN(cmd);
1678 if (cmdlen > l) {
1679 printf("ipfw: opcode %d: size truncated\n",
1680 cmd->opcode);
1681 return (EINVAL);
1682 }
1683 if (ci->version != IP_FW3_OPVER)
1684 ret = (*check_opcode_f)(&cmd, &l, ci);
1685 else
1686 ret = ipfw_check_opcode(&cmd, &l, ci);
1687
1688 if (ret == CHECK_ACTION) {
1689 if (have_action != 0) {
1690 printf("ipfw: opcode %d: multiple actions"
1691 " not allowed\n", cmd->opcode);
1692 ret = FAILED;
1693 } else
1694 have_action = 1;
1695
1696 if (l != F_LEN(cmd)) {
1697 printf("ipfw: opcode %d: action must be"
1698 " last opcode\n", cmd->opcode);
1699 ret = FAILED;
1700 }
1701 }
1702 switch (ret) {
1703 case SUCCESS:
1704 continue;
1705 case BAD_SIZE:
1706 printf("ipfw: opcode %d: wrong size %d\n",
1707 cmd->opcode, cmdlen);
1708 /* FALLTHROUGH */
1709 case FAILED:
1710 return (EINVAL);
1711 }
1712 }
1713 if (have_action == 0) {
1714 printf("ipfw: missing action\n");
1715 return (EINVAL);
1716 }
1717 return (0);
1718 }
1719
1720 struct dump_args {
1721 uint32_t b; /* start rule */
1722 uint32_t e; /* end rule */
1723 uint32_t rcount; /* number of rules */
1724 uint32_t rsize; /* rules size */
1725 uint32_t tcount; /* number of tables */
1726 int rcounters; /* counters */
1727 uint32_t *bmask; /* index bitmask of used named objects */
1728 };
1729
1730 void
ipfw_export_obj_ntlv(struct named_object * no,ipfw_obj_ntlv * ntlv)1731 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
1732 {
1733
1734 ntlv->head.type = no->etlv;
1735 ntlv->head.length = sizeof(*ntlv);
1736 ntlv->idx = no->kidx;
1737 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
1738 }
1739
1740 /*
1741 * Export named object info in instance @ni, identified by @kidx
1742 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
1743 *
1744 * Returns 0 on success.
1745 */
1746 static int
export_objhash_ntlv(struct namedobj_instance * ni,uint32_t kidx,struct sockopt_data * sd)1747 export_objhash_ntlv(struct namedobj_instance *ni, uint32_t kidx,
1748 struct sockopt_data *sd)
1749 {
1750 struct named_object *no;
1751 ipfw_obj_ntlv *ntlv;
1752
1753 no = ipfw_objhash_lookup_kidx(ni, kidx);
1754 KASSERT(no != NULL, ("invalid object kernel index passed"));
1755
1756 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
1757 if (ntlv == NULL)
1758 return (ENOMEM);
1759
1760 ipfw_export_obj_ntlv(no, ntlv);
1761 return (0);
1762 }
1763
1764 static int
export_named_objects(struct namedobj_instance * ni,struct dump_args * da,struct sockopt_data * sd)1765 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
1766 struct sockopt_data *sd)
1767 {
1768 uint32_t i;
1769 int error;
1770
1771 for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
1772 if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
1773 continue;
1774 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
1775 return (error);
1776 da->tcount--;
1777 }
1778 return (0);
1779 }
1780
1781 static int
dump_named_objects(struct ip_fw_chain * ch,struct dump_args * da,struct sockopt_data * sd)1782 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
1783 struct sockopt_data *sd)
1784 {
1785 ipfw_obj_ctlv *ctlv;
1786 int error;
1787
1788 MPASS(da->tcount > 0);
1789 /* Header first */
1790 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1791 if (ctlv == NULL)
1792 return (ENOMEM);
1793 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
1794 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
1795 sizeof(*ctlv);
1796 ctlv->count = da->tcount;
1797 ctlv->objsize = sizeof(ipfw_obj_ntlv);
1798
1799 /* Dump table names first (if any) */
1800 error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
1801 if (error != 0)
1802 return (error);
1803 /* Then dump another named objects */
1804 da->bmask += IPFW_TABLES_MAX / 32;
1805 return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
1806 }
1807
1808 /*
1809 * Dumps static rules with table TLVs in buffer @sd.
1810 *
1811 * Returns 0 on success.
1812 */
1813 static int
dump_static_rules(struct ip_fw_chain * chain,struct dump_args * da,struct sockopt_data * sd)1814 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
1815 struct sockopt_data *sd)
1816 {
1817 ipfw_obj_ctlv *ctlv;
1818 struct ip_fw *krule;
1819 caddr_t dst;
1820 int i, l;
1821
1822 /* Dump rules */
1823 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1824 if (ctlv == NULL)
1825 return (ENOMEM);
1826 ctlv->head.type = IPFW_TLV_RULE_LIST;
1827 ctlv->head.length = da->rsize + sizeof(*ctlv);
1828 ctlv->count = da->rcount;
1829
1830 for (i = da->b; i < da->e; i++) {
1831 krule = chain->map[i];
1832
1833 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
1834 if (da->rcounters != 0)
1835 l += sizeof(struct ip_fw_bcounter);
1836 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
1837 if (dst == NULL)
1838 return (ENOMEM);
1839
1840 export_rule1(krule, dst, l, da->rcounters);
1841 }
1842
1843 return (0);
1844 }
1845
1846 int
ipfw_mark_object_kidx(uint32_t * bmask,uint16_t etlv,uint32_t kidx)1847 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint32_t kidx)
1848 {
1849 uint32_t bidx;
1850
1851 /*
1852 * Maintain separate bitmasks for table and non-table objects.
1853 */
1854 bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
1855 bidx += kidx / 32;
1856 if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
1857 return (0);
1858
1859 bmask[bidx] |= 1 << (kidx % 32);
1860 return (1);
1861 }
1862
1863 /*
1864 * Marks every object index used in @rule with bit in @bmask.
1865 * Used to generate bitmask of referenced tables/objects for given ruleset
1866 * or its part.
1867 */
1868 static void
mark_rule_objects(struct ip_fw_chain * ch,struct ip_fw * rule,struct dump_args * da)1869 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
1870 struct dump_args *da)
1871 {
1872 struct opcode_obj_rewrite *rw;
1873 ipfw_insn *cmd;
1874 uint32_t kidx;
1875 int cmdlen, l;
1876 uint8_t subtype;
1877
1878 l = rule->cmd_len;
1879 cmd = rule->cmd;
1880 cmdlen = 0;
1881 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1882 cmdlen = F_LEN(cmd);
1883
1884 rw = find_op_rw(cmd, &kidx, &subtype);
1885 if (rw == NULL)
1886 continue;
1887
1888 if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
1889 da->tcount++;
1890 }
1891 }
1892
1893 /*
1894 * Dumps requested objects data
1895 * Data layout (version 0)(current):
1896 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
1897 * size = ipfw_cfg_lheader.size
1898 * Reply: [ ipfw_cfg_lheader
1899 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
1900 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
1901 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
1902 * ] (optional)
1903 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
1904 * ]
1905 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
1906 * The rest (size, count) are set to zero and needs to be ignored.
1907 *
1908 * Returns 0 on success.
1909 */
1910 static int
dump_config(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)1911 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1912 struct sockopt_data *sd)
1913 {
1914 struct dump_args da;
1915 ipfw_cfg_lheader *hdr;
1916 struct ip_fw *rule;
1917 size_t sz, rnum;
1918 uint32_t hdr_flags, *bmask;
1919 int error, i;
1920
1921 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
1922 if (hdr == NULL)
1923 return (EINVAL);
1924
1925 error = 0;
1926 bmask = NULL;
1927 memset(&da, 0, sizeof(da));
1928 /*
1929 * Allocate needed state.
1930 * Note we allocate 2xspace mask, for table & srv
1931 */
1932 if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
1933 da.bmask = bmask = malloc(
1934 sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
1935 M_WAITOK | M_ZERO);
1936 IPFW_UH_RLOCK(chain);
1937
1938 /*
1939 * STAGE 1: Determine size/count for objects in range.
1940 * Prepare used tables bitmask.
1941 */
1942 sz = sizeof(ipfw_cfg_lheader);
1943 da.e = chain->n_rules;
1944
1945 if (hdr->end_rule != 0) {
1946 /* Handle custom range */
1947 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
1948 rnum = IPFW_DEFAULT_RULE;
1949 da.b = ipfw_find_rule(chain, rnum, 0);
1950 rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
1951 hdr->end_rule + 1: IPFW_DEFAULT_RULE;
1952 da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
1953 }
1954
1955 if (hdr->flags & IPFW_CFG_GET_STATIC) {
1956 for (i = da.b; i < da.e; i++) {
1957 rule = chain->map[i];
1958 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
1959 da.rcount++;
1960 /* Update bitmask of used objects for given range */
1961 mark_rule_objects(chain, rule, &da);
1962 }
1963 /* Add counters if requested */
1964 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
1965 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
1966 da.rcounters = 1;
1967 }
1968 sz += da.rsize + sizeof(ipfw_obj_ctlv);
1969 }
1970
1971 if (hdr->flags & IPFW_CFG_GET_STATES) {
1972 sz += sizeof(ipfw_obj_ctlv) +
1973 ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
1974 da.tcount += i;
1975 }
1976
1977 if (da.tcount > 0)
1978 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
1979 sizeof(ipfw_obj_ctlv);
1980
1981 /*
1982 * Fill header anyway.
1983 * Note we have to save header fields to stable storage
1984 * buffer inside @sd can be flushed after dumping rules
1985 */
1986 hdr->size = sz;
1987 hdr->set_mask = ~V_set_disable;
1988 hdr_flags = hdr->flags;
1989 hdr = NULL;
1990
1991 if (sd->valsize < sz) {
1992 error = ENOMEM;
1993 goto cleanup;
1994 }
1995
1996 /* STAGE2: Store actual data */
1997 if (da.tcount > 0) {
1998 error = dump_named_objects(chain, &da, sd);
1999 if (error != 0)
2000 goto cleanup;
2001 }
2002
2003 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2004 error = dump_static_rules(chain, &da, sd);
2005 if (error != 0)
2006 goto cleanup;
2007 }
2008
2009 if (hdr_flags & IPFW_CFG_GET_STATES)
2010 error = ipfw_dump_states(chain, sd);
2011
2012 cleanup:
2013 IPFW_UH_RUNLOCK(chain);
2014
2015 if (bmask != NULL)
2016 free(bmask, M_TEMP);
2017
2018 return (error);
2019 }
2020
2021 int
ipfw_check_object_name_generic(const char * name)2022 ipfw_check_object_name_generic(const char *name)
2023 {
2024 int nsize;
2025
2026 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2027 if (strnlen(name, nsize) == nsize)
2028 return (EINVAL);
2029 if (name[0] == '\0')
2030 return (EINVAL);
2031 return (0);
2032 }
2033
2034 /*
2035 * Creates non-existent objects referenced by rule.
2036 *
2037 * Return 0 on success.
2038 */
2039 int
create_objects_compat(struct ip_fw_chain * ch,ipfw_insn * cmd,struct obj_idx * oib,struct obj_idx * pidx,struct tid_info * ti)2040 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2041 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2042 {
2043 struct opcode_obj_rewrite *rw;
2044 struct obj_idx *p;
2045 uint32_t kidx;
2046 int error;
2047
2048 /*
2049 * Compatibility stuff: do actual creation for non-existing,
2050 * but referenced objects.
2051 */
2052 for (p = oib; p < pidx; p++) {
2053 if (p->kidx != 0)
2054 continue;
2055
2056 ti->uidx = p->uidx;
2057 ti->type = p->type;
2058 ti->atype = 0;
2059
2060 rw = find_op_rw(cmd + p->off, NULL, NULL);
2061 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2062 (cmd + p->off)->opcode));
2063
2064 if (rw->create_object == NULL)
2065 error = EOPNOTSUPP;
2066 else
2067 error = rw->create_object(ch, ti, &kidx);
2068 if (error == 0) {
2069 p->kidx = kidx;
2070 continue;
2071 }
2072
2073 /*
2074 * Error happened. We have to rollback everything.
2075 * Drop all already acquired references.
2076 */
2077 IPFW_UH_WLOCK(ch);
2078 unref_oib_objects(ch, cmd, oib, pidx);
2079 IPFW_UH_WUNLOCK(ch);
2080
2081 return (error);
2082 }
2083
2084 return (0);
2085 }
2086
2087 /*
2088 * Unreferences all already-referenced objects in given @cmd rule,
2089 * using information in @oib.
2090 *
2091 * Used to rollback partially converted rule on error.
2092 */
2093 static void
unref_oib_objects(struct ip_fw_chain * ch,ipfw_insn * cmd,struct obj_idx * oib,struct obj_idx * end)2094 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2095 struct obj_idx *end)
2096 {
2097 struct opcode_obj_rewrite *rw;
2098 struct named_object *no;
2099 struct obj_idx *p;
2100
2101 IPFW_UH_WLOCK_ASSERT(ch);
2102
2103 for (p = oib; p < end; p++) {
2104 if (p->kidx == 0)
2105 continue;
2106
2107 rw = find_op_rw(cmd + p->off, NULL, NULL);
2108 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2109 (cmd + p->off)->opcode));
2110
2111 /* Find & unref by existing idx */
2112 no = rw->find_bykidx(ch, p->kidx);
2113 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2114 no->refcnt--;
2115 }
2116 }
2117
2118 /*
2119 * Remove references from every object used in @rule.
2120 * Used at rule removal code.
2121 */
2122 static void
unref_rule_objects(struct ip_fw_chain * ch,struct ip_fw * rule)2123 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2124 {
2125 struct opcode_obj_rewrite *rw;
2126 struct named_object *no;
2127 ipfw_insn *cmd;
2128 uint32_t kidx;
2129 int cmdlen, l;
2130 uint8_t subtype;
2131
2132 IPFW_UH_WLOCK_ASSERT(ch);
2133
2134 l = rule->cmd_len;
2135 cmd = rule->cmd;
2136 cmdlen = 0;
2137 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2138 cmdlen = F_LEN(cmd);
2139
2140 rw = find_op_rw(cmd, &kidx, &subtype);
2141 if (rw == NULL)
2142 continue;
2143 no = rw->find_bykidx(ch, kidx);
2144
2145 KASSERT(no != NULL, ("object id %d not found", kidx));
2146 KASSERT(no->subtype == subtype,
2147 ("wrong type %d (%d) for object id %d",
2148 no->subtype, subtype, kidx));
2149 KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2150 kidx, no->refcnt));
2151
2152 if (no->refcnt == 1 && rw->destroy_object != NULL)
2153 rw->destroy_object(ch, no);
2154 else
2155 no->refcnt--;
2156 }
2157 }
2158
2159 /*
2160 * Find and reference object (if any) stored in instruction @cmd.
2161 *
2162 * Saves object info in @pidx, sets
2163 * - @unresolved to 1 if object should exists but not found
2164 *
2165 * Returns non-zero value in case of error.
2166 */
2167 static int
ref_opcode_object(struct ip_fw_chain * ch,ipfw_insn * cmd,struct tid_info * ti,struct obj_idx * pidx,int * unresolved)2168 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2169 struct obj_idx *pidx, int *unresolved)
2170 {
2171 struct named_object *no;
2172 struct opcode_obj_rewrite *rw;
2173 int error;
2174
2175 /* Check if this opcode is candidate for rewrite */
2176 rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2177 if (rw == NULL)
2178 return (0);
2179
2180 /* Need to rewrite. Save necessary fields */
2181 pidx->uidx = ti->uidx;
2182 pidx->type = ti->type;
2183
2184 /* Try to find referenced kernel object */
2185 error = rw->find_byname(ch, ti, &no);
2186 if (error != 0)
2187 return (error);
2188 if (no == NULL) {
2189 /*
2190 * Report about unresolved object for automaic
2191 * creation.
2192 */
2193 *unresolved = 1;
2194 return (0);
2195 }
2196
2197 /*
2198 * Object is already exist.
2199 * Its subtype should match with expected value.
2200 */
2201 if (ti->type != no->subtype)
2202 return (EINVAL);
2203
2204 /* Bump refcount and update kidx. */
2205 no->refcnt++;
2206 rw->update(cmd, no->kidx);
2207 return (0);
2208 }
2209
2210 /*
2211 * Finds and bumps refcount for objects referenced by given @rule.
2212 * Auto-creates non-existing tables.
2213 * Fills in @oib array with userland/kernel indexes.
2214 *
2215 * Returns 0 on success.
2216 */
2217 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)2218 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2219 struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2220 {
2221 struct obj_idx *pidx;
2222 ipfw_insn *cmd;
2223 int cmdlen, error, l, unresolved;
2224
2225 pidx = oib;
2226 l = rule->cmd_len;
2227 cmd = rule->cmd;
2228 cmdlen = 0;
2229 error = 0;
2230
2231 IPFW_UH_WLOCK(ch);
2232
2233 /* Increase refcount on each existing referenced table. */
2234 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2235 cmdlen = F_LEN(cmd);
2236 unresolved = 0;
2237
2238 error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2239 if (error != 0)
2240 break;
2241 /*
2242 * Compatibility stuff for old clients:
2243 * prepare to automaitcally create non-existing objects.
2244 */
2245 if (unresolved != 0) {
2246 pidx->off = rule->cmd_len - l;
2247 pidx++;
2248 }
2249 }
2250
2251 if (error != 0) {
2252 /* Unref everything we have already done */
2253 unref_oib_objects(ch, rule->cmd, oib, pidx);
2254 IPFW_UH_WUNLOCK(ch);
2255 return (error);
2256 }
2257 IPFW_UH_WUNLOCK(ch);
2258
2259 /* Perform auto-creation for non-existing objects */
2260 if (pidx != oib)
2261 error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2262
2263 /* Calculate real number of dynamic objects */
2264 ci->object_opcodes = (uint16_t)(pidx - oib);
2265
2266 return (error);
2267 }
2268
2269 /*
2270 * Checks is opcode is referencing table of appropriate type.
2271 * Adds reference count for found table if true.
2272 * Rewrites user-supplied opcode values with kernel ones.
2273 *
2274 * Returns 0 on success and appropriate error code otherwise.
2275 */
2276 static int
rewrite_rule_uidx(struct ip_fw_chain * chain,struct rule_check_info * ci)2277 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2278 {
2279 int error;
2280 ipfw_insn *cmd;
2281 struct obj_idx *p, *pidx_first, *pidx_last;
2282 struct tid_info ti;
2283
2284 /*
2285 * Prepare an array for storing opcode indices.
2286 * Use stack allocation by default.
2287 */
2288 if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2289 /* Stack */
2290 pidx_first = ci->obuf;
2291 } else
2292 pidx_first = malloc(
2293 ci->object_opcodes * sizeof(struct obj_idx),
2294 M_IPFW, M_WAITOK | M_ZERO);
2295
2296 error = 0;
2297 memset(&ti, 0, sizeof(ti));
2298
2299 /* Use set rule is assigned to. */
2300 ti.set = ci->krule->set;
2301 if (ci->ctlv != NULL) {
2302 ti.tlvs = (void *)(ci->ctlv + 1);
2303 ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2304 }
2305
2306 /* Reference all used tables and other objects */
2307 error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2308 if (error != 0)
2309 goto free;
2310 /*
2311 * Note that ref_rule_objects() might have updated ci->object_opcodes
2312 * to reflect actual number of object opcodes.
2313 */
2314
2315 /* Perform rewrite of remaining opcodes */
2316 p = pidx_first;
2317 pidx_last = pidx_first + ci->object_opcodes;
2318 for (p = pidx_first; p < pidx_last; p++) {
2319 cmd = ci->krule->cmd + p->off;
2320 update_opcode_kidx(cmd, p->kidx);
2321 }
2322
2323 free:
2324 if (pidx_first != ci->obuf)
2325 free(pidx_first, M_IPFW);
2326
2327 return (error);
2328 }
2329
2330 /*
2331 * Parses one or more rules from userland.
2332 * Data layout (version 1)(current):
2333 * Request:
2334 * [
2335 * ip_fw3_opheader
2336 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2337 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2338 * ]
2339 * Reply:
2340 * [
2341 * ip_fw3_opheader
2342 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2343 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2344 * ]
2345 *
2346 * Rules in reply are modified to store their actual ruleset number.
2347 *
2348 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2349 * according to their idx field and there has to be no duplicates.
2350 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2351 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2352 *
2353 * Returns 0 on success.
2354 */
2355 static __noinline int
parse_rules_v1(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd,ipfw_obj_ctlv ** prtlv,struct rule_check_info ** pci)2356 parse_rules_v1(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2357 struct sockopt_data *sd, ipfw_obj_ctlv **prtlv,
2358 struct rule_check_info **pci)
2359 {
2360 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2361 ipfw_obj_ntlv *ntlv;
2362 struct rule_check_info *ci, *cbuf;
2363 struct ip_fw_rule *r;
2364 size_t count, clen, read, rsize;
2365 uint32_t idx, rulenum;
2366 int error;
2367
2368 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2369 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2370 read = sizeof(ip_fw3_opheader);
2371 if (read + sizeof(*ctlv) > sd->valsize)
2372 return (EINVAL);
2373
2374 rtlv = NULL;
2375 tstate = NULL;
2376 cbuf = NULL;
2377 /* Table names or other named objects. */
2378 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2379 /* Check size and alignment. */
2380 clen = ctlv->head.length;
2381 if (read + clen > sd->valsize || clen < sizeof(*ctlv) ||
2382 (clen % sizeof(uint64_t)) != 0)
2383 return (EINVAL);
2384 /* Check for validness. */
2385 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2386 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2387 return (EINVAL);
2388 /*
2389 * Check each TLV.
2390 * Ensure TLVs are sorted ascending and
2391 * there are no duplicates.
2392 */
2393 idx = 0;
2394 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2395 while (count > 0) {
2396 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2397 return (EINVAL);
2398
2399 error = ipfw_check_object_name_generic(ntlv->name);
2400 if (error != 0)
2401 return (error);
2402
2403 if (ntlv->idx <= idx)
2404 return (EINVAL);
2405
2406 idx = ntlv->idx;
2407 count--;
2408 ntlv++;
2409 }
2410
2411 tstate = ctlv;
2412 read += ctlv->head.length;
2413 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2414
2415 if (read + sizeof(*ctlv) > sd->valsize)
2416 return (EINVAL);
2417 }
2418
2419 /* List of rules. */
2420 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2421 clen = ctlv->head.length;
2422 if (read + clen > sd->valsize || clen < sizeof(*ctlv) ||
2423 (clen % sizeof(uint64_t)) != 0)
2424 return (EINVAL);
2425
2426 clen -= sizeof(*ctlv);
2427 if (ctlv->count == 0 ||
2428 ctlv->count > clen / sizeof(struct ip_fw_rule))
2429 return (EINVAL);
2430
2431 /* Allocate state for each rule */
2432 cbuf = malloc(ctlv->count * sizeof(struct rule_check_info),
2433 M_TEMP, M_WAITOK | M_ZERO);
2434
2435 /*
2436 * Check each rule for validness.
2437 * Ensure numbered rules are sorted ascending
2438 * and properly aligned
2439 */
2440 rulenum = 0;
2441 count = 0;
2442 error = 0;
2443 ci = cbuf;
2444 r = (struct ip_fw_rule *)(ctlv + 1);
2445 while (clen > 0) {
2446 rsize = RULEUSIZE1(r);
2447 if (rsize > clen || count > ctlv->count) {
2448 error = EINVAL;
2449 break;
2450 }
2451 ci->ctlv = tstate;
2452 ci->version = IP_FW3_OPVER;
2453 error = ipfw_check_rule(r, rsize, ci);
2454 if (error != 0)
2455 break;
2456
2457 /* Check sorting */
2458 if (count != 0 && ((rulenum == 0) != (r->rulenum == 0) ||
2459 r->rulenum < rulenum)) {
2460 printf("ipfw: wrong order: rulenum %u"
2461 " vs %u\n", r->rulenum, rulenum);
2462 error = EINVAL;
2463 break;
2464 }
2465 rulenum = r->rulenum;
2466 ci->urule = (caddr_t)r;
2467 clen -= rsize;
2468 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2469 count++;
2470 ci++;
2471 }
2472
2473 if (ctlv->count != count || error != 0) {
2474 free(cbuf, M_TEMP);
2475 return (EINVAL);
2476 }
2477
2478 rtlv = ctlv;
2479 read += ctlv->head.length;
2480 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2481 }
2482
2483 if (read != sd->valsize || rtlv == NULL) {
2484 free(cbuf, M_TEMP);
2485 return (EINVAL);
2486 }
2487
2488 *prtlv = rtlv;
2489 *pci = cbuf;
2490 return (0);
2491 }
2492
2493 /*
2494 * Copy rule @urule from v1 userland format (current) to kernel @krule.
2495 */
2496 static void
import_rule_v1(struct ip_fw_chain * chain,struct rule_check_info * ci)2497 import_rule_v1(struct ip_fw_chain *chain, struct rule_check_info *ci)
2498 {
2499 struct ip_fw_rule *urule;
2500 struct ip_fw *krule;
2501
2502 urule = (struct ip_fw_rule *)ci->urule;
2503 krule = ci->krule = ipfw_alloc_rule(chain, RULEKSIZE1(urule));
2504
2505 krule->act_ofs = urule->act_ofs;
2506 krule->cmd_len = urule->cmd_len;
2507 krule->rulenum = urule->rulenum;
2508 krule->set = urule->set;
2509 krule->flags = urule->flags;
2510
2511 /* Save rulenum offset */
2512 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
2513
2514 /* Copy opcodes */
2515 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
2516
2517 if (ACTION_PTR(krule)->opcode == O_LOG)
2518 ipfw_tap_alloc(krule->rulenum);
2519 }
2520
2521 /*
2522 * Adds one or more rules to ipfw @chain.
2523 */
2524 static int
add_rules(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2525 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2526 struct sockopt_data *sd)
2527 {
2528 ipfw_obj_ctlv *rtlv;
2529 struct rule_check_info *ci, *nci;
2530 int i, ret;
2531
2532 /*
2533 * Check rules buffer for validness.
2534 */
2535 ret = parse_rules_v1(chain, op3, sd, &rtlv, &nci);
2536 if (ret != 0)
2537 return (ret);
2538 /*
2539 * Allocate storage for the kernel representation of rules.
2540 */
2541 for (i = 0, ci = nci; i < rtlv->count; i++, ci++)
2542 import_rule_v1(chain, ci);
2543 /*
2544 * Try to add new rules to the chain.
2545 */
2546 if ((ret = ipfw_commit_rules(chain, nci, rtlv->count)) != 0) {
2547 for (i = 0, ci = nci; i < rtlv->count; i++, ci++)
2548 ipfw_free_rule(ci->krule);
2549 }
2550 /* Cleanup after parse_rules() */
2551 free(nci, M_TEMP);
2552 return (ret);
2553 }
2554
2555 /*
2556 * Lists all sopts currently registered.
2557 * Data layout (v1)(current):
2558 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
2559 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
2560 *
2561 * Returns 0 on success
2562 */
2563 static int
dump_soptcodes(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2564 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2565 struct sockopt_data *sd)
2566 {
2567 struct _ipfw_obj_lheader *olh;
2568 ipfw_sopt_info *i;
2569 struct ipfw_sopt_handler *sh;
2570 uint32_t count, n, size;
2571
2572 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,
2573 sizeof(*olh));
2574 if (olh == NULL)
2575 return (EINVAL);
2576 if (sd->valsize < olh->size)
2577 return (EINVAL);
2578
2579 CTL3_LOCK();
2580 count = ctl3_hsize;
2581 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
2582
2583 /* Fill in header regadless of buffer size */
2584 olh->count = count;
2585 olh->objsize = sizeof(ipfw_sopt_info);
2586
2587 if (size > olh->size) {
2588 olh->size = size;
2589 CTL3_UNLOCK();
2590 return (ENOMEM);
2591 }
2592 olh->size = size;
2593
2594 for (n = 0; n < count; n++) {
2595 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
2596 KASSERT(i != NULL, ("previously checked buffer is not enough"));
2597 sh = &ctl3_handlers[n];
2598 i->opcode = sh->opcode;
2599 i->version = sh->version;
2600 i->refcnt = sh->refcnt;
2601 }
2602 CTL3_UNLOCK();
2603
2604 return (0);
2605 }
2606
2607 /*
2608 * Compares two opcodes.
2609 * Used both in qsort() and bsearch().
2610 *
2611 * Returns 0 if match is found.
2612 */
2613 static int
compare_opcodes(const void * _a,const void * _b)2614 compare_opcodes(const void *_a, const void *_b)
2615 {
2616 const struct opcode_obj_rewrite *a, *b;
2617
2618 a = (const struct opcode_obj_rewrite *)_a;
2619 b = (const struct opcode_obj_rewrite *)_b;
2620
2621 if (a->opcode < b->opcode)
2622 return (-1);
2623 else if (a->opcode > b->opcode)
2624 return (1);
2625
2626 return (0);
2627 }
2628
2629 /*
2630 * XXX: Rewrite bsearch()
2631 */
2632 static int
find_op_rw_range(uint16_t op,struct opcode_obj_rewrite ** plo,struct opcode_obj_rewrite ** phi)2633 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
2634 struct opcode_obj_rewrite **phi)
2635 {
2636 struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
2637
2638 memset(&h, 0, sizeof(h));
2639 h.opcode = op;
2640
2641 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
2642 ctl3_rsize, sizeof(h), compare_opcodes);
2643 if (rw == NULL)
2644 return (1);
2645
2646 /* Find the first element matching the same opcode */
2647 lo = rw;
2648 for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
2649 ;
2650
2651 /* Find the last element matching the same opcode */
2652 hi = rw;
2653 ctl3_max = ctl3_rewriters + ctl3_rsize;
2654 for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
2655 ;
2656
2657 *plo = lo;
2658 *phi = hi;
2659
2660 return (0);
2661 }
2662
2663 /*
2664 * Finds opcode object rewriter based on @code.
2665 *
2666 * Returns pointer to handler or NULL.
2667 */
2668 static struct opcode_obj_rewrite *
find_op_rw(ipfw_insn * cmd,uint32_t * puidx,uint8_t * ptype)2669 find_op_rw(ipfw_insn *cmd, uint32_t *puidx, uint8_t *ptype)
2670 {
2671 struct opcode_obj_rewrite *rw, *lo, *hi;
2672 uint32_t uidx;
2673 uint8_t subtype;
2674
2675 if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
2676 return (NULL);
2677
2678 for (rw = lo; rw <= hi; rw++) {
2679 if (rw->classifier(cmd, &uidx, &subtype) == 0) {
2680 if (puidx != NULL)
2681 *puidx = uidx;
2682 if (ptype != NULL)
2683 *ptype = subtype;
2684 return (rw);
2685 }
2686 }
2687
2688 return (NULL);
2689 }
2690 int
classify_opcode_kidx(ipfw_insn * cmd,uint32_t * puidx)2691 classify_opcode_kidx(ipfw_insn *cmd, uint32_t *puidx)
2692 {
2693
2694 if (find_op_rw(cmd, puidx, NULL) == NULL)
2695 return (1);
2696 return (0);
2697 }
2698
2699 void
update_opcode_kidx(ipfw_insn * cmd,uint32_t idx)2700 update_opcode_kidx(ipfw_insn *cmd, uint32_t idx)
2701 {
2702 struct opcode_obj_rewrite *rw;
2703
2704 rw = find_op_rw(cmd, NULL, NULL);
2705 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
2706 rw->update(cmd, idx);
2707 }
2708
2709 void
ipfw_init_obj_rewriter(void)2710 ipfw_init_obj_rewriter(void)
2711 {
2712 ctl3_rewriters = NULL;
2713 ctl3_rsize = 0;
2714 }
2715
2716 void
ipfw_destroy_obj_rewriter(void)2717 ipfw_destroy_obj_rewriter(void)
2718 {
2719 if (ctl3_rewriters != NULL)
2720 free(ctl3_rewriters, M_IPFW);
2721 ctl3_rewriters = NULL;
2722 ctl3_rsize = 0;
2723 }
2724
2725 /*
2726 * Adds one or more opcode object rewrite handlers to the global array.
2727 * Function may sleep.
2728 */
2729 void
ipfw_add_obj_rewriter(struct opcode_obj_rewrite * rw,size_t count)2730 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2731 {
2732 size_t sz;
2733 struct opcode_obj_rewrite *tmp;
2734
2735 CTL3_LOCK();
2736
2737 for (;;) {
2738 sz = ctl3_rsize + count;
2739 CTL3_UNLOCK();
2740 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
2741 CTL3_LOCK();
2742 if (ctl3_rsize + count <= sz)
2743 break;
2744
2745 /* Retry */
2746 free(tmp, M_IPFW);
2747 }
2748
2749 /* Merge old & new arrays */
2750 sz = ctl3_rsize + count;
2751 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
2752 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
2753 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
2754 /* Switch new and free old */
2755 if (ctl3_rewriters != NULL)
2756 free(ctl3_rewriters, M_IPFW);
2757 ctl3_rewriters = tmp;
2758 ctl3_rsize = sz;
2759
2760 CTL3_UNLOCK();
2761 }
2762
2763 /*
2764 * Removes one or more object rewrite handlers from the global array.
2765 */
2766 int
ipfw_del_obj_rewriter(struct opcode_obj_rewrite * rw,size_t count)2767 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2768 {
2769 size_t sz;
2770 struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
2771 int i;
2772
2773 CTL3_LOCK();
2774
2775 for (i = 0; i < count; i++) {
2776 if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
2777 continue;
2778
2779 for (ktmp = lo; ktmp <= hi; ktmp++) {
2780 if (ktmp->classifier != rw[i].classifier)
2781 continue;
2782
2783 ctl3_max = ctl3_rewriters + ctl3_rsize;
2784 sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
2785 memmove(ktmp, ktmp + 1, sz);
2786 ctl3_rsize--;
2787 break;
2788 }
2789 }
2790
2791 if (ctl3_rsize == 0) {
2792 if (ctl3_rewriters != NULL)
2793 free(ctl3_rewriters, M_IPFW);
2794 ctl3_rewriters = NULL;
2795 }
2796
2797 CTL3_UNLOCK();
2798
2799 return (0);
2800 }
2801
2802 static int
export_objhash_ntlv_internal(struct namedobj_instance * ni,struct named_object * no,void * arg)2803 export_objhash_ntlv_internal(struct namedobj_instance *ni,
2804 struct named_object *no, void *arg)
2805 {
2806 struct sockopt_data *sd;
2807 ipfw_obj_ntlv *ntlv;
2808
2809 sd = (struct sockopt_data *)arg;
2810 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2811 if (ntlv == NULL)
2812 return (ENOMEM);
2813 ipfw_export_obj_ntlv(no, ntlv);
2814 return (0);
2815 }
2816
2817 /*
2818 * Lists all service objects.
2819 * Data layout (v0)(current):
2820 * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
2821 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
2822 * Returns 0 on success
2823 */
2824 static int
dump_srvobjects(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2825 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2826 struct sockopt_data *sd)
2827 {
2828 ipfw_obj_lheader *hdr;
2829 int count;
2830
2831 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2832 if (hdr == NULL)
2833 return (EINVAL);
2834
2835 IPFW_UH_RLOCK(chain);
2836 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
2837 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
2838 if (sd->valsize < hdr->size) {
2839 IPFW_UH_RUNLOCK(chain);
2840 return (ENOMEM);
2841 }
2842 hdr->count = count;
2843 hdr->objsize = sizeof(ipfw_obj_ntlv);
2844 if (count > 0)
2845 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
2846 export_objhash_ntlv_internal, sd);
2847 IPFW_UH_RUNLOCK(chain);
2848 return (0);
2849 }
2850
2851 void
ipfw_enable_skipto_cache(struct ip_fw_chain * chain)2852 ipfw_enable_skipto_cache(struct ip_fw_chain *chain)
2853 {
2854
2855 IPFW_UH_WLOCK_ASSERT(chain);
2856 update_skipto_cache(chain, chain->map);
2857
2858 IPFW_WLOCK(chain);
2859 swap_skipto_cache(chain);
2860 V_skipto_cache = 1;
2861 IPFW_WUNLOCK(chain);
2862 }
2863
2864 /*
2865 * Enables or disable skipto cache.
2866 * Request: [ ipfw_cmd_header ] size = ipfw_cmd_header.size
2867 * Reply: [ ipfw_cmd_header ]
2868 * Returns 0 on success
2869 */
2870 static int
manage_skiptocache(struct ip_fw_chain * chain,ip_fw3_opheader * op3,struct sockopt_data * sd)2871 manage_skiptocache(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2872 struct sockopt_data *sd)
2873 {
2874 ipfw_cmd_header *hdr;
2875
2876 if (sd->valsize != sizeof(*hdr))
2877 return (EINVAL);
2878
2879 hdr = (ipfw_cmd_header *)ipfw_get_sopt_space(sd, sd->valsize);
2880 if (hdr->cmd != SKIPTO_CACHE_DISABLE &&
2881 hdr->cmd != SKIPTO_CACHE_ENABLE)
2882 return (EOPNOTSUPP);
2883
2884 IPFW_UH_WLOCK(chain);
2885 if (hdr->cmd != V_skipto_cache) {
2886 if (hdr->cmd == SKIPTO_CACHE_ENABLE)
2887 ipfw_enable_skipto_cache(chain);
2888 V_skipto_cache = hdr->cmd;
2889 }
2890 IPFW_UH_WUNLOCK(chain);
2891 return (0);
2892 }
2893
2894 /*
2895 * Compares two sopt handlers (code, version and handler ptr).
2896 * Used both as qsort() and bsearch().
2897 * Does not compare handler for latter case.
2898 *
2899 * Returns 0 if match is found.
2900 */
2901 static int
compare_sh(const void * _a,const void * _b)2902 compare_sh(const void *_a, const void *_b)
2903 {
2904 const struct ipfw_sopt_handler *a, *b;
2905
2906 a = (const struct ipfw_sopt_handler *)_a;
2907 b = (const struct ipfw_sopt_handler *)_b;
2908
2909 if (a->opcode < b->opcode)
2910 return (-1);
2911 else if (a->opcode > b->opcode)
2912 return (1);
2913
2914 if (a->version < b->version)
2915 return (-1);
2916 else if (a->version > b->version)
2917 return (1);
2918
2919 /* bsearch helper */
2920 if (a->handler == NULL)
2921 return (0);
2922
2923 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
2924 return (-1);
2925 else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
2926 return (1);
2927
2928 return (0);
2929 }
2930
2931 /*
2932 * Finds sopt handler based on @code and @version.
2933 *
2934 * Returns pointer to handler or NULL.
2935 */
2936 static struct ipfw_sopt_handler *
find_sh(uint16_t code,uint8_t version,sopt_handler_f * handler)2937 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
2938 {
2939 struct ipfw_sopt_handler *sh, h;
2940
2941 memset(&h, 0, sizeof(h));
2942 h.opcode = code;
2943 h.version = version;
2944 h.handler = handler;
2945
2946 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
2947 ctl3_hsize, sizeof(h), compare_sh);
2948
2949 return (sh);
2950 }
2951
2952 static int
find_ref_sh(uint16_t opcode,uint8_t version,struct ipfw_sopt_handler * psh)2953 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
2954 {
2955 struct ipfw_sopt_handler *sh;
2956
2957 CTL3_LOCK();
2958 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
2959 CTL3_UNLOCK();
2960 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
2961 opcode, version);
2962 return (EINVAL);
2963 }
2964 sh->refcnt++;
2965 ctl3_refct++;
2966 /* Copy handler data to requested buffer */
2967 *psh = *sh;
2968 CTL3_UNLOCK();
2969
2970 return (0);
2971 }
2972
2973 static void
find_unref_sh(struct ipfw_sopt_handler * psh)2974 find_unref_sh(struct ipfw_sopt_handler *psh)
2975 {
2976 struct ipfw_sopt_handler *sh;
2977
2978 CTL3_LOCK();
2979 sh = find_sh(psh->opcode, psh->version, NULL);
2980 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
2981 sh->refcnt--;
2982 ctl3_refct--;
2983 CTL3_UNLOCK();
2984 }
2985
2986 void
ipfw_init_sopt_handler(void)2987 ipfw_init_sopt_handler(void)
2988 {
2989 CTL3_LOCK_INIT();
2990 IPFW_ADD_SOPT_HANDLER(1, scodes);
2991 }
2992
2993 void
ipfw_destroy_sopt_handler(void)2994 ipfw_destroy_sopt_handler(void)
2995 {
2996 IPFW_DEL_SOPT_HANDLER(1, scodes);
2997 CTL3_LOCK_DESTROY();
2998 }
2999
3000 void
ipfw_register_compat(ipfw_check_opcode_t f)3001 ipfw_register_compat(ipfw_check_opcode_t f)
3002 {
3003 check_opcode_f = f;
3004 }
3005
3006 void
ipfw_unregister_compat(void)3007 ipfw_unregister_compat(void)
3008 {
3009 check_opcode_f = check_opcode_compat_nop;
3010 }
3011
3012 /*
3013 * Adds one or more sockopt handlers to the global array.
3014 * Function may sleep.
3015 */
3016 void
ipfw_add_sopt_handler(struct ipfw_sopt_handler * sh,size_t count)3017 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3018 {
3019 size_t sz;
3020 struct ipfw_sopt_handler *tmp;
3021
3022 CTL3_LOCK();
3023
3024 for (;;) {
3025 sz = ctl3_hsize + count;
3026 CTL3_UNLOCK();
3027 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3028 CTL3_LOCK();
3029 if (ctl3_hsize + count <= sz)
3030 break;
3031
3032 /* Retry */
3033 free(tmp, M_IPFW);
3034 }
3035
3036 /* Merge old & new arrays */
3037 sz = ctl3_hsize + count;
3038 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3039 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3040 qsort(tmp, sz, sizeof(*sh), compare_sh);
3041 /* Switch new and free old */
3042 if (ctl3_handlers != NULL)
3043 free(ctl3_handlers, M_IPFW);
3044 ctl3_handlers = tmp;
3045 ctl3_hsize = sz;
3046 ctl3_gencnt++;
3047
3048 CTL3_UNLOCK();
3049 }
3050
3051 /*
3052 * Removes one or more sockopt handlers from the global array.
3053 */
3054 int
ipfw_del_sopt_handler(struct ipfw_sopt_handler * sh,size_t count)3055 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3056 {
3057 size_t sz;
3058 struct ipfw_sopt_handler *tmp, *h;
3059 int i;
3060
3061 CTL3_LOCK();
3062
3063 for (i = 0; i < count; i++) {
3064 tmp = &sh[i];
3065 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3066 if (h == NULL)
3067 continue;
3068
3069 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3070 memmove(h, h + 1, sz);
3071 ctl3_hsize--;
3072 }
3073
3074 if (ctl3_hsize == 0) {
3075 if (ctl3_handlers != NULL)
3076 free(ctl3_handlers, M_IPFW);
3077 ctl3_handlers = NULL;
3078 }
3079
3080 ctl3_gencnt++;
3081
3082 CTL3_UNLOCK();
3083
3084 return (0);
3085 }
3086
3087 /*
3088 * Writes data accumulated in @sd to sockopt buffer.
3089 * Zeroes internal @sd buffer.
3090 */
3091 static int
ipfw_flush_sopt_data(struct sockopt_data * sd)3092 ipfw_flush_sopt_data(struct sockopt_data *sd)
3093 {
3094 struct sockopt *sopt;
3095 int error;
3096 size_t sz;
3097
3098 sz = sd->koff;
3099 if (sz == 0)
3100 return (0);
3101
3102 sopt = sd->sopt;
3103
3104 if (sopt->sopt_dir == SOPT_GET) {
3105 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3106 if (error != 0)
3107 return (error);
3108 }
3109
3110 memset(sd->kbuf, 0, sd->ksize);
3111 sd->ktotal += sz;
3112 sd->koff = 0;
3113 if (sd->ktotal + sd->ksize < sd->valsize)
3114 sd->kavail = sd->ksize;
3115 else
3116 sd->kavail = sd->valsize - sd->ktotal;
3117
3118 /* Update sopt buffer data */
3119 sopt->sopt_valsize = sd->ktotal;
3120 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3121
3122 return (0);
3123 }
3124
3125 /*
3126 * Ensures that @sd buffer has contiguous @neeeded number of
3127 * bytes.
3128 *
3129 * Returns pointer to requested space or NULL.
3130 */
3131 caddr_t
ipfw_get_sopt_space(struct sockopt_data * sd,size_t needed)3132 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3133 {
3134 int error;
3135 caddr_t addr;
3136
3137 if (sd->kavail < needed) {
3138 /*
3139 * Flush data and try another time.
3140 */
3141 error = ipfw_flush_sopt_data(sd);
3142
3143 if (sd->kavail < needed || error != 0)
3144 return (NULL);
3145 }
3146
3147 addr = sd->kbuf + sd->koff;
3148 sd->koff += needed;
3149 sd->kavail -= needed;
3150 return (addr);
3151 }
3152
3153 /*
3154 * Requests @needed contiguous bytes from @sd buffer.
3155 * Function is used to notify subsystem that we are
3156 * interesed in first @needed bytes (request header)
3157 * and the rest buffer can be safely zeroed.
3158 *
3159 * Returns pointer to requested space or NULL.
3160 */
3161 caddr_t
ipfw_get_sopt_header(struct sockopt_data * sd,size_t needed)3162 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3163 {
3164 caddr_t addr;
3165
3166 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3167 return (NULL);
3168
3169 if (sd->kavail > 0)
3170 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3171
3172 return (addr);
3173 }
3174
3175 /*
3176 * New sockopt handler.
3177 */
3178 int
ipfw_ctl3(struct sockopt * sopt)3179 ipfw_ctl3(struct sockopt *sopt)
3180 {
3181 int error, locked;
3182 size_t size, valsize;
3183 struct ip_fw_chain *chain;
3184 char xbuf[256];
3185 struct sockopt_data sdata;
3186 struct ipfw_sopt_handler h;
3187 ip_fw3_opheader *op3 = NULL;
3188
3189 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3190 if (error != 0)
3191 return (error);
3192
3193 if (sopt->sopt_name != IP_FW3)
3194 return (EOPNOTSUPP);
3195
3196 chain = &V_layer3_chain;
3197 error = 0;
3198
3199 /* Save original valsize before it is altered via sooptcopyin() */
3200 valsize = sopt->sopt_valsize;
3201 memset(&sdata, 0, sizeof(sdata));
3202 /* Read op3 header first to determine actual operation */
3203 op3 = (ip_fw3_opheader *)xbuf;
3204 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3205 if (error != 0)
3206 return (error);
3207 sopt->sopt_valsize = valsize;
3208
3209 /*
3210 * Find and reference command.
3211 */
3212 error = find_ref_sh(op3->opcode, op3->version, &h);
3213 if (error != 0)
3214 return (error);
3215
3216 /*
3217 * Disallow modifications in really-really secure mode, but still allow
3218 * the logging counters to be reset.
3219 */
3220 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3221 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3222 if (error != 0) {
3223 find_unref_sh(&h);
3224 return (error);
3225 }
3226 }
3227
3228 /*
3229 * Fill in sockopt_data structure that may be useful for
3230 * IP_FW3 get requests.
3231 */
3232 locked = 0;
3233 if (valsize <= sizeof(xbuf)) {
3234 /* use on-stack buffer */
3235 sdata.kbuf = xbuf;
3236 sdata.ksize = sizeof(xbuf);
3237 sdata.kavail = valsize;
3238 } else {
3239 /*
3240 * Determine opcode type/buffer size:
3241 * allocate sliding-window buf for data export or
3242 * contiguous buffer for special ops.
3243 */
3244 if ((h.dir & HDIR_SET) != 0) {
3245 /* Set request. Allocate contigous buffer. */
3246 if (valsize > CTL3_LARGEBUF) {
3247 find_unref_sh(&h);
3248 return (EFBIG);
3249 }
3250
3251 size = valsize;
3252 } else {
3253 /* Get request. Allocate sliding window buffer */
3254 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3255
3256 if (size < valsize) {
3257 /* We have to wire user buffer */
3258 error = vslock(sopt->sopt_val, valsize);
3259 if (error != 0)
3260 return (error);
3261 locked = 1;
3262 }
3263 }
3264
3265 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3266 sdata.ksize = size;
3267 sdata.kavail = size;
3268 }
3269
3270 sdata.sopt = sopt;
3271 sdata.sopt_val = sopt->sopt_val;
3272 sdata.valsize = valsize;
3273
3274 /*
3275 * Copy either all request (if valsize < bsize_max)
3276 * or first bsize_max bytes to guarantee most consumers
3277 * that all necessary data has been copied).
3278 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3279 */
3280 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3281 sizeof(ip_fw3_opheader))) != 0)
3282 return (error);
3283 op3 = (ip_fw3_opheader *)sdata.kbuf;
3284
3285 /* Finally, run handler */
3286 error = h.handler(chain, op3, &sdata);
3287 find_unref_sh(&h);
3288
3289 /* Flush state and free buffers */
3290 if (error == 0)
3291 error = ipfw_flush_sopt_data(&sdata);
3292 else
3293 ipfw_flush_sopt_data(&sdata);
3294
3295 if (locked != 0)
3296 vsunlock(sdata.sopt_val, valsize);
3297
3298 /* Restore original pointer and set number of bytes written */
3299 sopt->sopt_val = sdata.sopt_val;
3300 sopt->sopt_valsize = sdata.ktotal;
3301 if (sdata.kbuf != xbuf)
3302 free(sdata.kbuf, M_TEMP);
3303
3304 return (error);
3305 }
3306
3307 /*
3308 * Named object api
3309 *
3310 */
3311
3312 void
ipfw_init_srv(struct ip_fw_chain * ch)3313 ipfw_init_srv(struct ip_fw_chain *ch)
3314 {
3315 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT,
3316 DEFAULT_OBJHASH_SIZE);
3317 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
3318 M_IPFW, M_WAITOK | M_ZERO);
3319 }
3320
3321 void
ipfw_destroy_srv(struct ip_fw_chain * ch)3322 ipfw_destroy_srv(struct ip_fw_chain *ch)
3323 {
3324 free(ch->srvstate, M_IPFW);
3325 ipfw_objhash_destroy(ch->srvmap);
3326 }
3327
3328 /*
3329 * Allocate new bitmask which can be used to enlarge/shrink
3330 * named instance index.
3331 */
3332 void
ipfw_objhash_bitmap_alloc(uint32_t items,void ** idx,int * pblocks)3333 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
3334 {
3335 size_t size;
3336 int max_blocks;
3337 u_long *idx_mask;
3338
3339 KASSERT((items % BLOCK_ITEMS) == 0,
3340 ("bitmask size needs to power of 2 and greater or equal to %zu",
3341 BLOCK_ITEMS));
3342
3343 max_blocks = items / BLOCK_ITEMS;
3344 size = items / 8;
3345 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
3346 /* Mark all as free */
3347 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
3348 *idx_mask &= ~(u_long)1; /* Skip index 0 */
3349
3350 *idx = idx_mask;
3351 *pblocks = max_blocks;
3352 }
3353
3354 /*
3355 * Copy current bitmask index to new one.
3356 */
3357 void
ipfw_objhash_bitmap_merge(struct namedobj_instance * ni,void ** idx,int * blocks)3358 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
3359 {
3360 int old_blocks, new_blocks;
3361 u_long *old_idx, *new_idx;
3362 int i;
3363
3364 old_idx = ni->idx_mask;
3365 old_blocks = ni->max_blocks;
3366 new_idx = *idx;
3367 new_blocks = *blocks;
3368
3369 for (i = 0; i < IPFW_MAX_SETS; i++) {
3370 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
3371 old_blocks * sizeof(u_long));
3372 }
3373 }
3374
3375 /*
3376 * Swaps current @ni index with new one.
3377 */
3378 void
ipfw_objhash_bitmap_swap(struct namedobj_instance * ni,void ** idx,int * blocks)3379 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
3380 {
3381 int old_blocks;
3382 u_long *old_idx;
3383
3384 old_idx = ni->idx_mask;
3385 old_blocks = ni->max_blocks;
3386
3387 ni->idx_mask = *idx;
3388 ni->max_blocks = *blocks;
3389
3390 /* Save old values */
3391 *idx = old_idx;
3392 *blocks = old_blocks;
3393 }
3394
3395 void
ipfw_objhash_bitmap_free(void * idx,int blocks)3396 ipfw_objhash_bitmap_free(void *idx, int blocks)
3397 {
3398 free(idx, M_IPFW);
3399 }
3400
3401 /*
3402 * Creates named hash instance.
3403 * Must be called without holding any locks.
3404 * Return pointer to new instance.
3405 */
3406 struct namedobj_instance *
ipfw_objhash_create(uint32_t items,size_t hash_size)3407 ipfw_objhash_create(uint32_t items, size_t hash_size)
3408 {
3409 struct namedobj_instance *ni;
3410 int i;
3411 size_t size;
3412
3413 size = sizeof(struct namedobj_instance) +
3414 sizeof(struct namedobjects_head) * hash_size +
3415 sizeof(struct namedobjects_head) * hash_size;
3416
3417 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
3418 ni->nn_size = hash_size;
3419 ni->nv_size = hash_size;
3420
3421 ni->names = (struct namedobjects_head *)(ni +1);
3422 ni->values = &ni->names[ni->nn_size];
3423
3424 for (i = 0; i < ni->nn_size; i++)
3425 TAILQ_INIT(&ni->names[i]);
3426
3427 for (i = 0; i < ni->nv_size; i++)
3428 TAILQ_INIT(&ni->values[i]);
3429
3430 /* Set default hashing/comparison functions */
3431 ni->hash_f = objhash_hash_name;
3432 ni->cmp_f = objhash_cmp_name;
3433
3434 /* Allocate bitmask separately due to possible resize */
3435 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
3436
3437 return (ni);
3438 }
3439
3440 void
ipfw_objhash_destroy(struct namedobj_instance * ni)3441 ipfw_objhash_destroy(struct namedobj_instance *ni)
3442 {
3443 free(ni->idx_mask, M_IPFW);
3444 free(ni, M_IPFW);
3445 }
3446
3447 void
ipfw_objhash_set_funcs(struct namedobj_instance * ni,objhash_hash_f * hash_f,objhash_cmp_f * cmp_f)3448 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
3449 objhash_cmp_f *cmp_f)
3450 {
3451
3452 ni->hash_f = hash_f;
3453 ni->cmp_f = cmp_f;
3454 }
3455
3456 static uint32_t
objhash_hash_name(struct namedobj_instance * ni,const void * name,uint32_t set)3457 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
3458 {
3459
3460 return (fnv_32_str((const char *)name, FNV1_32_INIT));
3461 }
3462
3463 static int
objhash_cmp_name(struct named_object * no,const void * name,uint32_t set)3464 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
3465 {
3466
3467 if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
3468 return (0);
3469
3470 return (1);
3471 }
3472
3473 static uint32_t
objhash_hash_idx(struct namedobj_instance * ni,uint32_t val)3474 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
3475 {
3476 uint32_t v;
3477
3478 v = val % (ni->nv_size - 1);
3479
3480 return (v);
3481 }
3482
3483 struct named_object *
ipfw_objhash_lookup_name(struct namedobj_instance * ni,uint32_t set,const char * name)3484 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set,
3485 const char *name)
3486 {
3487 struct named_object *no;
3488 uint32_t hash;
3489
3490 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3491
3492 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3493 if (ni->cmp_f(no, name, set) == 0)
3494 return (no);
3495 }
3496
3497 return (NULL);
3498 }
3499
3500 /*
3501 * Find named object by @uid.
3502 * Check @tlvs for valid data inside.
3503 *
3504 * Returns pointer to found TLV or NULL.
3505 */
3506 ipfw_obj_ntlv *
ipfw_find_name_tlv_type(void * tlvs,int len,uint32_t uidx,uint32_t etlv)3507 ipfw_find_name_tlv_type(void *tlvs, int len, uint32_t uidx, uint32_t etlv)
3508 {
3509 ipfw_obj_ntlv *ntlv;
3510 uintptr_t pa, pe;
3511 int l;
3512
3513 pa = (uintptr_t)tlvs;
3514 pe = pa + len;
3515 l = 0;
3516 for (; pa < pe; pa += l) {
3517 ntlv = (ipfw_obj_ntlv *)pa;
3518 l = ntlv->head.length;
3519
3520 if (l != sizeof(*ntlv))
3521 return (NULL);
3522
3523 if (ntlv->idx != uidx)
3524 continue;
3525 /*
3526 * When userland has specified zero TLV type, do
3527 * not compare it with eltv. In some cases userland
3528 * doesn't know what type should it have. Use only
3529 * uidx and name for search named_object.
3530 */
3531 if (ntlv->head.type != 0 &&
3532 ntlv->head.type != (uint16_t)etlv)
3533 continue;
3534
3535 if (ipfw_check_object_name_generic(ntlv->name) != 0)
3536 return (NULL);
3537
3538 return (ntlv);
3539 }
3540
3541 return (NULL);
3542 }
3543
3544 /*
3545 * Finds object config based on either legacy index
3546 * or name in ntlv.
3547 * Note @ti structure contains unchecked data from userland.
3548 *
3549 * Returns 0 in success and fills in @pno with found config
3550 */
3551 int
ipfw_objhash_find_type(struct namedobj_instance * ni,struct tid_info * ti,uint32_t etlv,struct named_object ** pno)3552 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
3553 uint32_t etlv, struct named_object **pno)
3554 {
3555 char *name;
3556 ipfw_obj_ntlv *ntlv;
3557 uint32_t set;
3558
3559 if (ti->tlvs == NULL)
3560 return (EINVAL);
3561
3562 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
3563 if (ntlv == NULL)
3564 return (EINVAL);
3565 name = ntlv->name;
3566
3567 /*
3568 * Use set provided by @ti instead of @ntlv one.
3569 * This is needed due to different sets behavior
3570 * controlled by V_fw_tables_sets.
3571 */
3572 set = ti->set;
3573 *pno = ipfw_objhash_lookup_name(ni, set, name);
3574 if (*pno == NULL)
3575 return (ESRCH);
3576 return (0);
3577 }
3578
3579 /*
3580 * Find named object by name, considering also its TLV type.
3581 */
3582 struct named_object *
ipfw_objhash_lookup_name_type(struct namedobj_instance * ni,uint32_t set,uint32_t type,const char * name)3583 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
3584 uint32_t type, const char *name)
3585 {
3586 struct named_object *no;
3587 uint32_t hash;
3588
3589 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3590
3591 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3592 if (ni->cmp_f(no, name, set) == 0 &&
3593 no->etlv == (uint16_t)type)
3594 return (no);
3595 }
3596
3597 return (NULL);
3598 }
3599
3600 struct named_object *
ipfw_objhash_lookup_kidx(struct namedobj_instance * ni,uint32_t kidx)3601 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint32_t kidx)
3602 {
3603 struct named_object *no;
3604 uint32_t hash;
3605
3606 hash = objhash_hash_idx(ni, kidx);
3607
3608 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
3609 if (no->kidx == kidx)
3610 return (no);
3611 }
3612
3613 return (NULL);
3614 }
3615
3616 int
ipfw_objhash_same_name(struct namedobj_instance * ni,struct named_object * a,struct named_object * b)3617 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
3618 struct named_object *b)
3619 {
3620
3621 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
3622 return (1);
3623
3624 return (0);
3625 }
3626
3627 void
ipfw_objhash_add(struct namedobj_instance * ni,struct named_object * no)3628 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
3629 {
3630 uint32_t hash;
3631
3632 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3633 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
3634
3635 hash = objhash_hash_idx(ni, no->kidx);
3636 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
3637
3638 ni->count++;
3639 }
3640
3641 void
ipfw_objhash_del(struct namedobj_instance * ni,struct named_object * no)3642 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
3643 {
3644 uint32_t hash;
3645
3646 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3647 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
3648
3649 hash = objhash_hash_idx(ni, no->kidx);
3650 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
3651
3652 ni->count--;
3653 }
3654
3655 uint32_t
ipfw_objhash_count(struct namedobj_instance * ni)3656 ipfw_objhash_count(struct namedobj_instance *ni)
3657 {
3658
3659 return (ni->count);
3660 }
3661
3662 uint32_t
ipfw_objhash_count_type(struct namedobj_instance * ni,uint16_t type)3663 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
3664 {
3665 struct named_object *no;
3666 uint32_t count;
3667 int i;
3668
3669 count = 0;
3670 for (i = 0; i < ni->nn_size; i++) {
3671 TAILQ_FOREACH(no, &ni->names[i], nn_next) {
3672 if (no->etlv == type)
3673 count++;
3674 }
3675 }
3676 return (count);
3677 }
3678
3679 /*
3680 * Runs @func for each found named object.
3681 * It is safe to delete objects from callback
3682 */
3683 int
ipfw_objhash_foreach(struct namedobj_instance * ni,objhash_cb_t * f,void * arg)3684 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
3685 {
3686 struct named_object *no, *no_tmp;
3687 int i, ret;
3688
3689 for (i = 0; i < ni->nn_size; i++) {
3690 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
3691 ret = f(ni, no, arg);
3692 if (ret != 0)
3693 return (ret);
3694 }
3695 }
3696 return (0);
3697 }
3698
3699 /*
3700 * Runs @f for each found named object with type @type.
3701 * It is safe to delete objects from callback
3702 */
3703 int
ipfw_objhash_foreach_type(struct namedobj_instance * ni,objhash_cb_t * f,void * arg,uint16_t type)3704 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
3705 void *arg, uint16_t type)
3706 {
3707 struct named_object *no, *no_tmp;
3708 int i, ret;
3709
3710 for (i = 0; i < ni->nn_size; i++) {
3711 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
3712 if (no->etlv != type)
3713 continue;
3714 ret = f(ni, no, arg);
3715 if (ret != 0)
3716 return (ret);
3717 }
3718 }
3719 return (0);
3720 }
3721
3722 /*
3723 * Removes index from given set.
3724 * Returns 0 on success.
3725 */
3726 int
ipfw_objhash_free_idx(struct namedobj_instance * ni,uint32_t idx)3727 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint32_t idx)
3728 {
3729 u_long *mask;
3730 int i, v;
3731
3732 i = idx / BLOCK_ITEMS;
3733 v = idx % BLOCK_ITEMS;
3734
3735 if (i >= ni->max_blocks)
3736 return (1);
3737
3738 mask = &ni->idx_mask[i];
3739
3740 if ((*mask & ((u_long)1 << v)) != 0)
3741 return (1);
3742
3743 /* Mark as free */
3744 *mask |= (u_long)1 << v;
3745
3746 /* Update free offset */
3747 if (ni->free_off[0] > i)
3748 ni->free_off[0] = i;
3749
3750 return (0);
3751 }
3752
3753 /*
3754 * Allocate new index in given instance and stores in in @pidx.
3755 * Returns 0 on success.
3756 */
3757 int
ipfw_objhash_alloc_idx(void * n,uint32_t * pidx)3758 ipfw_objhash_alloc_idx(void *n, uint32_t *pidx)
3759 {
3760 struct namedobj_instance *ni;
3761 u_long *mask;
3762 int i, off, v;
3763
3764 ni = (struct namedobj_instance *)n;
3765
3766 off = ni->free_off[0];
3767 mask = &ni->idx_mask[off];
3768
3769 for (i = off; i < ni->max_blocks; i++, mask++) {
3770 if ((v = ffsl(*mask)) == 0)
3771 continue;
3772
3773 /* Mark as busy */
3774 *mask &= ~ ((u_long)1 << (v - 1));
3775
3776 ni->free_off[0] = i;
3777
3778 v = BLOCK_ITEMS * i + v - 1;
3779
3780 *pidx = v;
3781 return (0);
3782 }
3783
3784 return (1);
3785 }
3786
3787 /* end of file */
3788