ip_fw_sockopt.c revision 231076
1/*-
2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 *
4 * Supported by: Valeria Paoli
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw_sockopt.c 231076 2012-02-06 11:35:29Z glebius $");
30
31/*
32 * Sockopt support for ipfw. The routines here implement
33 * the upper half of the ipfw code.
34 */
35
36#include "opt_ipfw.h"
37#include "opt_inet.h"
38#ifndef INET
39#error IPFIREWALL requires INET.
40#endif /* INET */
41#include "opt_inet6.h"
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>	/* struct m_tag used by nested headers */
47#include <sys/kernel.h>
48#include <sys/lock.h>
49#include <sys/priv.h>
50#include <sys/proc.h>
51#include <sys/rwlock.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/sysctl.h>
55#include <sys/syslog.h>
56#include <net/if.h>
57#include <net/route.h>
58#include <net/vnet.h>
59
60#include <netinet/in.h>
61#include <netinet/ip_var.h> /* hooks */
62#include <netinet/ip_fw.h>
63#include <netinet/ipfw/ip_fw_private.h>
64
65#ifdef MAC
66#include <security/mac/mac_framework.h>
67#endif
68
69MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
70
71/*
72 * static variables followed by global ones (none in this file)
73 */
74
75/*
76 * Find the smallest rule >= key, id.
77 * We could use bsearch but it is so simple that we code it directly
78 */
79int
80ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
81{
82	int i, lo, hi;
83	struct ip_fw *r;
84
85  	for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
86		i = (lo + hi) / 2;
87		r = chain->map[i];
88		if (r->rulenum < key)
89			lo = i + 1;	/* continue from the next one */
90		else if (r->rulenum > key)
91			hi = i;		/* this might be good */
92		else if (r->id < id)
93			lo = i + 1;	/* continue from the next one */
94		else /* r->id >= id */
95			hi = i;		/* this might be good */
96	};
97	return hi;
98}
99
100/*
101 * allocate a new map, returns the chain locked. extra is the number
102 * of entries to add or delete.
103 */
104static struct ip_fw **
105get_map(struct ip_fw_chain *chain, int extra, int locked)
106{
107
108	for (;;) {
109		struct ip_fw **map;
110		int i;
111
112		i = chain->n_rules + extra;
113		map = malloc(i * sizeof(struct ip_fw *), M_IPFW,
114			locked ? M_NOWAIT : M_WAITOK);
115		if (map == NULL) {
116			printf("%s: cannot allocate map\n", __FUNCTION__);
117			return NULL;
118		}
119		if (!locked)
120			IPFW_UH_WLOCK(chain);
121		if (i >= chain->n_rules + extra) /* good */
122			return map;
123		/* otherwise we lost the race, free and retry */
124		if (!locked)
125			IPFW_UH_WUNLOCK(chain);
126		free(map, M_IPFW);
127	}
128}
129
130/*
131 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
132 */
133static struct ip_fw **
134swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
135{
136	struct ip_fw **old_map;
137
138	IPFW_WLOCK(chain);
139	chain->id++;
140	chain->n_rules = new_len;
141	old_map = chain->map;
142	chain->map = new_map;
143	IPFW_WUNLOCK(chain);
144	return old_map;
145}
146
147/*
148 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
149 * possibly create a rule number and add the rule to the list.
150 * Update the rule_number in the input struct so the caller knows it as well.
151 * XXX DO NOT USE FOR THE DEFAULT RULE.
152 * Must be called without IPFW_UH held
153 */
154int
155ipfw_add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
156{
157	struct ip_fw *rule;
158	int i, l, insert_before;
159	struct ip_fw **map;	/* the new array of pointers */
160
161	if (chain->rules == NULL || input_rule->rulenum > IPFW_DEFAULT_RULE-1)
162		return (EINVAL);
163
164	l = RULESIZE(input_rule);
165	rule = malloc(l, M_IPFW, M_WAITOK | M_ZERO);
166	if (rule == NULL)
167		return (ENOSPC);
168	/* get_map returns with IPFW_UH_WLOCK if successful */
169	map = get_map(chain, 1, 0 /* not locked */);
170	if (map == NULL) {
171		free(rule, M_IPFW);
172		return ENOSPC;
173	}
174
175	bcopy(input_rule, rule, l);
176	/* clear fields not settable from userland */
177	rule->x_next = NULL;
178	rule->next_rule = NULL;
179	rule->pcnt = 0;
180	rule->bcnt = 0;
181	rule->timestamp = 0;
182
183	if (V_autoinc_step < 1)
184		V_autoinc_step = 1;
185	else if (V_autoinc_step > 1000)
186		V_autoinc_step = 1000;
187	/* find the insertion point, we will insert before */
188	insert_before = rule->rulenum ? rule->rulenum + 1 : IPFW_DEFAULT_RULE;
189	i = ipfw_find_rule(chain, insert_before, 0);
190	/* duplicate first part */
191	if (i > 0)
192		bcopy(chain->map, map, i * sizeof(struct ip_fw *));
193	map[i] = rule;
194	/* duplicate remaining part, we always have the default rule */
195	bcopy(chain->map + i, map + i + 1,
196		sizeof(struct ip_fw *) *(chain->n_rules - i));
197	if (rule->rulenum == 0) {
198		/* write back the number */
199		rule->rulenum = i > 0 ? map[i-1]->rulenum : 0;
200		if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
201			rule->rulenum += V_autoinc_step;
202		input_rule->rulenum = rule->rulenum;
203	}
204
205	rule->id = chain->id + 1;
206	map = swap_map(chain, map, chain->n_rules + 1);
207	chain->static_len += l;
208	IPFW_UH_WUNLOCK(chain);
209	if (map)
210		free(map, M_IPFW);
211	return (0);
212}
213
214/*
215 * Reclaim storage associated with a list of rules.  This is
216 * typically the list created using remove_rule.
217 * A NULL pointer on input is handled correctly.
218 */
219void
220ipfw_reap_rules(struct ip_fw *head)
221{
222	struct ip_fw *rule;
223
224	while ((rule = head) != NULL) {
225		head = head->x_next;
226		free(rule, M_IPFW);
227	}
228}
229
230/*
231 * Used by del_entry() to check if a rule should be kept.
232 * Returns 1 if the rule must be kept, 0 otherwise.
233 *
234 * Called with cmd = {0,1,5}.
235 * cmd == 0 matches on rule numbers, excludes rules in RESVD_SET if n == 0 ;
236 * cmd == 1 matches on set numbers only, rule numbers are ignored;
237 * cmd == 5 matches on rule and set numbers.
238 *
239 * n == 0 is a wildcard for rule numbers, there is no wildcard for sets.
240 *
241 * Rules to keep are
242 *	(default || reserved || !match_set || !match_number)
243 * where
244 *   default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
245 *	// the default rule is always protected
246 *
247 *   reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
248 *	// RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
249 *
250 *   match_set ::= (cmd == 0 || rule->set == set)
251 *	// set number is ignored for cmd == 0
252 *
253 *   match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
254 *	// number is ignored for cmd == 1 or n == 0
255 *
256 */
257static int
258keep_rule(struct ip_fw *rule, uint8_t cmd, uint8_t set, uint32_t n)
259{
260	return
261		 (rule->rulenum == IPFW_DEFAULT_RULE)		||
262		 (cmd == 0 && n == 0 && rule->set == RESVD_SET)	||
263		!(cmd == 0 || rule->set == set)			||
264		!(cmd == 1 || n == 0 || n == rule->rulenum);
265}
266
267/**
268 * Remove all rules with given number, or do set manipulation.
269 * Assumes chain != NULL && *chain != NULL.
270 *
271 * The argument is an uint32_t. The low 16 bit are the rule or set number;
272 * the next 8 bits are the new set; the top 8 bits indicate the command:
273 *
274 *	0	delete rules numbered "rulenum"
275 *	1	delete rules in set "rulenum"
276 *	2	move rules "rulenum" to set "new_set"
277 *	3	move rules from set "rulenum" to set "new_set"
278 *	4	swap sets "rulenum" and "new_set"
279 *	5	delete rules "rulenum" and set "new_set"
280 */
281static int
282del_entry(struct ip_fw_chain *chain, uint32_t arg)
283{
284	struct ip_fw *rule;
285	uint32_t num;	/* rule number or old_set */
286	uint8_t cmd, new_set;
287	int start, end, i, ofs, n;
288	struct ip_fw **map = NULL;
289	int error = 0;
290
291	num = arg & 0xffff;
292	cmd = (arg >> 24) & 0xff;
293	new_set = (arg >> 16) & 0xff;
294
295	if (cmd > 5 || new_set > RESVD_SET)
296		return EINVAL;
297	if (cmd == 0 || cmd == 2 || cmd == 5) {
298		if (num >= IPFW_DEFAULT_RULE)
299			return EINVAL;
300	} else {
301		if (num > RESVD_SET)	/* old_set */
302			return EINVAL;
303	}
304
305	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
306	chain->reap = NULL;	/* prepare for deletions */
307
308	switch (cmd) {
309	case 0:	/* delete rules "num" (num == 0 matches all) */
310	case 1:	/* delete all rules in set N */
311	case 5: /* delete rules with number N and set "new_set". */
312
313		/*
314		 * Locate first rule to delete (start), the rule after
315		 * the last one to delete (end), and count how many
316		 * rules to delete (n). Always use keep_rule() to
317		 * determine which rules to keep.
318		 */
319		n = 0;
320		if (cmd == 1) {
321			/* look for a specific set including RESVD_SET.
322			 * Must scan the entire range, ignore num.
323			 */
324			new_set = num;
325			for (start = -1, end = i = 0; i < chain->n_rules; i++) {
326				if (keep_rule(chain->map[i], cmd, new_set, 0))
327					continue;
328				if (start < 0)
329					start = i;
330				end = i;
331				n++;
332			}
333			end++;	/* first non-matching */
334		} else {
335			/* Optimized search on rule numbers */
336			start = ipfw_find_rule(chain, num, 0);
337			for (end = start; end < chain->n_rules; end++) {
338				rule = chain->map[end];
339				if (num > 0 && rule->rulenum != num)
340					break;
341				if (!keep_rule(rule, cmd, new_set, num))
342					n++;
343			}
344		}
345
346		if (n == 0) {
347			/* A flush request (arg == 0 or cmd == 1) on empty
348			 * ruleset returns with no error. On the contrary,
349			 * if there is no match on a specific request,
350			 * we return EINVAL.
351			 */
352			if (arg != 0 && cmd != 1)
353				error = EINVAL;
354			break;
355		}
356
357		/* We have something to delete. Allocate the new map */
358		map = get_map(chain, -n, 1 /* locked */);
359		if (map == NULL) {
360			error = EINVAL;
361			break;
362		}
363
364		/* 1. bcopy the initial part of the map */
365		if (start > 0)
366			bcopy(chain->map, map, start * sizeof(struct ip_fw *));
367		/* 2. copy active rules between start and end */
368		for (i = ofs = start; i < end; i++) {
369			rule = chain->map[i];
370			if (keep_rule(rule, cmd, new_set, num))
371				map[ofs++] = rule;
372		}
373		/* 3. copy the final part of the map */
374		bcopy(chain->map + end, map + ofs,
375			(chain->n_rules - end) * sizeof(struct ip_fw *));
376		/* 4. swap the maps (under BH_LOCK) */
377		map = swap_map(chain, map, chain->n_rules - n);
378		/* 5. now remove the rules deleted from the old map */
379		for (i = start; i < end; i++) {
380			int l;
381			rule = map[i];
382			if (keep_rule(rule, cmd, new_set, num))
383				continue;
384			l = RULESIZE(rule);
385			chain->static_len -= l;
386			ipfw_remove_dyn_children(rule);
387			rule->x_next = chain->reap;
388			chain->reap = rule;
389		}
390		break;
391
392	/*
393	 * In the next 3 cases the loop stops at (n_rules - 1)
394	 * because the default rule is never eligible..
395	 */
396
397	case 2:	/* move rules with given RULE number to new set */
398		for (i = 0; i < chain->n_rules - 1; i++) {
399			rule = chain->map[i];
400			if (rule->rulenum == num)
401				rule->set = new_set;
402		}
403		break;
404
405	case 3: /* move rules with given SET number to new set */
406		for (i = 0; i < chain->n_rules - 1; i++) {
407			rule = chain->map[i];
408			if (rule->set == num)
409				rule->set = new_set;
410		}
411		break;
412
413	case 4: /* swap two sets */
414		for (i = 0; i < chain->n_rules - 1; i++) {
415			rule = chain->map[i];
416			if (rule->set == num)
417				rule->set = new_set;
418			else if (rule->set == new_set)
419				rule->set = num;
420		}
421		break;
422	}
423
424	rule = chain->reap;
425	chain->reap = NULL;
426	IPFW_UH_WUNLOCK(chain);
427	ipfw_reap_rules(rule);
428	if (map)
429		free(map, M_IPFW);
430	return error;
431}
432
433/*
434 * Clear counters for a specific rule.
435 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
436 * so we only care that rules do not disappear.
437 */
438static void
439clear_counters(struct ip_fw *rule, int log_only)
440{
441	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
442
443	if (log_only == 0) {
444		rule->bcnt = rule->pcnt = 0;
445		rule->timestamp = 0;
446	}
447	if (l->o.opcode == O_LOG)
448		l->log_left = l->max_log;
449}
450
451/**
452 * Reset some or all counters on firewall rules.
453 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
454 * the next 8 bits are the set number, the top 8 bits are the command:
455 *	0	work with rules from all set's;
456 *	1	work with rules only from specified set.
457 * Specified rule number is zero if we want to clear all entries.
458 * log_only is 1 if we only want to reset logs, zero otherwise.
459 */
460static int
461zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
462{
463	struct ip_fw *rule;
464	char *msg;
465	int i;
466
467	uint16_t rulenum = arg & 0xffff;
468	uint8_t set = (arg >> 16) & 0xff;
469	uint8_t cmd = (arg >> 24) & 0xff;
470
471	if (cmd > 1)
472		return (EINVAL);
473	if (cmd == 1 && set > RESVD_SET)
474		return (EINVAL);
475
476	IPFW_UH_RLOCK(chain);
477	if (rulenum == 0) {
478		V_norule_counter = 0;
479		for (i = 0; i < chain->n_rules; i++) {
480			rule = chain->map[i];
481			/* Skip rules not in our set. */
482			if (cmd == 1 && rule->set != set)
483				continue;
484			clear_counters(rule, log_only);
485		}
486		msg = log_only ? "All logging counts reset" :
487		    "Accounting cleared";
488	} else {
489		int cleared = 0;
490		for (i = 0; i < chain->n_rules; i++) {
491			rule = chain->map[i];
492			if (rule->rulenum == rulenum) {
493				if (cmd == 0 || rule->set == set)
494					clear_counters(rule, log_only);
495				cleared = 1;
496			}
497			if (rule->rulenum > rulenum)
498				break;
499		}
500		if (!cleared) {	/* we did not find any matching rules */
501			IPFW_UH_RUNLOCK(chain);
502			return (EINVAL);
503		}
504		msg = log_only ? "logging count reset" : "cleared";
505	}
506	IPFW_UH_RUNLOCK(chain);
507
508	if (V_fw_verbose) {
509		int lev = LOG_SECURITY | LOG_NOTICE;
510
511		if (rulenum)
512			log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
513		else
514			log(lev, "ipfw: %s.\n", msg);
515	}
516	return (0);
517}
518
519/*
520 * Check validity of the structure before insert.
521 * Rules are simple, so this mostly need to check rule sizes.
522 */
523static int
524check_ipfw_struct(struct ip_fw *rule, int size)
525{
526	int l, cmdlen = 0;
527	int have_action=0;
528	ipfw_insn *cmd;
529
530	if (size < sizeof(*rule)) {
531		printf("ipfw: rule too short\n");
532		return (EINVAL);
533	}
534	/* first, check for valid size */
535	l = RULESIZE(rule);
536	if (l != size) {
537		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
538		return (EINVAL);
539	}
540	if (rule->act_ofs >= rule->cmd_len) {
541		printf("ipfw: bogus action offset (%u > %u)\n",
542		    rule->act_ofs, rule->cmd_len - 1);
543		return (EINVAL);
544	}
545	/*
546	 * Now go for the individual checks. Very simple ones, basically only
547	 * instruction sizes.
548	 */
549	for (l = rule->cmd_len, cmd = rule->cmd ;
550			l > 0 ; l -= cmdlen, cmd += cmdlen) {
551		cmdlen = F_LEN(cmd);
552		if (cmdlen > l) {
553			printf("ipfw: opcode %d size truncated\n",
554			    cmd->opcode);
555			return EINVAL;
556		}
557		switch (cmd->opcode) {
558		case O_PROBE_STATE:
559		case O_KEEP_STATE:
560		case O_PROTO:
561		case O_IP_SRC_ME:
562		case O_IP_DST_ME:
563		case O_LAYER2:
564		case O_IN:
565		case O_FRAG:
566		case O_DIVERTED:
567		case O_IPOPT:
568		case O_IPTOS:
569		case O_IPPRECEDENCE:
570		case O_IPVER:
571		case O_SOCKARG:
572		case O_TCPFLAGS:
573		case O_TCPOPTS:
574		case O_ESTAB:
575		case O_VERREVPATH:
576		case O_VERSRCREACH:
577		case O_ANTISPOOF:
578		case O_IPSEC:
579#ifdef INET6
580		case O_IP6_SRC_ME:
581		case O_IP6_DST_ME:
582		case O_EXT_HDR:
583		case O_IP6:
584#endif
585		case O_IP4:
586		case O_TAG:
587			if (cmdlen != F_INSN_SIZE(ipfw_insn))
588				goto bad_size;
589			break;
590
591		case O_FIB:
592			if (cmdlen != F_INSN_SIZE(ipfw_insn))
593				goto bad_size;
594			if (cmd->arg1 >= rt_numfibs) {
595				printf("ipfw: invalid fib number %d\n",
596					cmd->arg1);
597				return EINVAL;
598			}
599			break;
600
601		case O_SETFIB:
602			if (cmdlen != F_INSN_SIZE(ipfw_insn))
603				goto bad_size;
604			if ((cmd->arg1 != IP_FW_TABLEARG) &&
605			    (cmd->arg1 >= rt_numfibs)) {
606				printf("ipfw: invalid fib number %d\n",
607					cmd->arg1);
608				return EINVAL;
609			}
610			goto check_action;
611
612		case O_UID:
613		case O_GID:
614		case O_JAIL:
615		case O_IP_SRC:
616		case O_IP_DST:
617		case O_TCPSEQ:
618		case O_TCPACK:
619		case O_PROB:
620		case O_ICMPTYPE:
621			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
622				goto bad_size;
623			break;
624
625		case O_LIMIT:
626			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
627				goto bad_size;
628			break;
629
630		case O_LOG:
631			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
632				goto bad_size;
633
634			((ipfw_insn_log *)cmd)->log_left =
635			    ((ipfw_insn_log *)cmd)->max_log;
636
637			break;
638
639		case O_IP_SRC_MASK:
640		case O_IP_DST_MASK:
641			/* only odd command lengths */
642			if ( !(cmdlen & 1) || cmdlen > 31)
643				goto bad_size;
644			break;
645
646		case O_IP_SRC_SET:
647		case O_IP_DST_SET:
648			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
649				printf("ipfw: invalid set size %d\n",
650					cmd->arg1);
651				return EINVAL;
652			}
653			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
654			    (cmd->arg1+31)/32 )
655				goto bad_size;
656			break;
657
658		case O_IP_SRC_LOOKUP:
659		case O_IP_DST_LOOKUP:
660			if (cmd->arg1 >= IPFW_TABLES_MAX) {
661				printf("ipfw: invalid table number %d\n",
662				    cmd->arg1);
663				return (EINVAL);
664			}
665			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
666			    cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
667			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
668				goto bad_size;
669			break;
670
671		case O_MACADDR2:
672			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
673				goto bad_size;
674			break;
675
676		case O_NOP:
677		case O_IPID:
678		case O_IPTTL:
679		case O_IPLEN:
680		case O_TCPDATALEN:
681		case O_TCPWIN:
682		case O_TAGGED:
683			if (cmdlen < 1 || cmdlen > 31)
684				goto bad_size;
685			break;
686
687		case O_MAC_TYPE:
688		case O_IP_SRCPORT:
689		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
690			if (cmdlen < 2 || cmdlen > 31)
691				goto bad_size;
692			break;
693
694		case O_RECV:
695		case O_XMIT:
696		case O_VIA:
697			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
698				goto bad_size;
699			break;
700
701		case O_ALTQ:
702			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
703				goto bad_size;
704			break;
705
706		case O_PIPE:
707		case O_QUEUE:
708			if (cmdlen != F_INSN_SIZE(ipfw_insn))
709				goto bad_size;
710			goto check_action;
711
712		case O_FORWARD_IP:
713#ifdef	IPFIREWALL_FORWARD
714			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
715				goto bad_size;
716			goto check_action;
717#else
718			return EINVAL;
719#endif
720
721#ifdef INET6
722		case O_FORWARD_IP6:
723#ifdef IPFIREWALL_FORWARD
724			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
725				goto bad_size;
726			goto check_action;
727#else
728			return (EINVAL);
729#endif
730#endif /* INET6 */
731
732		case O_DIVERT:
733		case O_TEE:
734			if (ip_divert_ptr == NULL)
735				return EINVAL;
736			else
737				goto check_size;
738		case O_NETGRAPH:
739		case O_NGTEE:
740			if (ng_ipfw_input_p == NULL)
741				return EINVAL;
742			else
743				goto check_size;
744		case O_NAT:
745			if (!IPFW_NAT_LOADED)
746				return EINVAL;
747			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
748 				goto bad_size;
749 			goto check_action;
750		case O_FORWARD_MAC: /* XXX not implemented yet */
751		case O_CHECK_STATE:
752		case O_COUNT:
753		case O_ACCEPT:
754		case O_DENY:
755		case O_REJECT:
756#ifdef INET6
757		case O_UNREACH6:
758#endif
759		case O_SKIPTO:
760		case O_REASS:
761		case O_CALLRETURN:
762check_size:
763			if (cmdlen != F_INSN_SIZE(ipfw_insn))
764				goto bad_size;
765check_action:
766			if (have_action) {
767				printf("ipfw: opcode %d, multiple actions"
768					" not allowed\n",
769					cmd->opcode);
770				return EINVAL;
771			}
772			have_action = 1;
773			if (l != cmdlen) {
774				printf("ipfw: opcode %d, action must be"
775					" last opcode\n",
776					cmd->opcode);
777				return EINVAL;
778			}
779			break;
780#ifdef INET6
781		case O_IP6_SRC:
782		case O_IP6_DST:
783			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
784			    F_INSN_SIZE(ipfw_insn))
785				goto bad_size;
786			break;
787
788		case O_FLOW6ID:
789			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
790			    ((ipfw_insn_u32 *)cmd)->o.arg1)
791				goto bad_size;
792			break;
793
794		case O_IP6_SRC_MASK:
795		case O_IP6_DST_MASK:
796			if ( !(cmdlen & 1) || cmdlen > 127)
797				goto bad_size;
798			break;
799		case O_ICMP6TYPE:
800			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
801				goto bad_size;
802			break;
803#endif
804
805		default:
806			switch (cmd->opcode) {
807#ifndef INET6
808			case O_IP6_SRC_ME:
809			case O_IP6_DST_ME:
810			case O_EXT_HDR:
811			case O_IP6:
812			case O_UNREACH6:
813			case O_IP6_SRC:
814			case O_IP6_DST:
815			case O_FLOW6ID:
816			case O_IP6_SRC_MASK:
817			case O_IP6_DST_MASK:
818			case O_ICMP6TYPE:
819				printf("ipfw: no IPv6 support in kernel\n");
820				return EPROTONOSUPPORT;
821#endif
822			default:
823				printf("ipfw: opcode %d, unknown opcode\n",
824					cmd->opcode);
825				return EINVAL;
826			}
827		}
828	}
829	if (have_action == 0) {
830		printf("ipfw: missing action\n");
831		return EINVAL;
832	}
833	return 0;
834
835bad_size:
836	printf("ipfw: opcode %d size %d wrong\n",
837		cmd->opcode, cmdlen);
838	return EINVAL;
839}
840
841
842/*
843 * Translation of requests for compatibility with FreeBSD 7.2/8.
844 * a static variable tells us if we have an old client from userland,
845 * and if necessary we translate requests and responses between the
846 * two formats.
847 */
848static int is7 = 0;
849
850struct ip_fw7 {
851	struct ip_fw7	*next;		/* linked list of rules     */
852	struct ip_fw7	*next_rule;	/* ptr to next [skipto] rule    */
853	/* 'next_rule' is used to pass up 'set_disable' status      */
854
855	uint16_t	act_ofs;	/* offset of action in 32-bit units */
856	uint16_t	cmd_len;	/* # of 32-bit words in cmd */
857	uint16_t	rulenum;	/* rule number          */
858	uint8_t		set;		/* rule set (0..31)     */
859	// #define RESVD_SET   31  /* set for default and persistent rules */
860	uint8_t		_pad;		/* padding          */
861	// uint32_t        id;             /* rule id, only in v.8 */
862	/* These fields are present in all rules.           */
863	uint64_t	pcnt;		/* Packet counter       */
864	uint64_t	bcnt;		/* Byte counter         */
865	uint32_t	timestamp;	/* tv_sec of last match     */
866
867	ipfw_insn	cmd[1];		/* storage for commands     */
868};
869
870	int convert_rule_to_7(struct ip_fw *rule);
871int convert_rule_to_8(struct ip_fw *rule);
872
873#ifndef RULESIZE7
874#define RULESIZE7(rule)  (sizeof(struct ip_fw7) + \
875	((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
876#endif
877
878
879/*
880 * Copy the static and dynamic rules to the supplied buffer
881 * and return the amount of space actually used.
882 * Must be run under IPFW_UH_RLOCK
883 */
884static size_t
885ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
886{
887	char *bp = buf;
888	char *ep = bp + space;
889	struct ip_fw *rule, *dst;
890	int l, i;
891	time_t	boot_seconds;
892
893        boot_seconds = boottime.tv_sec;
894	for (i = 0; i < chain->n_rules; i++) {
895		rule = chain->map[i];
896
897		if (is7) {
898		    /* Convert rule to FreeBSd 7.2 format */
899		    l = RULESIZE7(rule);
900		    if (bp + l + sizeof(uint32_t) <= ep) {
901			int error;
902			bcopy(rule, bp, l + sizeof(uint32_t));
903			error = convert_rule_to_7((struct ip_fw *) bp);
904			if (error)
905				return 0; /*XXX correct? */
906			/*
907			 * XXX HACK. Store the disable mask in the "next"
908			 * pointer in a wild attempt to keep the ABI the same.
909			 * Why do we do this on EVERY rule?
910			 */
911			bcopy(&V_set_disable,
912				&(((struct ip_fw7 *)bp)->next_rule),
913				sizeof(V_set_disable));
914			if (((struct ip_fw7 *)bp)->timestamp)
915			    ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
916			bp += l;
917		    }
918		    continue; /* go to next rule */
919		}
920
921		/* normal mode, don't touch rules */
922		l = RULESIZE(rule);
923		if (bp + l > ep) { /* should not happen */
924			printf("overflow dumping static rules\n");
925			break;
926		}
927		dst = (struct ip_fw *)bp;
928		bcopy(rule, dst, l);
929		/*
930		 * XXX HACK. Store the disable mask in the "next"
931		 * pointer in a wild attempt to keep the ABI the same.
932		 * Why do we do this on EVERY rule?
933		 */
934		bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
935		if (dst->timestamp)
936			dst->timestamp += boot_seconds;
937		bp += l;
938	}
939	ipfw_get_dynamic(&bp, ep); /* protected by the dynamic lock */
940	return (bp - (char *)buf);
941}
942
943
944/**
945 * {set|get}sockopt parser.
946 */
947int
948ipfw_ctl(struct sockopt *sopt)
949{
950#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
951	int error;
952	size_t size;
953	struct ip_fw *buf, *rule;
954	struct ip_fw_chain *chain;
955	u_int32_t rulenum[2];
956
957	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
958	if (error)
959		return (error);
960
961	/*
962	 * Disallow modifications in really-really secure mode, but still allow
963	 * the logging counters to be reset.
964	 */
965	if (sopt->sopt_name == IP_FW_ADD ||
966	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
967		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
968		if (error)
969			return (error);
970	}
971
972	chain = &V_layer3_chain;
973	error = 0;
974
975	switch (sopt->sopt_name) {
976	case IP_FW_GET:
977		/*
978		 * pass up a copy of the current rules. Static rules
979		 * come first (the last of which has number IPFW_DEFAULT_RULE),
980		 * followed by a possibly empty list of dynamic rule.
981		 * The last dynamic rule has NULL in the "next" field.
982		 *
983		 * Note that the calculated size is used to bound the
984		 * amount of data returned to the user.  The rule set may
985		 * change between calculating the size and returning the
986		 * data in which case we'll just return what fits.
987		 */
988		for (;;) {
989			int len = 0, want;
990
991			size = chain->static_len;
992			size += ipfw_dyn_len();
993			if (size >= sopt->sopt_valsize)
994				break;
995			buf = malloc(size, M_TEMP, M_WAITOK);
996			if (buf == NULL)
997				break;
998			IPFW_UH_RLOCK(chain);
999			/* check again how much space we need */
1000			want = chain->static_len + ipfw_dyn_len();
1001			if (size >= want)
1002				len = ipfw_getrules(chain, buf, size);
1003			IPFW_UH_RUNLOCK(chain);
1004			if (size >= want)
1005				error = sooptcopyout(sopt, buf, len);
1006			free(buf, M_TEMP);
1007			if (size >= want)
1008				break;
1009		}
1010		break;
1011
1012	case IP_FW_FLUSH:
1013		/* locking is done within del_entry() */
1014		error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
1015		break;
1016
1017	case IP_FW_ADD:
1018		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
1019		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
1020			sizeof(struct ip_fw7) );
1021
1022		/*
1023		 * If the size of commands equals RULESIZE7 then we assume
1024		 * a FreeBSD7.2 binary is talking to us (set is7=1).
1025		 * is7 is persistent so the next 'ipfw list' command
1026		 * will use this format.
1027		 * NOTE: If wrong version is guessed (this can happen if
1028		 *       the first ipfw command is 'ipfw [pipe] list')
1029		 *       the ipfw binary may crash or loop infinitly...
1030		 */
1031		if (sopt->sopt_valsize == RULESIZE7(rule)) {
1032		    is7 = 1;
1033		    error = convert_rule_to_8(rule);
1034		    if (error)
1035			return error;
1036		    if (error == 0)
1037			error = check_ipfw_struct(rule, RULESIZE(rule));
1038		} else {
1039		    is7 = 0;
1040		if (error == 0)
1041			error = check_ipfw_struct(rule, sopt->sopt_valsize);
1042		}
1043		if (error == 0) {
1044			/* locking is done within ipfw_add_rule() */
1045			error = ipfw_add_rule(chain, rule);
1046			size = RULESIZE(rule);
1047			if (!error && sopt->sopt_dir == SOPT_GET) {
1048				if (is7) {
1049					error = convert_rule_to_7(rule);
1050					size = RULESIZE7(rule);
1051					if (error)
1052						return error;
1053				}
1054				error = sooptcopyout(sopt, rule, size);
1055		}
1056		}
1057		free(rule, M_TEMP);
1058		break;
1059
1060	case IP_FW_DEL:
1061		/*
1062		 * IP_FW_DEL is used for deleting single rules or sets,
1063		 * and (ab)used to atomically manipulate sets. Argument size
1064		 * is used to distinguish between the two:
1065		 *    sizeof(u_int32_t)
1066		 *	delete single rule or set of rules,
1067		 *	or reassign rules (or sets) to a different set.
1068		 *    2*sizeof(u_int32_t)
1069		 *	atomic disable/enable sets.
1070		 *	first u_int32_t contains sets to be disabled,
1071		 *	second u_int32_t contains sets to be enabled.
1072		 */
1073		error = sooptcopyin(sopt, rulenum,
1074			2*sizeof(u_int32_t), sizeof(u_int32_t));
1075		if (error)
1076			break;
1077		size = sopt->sopt_valsize;
1078		if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
1079			/* delete or reassign, locking done in del_entry() */
1080			error = del_entry(chain, rulenum[0]);
1081		} else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
1082			IPFW_UH_WLOCK(chain);
1083			V_set_disable =
1084			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
1085			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
1086			IPFW_UH_WUNLOCK(chain);
1087		} else
1088			error = EINVAL;
1089		break;
1090
1091	case IP_FW_ZERO:
1092	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
1093		rulenum[0] = 0;
1094		if (sopt->sopt_val != 0) {
1095		    error = sooptcopyin(sopt, rulenum,
1096			    sizeof(u_int32_t), sizeof(u_int32_t));
1097		    if (error)
1098			break;
1099		}
1100		error = zero_entry(chain, rulenum[0],
1101			sopt->sopt_name == IP_FW_RESETLOG);
1102		break;
1103
1104	/*--- TABLE manipulations are protected by the IPFW_LOCK ---*/
1105	case IP_FW_TABLE_ADD:
1106		{
1107			ipfw_table_entry ent;
1108
1109			error = sooptcopyin(sopt, &ent,
1110			    sizeof(ent), sizeof(ent));
1111			if (error)
1112				break;
1113			error = ipfw_add_table_entry(chain, ent.tbl,
1114			    ent.addr, ent.masklen, ent.value);
1115		}
1116		break;
1117
1118	case IP_FW_TABLE_DEL:
1119		{
1120			ipfw_table_entry ent;
1121
1122			error = sooptcopyin(sopt, &ent,
1123			    sizeof(ent), sizeof(ent));
1124			if (error)
1125				break;
1126			error = ipfw_del_table_entry(chain, ent.tbl,
1127			    ent.addr, ent.masklen);
1128		}
1129		break;
1130
1131	case IP_FW_TABLE_FLUSH:
1132		{
1133			u_int16_t tbl;
1134
1135			error = sooptcopyin(sopt, &tbl,
1136			    sizeof(tbl), sizeof(tbl));
1137			if (error)
1138				break;
1139			IPFW_WLOCK(chain);
1140			error = ipfw_flush_table(chain, tbl);
1141			IPFW_WUNLOCK(chain);
1142		}
1143		break;
1144
1145	case IP_FW_TABLE_GETSIZE:
1146		{
1147			u_int32_t tbl, cnt;
1148
1149			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
1150			    sizeof(tbl))))
1151				break;
1152			IPFW_RLOCK(chain);
1153			error = ipfw_count_table(chain, tbl, &cnt);
1154			IPFW_RUNLOCK(chain);
1155			if (error)
1156				break;
1157			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
1158		}
1159		break;
1160
1161	case IP_FW_TABLE_LIST:
1162		{
1163			ipfw_table *tbl;
1164
1165			if (sopt->sopt_valsize < sizeof(*tbl)) {
1166				error = EINVAL;
1167				break;
1168			}
1169			size = sopt->sopt_valsize;
1170			tbl = malloc(size, M_TEMP, M_WAITOK);
1171			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
1172			if (error) {
1173				free(tbl, M_TEMP);
1174				break;
1175			}
1176			tbl->size = (size - sizeof(*tbl)) /
1177			    sizeof(ipfw_table_entry);
1178			IPFW_RLOCK(chain);
1179			error = ipfw_dump_table(chain, tbl);
1180			IPFW_RUNLOCK(chain);
1181			if (error) {
1182				free(tbl, M_TEMP);
1183				break;
1184			}
1185			error = sooptcopyout(sopt, tbl, size);
1186			free(tbl, M_TEMP);
1187		}
1188		break;
1189
1190	/*--- NAT operations are protected by the IPFW_LOCK ---*/
1191	case IP_FW_NAT_CFG:
1192		if (IPFW_NAT_LOADED)
1193			error = ipfw_nat_cfg_ptr(sopt);
1194		else {
1195			printf("IP_FW_NAT_CFG: %s\n",
1196			    "ipfw_nat not present, please load it");
1197			error = EINVAL;
1198		}
1199		break;
1200
1201	case IP_FW_NAT_DEL:
1202		if (IPFW_NAT_LOADED)
1203			error = ipfw_nat_del_ptr(sopt);
1204		else {
1205			printf("IP_FW_NAT_DEL: %s\n",
1206			    "ipfw_nat not present, please load it");
1207			error = EINVAL;
1208		}
1209		break;
1210
1211	case IP_FW_NAT_GET_CONFIG:
1212		if (IPFW_NAT_LOADED)
1213			error = ipfw_nat_get_cfg_ptr(sopt);
1214		else {
1215			printf("IP_FW_NAT_GET_CFG: %s\n",
1216			    "ipfw_nat not present, please load it");
1217			error = EINVAL;
1218		}
1219		break;
1220
1221	case IP_FW_NAT_GET_LOG:
1222		if (IPFW_NAT_LOADED)
1223			error = ipfw_nat_get_log_ptr(sopt);
1224		else {
1225			printf("IP_FW_NAT_GET_LOG: %s\n",
1226			    "ipfw_nat not present, please load it");
1227			error = EINVAL;
1228		}
1229		break;
1230
1231	default:
1232		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
1233		error = EINVAL;
1234	}
1235
1236	return (error);
1237#undef RULE_MAXSIZE
1238}
1239
1240
1241#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
1242
1243/* Functions to convert rules 7.2 <==> 8.0 */
1244int
1245convert_rule_to_7(struct ip_fw *rule)
1246{
1247	/* Used to modify original rule */
1248	struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
1249	/* copy of original rule, version 8 */
1250	struct ip_fw *tmp;
1251
1252	/* Used to copy commands */
1253	ipfw_insn *ccmd, *dst;
1254	int ll = 0, ccmdlen = 0;
1255
1256	tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
1257	if (tmp == NULL) {
1258		return 1; //XXX error
1259	}
1260	bcopy(rule, tmp, RULE_MAXSIZE);
1261
1262	/* Copy fields */
1263	rule7->_pad = tmp->_pad;
1264	rule7->set = tmp->set;
1265	rule7->rulenum = tmp->rulenum;
1266	rule7->cmd_len = tmp->cmd_len;
1267	rule7->act_ofs = tmp->act_ofs;
1268	rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
1269	rule7->next = (struct ip_fw7 *)tmp->x_next;
1270	rule7->cmd_len = tmp->cmd_len;
1271	rule7->pcnt = tmp->pcnt;
1272	rule7->bcnt = tmp->bcnt;
1273	rule7->timestamp = tmp->timestamp;
1274
1275	/* Copy commands */
1276	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
1277			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
1278		ccmdlen = F_LEN(ccmd);
1279
1280		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
1281
1282		if (dst->opcode > O_NAT)
1283			/* O_REASS doesn't exists in 7.2 version, so
1284			 * decrement opcode if it is after O_REASS
1285			 */
1286			dst->opcode--;
1287
1288		if (ccmdlen > ll) {
1289			printf("ipfw: opcode %d size truncated\n",
1290				ccmd->opcode);
1291			return EINVAL;
1292		}
1293	}
1294	free(tmp, M_TEMP);
1295
1296	return 0;
1297}
1298
1299int
1300convert_rule_to_8(struct ip_fw *rule)
1301{
1302	/* Used to modify original rule */
1303	struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
1304
1305	/* Used to copy commands */
1306	ipfw_insn *ccmd, *dst;
1307	int ll = 0, ccmdlen = 0;
1308
1309	/* Copy of original rule */
1310	struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
1311	if (tmp == NULL) {
1312		return 1; //XXX error
1313	}
1314
1315	bcopy(rule7, tmp, RULE_MAXSIZE);
1316
1317	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
1318			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
1319		ccmdlen = F_LEN(ccmd);
1320
1321		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
1322
1323		if (dst->opcode > O_NAT)
1324			/* O_REASS doesn't exists in 7.2 version, so
1325			 * increment opcode if it is after O_REASS
1326			 */
1327			dst->opcode++;
1328
1329		if (ccmdlen > ll) {
1330			printf("ipfw: opcode %d size truncated\n",
1331			    ccmd->opcode);
1332			return EINVAL;
1333		}
1334	}
1335
1336	rule->_pad = tmp->_pad;
1337	rule->set = tmp->set;
1338	rule->rulenum = tmp->rulenum;
1339	rule->cmd_len = tmp->cmd_len;
1340	rule->act_ofs = tmp->act_ofs;
1341	rule->next_rule = (struct ip_fw *)tmp->next_rule;
1342	rule->x_next = (struct ip_fw *)tmp->next;
1343	rule->cmd_len = tmp->cmd_len;
1344	rule->id = 0; /* XXX see if is ok = 0 */
1345	rule->pcnt = tmp->pcnt;
1346	rule->bcnt = tmp->bcnt;
1347	rule->timestamp = tmp->timestamp;
1348
1349	free (tmp, M_TEMP);
1350	return 0;
1351}
1352
1353/* end of file */
1354