• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * x_tables core - Backend for {ip,ip6,arp}_tables
3  *
4  * Copyright (C) 2006-2006 Harald Welte <laforge@netfilter.org>
5  * Copyright (C) 2006-2012 Patrick McHardy <kaber@trash.net>
6  *
7  * Based on existing ip_tables code which is
8  *   Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
9  *   Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2 as
13  * published by the Free Software Foundation.
14  *
15  */
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/socket.h>
20 #include <linux/net.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/string.h>
24 #include <linux/vmalloc.h>
25 #include <linux/mutex.h>
26 #include <linux/mm.h>
27 #include <linux/slab.h>
28 #include <linux/audit.h>
29 #include <net/net_namespace.h>
30 
31 #include <linux/netfilter/x_tables.h>
32 #include <linux/netfilter_arp.h>
33 #include <linux/netfilter_ipv4/ip_tables.h>
34 #include <linux/netfilter_ipv6/ip6_tables.h>
35 #include <linux/netfilter_arp/arp_tables.h>
36 
37 MODULE_LICENSE("GPL");
38 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
39 MODULE_DESCRIPTION("{ip,ip6,arp,eb}_tables backend module");
40 
41 #define XT_PCPU_BLOCK_SIZE 4096
42 
43 struct compat_delta {
44 	unsigned int offset; /* offset in kernel */
45 	int delta; /* delta in 32bit user land */
46 };
47 
48 struct xt_af {
49 	struct mutex mutex;
50 	struct list_head match;
51 	struct list_head target;
52 #ifdef CONFIG_COMPAT
53 	struct mutex compat_mutex;
54 	struct compat_delta *compat_tab;
55 	unsigned int number; /* number of slots in compat_tab[] */
56 	unsigned int cur; /* number of used slots in compat_tab[] */
57 #endif
58 };
59 
60 static struct xt_af *xt;
61 
62 static const char *const xt_prefix[NFPROTO_NUMPROTO] = {
63 	[NFPROTO_UNSPEC] = "x",
64 	[NFPROTO_IPV4]   = "ip",
65 	[NFPROTO_ARP]    = "arp",
66 	[NFPROTO_BRIDGE] = "eb",
67 	[NFPROTO_IPV6]   = "ip6",
68 };
69 
70 /* Registration hooks for targets. */
xt_register_target(struct xt_target * target)71 int xt_register_target(struct xt_target *target)
72 {
73 	u_int8_t af = target->family;
74 
75 	mutex_lock(&xt[af].mutex);
76 	list_add(&target->list, &xt[af].target);
77 	mutex_unlock(&xt[af].mutex);
78 	return 0;
79 }
80 EXPORT_SYMBOL(xt_register_target);
81 
82 void
xt_unregister_target(struct xt_target * target)83 xt_unregister_target(struct xt_target *target)
84 {
85 	u_int8_t af = target->family;
86 
87 	mutex_lock(&xt[af].mutex);
88 	list_del(&target->list);
89 	mutex_unlock(&xt[af].mutex);
90 }
91 EXPORT_SYMBOL(xt_unregister_target);
92 
93 int
xt_register_targets(struct xt_target * target,unsigned int n)94 xt_register_targets(struct xt_target *target, unsigned int n)
95 {
96 	unsigned int i;
97 	int err = 0;
98 
99 	for (i = 0; i < n; i++) {
100 		err = xt_register_target(&target[i]);
101 		if (err)
102 			goto err;
103 	}
104 	return err;
105 
106 err:
107 	if (i > 0)
108 		xt_unregister_targets(target, i);
109 	return err;
110 }
111 EXPORT_SYMBOL(xt_register_targets);
112 
113 void
xt_unregister_targets(struct xt_target * target,unsigned int n)114 xt_unregister_targets(struct xt_target *target, unsigned int n)
115 {
116 	while (n-- > 0)
117 		xt_unregister_target(&target[n]);
118 }
119 EXPORT_SYMBOL(xt_unregister_targets);
120 
xt_register_match(struct xt_match * match)121 int xt_register_match(struct xt_match *match)
122 {
123 	u_int8_t af = match->family;
124 
125 	mutex_lock(&xt[af].mutex);
126 	list_add(&match->list, &xt[af].match);
127 	mutex_unlock(&xt[af].mutex);
128 	return 0;
129 }
130 EXPORT_SYMBOL(xt_register_match);
131 
132 void
xt_unregister_match(struct xt_match * match)133 xt_unregister_match(struct xt_match *match)
134 {
135 	u_int8_t af = match->family;
136 
137 	mutex_lock(&xt[af].mutex);
138 	list_del(&match->list);
139 	mutex_unlock(&xt[af].mutex);
140 }
141 EXPORT_SYMBOL(xt_unregister_match);
142 
143 int
xt_register_matches(struct xt_match * match,unsigned int n)144 xt_register_matches(struct xt_match *match, unsigned int n)
145 {
146 	unsigned int i;
147 	int err = 0;
148 
149 	for (i = 0; i < n; i++) {
150 		err = xt_register_match(&match[i]);
151 		if (err)
152 			goto err;
153 	}
154 	return err;
155 
156 err:
157 	if (i > 0)
158 		xt_unregister_matches(match, i);
159 	return err;
160 }
161 EXPORT_SYMBOL(xt_register_matches);
162 
163 void
xt_unregister_matches(struct xt_match * match,unsigned int n)164 xt_unregister_matches(struct xt_match *match, unsigned int n)
165 {
166 	while (n-- > 0)
167 		xt_unregister_match(&match[n]);
168 }
169 EXPORT_SYMBOL(xt_unregister_matches);
170 
171 
172 /*
173  * These are weird, but module loading must not be done with mutex
174  * held (since they will register), and we have to have a single
175  * function to use.
176  */
177 
178 /* Find match, grabs ref.  Returns ERR_PTR() on error. */
xt_find_match(u8 af,const char * name,u8 revision)179 struct xt_match *xt_find_match(u8 af, const char *name, u8 revision)
180 {
181 	struct xt_match *m;
182 	int err = -ENOENT;
183 
184 	mutex_lock(&xt[af].mutex);
185 	list_for_each_entry(m, &xt[af].match, list) {
186 		if (strcmp(m->name, name) == 0) {
187 			if (m->revision == revision) {
188 				if (try_module_get(m->me)) {
189 					mutex_unlock(&xt[af].mutex);
190 					return m;
191 				}
192 			} else
193 				err = -EPROTOTYPE; /* Found something. */
194 		}
195 	}
196 	mutex_unlock(&xt[af].mutex);
197 
198 	if (af != NFPROTO_UNSPEC)
199 		/* Try searching again in the family-independent list */
200 		return xt_find_match(NFPROTO_UNSPEC, name, revision);
201 
202 	return ERR_PTR(err);
203 }
204 EXPORT_SYMBOL(xt_find_match);
205 
206 struct xt_match *
xt_request_find_match(uint8_t nfproto,const char * name,uint8_t revision)207 xt_request_find_match(uint8_t nfproto, const char *name, uint8_t revision)
208 {
209 	struct xt_match *match;
210 
211 	if (strnlen(name, XT_EXTENSION_MAXNAMELEN) == XT_EXTENSION_MAXNAMELEN)
212 		return ERR_PTR(-EINVAL);
213 
214 	match = xt_find_match(nfproto, name, revision);
215 	if (IS_ERR(match)) {
216 		request_module("%st_%s", xt_prefix[nfproto], name);
217 		match = xt_find_match(nfproto, name, revision);
218 	}
219 
220 	return match;
221 }
222 EXPORT_SYMBOL_GPL(xt_request_find_match);
223 
224 /* Find target, grabs ref.  Returns ERR_PTR() on error. */
xt_find_target(u8 af,const char * name,u8 revision)225 struct xt_target *xt_find_target(u8 af, const char *name, u8 revision)
226 {
227 	struct xt_target *t;
228 	int err = -ENOENT;
229 
230 	mutex_lock(&xt[af].mutex);
231 	list_for_each_entry(t, &xt[af].target, list) {
232 		if (strcmp(t->name, name) == 0) {
233 			if (t->revision == revision) {
234 				if (try_module_get(t->me)) {
235 					mutex_unlock(&xt[af].mutex);
236 					return t;
237 				}
238 			} else
239 				err = -EPROTOTYPE; /* Found something. */
240 		}
241 	}
242 	mutex_unlock(&xt[af].mutex);
243 
244 	if (af != NFPROTO_UNSPEC)
245 		/* Try searching again in the family-independent list */
246 		return xt_find_target(NFPROTO_UNSPEC, name, revision);
247 
248 	return ERR_PTR(err);
249 }
250 EXPORT_SYMBOL(xt_find_target);
251 
xt_request_find_target(u8 af,const char * name,u8 revision)252 struct xt_target *xt_request_find_target(u8 af, const char *name, u8 revision)
253 {
254 	struct xt_target *target;
255 
256 	if (strnlen(name, XT_EXTENSION_MAXNAMELEN) == XT_EXTENSION_MAXNAMELEN)
257 		return ERR_PTR(-EINVAL);
258 
259 	target = xt_find_target(af, name, revision);
260 	if (IS_ERR(target)) {
261 		request_module("%st_%s", xt_prefix[af], name);
262 		target = xt_find_target(af, name, revision);
263 	}
264 
265 	return target;
266 }
267 EXPORT_SYMBOL_GPL(xt_request_find_target);
268 
269 
xt_obj_to_user(u16 __user * psize,u16 size,void __user * pname,const char * name,u8 __user * prev,u8 rev)270 static int xt_obj_to_user(u16 __user *psize, u16 size,
271 			  void __user *pname, const char *name,
272 			  u8 __user *prev, u8 rev)
273 {
274 	if (put_user(size, psize))
275 		return -EFAULT;
276 	if (copy_to_user(pname, name, strlen(name) + 1))
277 		return -EFAULT;
278 	if (put_user(rev, prev))
279 		return -EFAULT;
280 
281 	return 0;
282 }
283 
284 #define XT_OBJ_TO_USER(U, K, TYPE, C_SIZE)				\
285 	xt_obj_to_user(&U->u.TYPE##_size, C_SIZE ? : K->u.TYPE##_size,	\
286 		       U->u.user.name, K->u.kernel.TYPE->name,		\
287 		       &U->u.user.revision, K->u.kernel.TYPE->revision)
288 
xt_data_to_user(void __user * dst,const void * src,int usersize,int size)289 int xt_data_to_user(void __user *dst, const void *src,
290 		    int usersize, int size)
291 {
292 	usersize = usersize ? : size;
293 	if (copy_to_user(dst, src, usersize))
294 		return -EFAULT;
295 	if (usersize != size && clear_user(dst + usersize, size - usersize))
296 		return -EFAULT;
297 
298 	return 0;
299 }
300 EXPORT_SYMBOL_GPL(xt_data_to_user);
301 
302 #define XT_DATA_TO_USER(U, K, TYPE, C_SIZE)				\
303 	xt_data_to_user(U->data, K->data,				\
304 			K->u.kernel.TYPE->usersize,			\
305 			C_SIZE ? : K->u.kernel.TYPE->TYPE##size)
306 
xt_match_to_user(const struct xt_entry_match * m,struct xt_entry_match __user * u)307 int xt_match_to_user(const struct xt_entry_match *m,
308 		     struct xt_entry_match __user *u)
309 {
310 	return XT_OBJ_TO_USER(u, m, match, 0) ||
311 	       XT_DATA_TO_USER(u, m, match, 0);
312 }
313 EXPORT_SYMBOL_GPL(xt_match_to_user);
314 
xt_target_to_user(const struct xt_entry_target * t,struct xt_entry_target __user * u)315 int xt_target_to_user(const struct xt_entry_target *t,
316 		      struct xt_entry_target __user *u)
317 {
318 	return XT_OBJ_TO_USER(u, t, target, 0) ||
319 	       XT_DATA_TO_USER(u, t, target, 0);
320 }
321 EXPORT_SYMBOL_GPL(xt_target_to_user);
322 
match_revfn(u8 af,const char * name,u8 revision,int * bestp)323 static int match_revfn(u8 af, const char *name, u8 revision, int *bestp)
324 {
325 	const struct xt_match *m;
326 	int have_rev = 0;
327 
328 	mutex_lock(&xt[af].mutex);
329 	list_for_each_entry(m, &xt[af].match, list) {
330 		if (strcmp(m->name, name) == 0) {
331 			if (m->revision > *bestp)
332 				*bestp = m->revision;
333 			if (m->revision == revision)
334 				have_rev = 1;
335 		}
336 	}
337 	mutex_unlock(&xt[af].mutex);
338 
339 	if (af != NFPROTO_UNSPEC && !have_rev)
340 		return match_revfn(NFPROTO_UNSPEC, name, revision, bestp);
341 
342 	return have_rev;
343 }
344 
target_revfn(u8 af,const char * name,u8 revision,int * bestp)345 static int target_revfn(u8 af, const char *name, u8 revision, int *bestp)
346 {
347 	const struct xt_target *t;
348 	int have_rev = 0;
349 
350 	mutex_lock(&xt[af].mutex);
351 	list_for_each_entry(t, &xt[af].target, list) {
352 		if (strcmp(t->name, name) == 0) {
353 			if (t->revision > *bestp)
354 				*bestp = t->revision;
355 			if (t->revision == revision)
356 				have_rev = 1;
357 		}
358 	}
359 	mutex_unlock(&xt[af].mutex);
360 
361 	if (af != NFPROTO_UNSPEC && !have_rev)
362 		return target_revfn(NFPROTO_UNSPEC, name, revision, bestp);
363 
364 	return have_rev;
365 }
366 
367 /* Returns true or false (if no such extension at all) */
xt_find_revision(u8 af,const char * name,u8 revision,int target,int * err)368 int xt_find_revision(u8 af, const char *name, u8 revision, int target,
369 		     int *err)
370 {
371 	int have_rev, best = -1;
372 
373 	if (target == 1)
374 		have_rev = target_revfn(af, name, revision, &best);
375 	else
376 		have_rev = match_revfn(af, name, revision, &best);
377 
378 	/* Nothing at all?  Return 0 to try loading module. */
379 	if (best == -1) {
380 		*err = -ENOENT;
381 		return 0;
382 	}
383 
384 	*err = best;
385 	if (!have_rev)
386 		*err = -EPROTONOSUPPORT;
387 	return 1;
388 }
389 EXPORT_SYMBOL_GPL(xt_find_revision);
390 
391 static char *
textify_hooks(char * buf,size_t size,unsigned int mask,uint8_t nfproto)392 textify_hooks(char *buf, size_t size, unsigned int mask, uint8_t nfproto)
393 {
394 	static const char *const inetbr_names[] = {
395 		"PREROUTING", "INPUT", "FORWARD",
396 		"OUTPUT", "POSTROUTING", "BROUTING",
397 	};
398 	static const char *const arp_names[] = {
399 		"INPUT", "FORWARD", "OUTPUT",
400 	};
401 	const char *const *names;
402 	unsigned int i, max;
403 	char *p = buf;
404 	bool np = false;
405 	int res;
406 
407 	names = (nfproto == NFPROTO_ARP) ? arp_names : inetbr_names;
408 	max   = (nfproto == NFPROTO_ARP) ? ARRAY_SIZE(arp_names) :
409 	                                   ARRAY_SIZE(inetbr_names);
410 	*p = '\0';
411 	for (i = 0; i < max; ++i) {
412 		if (!(mask & (1 << i)))
413 			continue;
414 		res = snprintf(p, size, "%s%s", np ? "/" : "", names[i]);
415 		if (res > 0) {
416 			size -= res;
417 			p += res;
418 		}
419 		np = true;
420 	}
421 
422 	return buf;
423 }
424 
425 /**
426  * xt_check_proc_name - check that name is suitable for /proc file creation
427  *
428  * @name: file name candidate
429  * @size: length of buffer
430  *
431  * some x_tables modules wish to create a file in /proc.
432  * This function makes sure that the name is suitable for this
433  * purpose, it checks that name is NUL terminated and isn't a 'special'
434  * name, like "..".
435  *
436  * returns negative number on error or 0 if name is useable.
437  */
xt_check_proc_name(const char * name,unsigned int size)438 int xt_check_proc_name(const char *name, unsigned int size)
439 {
440 	if (name[0] == '\0')
441 		return -EINVAL;
442 
443 	if (strnlen(name, size) == size)
444 		return -ENAMETOOLONG;
445 
446 	if (strcmp(name, ".") == 0 ||
447 	    strcmp(name, "..") == 0 ||
448 	    strchr(name, '/'))
449 		return -EINVAL;
450 
451 	return 0;
452 }
453 EXPORT_SYMBOL(xt_check_proc_name);
454 
xt_check_match(struct xt_mtchk_param * par,unsigned int size,u_int8_t proto,bool inv_proto)455 int xt_check_match(struct xt_mtchk_param *par,
456 		   unsigned int size, u_int8_t proto, bool inv_proto)
457 {
458 	int ret;
459 
460 	if (XT_ALIGN(par->match->matchsize) != size &&
461 	    par->match->matchsize != -1) {
462 		/*
463 		 * ebt_among is exempt from centralized matchsize checking
464 		 * because it uses a dynamic-size data set.
465 		 */
466 		pr_err("%s_tables: %s.%u match: invalid size "
467 		       "%u (kernel) != (user) %u\n",
468 		       xt_prefix[par->family], par->match->name,
469 		       par->match->revision,
470 		       XT_ALIGN(par->match->matchsize), size);
471 		return -EINVAL;
472 	}
473 	if (par->match->table != NULL &&
474 	    strcmp(par->match->table, par->table) != 0) {
475 		pr_err("%s_tables: %s match: only valid in %s table, not %s\n",
476 		       xt_prefix[par->family], par->match->name,
477 		       par->match->table, par->table);
478 		return -EINVAL;
479 	}
480 	if (par->match->hooks && (par->hook_mask & ~par->match->hooks) != 0) {
481 		char used[64], allow[64];
482 
483 		pr_err("%s_tables: %s match: used from hooks %s, but only "
484 		       "valid from %s\n",
485 		       xt_prefix[par->family], par->match->name,
486 		       textify_hooks(used, sizeof(used), par->hook_mask,
487 		                     par->family),
488 		       textify_hooks(allow, sizeof(allow), par->match->hooks,
489 		                     par->family));
490 		return -EINVAL;
491 	}
492 	if (par->match->proto && (par->match->proto != proto || inv_proto)) {
493 		pr_err("%s_tables: %s match: only valid for protocol %u\n",
494 		       xt_prefix[par->family], par->match->name,
495 		       par->match->proto);
496 		return -EINVAL;
497 	}
498 	if (par->match->checkentry != NULL) {
499 		ret = par->match->checkentry(par);
500 		if (ret < 0)
501 			return ret;
502 		else if (ret > 0)
503 			/* Flag up potential errors. */
504 			return -EIO;
505 	}
506 	return 0;
507 }
508 EXPORT_SYMBOL_GPL(xt_check_match);
509 
510 /** xt_check_entry_match - check that matches end before start of target
511  *
512  * @match: beginning of xt_entry_match
513  * @target: beginning of this rules target (alleged end of matches)
514  * @alignment: alignment requirement of match structures
515  *
516  * Validates that all matches add up to the beginning of the target,
517  * and that each match covers at least the base structure size.
518  *
519  * Return: 0 on success, negative errno on failure.
520  */
xt_check_entry_match(const char * match,const char * target,const size_t alignment)521 static int xt_check_entry_match(const char *match, const char *target,
522 				const size_t alignment)
523 {
524 	const struct xt_entry_match *pos;
525 	int length = target - match;
526 
527 	if (length == 0) /* no matches */
528 		return 0;
529 
530 	pos = (struct xt_entry_match *)match;
531 	do {
532 		if ((unsigned long)pos % alignment)
533 			return -EINVAL;
534 
535 		if (length < (int)sizeof(struct xt_entry_match))
536 			return -EINVAL;
537 
538 		if (pos->u.match_size < sizeof(struct xt_entry_match))
539 			return -EINVAL;
540 
541 		if (pos->u.match_size > length)
542 			return -EINVAL;
543 
544 		length -= pos->u.match_size;
545 		pos = ((void *)((char *)(pos) + (pos)->u.match_size));
546 	} while (length > 0);
547 
548 	return 0;
549 }
550 
551 #ifdef CONFIG_COMPAT
xt_compat_add_offset(u_int8_t af,unsigned int offset,int delta)552 int xt_compat_add_offset(u_int8_t af, unsigned int offset, int delta)
553 {
554 	struct xt_af *xp = &xt[af];
555 
556 	if (!xp->compat_tab) {
557 		if (!xp->number)
558 			return -EINVAL;
559 		xp->compat_tab = vmalloc(sizeof(struct compat_delta) * xp->number);
560 		if (!xp->compat_tab)
561 			return -ENOMEM;
562 		xp->cur = 0;
563 	}
564 
565 	if (xp->cur >= xp->number)
566 		return -EINVAL;
567 
568 	if (xp->cur)
569 		delta += xp->compat_tab[xp->cur - 1].delta;
570 	xp->compat_tab[xp->cur].offset = offset;
571 	xp->compat_tab[xp->cur].delta = delta;
572 	xp->cur++;
573 	return 0;
574 }
575 EXPORT_SYMBOL_GPL(xt_compat_add_offset);
576 
xt_compat_flush_offsets(u_int8_t af)577 void xt_compat_flush_offsets(u_int8_t af)
578 {
579 	if (xt[af].compat_tab) {
580 		vfree(xt[af].compat_tab);
581 		xt[af].compat_tab = NULL;
582 		xt[af].number = 0;
583 		xt[af].cur = 0;
584 	}
585 }
586 EXPORT_SYMBOL_GPL(xt_compat_flush_offsets);
587 
xt_compat_calc_jump(u_int8_t af,unsigned int offset)588 int xt_compat_calc_jump(u_int8_t af, unsigned int offset)
589 {
590 	struct compat_delta *tmp = xt[af].compat_tab;
591 	int mid, left = 0, right = xt[af].cur - 1;
592 
593 	while (left <= right) {
594 		mid = (left + right) >> 1;
595 		if (offset > tmp[mid].offset)
596 			left = mid + 1;
597 		else if (offset < tmp[mid].offset)
598 			right = mid - 1;
599 		else
600 			return mid ? tmp[mid - 1].delta : 0;
601 	}
602 	return left ? tmp[left - 1].delta : 0;
603 }
604 EXPORT_SYMBOL_GPL(xt_compat_calc_jump);
605 
xt_compat_init_offsets(u_int8_t af,unsigned int number)606 void xt_compat_init_offsets(u_int8_t af, unsigned int number)
607 {
608 	xt[af].number = number;
609 	xt[af].cur = 0;
610 }
611 EXPORT_SYMBOL(xt_compat_init_offsets);
612 
xt_compat_match_offset(const struct xt_match * match)613 int xt_compat_match_offset(const struct xt_match *match)
614 {
615 	u_int16_t csize = match->compatsize ? : match->matchsize;
616 	return XT_ALIGN(match->matchsize) - COMPAT_XT_ALIGN(csize);
617 }
618 EXPORT_SYMBOL_GPL(xt_compat_match_offset);
619 
xt_compat_match_from_user(struct xt_entry_match * m,void ** dstptr,unsigned int * size)620 void xt_compat_match_from_user(struct xt_entry_match *m, void **dstptr,
621 			       unsigned int *size)
622 {
623 	const struct xt_match *match = m->u.kernel.match;
624 	struct compat_xt_entry_match *cm = (struct compat_xt_entry_match *)m;
625 	int off = xt_compat_match_offset(match);
626 	u_int16_t msize = cm->u.user.match_size;
627 	char name[sizeof(m->u.user.name)];
628 
629 	m = *dstptr;
630 	memcpy(m, cm, sizeof(*cm));
631 	if (match->compat_from_user)
632 		match->compat_from_user(m->data, cm->data);
633 	else
634 		memcpy(m->data, cm->data, msize - sizeof(*cm));
635 
636 	msize += off;
637 	m->u.user.match_size = msize;
638 	strlcpy(name, match->name, sizeof(name));
639 	module_put(match->me);
640 	strncpy(m->u.user.name, name, sizeof(m->u.user.name));
641 
642 	*size += off;
643 	*dstptr += msize;
644 }
645 EXPORT_SYMBOL_GPL(xt_compat_match_from_user);
646 
xt_compat_match_to_user(const struct xt_entry_match * m,void __user ** dstptr,unsigned int * size)647 int xt_compat_match_to_user(const struct xt_entry_match *m,
648 			    void __user **dstptr, unsigned int *size)
649 {
650 	const struct xt_match *match = m->u.kernel.match;
651 	struct compat_xt_entry_match __user *cm = *dstptr;
652 	int off = xt_compat_match_offset(match);
653 	u_int16_t msize = m->u.user.match_size - off;
654 
655 	if (copy_to_user(cm, m, sizeof(*cm)) ||
656 	    put_user(msize, &cm->u.user.match_size) ||
657 	    copy_to_user(cm->u.user.name, m->u.kernel.match->name,
658 			 strlen(m->u.kernel.match->name) + 1))
659 		return -EFAULT;
660 
661 	if (match->compat_to_user) {
662 		if (match->compat_to_user((void __user *)cm->data, m->data))
663 			return -EFAULT;
664 	} else {
665 		if (copy_to_user(cm->data, m->data, msize - sizeof(*cm)))
666 			return -EFAULT;
667 	}
668 
669 	*size -= off;
670 	*dstptr += msize;
671 	return 0;
672 }
673 EXPORT_SYMBOL_GPL(xt_compat_match_to_user);
674 
675 /* non-compat version may have padding after verdict */
676 struct compat_xt_standard_target {
677 	struct compat_xt_entry_target t;
678 	compat_uint_t verdict;
679 };
680 
xt_compat_check_entry_offsets(const void * base,const char * elems,unsigned int target_offset,unsigned int next_offset)681 int xt_compat_check_entry_offsets(const void *base, const char *elems,
682 				  unsigned int target_offset,
683 				  unsigned int next_offset)
684 {
685 	long size_of_base_struct = elems - (const char *)base;
686 	const struct compat_xt_entry_target *t;
687 	const char *e = base;
688 
689 	if (target_offset < size_of_base_struct)
690 		return -EINVAL;
691 
692 	if (target_offset + sizeof(*t) > next_offset)
693 		return -EINVAL;
694 
695 	t = (void *)(e + target_offset);
696 	if (t->u.target_size < sizeof(*t))
697 		return -EINVAL;
698 
699 	if (target_offset + t->u.target_size > next_offset)
700 		return -EINVAL;
701 
702 	if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
703 	    COMPAT_XT_ALIGN(target_offset + sizeof(struct compat_xt_standard_target)) != next_offset)
704 		return -EINVAL;
705 
706 	/* compat_xt_entry match has less strict aligment requirements,
707 	 * otherwise they are identical.  In case of padding differences
708 	 * we need to add compat version of xt_check_entry_match.
709 	 */
710 	BUILD_BUG_ON(sizeof(struct compat_xt_entry_match) != sizeof(struct xt_entry_match));
711 
712 	return xt_check_entry_match(elems, base + target_offset,
713 				    __alignof__(struct compat_xt_entry_match));
714 }
715 EXPORT_SYMBOL(xt_compat_check_entry_offsets);
716 #endif /* CONFIG_COMPAT */
717 
718 /**
719  * xt_check_entry_offsets - validate arp/ip/ip6t_entry
720  *
721  * @base: pointer to arp/ip/ip6t_entry
722  * @elems: pointer to first xt_entry_match, i.e. ip(6)t_entry->elems
723  * @target_offset: the arp/ip/ip6_t->target_offset
724  * @next_offset: the arp/ip/ip6_t->next_offset
725  *
726  * validates that target_offset and next_offset are sane and that all
727  * match sizes (if any) align with the target offset.
728  *
729  * This function does not validate the targets or matches themselves, it
730  * only tests that all the offsets and sizes are correct, that all
731  * match structures are aligned, and that the last structure ends where
732  * the target structure begins.
733  *
734  * Also see xt_compat_check_entry_offsets for CONFIG_COMPAT version.
735  *
736  * The arp/ip/ip6t_entry structure @base must have passed following tests:
737  * - it must point to a valid memory location
738  * - base to base + next_offset must be accessible, i.e. not exceed allocated
739  *   length.
740  *
741  * A well-formed entry looks like this:
742  *
743  * ip(6)t_entry   match [mtdata]  match [mtdata] target [tgdata] ip(6)t_entry
744  * e->elems[]-----'                              |               |
745  *                matchsize                      |               |
746  *                                matchsize      |               |
747  *                                               |               |
748  * target_offset---------------------------------'               |
749  * next_offset---------------------------------------------------'
750  *
751  * elems[]: flexible array member at end of ip(6)/arpt_entry struct.
752  *          This is where matches (if any) and the target reside.
753  * target_offset: beginning of target.
754  * next_offset: start of the next rule; also: size of this rule.
755  * Since targets have a minimum size, target_offset + minlen <= next_offset.
756  *
757  * Every match stores its size, sum of sizes must not exceed target_offset.
758  *
759  * Return: 0 on success, negative errno on failure.
760  */
xt_check_entry_offsets(const void * base,const char * elems,unsigned int target_offset,unsigned int next_offset)761 int xt_check_entry_offsets(const void *base,
762 			   const char *elems,
763 			   unsigned int target_offset,
764 			   unsigned int next_offset)
765 {
766 	long size_of_base_struct = elems - (const char *)base;
767 	const struct xt_entry_target *t;
768 	const char *e = base;
769 
770 	/* target start is within the ip/ip6/arpt_entry struct */
771 	if (target_offset < size_of_base_struct)
772 		return -EINVAL;
773 
774 	if (target_offset + sizeof(*t) > next_offset)
775 		return -EINVAL;
776 
777 	t = (void *)(e + target_offset);
778 	if (t->u.target_size < sizeof(*t))
779 		return -EINVAL;
780 
781 	if (target_offset + t->u.target_size > next_offset)
782 		return -EINVAL;
783 
784 	if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
785 	    XT_ALIGN(target_offset + sizeof(struct xt_standard_target)) != next_offset)
786 		return -EINVAL;
787 
788 	return xt_check_entry_match(elems, base + target_offset,
789 				    __alignof__(struct xt_entry_match));
790 }
791 EXPORT_SYMBOL(xt_check_entry_offsets);
792 
793 /**
794  * xt_alloc_entry_offsets - allocate array to store rule head offsets
795  *
796  * @size: number of entries
797  *
798  * Return: NULL or kmalloc'd or vmalloc'd array
799  */
xt_alloc_entry_offsets(unsigned int size)800 unsigned int *xt_alloc_entry_offsets(unsigned int size)
801 {
802 	unsigned int *off;
803 
804 	off = kcalloc(size, sizeof(unsigned int), GFP_KERNEL | __GFP_NOWARN);
805 
806 	if (off)
807 		return off;
808 
809 	if (size < (SIZE_MAX / sizeof(unsigned int)))
810 		off = vmalloc(size * sizeof(unsigned int));
811 
812 	return off;
813 }
814 EXPORT_SYMBOL(xt_alloc_entry_offsets);
815 
816 /**
817  * xt_find_jump_offset - check if target is a valid jump offset
818  *
819  * @offsets: array containing all valid rule start offsets of a rule blob
820  * @target: the jump target to search for
821  * @size: entries in @offset
822  */
xt_find_jump_offset(const unsigned int * offsets,unsigned int target,unsigned int size)823 bool xt_find_jump_offset(const unsigned int *offsets,
824 			 unsigned int target, unsigned int size)
825 {
826 	int m, low = 0, hi = size;
827 
828 	while (hi > low) {
829 		m = (low + hi) / 2u;
830 
831 		if (offsets[m] > target)
832 			hi = m;
833 		else if (offsets[m] < target)
834 			low = m + 1;
835 		else
836 			return true;
837 	}
838 
839 	return false;
840 }
841 EXPORT_SYMBOL(xt_find_jump_offset);
842 
xt_check_target(struct xt_tgchk_param * par,unsigned int size,u_int8_t proto,bool inv_proto)843 int xt_check_target(struct xt_tgchk_param *par,
844 		    unsigned int size, u_int8_t proto, bool inv_proto)
845 {
846 	int ret;
847 
848 	if (XT_ALIGN(par->target->targetsize) != size) {
849 		pr_err("%s_tables: %s.%u target: invalid size "
850 		       "%u (kernel) != (user) %u\n",
851 		       xt_prefix[par->family], par->target->name,
852 		       par->target->revision,
853 		       XT_ALIGN(par->target->targetsize), size);
854 		return -EINVAL;
855 	}
856 	if (par->target->table != NULL &&
857 	    strcmp(par->target->table, par->table) != 0) {
858 		pr_err("%s_tables: %s target: only valid in %s table, not %s\n",
859 		       xt_prefix[par->family], par->target->name,
860 		       par->target->table, par->table);
861 		return -EINVAL;
862 	}
863 	if (par->target->hooks && (par->hook_mask & ~par->target->hooks) != 0) {
864 		char used[64], allow[64];
865 
866 		pr_err("%s_tables: %s target: used from hooks %s, but only "
867 		       "usable from %s\n",
868 		       xt_prefix[par->family], par->target->name,
869 		       textify_hooks(used, sizeof(used), par->hook_mask,
870 		                     par->family),
871 		       textify_hooks(allow, sizeof(allow), par->target->hooks,
872 		                     par->family));
873 		return -EINVAL;
874 	}
875 	if (par->target->proto && (par->target->proto != proto || inv_proto)) {
876 		pr_err("%s_tables: %s target: only valid for protocol %u\n",
877 		       xt_prefix[par->family], par->target->name,
878 		       par->target->proto);
879 		return -EINVAL;
880 	}
881 	if (par->target->checkentry != NULL) {
882 		ret = par->target->checkentry(par);
883 		if (ret < 0)
884 			return ret;
885 		else if (ret > 0)
886 			/* Flag up potential errors. */
887 			return -EIO;
888 	}
889 	return 0;
890 }
891 EXPORT_SYMBOL_GPL(xt_check_target);
892 
893 /**
894  * xt_copy_counters_from_user - copy counters and metadata from userspace
895  *
896  * @user: src pointer to userspace memory
897  * @len: alleged size of userspace memory
898  * @info: where to store the xt_counters_info metadata
899  * @compat: true if we setsockopt call is done by 32bit task on 64bit kernel
900  *
901  * Copies counter meta data from @user and stores it in @info.
902  *
903  * vmallocs memory to hold the counters, then copies the counter data
904  * from @user to the new memory and returns a pointer to it.
905  *
906  * If @compat is true, @info gets converted automatically to the 64bit
907  * representation.
908  *
909  * The metadata associated with the counters is stored in @info.
910  *
911  * Return: returns pointer that caller has to test via IS_ERR().
912  * If IS_ERR is false, caller has to vfree the pointer.
913  */
xt_copy_counters_from_user(const void __user * user,unsigned int len,struct xt_counters_info * info,bool compat)914 void *xt_copy_counters_from_user(const void __user *user, unsigned int len,
915 				 struct xt_counters_info *info, bool compat)
916 {
917 	void *mem;
918 	u64 size;
919 
920 #ifdef CONFIG_COMPAT
921 	if (compat) {
922 		/* structures only differ in size due to alignment */
923 		struct compat_xt_counters_info compat_tmp;
924 
925 		if (len <= sizeof(compat_tmp))
926 			return ERR_PTR(-EINVAL);
927 
928 		len -= sizeof(compat_tmp);
929 		if (copy_from_user(&compat_tmp, user, sizeof(compat_tmp)) != 0)
930 			return ERR_PTR(-EFAULT);
931 
932 		memcpy(info->name, compat_tmp.name, sizeof(info->name) - 1);
933 		info->num_counters = compat_tmp.num_counters;
934 		user += sizeof(compat_tmp);
935 	} else
936 #endif
937 	{
938 		if (len <= sizeof(*info))
939 			return ERR_PTR(-EINVAL);
940 
941 		len -= sizeof(*info);
942 		if (copy_from_user(info, user, sizeof(*info)) != 0)
943 			return ERR_PTR(-EFAULT);
944 
945 		user += sizeof(*info);
946 	}
947 	info->name[sizeof(info->name) - 1] = '\0';
948 
949 	size = sizeof(struct xt_counters);
950 	size *= info->num_counters;
951 
952 	if (size != (u64)len)
953 		return ERR_PTR(-EINVAL);
954 
955 	mem = vmalloc(len);
956 	if (!mem)
957 		return ERR_PTR(-ENOMEM);
958 
959 	if (copy_from_user(mem, user, len) == 0)
960 		return mem;
961 
962 	vfree(mem);
963 	return ERR_PTR(-EFAULT);
964 }
965 EXPORT_SYMBOL_GPL(xt_copy_counters_from_user);
966 
967 #ifdef CONFIG_COMPAT
xt_compat_target_offset(const struct xt_target * target)968 int xt_compat_target_offset(const struct xt_target *target)
969 {
970 	u_int16_t csize = target->compatsize ? : target->targetsize;
971 	return XT_ALIGN(target->targetsize) - COMPAT_XT_ALIGN(csize);
972 }
973 EXPORT_SYMBOL_GPL(xt_compat_target_offset);
974 
xt_compat_target_from_user(struct xt_entry_target * t,void ** dstptr,unsigned int * size)975 void xt_compat_target_from_user(struct xt_entry_target *t, void **dstptr,
976 				unsigned int *size)
977 {
978 	const struct xt_target *target = t->u.kernel.target;
979 	struct compat_xt_entry_target *ct = (struct compat_xt_entry_target *)t;
980 	int off = xt_compat_target_offset(target);
981 	u_int16_t tsize = ct->u.user.target_size;
982 	char name[sizeof(t->u.user.name)];
983 
984 	t = *dstptr;
985 	memcpy(t, ct, sizeof(*ct));
986 	if (target->compat_from_user)
987 		target->compat_from_user(t->data, ct->data);
988 	else
989 		memcpy(t->data, ct->data, tsize - sizeof(*ct));
990 
991 	tsize += off;
992 	t->u.user.target_size = tsize;
993 	strlcpy(name, target->name, sizeof(name));
994 	module_put(target->me);
995 	strncpy(t->u.user.name, name, sizeof(t->u.user.name));
996 
997 	*size += off;
998 	*dstptr += tsize;
999 }
1000 EXPORT_SYMBOL_GPL(xt_compat_target_from_user);
1001 
xt_compat_target_to_user(const struct xt_entry_target * t,void __user ** dstptr,unsigned int * size)1002 int xt_compat_target_to_user(const struct xt_entry_target *t,
1003 			     void __user **dstptr, unsigned int *size)
1004 {
1005 	const struct xt_target *target = t->u.kernel.target;
1006 	struct compat_xt_entry_target __user *ct = *dstptr;
1007 	int off = xt_compat_target_offset(target);
1008 	u_int16_t tsize = t->u.user.target_size - off;
1009 
1010 	if (copy_to_user(ct, t, sizeof(*ct)) ||
1011 	    put_user(tsize, &ct->u.user.target_size) ||
1012 	    copy_to_user(ct->u.user.name, t->u.kernel.target->name,
1013 			 strlen(t->u.kernel.target->name) + 1))
1014 		return -EFAULT;
1015 
1016 	if (target->compat_to_user) {
1017 		if (target->compat_to_user((void __user *)ct->data, t->data))
1018 			return -EFAULT;
1019 	} else {
1020 		if (copy_to_user(ct->data, t->data, tsize - sizeof(*ct)))
1021 			return -EFAULT;
1022 	}
1023 
1024 	*size -= off;
1025 	*dstptr += tsize;
1026 	return 0;
1027 }
1028 EXPORT_SYMBOL_GPL(xt_compat_target_to_user);
1029 #endif
1030 
xt_alloc_table_info(unsigned int size)1031 struct xt_table_info *xt_alloc_table_info(unsigned int size)
1032 {
1033 	struct xt_table_info *info = NULL;
1034 	size_t sz = sizeof(*info) + size;
1035 
1036 	if (sz < sizeof(*info))
1037 		return NULL;
1038 
1039 	if (sz < sizeof(*info))
1040 		return NULL;
1041 
1042 	/* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */
1043 	if ((size >> PAGE_SHIFT) + 2 > totalram_pages)
1044 		return NULL;
1045 
1046 	if (sz <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
1047 		info = kmalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
1048 	if (!info) {
1049 		info = vmalloc(sz);
1050 		if (!info)
1051 			return NULL;
1052 	}
1053 	memset(info, 0, sizeof(*info));
1054 	info->size = size;
1055 	return info;
1056 }
1057 EXPORT_SYMBOL(xt_alloc_table_info);
1058 
xt_free_table_info(struct xt_table_info * info)1059 void xt_free_table_info(struct xt_table_info *info)
1060 {
1061 	int cpu;
1062 
1063 	if (info->jumpstack != NULL) {
1064 		for_each_possible_cpu(cpu)
1065 			kvfree(info->jumpstack[cpu]);
1066 		kvfree(info->jumpstack);
1067 	}
1068 
1069 	kvfree(info);
1070 }
1071 EXPORT_SYMBOL(xt_free_table_info);
1072 
1073 /* Find table by name, grabs mutex & ref.  Returns ERR_PTR() on error. */
xt_find_table_lock(struct net * net,u_int8_t af,const char * name)1074 struct xt_table *xt_find_table_lock(struct net *net, u_int8_t af,
1075 				    const char *name)
1076 {
1077 	struct xt_table *t;
1078 
1079 	mutex_lock(&xt[af].mutex);
1080 	list_for_each_entry(t, &net->xt.tables[af], list)
1081 		if (strcmp(t->name, name) == 0 && try_module_get(t->me))
1082 			return t;
1083 	mutex_unlock(&xt[af].mutex);
1084 	return NULL;
1085 }
1086 EXPORT_SYMBOL_GPL(xt_find_table_lock);
1087 
xt_table_unlock(struct xt_table * table)1088 void xt_table_unlock(struct xt_table *table)
1089 {
1090 	mutex_unlock(&xt[table->af].mutex);
1091 }
1092 EXPORT_SYMBOL_GPL(xt_table_unlock);
1093 
1094 #ifdef CONFIG_COMPAT
xt_compat_lock(u_int8_t af)1095 void xt_compat_lock(u_int8_t af)
1096 {
1097 	mutex_lock(&xt[af].compat_mutex);
1098 }
1099 EXPORT_SYMBOL_GPL(xt_compat_lock);
1100 
xt_compat_unlock(u_int8_t af)1101 void xt_compat_unlock(u_int8_t af)
1102 {
1103 	mutex_unlock(&xt[af].compat_mutex);
1104 }
1105 EXPORT_SYMBOL_GPL(xt_compat_unlock);
1106 #endif
1107 
1108 DEFINE_PER_CPU(seqcount_t, xt_recseq);
1109 EXPORT_PER_CPU_SYMBOL_GPL(xt_recseq);
1110 
1111 struct static_key xt_tee_enabled __read_mostly;
1112 EXPORT_SYMBOL_GPL(xt_tee_enabled);
1113 
xt_jumpstack_alloc(struct xt_table_info * i)1114 static int xt_jumpstack_alloc(struct xt_table_info *i)
1115 {
1116 	unsigned int size;
1117 	int cpu;
1118 
1119 	size = sizeof(void **) * nr_cpu_ids;
1120 	if (size > PAGE_SIZE)
1121 		i->jumpstack = vzalloc(size);
1122 	else
1123 		i->jumpstack = kzalloc(size, GFP_KERNEL);
1124 	if (i->jumpstack == NULL)
1125 		return -ENOMEM;
1126 
1127 	/* ruleset without jumps -- no stack needed */
1128 	if (i->stacksize == 0)
1129 		return 0;
1130 
1131 	/* Jumpstack needs to be able to record two full callchains, one
1132 	 * from the first rule set traversal, plus one table reentrancy
1133 	 * via -j TEE without clobbering the callchain that brought us to
1134 	 * TEE target.
1135 	 *
1136 	 * This is done by allocating two jumpstacks per cpu, on reentry
1137 	 * the upper half of the stack is used.
1138 	 *
1139 	 * see the jumpstack setup in ipt_do_table() for more details.
1140 	 */
1141 	size = sizeof(void *) * i->stacksize * 2u;
1142 	for_each_possible_cpu(cpu) {
1143 		if (size > PAGE_SIZE)
1144 			i->jumpstack[cpu] = vmalloc_node(size,
1145 				cpu_to_node(cpu));
1146 		else
1147 			i->jumpstack[cpu] = kmalloc_node(size,
1148 				GFP_KERNEL, cpu_to_node(cpu));
1149 		if (i->jumpstack[cpu] == NULL)
1150 			/*
1151 			 * Freeing will be done later on by the callers. The
1152 			 * chain is: xt_replace_table -> __do_replace ->
1153 			 * do_replace -> xt_free_table_info.
1154 			 */
1155 			return -ENOMEM;
1156 	}
1157 
1158 	return 0;
1159 }
1160 
1161 struct xt_table_info *
xt_replace_table(struct xt_table * table,unsigned int num_counters,struct xt_table_info * newinfo,int * error)1162 xt_replace_table(struct xt_table *table,
1163 	      unsigned int num_counters,
1164 	      struct xt_table_info *newinfo,
1165 	      int *error)
1166 {
1167 	struct xt_table_info *private;
1168 	int ret;
1169 
1170 	ret = xt_jumpstack_alloc(newinfo);
1171 	if (ret < 0) {
1172 		*error = ret;
1173 		return NULL;
1174 	}
1175 
1176 	/* Do the substitution. */
1177 	local_bh_disable();
1178 	private = table->private;
1179 
1180 	/* Check inside lock: is the old number correct? */
1181 	if (num_counters != private->number) {
1182 		pr_debug("num_counters != table->private->number (%u/%u)\n",
1183 			 num_counters, private->number);
1184 		local_bh_enable();
1185 		*error = -EAGAIN;
1186 		return NULL;
1187 	}
1188 
1189 	newinfo->initial_entries = private->initial_entries;
1190 	/*
1191 	 * Ensure contents of newinfo are visible before assigning to
1192 	 * private.
1193 	 */
1194 	smp_wmb();
1195 	table->private = newinfo;
1196 
1197 	/* make sure all cpus see new ->private value */
1198 	smp_mb();
1199 
1200 	/*
1201 	 * Even though table entries have now been swapped, other CPU's
1202 	 * may still be using the old entries. This is okay, because
1203 	 * resynchronization happens because of the locking done
1204 	 * during the get_counters() routine.
1205 	 */
1206 	local_bh_enable();
1207 
1208 #ifdef CONFIG_AUDIT
1209 	if (audit_enabled) {
1210 		struct audit_buffer *ab;
1211 
1212 		ab = audit_log_start(current->audit_context, GFP_KERNEL,
1213 				     AUDIT_NETFILTER_CFG);
1214 		if (ab) {
1215 			audit_log_format(ab, "table=%s family=%u entries=%u",
1216 					 table->name, table->af,
1217 					 private->number);
1218 			audit_log_end(ab);
1219 		}
1220 	}
1221 #endif
1222 
1223 	return private;
1224 }
1225 EXPORT_SYMBOL_GPL(xt_replace_table);
1226 
xt_register_table(struct net * net,const struct xt_table * input_table,struct xt_table_info * bootstrap,struct xt_table_info * newinfo)1227 struct xt_table *xt_register_table(struct net *net,
1228 				   const struct xt_table *input_table,
1229 				   struct xt_table_info *bootstrap,
1230 				   struct xt_table_info *newinfo)
1231 {
1232 	int ret;
1233 	struct xt_table_info *private;
1234 	struct xt_table *t, *table;
1235 
1236 	/* Don't add one object to multiple lists. */
1237 	table = kmemdup(input_table, sizeof(struct xt_table), GFP_KERNEL);
1238 	if (!table) {
1239 		ret = -ENOMEM;
1240 		goto out;
1241 	}
1242 
1243 	mutex_lock(&xt[table->af].mutex);
1244 	/* Don't autoload: we'd eat our tail... */
1245 	list_for_each_entry(t, &net->xt.tables[table->af], list) {
1246 		if (strcmp(t->name, table->name) == 0) {
1247 			ret = -EEXIST;
1248 			goto unlock;
1249 		}
1250 	}
1251 
1252 	/* Simplifies replace_table code. */
1253 	table->private = bootstrap;
1254 
1255 	if (!xt_replace_table(table, 0, newinfo, &ret))
1256 		goto unlock;
1257 
1258 	private = table->private;
1259 	pr_debug("table->private->number = %u\n", private->number);
1260 
1261 	/* save number of initial entries */
1262 	private->initial_entries = private->number;
1263 
1264 	list_add(&table->list, &net->xt.tables[table->af]);
1265 	mutex_unlock(&xt[table->af].mutex);
1266 	return table;
1267 
1268 unlock:
1269 	mutex_unlock(&xt[table->af].mutex);
1270 	kfree(table);
1271 out:
1272 	return ERR_PTR(ret);
1273 }
1274 EXPORT_SYMBOL_GPL(xt_register_table);
1275 
xt_unregister_table(struct xt_table * table)1276 void *xt_unregister_table(struct xt_table *table)
1277 {
1278 	struct xt_table_info *private;
1279 
1280 	mutex_lock(&xt[table->af].mutex);
1281 	private = table->private;
1282 	list_del(&table->list);
1283 	mutex_unlock(&xt[table->af].mutex);
1284 	kfree(table);
1285 
1286 	return private;
1287 }
1288 EXPORT_SYMBOL_GPL(xt_unregister_table);
1289 
1290 #ifdef CONFIG_PROC_FS
1291 struct xt_names_priv {
1292 	struct seq_net_private p;
1293 	u_int8_t af;
1294 };
xt_table_seq_start(struct seq_file * seq,loff_t * pos)1295 static void *xt_table_seq_start(struct seq_file *seq, loff_t *pos)
1296 {
1297 	struct xt_names_priv *priv = seq->private;
1298 	struct net *net = seq_file_net(seq);
1299 	u_int8_t af = priv->af;
1300 
1301 	mutex_lock(&xt[af].mutex);
1302 	return seq_list_start(&net->xt.tables[af], *pos);
1303 }
1304 
xt_table_seq_next(struct seq_file * seq,void * v,loff_t * pos)1305 static void *xt_table_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1306 {
1307 	struct xt_names_priv *priv = seq->private;
1308 	struct net *net = seq_file_net(seq);
1309 	u_int8_t af = priv->af;
1310 
1311 	return seq_list_next(v, &net->xt.tables[af], pos);
1312 }
1313 
xt_table_seq_stop(struct seq_file * seq,void * v)1314 static void xt_table_seq_stop(struct seq_file *seq, void *v)
1315 {
1316 	struct xt_names_priv *priv = seq->private;
1317 	u_int8_t af = priv->af;
1318 
1319 	mutex_unlock(&xt[af].mutex);
1320 }
1321 
xt_table_seq_show(struct seq_file * seq,void * v)1322 static int xt_table_seq_show(struct seq_file *seq, void *v)
1323 {
1324 	struct xt_table *table = list_entry(v, struct xt_table, list);
1325 
1326 	if (*table->name)
1327 		seq_printf(seq, "%s\n", table->name);
1328 	return 0;
1329 }
1330 
1331 static const struct seq_operations xt_table_seq_ops = {
1332 	.start	= xt_table_seq_start,
1333 	.next	= xt_table_seq_next,
1334 	.stop	= xt_table_seq_stop,
1335 	.show	= xt_table_seq_show,
1336 };
1337 
xt_table_open(struct inode * inode,struct file * file)1338 static int xt_table_open(struct inode *inode, struct file *file)
1339 {
1340 	int ret;
1341 	struct xt_names_priv *priv;
1342 
1343 	ret = seq_open_net(inode, file, &xt_table_seq_ops,
1344 			   sizeof(struct xt_names_priv));
1345 	if (!ret) {
1346 		priv = ((struct seq_file *)file->private_data)->private;
1347 		priv->af = (unsigned long)PDE_DATA(inode);
1348 	}
1349 	return ret;
1350 }
1351 
1352 static const struct file_operations xt_table_ops = {
1353 	.owner	 = THIS_MODULE,
1354 	.open	 = xt_table_open,
1355 	.read	 = seq_read,
1356 	.llseek	 = seq_lseek,
1357 	.release = seq_release_net,
1358 };
1359 
1360 /*
1361  * Traverse state for ip{,6}_{tables,matches} for helping crossing
1362  * the multi-AF mutexes.
1363  */
1364 struct nf_mttg_trav {
1365 	struct list_head *head, *curr;
1366 	uint8_t class, nfproto;
1367 };
1368 
1369 enum {
1370 	MTTG_TRAV_INIT,
1371 	MTTG_TRAV_NFP_UNSPEC,
1372 	MTTG_TRAV_NFP_SPEC,
1373 	MTTG_TRAV_DONE,
1374 };
1375 
xt_mttg_seq_next(struct seq_file * seq,void * v,loff_t * ppos,bool is_target)1376 static void *xt_mttg_seq_next(struct seq_file *seq, void *v, loff_t *ppos,
1377     bool is_target)
1378 {
1379 	static const uint8_t next_class[] = {
1380 		[MTTG_TRAV_NFP_UNSPEC] = MTTG_TRAV_NFP_SPEC,
1381 		[MTTG_TRAV_NFP_SPEC]   = MTTG_TRAV_DONE,
1382 	};
1383 	struct nf_mttg_trav *trav = seq->private;
1384 
1385 	switch (trav->class) {
1386 	case MTTG_TRAV_INIT:
1387 		trav->class = MTTG_TRAV_NFP_UNSPEC;
1388 		mutex_lock(&xt[NFPROTO_UNSPEC].mutex);
1389 		trav->head = trav->curr = is_target ?
1390 			&xt[NFPROTO_UNSPEC].target : &xt[NFPROTO_UNSPEC].match;
1391  		break;
1392 	case MTTG_TRAV_NFP_UNSPEC:
1393 		trav->curr = trav->curr->next;
1394 		if (trav->curr != trav->head)
1395 			break;
1396 		mutex_unlock(&xt[NFPROTO_UNSPEC].mutex);
1397 		mutex_lock(&xt[trav->nfproto].mutex);
1398 		trav->head = trav->curr = is_target ?
1399 			&xt[trav->nfproto].target : &xt[trav->nfproto].match;
1400 		trav->class = next_class[trav->class];
1401 		break;
1402 	case MTTG_TRAV_NFP_SPEC:
1403 		trav->curr = trav->curr->next;
1404 		if (trav->curr != trav->head)
1405 			break;
1406 		/* fallthru, _stop will unlock */
1407 	default:
1408 		return NULL;
1409 	}
1410 
1411 	if (ppos != NULL)
1412 		++*ppos;
1413 	return trav;
1414 }
1415 
xt_mttg_seq_start(struct seq_file * seq,loff_t * pos,bool is_target)1416 static void *xt_mttg_seq_start(struct seq_file *seq, loff_t *pos,
1417     bool is_target)
1418 {
1419 	struct nf_mttg_trav *trav = seq->private;
1420 	unsigned int j;
1421 
1422 	trav->class = MTTG_TRAV_INIT;
1423 	for (j = 0; j < *pos; ++j)
1424 		if (xt_mttg_seq_next(seq, NULL, NULL, is_target) == NULL)
1425 			return NULL;
1426 	return trav;
1427 }
1428 
xt_mttg_seq_stop(struct seq_file * seq,void * v)1429 static void xt_mttg_seq_stop(struct seq_file *seq, void *v)
1430 {
1431 	struct nf_mttg_trav *trav = seq->private;
1432 
1433 	switch (trav->class) {
1434 	case MTTG_TRAV_NFP_UNSPEC:
1435 		mutex_unlock(&xt[NFPROTO_UNSPEC].mutex);
1436 		break;
1437 	case MTTG_TRAV_NFP_SPEC:
1438 		mutex_unlock(&xt[trav->nfproto].mutex);
1439 		break;
1440 	}
1441 }
1442 
xt_match_seq_start(struct seq_file * seq,loff_t * pos)1443 static void *xt_match_seq_start(struct seq_file *seq, loff_t *pos)
1444 {
1445 	return xt_mttg_seq_start(seq, pos, false);
1446 }
1447 
xt_match_seq_next(struct seq_file * seq,void * v,loff_t * ppos)1448 static void *xt_match_seq_next(struct seq_file *seq, void *v, loff_t *ppos)
1449 {
1450 	return xt_mttg_seq_next(seq, v, ppos, false);
1451 }
1452 
xt_match_seq_show(struct seq_file * seq,void * v)1453 static int xt_match_seq_show(struct seq_file *seq, void *v)
1454 {
1455 	const struct nf_mttg_trav *trav = seq->private;
1456 	const struct xt_match *match;
1457 
1458 	switch (trav->class) {
1459 	case MTTG_TRAV_NFP_UNSPEC:
1460 	case MTTG_TRAV_NFP_SPEC:
1461 		if (trav->curr == trav->head)
1462 			return 0;
1463 		match = list_entry(trav->curr, struct xt_match, list);
1464 		if (*match->name)
1465 			seq_printf(seq, "%s\n", match->name);
1466 	}
1467 	return 0;
1468 }
1469 
1470 static const struct seq_operations xt_match_seq_ops = {
1471 	.start	= xt_match_seq_start,
1472 	.next	= xt_match_seq_next,
1473 	.stop	= xt_mttg_seq_stop,
1474 	.show	= xt_match_seq_show,
1475 };
1476 
xt_match_open(struct inode * inode,struct file * file)1477 static int xt_match_open(struct inode *inode, struct file *file)
1478 {
1479 	struct nf_mttg_trav *trav;
1480 	trav = __seq_open_private(file, &xt_match_seq_ops, sizeof(*trav));
1481 	if (!trav)
1482 		return -ENOMEM;
1483 
1484 	trav->nfproto = (unsigned long)PDE_DATA(inode);
1485 	return 0;
1486 }
1487 
1488 static const struct file_operations xt_match_ops = {
1489 	.owner	 = THIS_MODULE,
1490 	.open	 = xt_match_open,
1491 	.read	 = seq_read,
1492 	.llseek	 = seq_lseek,
1493 	.release = seq_release_private,
1494 };
1495 
xt_target_seq_start(struct seq_file * seq,loff_t * pos)1496 static void *xt_target_seq_start(struct seq_file *seq, loff_t *pos)
1497 {
1498 	return xt_mttg_seq_start(seq, pos, true);
1499 }
1500 
xt_target_seq_next(struct seq_file * seq,void * v,loff_t * ppos)1501 static void *xt_target_seq_next(struct seq_file *seq, void *v, loff_t *ppos)
1502 {
1503 	return xt_mttg_seq_next(seq, v, ppos, true);
1504 }
1505 
xt_target_seq_show(struct seq_file * seq,void * v)1506 static int xt_target_seq_show(struct seq_file *seq, void *v)
1507 {
1508 	const struct nf_mttg_trav *trav = seq->private;
1509 	const struct xt_target *target;
1510 
1511 	switch (trav->class) {
1512 	case MTTG_TRAV_NFP_UNSPEC:
1513 	case MTTG_TRAV_NFP_SPEC:
1514 		if (trav->curr == trav->head)
1515 			return 0;
1516 		target = list_entry(trav->curr, struct xt_target, list);
1517 		if (*target->name)
1518 			seq_printf(seq, "%s\n", target->name);
1519 	}
1520 	return 0;
1521 }
1522 
1523 static const struct seq_operations xt_target_seq_ops = {
1524 	.start	= xt_target_seq_start,
1525 	.next	= xt_target_seq_next,
1526 	.stop	= xt_mttg_seq_stop,
1527 	.show	= xt_target_seq_show,
1528 };
1529 
xt_target_open(struct inode * inode,struct file * file)1530 static int xt_target_open(struct inode *inode, struct file *file)
1531 {
1532 	struct nf_mttg_trav *trav;
1533 	trav = __seq_open_private(file, &xt_target_seq_ops, sizeof(*trav));
1534 	if (!trav)
1535 		return -ENOMEM;
1536 
1537 	trav->nfproto = (unsigned long)PDE_DATA(inode);
1538 	return 0;
1539 }
1540 
1541 static const struct file_operations xt_target_ops = {
1542 	.owner	 = THIS_MODULE,
1543 	.open	 = xt_target_open,
1544 	.read	 = seq_read,
1545 	.llseek	 = seq_lseek,
1546 	.release = seq_release_private,
1547 };
1548 
1549 #define FORMAT_TABLES	"_tables_names"
1550 #define	FORMAT_MATCHES	"_tables_matches"
1551 #define FORMAT_TARGETS 	"_tables_targets"
1552 
1553 #endif /* CONFIG_PROC_FS */
1554 
1555 /**
1556  * xt_hook_link - set up hooks for a new table
1557  * @table:	table with metadata needed to set up hooks
1558  * @fn:		Hook function
1559  *
1560  * This function will take care of creating and registering the necessary
1561  * Netfilter hooks for XT tables.
1562  */
xt_hook_link(const struct xt_table * table,nf_hookfn * fn)1563 struct nf_hook_ops *xt_hook_link(const struct xt_table *table, nf_hookfn *fn)
1564 {
1565 	unsigned int hook_mask = table->valid_hooks;
1566 	uint8_t i, num_hooks = hweight32(hook_mask);
1567 	uint8_t hooknum;
1568 	struct nf_hook_ops *ops;
1569 	int ret;
1570 
1571 	ops = kmalloc(sizeof(*ops) * num_hooks, GFP_KERNEL);
1572 	if (ops == NULL)
1573 		return ERR_PTR(-ENOMEM);
1574 
1575 	for (i = 0, hooknum = 0; i < num_hooks && hook_mask != 0;
1576 	     hook_mask >>= 1, ++hooknum) {
1577 		if (!(hook_mask & 1))
1578 			continue;
1579 		ops[i].hook     = fn;
1580 		ops[i].pf       = table->af;
1581 		ops[i].hooknum  = hooknum;
1582 		ops[i].priority = table->priority;
1583 		++i;
1584 	}
1585 
1586 	ret = nf_register_hooks(ops, num_hooks);
1587 	if (ret < 0) {
1588 		kfree(ops);
1589 		return ERR_PTR(ret);
1590 	}
1591 
1592 	return ops;
1593 }
1594 EXPORT_SYMBOL_GPL(xt_hook_link);
1595 
1596 /**
1597  * xt_hook_unlink - remove hooks for a table
1598  * @ops:	nf_hook_ops array as returned by nf_hook_link
1599  * @hook_mask:	the very same mask that was passed to nf_hook_link
1600  */
xt_hook_unlink(const struct xt_table * table,struct nf_hook_ops * ops)1601 void xt_hook_unlink(const struct xt_table *table, struct nf_hook_ops *ops)
1602 {
1603 	nf_unregister_hooks(ops, hweight32(table->valid_hooks));
1604 	kfree(ops);
1605 }
1606 EXPORT_SYMBOL_GPL(xt_hook_unlink);
1607 
xt_proto_init(struct net * net,u_int8_t af)1608 int xt_proto_init(struct net *net, u_int8_t af)
1609 {
1610 #ifdef CONFIG_PROC_FS
1611 	char buf[XT_FUNCTION_MAXNAMELEN];
1612 	struct proc_dir_entry *proc;
1613 #endif
1614 
1615 	if (af >= ARRAY_SIZE(xt_prefix))
1616 		return -EINVAL;
1617 
1618 
1619 #ifdef CONFIG_PROC_FS
1620 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1621 	strlcat(buf, FORMAT_TABLES, sizeof(buf));
1622 	proc = proc_create_data(buf, 0440, net->proc_net, &xt_table_ops,
1623 				(void *)(unsigned long)af);
1624 	if (!proc)
1625 		goto out;
1626 
1627 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1628 	strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1629 	proc = proc_create_data(buf, 0440, net->proc_net, &xt_match_ops,
1630 				(void *)(unsigned long)af);
1631 	if (!proc)
1632 		goto out_remove_tables;
1633 
1634 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1635 	strlcat(buf, FORMAT_TARGETS, sizeof(buf));
1636 	proc = proc_create_data(buf, 0440, net->proc_net, &xt_target_ops,
1637 				(void *)(unsigned long)af);
1638 	if (!proc)
1639 		goto out_remove_matches;
1640 #endif
1641 
1642 	return 0;
1643 
1644 #ifdef CONFIG_PROC_FS
1645 out_remove_matches:
1646 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1647 	strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1648 	remove_proc_entry(buf, net->proc_net);
1649 
1650 out_remove_tables:
1651 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1652 	strlcat(buf, FORMAT_TABLES, sizeof(buf));
1653 	remove_proc_entry(buf, net->proc_net);
1654 out:
1655 	return -1;
1656 #endif
1657 }
1658 EXPORT_SYMBOL_GPL(xt_proto_init);
1659 
xt_proto_fini(struct net * net,u_int8_t af)1660 void xt_proto_fini(struct net *net, u_int8_t af)
1661 {
1662 #ifdef CONFIG_PROC_FS
1663 	char buf[XT_FUNCTION_MAXNAMELEN];
1664 
1665 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1666 	strlcat(buf, FORMAT_TABLES, sizeof(buf));
1667 	remove_proc_entry(buf, net->proc_net);
1668 
1669 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1670 	strlcat(buf, FORMAT_TARGETS, sizeof(buf));
1671 	remove_proc_entry(buf, net->proc_net);
1672 
1673 	strlcpy(buf, xt_prefix[af], sizeof(buf));
1674 	strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1675 	remove_proc_entry(buf, net->proc_net);
1676 #endif /*CONFIG_PROC_FS*/
1677 }
1678 EXPORT_SYMBOL_GPL(xt_proto_fini);
1679 
1680 /**
1681  * xt_percpu_counter_alloc - allocate x_tables rule counter
1682  *
1683  * @state: pointer to xt_percpu allocation state
1684  * @counter: pointer to counter struct inside the ip(6)/arpt_entry struct
1685  *
1686  * On SMP, the packet counter [ ip(6)t_entry->counters.pcnt ] will then
1687  * contain the address of the real (percpu) counter.
1688  *
1689  * Rule evaluation needs to use xt_get_this_cpu_counter() helper
1690  * to fetch the real percpu counter.
1691  *
1692  * To speed up allocation and improve data locality, a 4kb block is
1693  * allocated.
1694  *
1695  * xt_percpu_counter_alloc_state contains the base address of the
1696  * allocated page and the current sub-offset.
1697  *
1698  * returns false on error.
1699  */
xt_percpu_counter_alloc(struct xt_percpu_counter_alloc_state * state,struct xt_counters * counter)1700 bool xt_percpu_counter_alloc(struct xt_percpu_counter_alloc_state *state,
1701 			     struct xt_counters *counter)
1702 {
1703 	BUILD_BUG_ON(XT_PCPU_BLOCK_SIZE < (sizeof(*counter) * 2));
1704 
1705 	if (nr_cpu_ids <= 1)
1706 		return true;
1707 
1708 	if (!state->mem) {
1709 		state->mem = __alloc_percpu(XT_PCPU_BLOCK_SIZE,
1710 					    XT_PCPU_BLOCK_SIZE);
1711 		if (!state->mem)
1712 			return false;
1713 	}
1714 	counter->pcnt = (__force unsigned long)(state->mem + state->off);
1715 	state->off += sizeof(*counter);
1716 	if (state->off > (XT_PCPU_BLOCK_SIZE - sizeof(*counter))) {
1717 		state->mem = NULL;
1718 		state->off = 0;
1719 	}
1720 	return true;
1721 }
1722 EXPORT_SYMBOL_GPL(xt_percpu_counter_alloc);
1723 
xt_percpu_counter_free(struct xt_counters * counters)1724 void xt_percpu_counter_free(struct xt_counters *counters)
1725 {
1726 	unsigned long pcnt = counters->pcnt;
1727 
1728 	if (nr_cpu_ids > 1 && (pcnt & (XT_PCPU_BLOCK_SIZE - 1)) == 0)
1729 		free_percpu((void __percpu *)pcnt);
1730 }
1731 EXPORT_SYMBOL_GPL(xt_percpu_counter_free);
1732 
xt_net_init(struct net * net)1733 static int __net_init xt_net_init(struct net *net)
1734 {
1735 	int i;
1736 
1737 	for (i = 0; i < NFPROTO_NUMPROTO; i++)
1738 		INIT_LIST_HEAD(&net->xt.tables[i]);
1739 	return 0;
1740 }
1741 
1742 static struct pernet_operations xt_net_ops = {
1743 	.init = xt_net_init,
1744 };
1745 
xt_init(void)1746 static int __init xt_init(void)
1747 {
1748 	unsigned int i;
1749 	int rv;
1750 
1751 	for_each_possible_cpu(i) {
1752 		seqcount_init(&per_cpu(xt_recseq, i));
1753 	}
1754 
1755 	xt = kcalloc(NFPROTO_NUMPROTO, sizeof(struct xt_af), GFP_KERNEL);
1756 	if (!xt)
1757 		return -ENOMEM;
1758 
1759 	for (i = 0; i < NFPROTO_NUMPROTO; i++) {
1760 		mutex_init(&xt[i].mutex);
1761 #ifdef CONFIG_COMPAT
1762 		mutex_init(&xt[i].compat_mutex);
1763 		xt[i].compat_tab = NULL;
1764 #endif
1765 		INIT_LIST_HEAD(&xt[i].target);
1766 		INIT_LIST_HEAD(&xt[i].match);
1767 	}
1768 	rv = register_pernet_subsys(&xt_net_ops);
1769 	if (rv < 0)
1770 		kfree(xt);
1771 	return rv;
1772 }
1773 
xt_fini(void)1774 static void __exit xt_fini(void)
1775 {
1776 	unregister_pernet_subsys(&xt_net_ops);
1777 	kfree(xt);
1778 }
1779 
1780 module_init(xt_init);
1781 module_exit(xt_fini);
1782 
1783