1/* iptables match extension for limiting packets per destination
2 *
3 * (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
4 *
5 * Development of this code was funded by Astaro AG, http://www.astaro.com/
6 *
7 * Based on ipt_limit.c by
8 * J�r�me de Vivie   <devivie@info.enserb.u-bordeaux.fr>
9 * Herv� Eychenne    <rv@wallfire.org>
10 *
11 * Error corections by nmalykh@bilim.com (22.01.2005)
12 */
13
14#include <stdio.h>
15#include <string.h>
16#include <stdlib.h>
17#include <getopt.h>
18#include <iptables.h>
19#include <stddef.h>
20#include <linux/netfilter_ipv4/ip_tables.h>
21#include <linux/netfilter_ipv4/ipt_hashlimit.h>
22
23#define IPT_HASHLIMIT_BURST	5
24
25/* miliseconds */
26#define IPT_HASHLIMIT_GCINTERVAL	1000
27#define IPT_HASHLIMIT_EXPIRE	10000
28
29/* Function which prints out usage message. */
30static void
31help(void)
32{
33	printf(
34"hashlimit v%s options:\n"
35"--hashlimit <avg>		max average match rate\n"
36"                                [Packets per second unless followed by \n"
37"                                /sec /minute /hour /day postfixes]\n"
38"--hashlimit-mode <mode>		mode is a comma-separated list of\n"
39"					dstip,srcip,dstport,srcport\n"
40"--hashlimit-name <name>		name for /proc/net/ipt_hashlimit/\n"
41"[--hashlimit-burst <num>]	number to match in a burst, default %u\n"
42"[--hashlimit-htable-size <num>]	number of hashtable buckets\n"
43"[--hashlimit-htable-max <num>]	number of hashtable entries\n"
44"[--hashlimit-htable-gcinterval]	interval between garbage collection runs\n"
45"[--hashlimit-htable-expire]	after which time are idle entries expired?\n"
46"\n", IPTABLES_VERSION, IPT_HASHLIMIT_BURST);
47}
48
49static struct option opts[] = {
50	{ "hashlimit", 1, 0, '%' },
51	{ "hashlimit-burst", 1, 0, '$' },
52	{ "hashlimit-htable-size", 1, 0, '&' },
53	{ "hashlimit-htable-max", 1, 0, '*' },
54	{ "hashlimit-htable-gcinterval", 1, 0, '(' },
55	{ "hashlimit-htable-expire", 1, 0, ')' },
56	{ "hashlimit-mode", 1, 0, '_' },
57	{ "hashlimit-name", 1, 0, '"' },
58	{ 0 }
59};
60
61static
62int parse_rate(const char *rate, u_int32_t *val)
63{
64	const char *delim;
65	u_int32_t r;
66	u_int32_t mult = 1;  /* Seconds by default. */
67
68	delim = strchr(rate, '/');
69	if (delim) {
70		if (strlen(delim+1) == 0)
71			return 0;
72
73		if (strncasecmp(delim+1, "second", strlen(delim+1)) == 0)
74			mult = 1;
75		else if (strncasecmp(delim+1, "minute", strlen(delim+1)) == 0)
76			mult = 60;
77		else if (strncasecmp(delim+1, "hour", strlen(delim+1)) == 0)
78			mult = 60*60;
79		else if (strncasecmp(delim+1, "day", strlen(delim+1)) == 0)
80			mult = 24*60*60;
81		else
82			return 0;
83	}
84	r = atoi(rate);
85	if (!r)
86		return 0;
87
88	/* This would get mapped to infinite (1/day is minimum they
89           can specify, so we're ok at that end). */
90	if (r / mult > IPT_HASHLIMIT_SCALE)
91		exit_error(PARAMETER_PROBLEM, "Rate too fast `%s'\n", rate);
92
93	*val = IPT_HASHLIMIT_SCALE * mult / r;
94	return 1;
95}
96
97/* Initialize the match. */
98static void
99init(struct ipt_entry_match *m, unsigned int *nfcache)
100{
101	struct ipt_hashlimit_info *r = (struct ipt_hashlimit_info *)m->data;
102
103	r->cfg.burst = IPT_HASHLIMIT_BURST;
104	r->cfg.gc_interval = IPT_HASHLIMIT_GCINTERVAL;
105	r->cfg.expire = IPT_HASHLIMIT_EXPIRE;
106
107}
108
109
110/* Parse a 'mode' parameter into the required bitmask */
111static int parse_mode(struct ipt_hashlimit_info *r, char *optarg)
112{
113	char *tok;
114	char *arg = strdup(optarg);
115
116	if (!arg)
117		return -1;
118
119	r->cfg.mode = 0;
120
121	for (tok = strtok(arg, ",|");
122	     tok;
123	     tok = strtok(NULL, ",|")) {
124		if (!strcmp(tok, "dstip"))
125			r->cfg.mode |= IPT_HASHLIMIT_HASH_DIP;
126		else if (!strcmp(tok, "srcip"))
127			r->cfg.mode |= IPT_HASHLIMIT_HASH_SIP;
128		else if (!strcmp(tok, "srcport"))
129			r->cfg.mode |= IPT_HASHLIMIT_HASH_SPT;
130		else if (!strcmp(tok, "dstport"))
131			r->cfg.mode |= IPT_HASHLIMIT_HASH_DPT;
132		else {
133			free(arg);
134			return -1;
135		}
136	}
137	free(arg);
138	return 0;
139}
140
141#define PARAM_LIMIT		0x00000001
142#define PARAM_BURST		0x00000002
143#define PARAM_MODE		0x00000004
144#define PARAM_NAME		0x00000008
145#define PARAM_SIZE		0x00000010
146#define PARAM_MAX		0x00000020
147#define PARAM_GCINTERVAL	0x00000040
148#define PARAM_EXPIRE		0x00000080
149
150/* Function which parses command options; returns true if it
151   ate an option */
152static int
153parse(int c, char **argv, int invert, unsigned int *flags,
154      const struct ipt_entry *entry,
155      unsigned int *nfcache,
156      struct ipt_entry_match **match)
157{
158	struct ipt_hashlimit_info *r =
159			(struct ipt_hashlimit_info *)(*match)->data;
160	unsigned int num;
161
162	switch(c) {
163	case '%':
164		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
165		if (!parse_rate(optarg, &r->cfg.avg))
166			exit_error(PARAMETER_PROBLEM,
167				   "bad rate `%s'", optarg);
168		*flags |= PARAM_LIMIT;
169		break;
170
171	case '$':
172		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
173		if (string_to_number(optarg, 0, 10000, &num) == -1)
174			exit_error(PARAMETER_PROBLEM,
175				   "bad --hashlimit-burst `%s'", optarg);
176		r->cfg.burst = num;
177		*flags |= PARAM_BURST;
178		break;
179	case '&':
180		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
181		if (string_to_number(optarg, 0, 0xffffffff, &num) == -1)
182			exit_error(PARAMETER_PROBLEM,
183				"bad --hashlimit-htable-size: `%s'", optarg);
184		r->cfg.size = num;
185		*flags |= PARAM_SIZE;
186		break;
187	case '*':
188		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
189		if (string_to_number(optarg, 0, 0xffffffff, &num) == -1)
190			exit_error(PARAMETER_PROBLEM,
191				"bad --hashlimit-htable-max: `%s'", optarg);
192		r->cfg.max = num;
193		*flags |= PARAM_MAX;
194		break;
195	case '(':
196		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
197		if (string_to_number(optarg, 0, 0xffffffff, &num) == -1)
198			exit_error(PARAMETER_PROBLEM,
199				"bad --hashlimit-htable-gcinterval: `%s'",
200				optarg);
201		r->cfg.gc_interval = num;
202		*flags |= PARAM_GCINTERVAL;
203		break;
204	case ')':
205		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
206		if (string_to_number(optarg, 0, 0xffffffff, &num) == -1)
207			exit_error(PARAMETER_PROBLEM,
208				"bad --hashlimit-htable-expire: `%s'", optarg);
209		r->cfg.expire = num;
210		*flags |= PARAM_EXPIRE;
211		break;
212	case '_':
213		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
214		if (parse_mode(r, optarg) < 0)
215			exit_error(PARAMETER_PROBLEM,
216				   "bad --hashlimit-mode: `%s'\n", optarg);
217		*flags |= PARAM_MODE;
218		break;
219	case '"':
220		if (check_inverse(argv[optind-1], &invert, &optind, 0)) break;
221		if (strlen(optarg) == 0)
222			exit_error(PARAMETER_PROBLEM, "Zero-length name?");
223		strncpy(r->name, optarg, sizeof(r->name));
224		*flags |= PARAM_NAME;
225		break;
226	default:
227		return 0;
228	}
229
230	if (invert)
231		exit_error(PARAMETER_PROBLEM,
232			   "hashlimit does not support invert");
233
234	return 1;
235}
236
237/* Final check; nothing. */
238static void final_check(unsigned int flags)
239{
240	if (!(flags & PARAM_LIMIT))
241		exit_error(PARAMETER_PROBLEM,
242				"You have to specify --hashlimit");
243	if (!(flags & PARAM_MODE))
244		exit_error(PARAMETER_PROBLEM,
245				"You have to specify --hashlimit-mode");
246	if (!(flags & PARAM_NAME))
247		exit_error(PARAMETER_PROBLEM,
248				"You have to specify --hashlimit-name");
249}
250
251static struct rates
252{
253	const char *name;
254	u_int32_t mult;
255} rates[] = { { "day", IPT_HASHLIMIT_SCALE*24*60*60 },
256	      { "hour", IPT_HASHLIMIT_SCALE*60*60 },
257	      { "min", IPT_HASHLIMIT_SCALE*60 },
258	      { "sec", IPT_HASHLIMIT_SCALE } };
259
260static void print_rate(u_int32_t period)
261{
262	unsigned int i;
263
264	for (i = 1; i < sizeof(rates)/sizeof(struct rates); i++) {
265		if (period > rates[i].mult
266            || rates[i].mult/period < rates[i].mult%period)
267			break;
268	}
269
270	printf("%u/%s ", rates[i-1].mult / period, rates[i-1].name);
271}
272
273static void print_mode(const struct ipt_hashlimit_info *r, char separator)
274{
275	int prevmode = 0;
276
277	if (r->cfg.mode & IPT_HASHLIMIT_HASH_SIP) {
278		if (prevmode)
279			putchar(separator);
280		fputs("srcip", stdout);
281		prevmode = 1;
282	}
283	if (r->cfg.mode & IPT_HASHLIMIT_HASH_SPT) {
284		if (prevmode)
285			putchar(separator);
286		fputs("srcport", stdout);
287		prevmode = 1;
288	}
289	if (r->cfg.mode & IPT_HASHLIMIT_HASH_DIP) {
290		if (prevmode)
291			putchar(separator);
292		fputs("dstip", stdout);
293		prevmode = 1;
294	}
295	if (r->cfg.mode & IPT_HASHLIMIT_HASH_DPT) {
296		if (prevmode)
297			putchar(separator);
298		fputs("dstport", stdout);
299	}
300	putchar(' ');
301}
302
303/* Prints out the matchinfo. */
304static void
305print(const struct ipt_ip *ip,
306      const struct ipt_entry_match *match,
307      int numeric)
308{
309	struct ipt_hashlimit_info *r =
310		(struct ipt_hashlimit_info *)match->data;
311	fputs("limit: avg ", stdout); print_rate(r->cfg.avg);
312	printf("burst %u ", r->cfg.burst);
313	fputs("mode ", stdout);
314	print_mode(r, '-');
315	if (r->cfg.size)
316		printf("htable-size %u ", r->cfg.size);
317	if (r->cfg.max)
318		printf("htable-max %u ", r->cfg.max);
319	if (r->cfg.gc_interval != IPT_HASHLIMIT_GCINTERVAL)
320		printf("htable-gcinterval %u ", r->cfg.gc_interval);
321	if (r->cfg.expire != IPT_HASHLIMIT_EXPIRE)
322		printf("htable-expire %u ", r->cfg.expire);
323}
324
325static void save(const struct ipt_ip *ip, const struct ipt_entry_match *match)
326{
327	struct ipt_hashlimit_info *r =
328		(struct ipt_hashlimit_info *)match->data;
329
330	fputs("--hashlimit ", stdout); print_rate(r->cfg.avg);
331	if (r->cfg.burst != IPT_HASHLIMIT_BURST)
332		printf("--hashlimit-burst %u ", r->cfg.burst);
333
334	fputs("--hashlimit-mode ", stdout);
335	print_mode(r, ',');
336
337	printf("--hashlimit-name %s ", r->name);
338
339	if (r->cfg.size)
340		printf("--hashlimit-htable-size %u ", r->cfg.size);
341	if (r->cfg.max)
342		printf("--hashlimit-htable-max %u ", r->cfg.max);
343	if (r->cfg.gc_interval != IPT_HASHLIMIT_GCINTERVAL)
344		printf("--hashlimit-htable-gcinterval %u", r->cfg.gc_interval);
345	if (r->cfg.expire != IPT_HASHLIMIT_EXPIRE)
346		printf("--hashlimit-htable-expire %u ", r->cfg.expire);
347}
348
349static struct iptables_match hashlimit = { NULL,
350	.name		= "hashlimit",
351	.version	= IPTABLES_VERSION,
352	.size		= IPT_ALIGN(sizeof(struct ipt_hashlimit_info)),
353	.userspacesize	= offsetof(struct ipt_hashlimit_info, hinfo),
354	.help		= &help,
355	.init		= &init,
356	.parse		= &parse,
357	.final_check	= &final_check,
358	.print		= &print,
359	.save		= &save,
360	.extra_opts	= opts
361};
362
363void _init(void)
364{
365	register_match(&hashlimit);
366}
367