• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Packet matching code.
3  *
4  * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
5  * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
6  * Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/cache.h>
14 #include <linux/capability.h>
15 #include <linux/skbuff.h>
16 #include <linux/kmod.h>
17 #include <linux/vmalloc.h>
18 #include <linux/netdevice.h>
19 #include <linux/module.h>
20 #include <linux/icmp.h>
21 #include <net/ip.h>
22 #include <net/compat.h>
23 #include <asm/uaccess.h>
24 #include <linux/mutex.h>
25 #include <linux/proc_fs.h>
26 #include <linux/err.h>
27 #include <linux/cpumask.h>
28 
29 #include <linux/netfilter/x_tables.h>
30 #include <linux/netfilter_ipv4/ip_tables.h>
31 #include <net/netfilter/nf_log.h>
32 #include "../../netfilter/xt_repldata.h"
33 
34 MODULE_LICENSE("GPL");
35 MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
36 MODULE_DESCRIPTION("IPv4 packet filter");
37 
38 /*#define DEBUG_IP_FIREWALL*/
39 /*#define DEBUG_ALLOW_ALL*/ /* Useful for remote debugging */
40 /*#define DEBUG_IP_FIREWALL_USER*/
41 
42 #ifdef DEBUG_IP_FIREWALL
43 #define dprintf(format, args...) pr_info(format , ## args)
44 #else
45 #define dprintf(format, args...)
46 #endif
47 
48 #ifdef DEBUG_IP_FIREWALL_USER
49 #define duprintf(format, args...) pr_info(format , ## args)
50 #else
51 #define duprintf(format, args...)
52 #endif
53 
54 #ifdef CONFIG_NETFILTER_DEBUG
55 #define IP_NF_ASSERT(x)		WARN_ON(!(x))
56 #else
57 #define IP_NF_ASSERT(x)
58 #endif
59 
60 #if 0
61 /* All the better to debug you with... */
62 #define static
63 #define inline
64 #endif
65 
ipt_alloc_initial_table(const struct xt_table * info)66 void *ipt_alloc_initial_table(const struct xt_table *info)
67 {
68 	return xt_alloc_initial_table(ipt, IPT);
69 }
70 EXPORT_SYMBOL_GPL(ipt_alloc_initial_table);
71 
72 /* Returns whether matches rule or not. */
73 /* Performance critical - called for every packet */
74 static inline bool
ip_packet_match(const struct iphdr * ip,const char * indev,const char * outdev,const struct ipt_ip * ipinfo,int isfrag)75 ip_packet_match(const struct iphdr *ip,
76 		const char *indev,
77 		const char *outdev,
78 		const struct ipt_ip *ipinfo,
79 		int isfrag)
80 {
81 	unsigned long ret;
82 
83 #define FWINV(bool, invflg) ((bool) ^ !!(ipinfo->invflags & (invflg)))
84 
85 	if (FWINV((ip->saddr&ipinfo->smsk.s_addr) != ipinfo->src.s_addr,
86 		  IPT_INV_SRCIP) ||
87 	    FWINV((ip->daddr&ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr,
88 		  IPT_INV_DSTIP)) {
89 		dprintf("Source or dest mismatch.\n");
90 
91 		dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n",
92 			&ip->saddr, &ipinfo->smsk.s_addr, &ipinfo->src.s_addr,
93 			ipinfo->invflags & IPT_INV_SRCIP ? " (INV)" : "");
94 		dprintf("DST: %pI4 Mask: %pI4 Target: %pI4.%s\n",
95 			&ip->daddr, &ipinfo->dmsk.s_addr, &ipinfo->dst.s_addr,
96 			ipinfo->invflags & IPT_INV_DSTIP ? " (INV)" : "");
97 		return false;
98 	}
99 
100 	ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask);
101 
102 	if (FWINV(ret != 0, IPT_INV_VIA_IN)) {
103 		dprintf("VIA in mismatch (%s vs %s).%s\n",
104 			indev, ipinfo->iniface,
105 			ipinfo->invflags&IPT_INV_VIA_IN ?" (INV)":"");
106 		return false;
107 	}
108 
109 	ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask);
110 
111 	if (FWINV(ret != 0, IPT_INV_VIA_OUT)) {
112 		dprintf("VIA out mismatch (%s vs %s).%s\n",
113 			outdev, ipinfo->outiface,
114 			ipinfo->invflags&IPT_INV_VIA_OUT ?" (INV)":"");
115 		return false;
116 	}
117 
118 	/* Check specific protocol */
119 	if (ipinfo->proto &&
120 	    FWINV(ip->protocol != ipinfo->proto, IPT_INV_PROTO)) {
121 		dprintf("Packet protocol %hi does not match %hi.%s\n",
122 			ip->protocol, ipinfo->proto,
123 			ipinfo->invflags&IPT_INV_PROTO ? " (INV)":"");
124 		return false;
125 	}
126 
127 	/* If we have a fragment rule but the packet is not a fragment
128 	 * then we return zero */
129 	if (FWINV((ipinfo->flags&IPT_F_FRAG) && !isfrag, IPT_INV_FRAG)) {
130 		dprintf("Fragment rule but not fragment.%s\n",
131 			ipinfo->invflags & IPT_INV_FRAG ? " (INV)" : "");
132 		return false;
133 	}
134 
135 	return true;
136 }
137 
138 static bool
ip_checkentry(const struct ipt_ip * ip)139 ip_checkentry(const struct ipt_ip *ip)
140 {
141 	if (ip->flags & ~IPT_F_MASK) {
142 		duprintf("Unknown flag bits set: %08X\n",
143 			 ip->flags & ~IPT_F_MASK);
144 		return false;
145 	}
146 	if (ip->invflags & ~IPT_INV_MASK) {
147 		duprintf("Unknown invflag bits set: %08X\n",
148 			 ip->invflags & ~IPT_INV_MASK);
149 		return false;
150 	}
151 	return true;
152 }
153 
154 static unsigned int
ipt_error(struct sk_buff * skb,const struct xt_action_param * par)155 ipt_error(struct sk_buff *skb, const struct xt_action_param *par)
156 {
157 	net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
158 
159 	return NF_DROP;
160 }
161 
162 /* Performance critical */
163 static inline struct ipt_entry *
get_entry(const void * base,unsigned int offset)164 get_entry(const void *base, unsigned int offset)
165 {
166 	return (struct ipt_entry *)(base + offset);
167 }
168 
169 /* All zeroes == unconditional rule. */
170 /* Mildly perf critical (only if packet tracing is on) */
unconditional(const struct ipt_entry * e)171 static inline bool unconditional(const struct ipt_entry *e)
172 {
173 	static const struct ipt_ip uncond;
174 
175 	return e->target_offset == sizeof(struct ipt_entry) &&
176 	       memcmp(&e->ip, &uncond, sizeof(uncond)) == 0;
177 #undef FWINV
178 }
179 
180 /* for const-correctness */
181 static inline const struct xt_entry_target *
ipt_get_target_c(const struct ipt_entry * e)182 ipt_get_target_c(const struct ipt_entry *e)
183 {
184 	return ipt_get_target((struct ipt_entry *)e);
185 }
186 
187 #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
188 static const char *const hooknames[] = {
189 	[NF_INET_PRE_ROUTING]		= "PREROUTING",
190 	[NF_INET_LOCAL_IN]		= "INPUT",
191 	[NF_INET_FORWARD]		= "FORWARD",
192 	[NF_INET_LOCAL_OUT]		= "OUTPUT",
193 	[NF_INET_POST_ROUTING]		= "POSTROUTING",
194 };
195 
196 enum nf_ip_trace_comments {
197 	NF_IP_TRACE_COMMENT_RULE,
198 	NF_IP_TRACE_COMMENT_RETURN,
199 	NF_IP_TRACE_COMMENT_POLICY,
200 };
201 
202 static const char *const comments[] = {
203 	[NF_IP_TRACE_COMMENT_RULE]	= "rule",
204 	[NF_IP_TRACE_COMMENT_RETURN]	= "return",
205 	[NF_IP_TRACE_COMMENT_POLICY]	= "policy",
206 };
207 
208 static struct nf_loginfo trace_loginfo = {
209 	.type = NF_LOG_TYPE_LOG,
210 	.u = {
211 		.log = {
212 			.level = 4,
213 			.logflags = NF_LOG_MASK,
214 		},
215 	},
216 };
217 
218 /* Mildly perf critical (only if packet tracing is on) */
219 static inline int
get_chainname_rulenum(const struct ipt_entry * s,const struct ipt_entry * e,const char * hookname,const char ** chainname,const char ** comment,unsigned int * rulenum)220 get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,
221 		      const char *hookname, const char **chainname,
222 		      const char **comment, unsigned int *rulenum)
223 {
224 	const struct xt_standard_target *t = (void *)ipt_get_target_c(s);
225 
226 	if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
227 		/* Head of user chain: ERROR target with chainname */
228 		*chainname = t->target.data;
229 		(*rulenum) = 0;
230 	} else if (s == e) {
231 		(*rulenum)++;
232 
233 		if (unconditional(s) &&
234 		    strcmp(t->target.u.kernel.target->name,
235 			   XT_STANDARD_TARGET) == 0 &&
236 		   t->verdict < 0) {
237 			/* Tail of chains: STANDARD target (return/policy) */
238 			*comment = *chainname == hookname
239 				? comments[NF_IP_TRACE_COMMENT_POLICY]
240 				: comments[NF_IP_TRACE_COMMENT_RETURN];
241 		}
242 		return 1;
243 	} else
244 		(*rulenum)++;
245 
246 	return 0;
247 }
248 
trace_packet(const struct sk_buff * skb,unsigned int hook,const struct net_device * in,const struct net_device * out,const char * tablename,const struct xt_table_info * private,const struct ipt_entry * e)249 static void trace_packet(const struct sk_buff *skb,
250 			 unsigned int hook,
251 			 const struct net_device *in,
252 			 const struct net_device *out,
253 			 const char *tablename,
254 			 const struct xt_table_info *private,
255 			 const struct ipt_entry *e)
256 {
257 	const void *table_base;
258 	const struct ipt_entry *root;
259 	const char *hookname, *chainname, *comment;
260 	const struct ipt_entry *iter;
261 	unsigned int rulenum = 0;
262 	struct net *net = dev_net(in ? in : out);
263 
264 	table_base = private->entries[smp_processor_id()];
265 	root = get_entry(table_base, private->hook_entry[hook]);
266 
267 	hookname = chainname = hooknames[hook];
268 	comment = comments[NF_IP_TRACE_COMMENT_RULE];
269 
270 	xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
271 		if (get_chainname_rulenum(iter, e, hookname,
272 		    &chainname, &comment, &rulenum) != 0)
273 			break;
274 
275 	nf_log_packet(net, AF_INET, hook, skb, in, out, &trace_loginfo,
276 		      "TRACE: %s:%s:%s:%u ",
277 		      tablename, chainname, comment, rulenum);
278 }
279 #endif
280 
281 static inline __pure
ipt_next_entry(const struct ipt_entry * entry)282 struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry)
283 {
284 	return (void *)entry + entry->next_offset;
285 }
286 
287 /* Returns one of the generic firewall policies, like NF_ACCEPT. */
288 unsigned int
ipt_do_table(struct sk_buff * skb,unsigned int hook,const struct net_device * in,const struct net_device * out,struct xt_table * table)289 ipt_do_table(struct sk_buff *skb,
290 	     unsigned int hook,
291 	     const struct net_device *in,
292 	     const struct net_device *out,
293 	     struct xt_table *table)
294 {
295 	static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
296 	const struct iphdr *ip;
297 	/* Initializing verdict to NF_DROP keeps gcc happy. */
298 	unsigned int verdict = NF_DROP;
299 	const char *indev, *outdev;
300 	const void *table_base;
301 	struct ipt_entry *e, **jumpstack;
302 	unsigned int *stackptr, origptr, cpu;
303 	const struct xt_table_info *private;
304 	struct xt_action_param acpar;
305 	unsigned int addend;
306 
307 	/* Initialization */
308 	ip = ip_hdr(skb);
309 	indev = in ? in->name : nulldevname;
310 	outdev = out ? out->name : nulldevname;
311 	/* We handle fragments by dealing with the first fragment as
312 	 * if it was a normal packet.  All other fragments are treated
313 	 * normally, except that they will NEVER match rules that ask
314 	 * things we don't know, ie. tcp syn flag or ports).  If the
315 	 * rule is also a fragment-specific rule, non-fragments won't
316 	 * match it. */
317 	acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
318 	acpar.thoff   = ip_hdrlen(skb);
319 	acpar.hotdrop = false;
320 	acpar.in      = in;
321 	acpar.out     = out;
322 	acpar.family  = NFPROTO_IPV4;
323 	acpar.hooknum = hook;
324 
325 	IP_NF_ASSERT(table->valid_hooks & (1 << hook));
326 	local_bh_disable();
327 	addend = xt_write_recseq_begin();
328 	private = table->private;
329 	cpu        = smp_processor_id();
330 	/*
331 	 * Ensure we load private-> members after we've fetched the base
332 	 * pointer.
333 	 */
334 	smp_read_barrier_depends();
335 	table_base = private->entries[cpu];
336 	jumpstack  = (struct ipt_entry **)private->jumpstack[cpu];
337 	stackptr   = per_cpu_ptr(private->stackptr, cpu);
338 	origptr    = *stackptr;
339 
340 	e = get_entry(table_base, private->hook_entry[hook]);
341 
342 	pr_debug("Entering %s(hook %u); sp at %u (UF %p)\n",
343 		 table->name, hook, origptr,
344 		 get_entry(table_base, private->underflow[hook]));
345 
346 	do {
347 		const struct xt_entry_target *t;
348 		const struct xt_entry_match *ematch;
349 
350 		IP_NF_ASSERT(e);
351 		if (!ip_packet_match(ip, indev, outdev,
352 		    &e->ip, acpar.fragoff)) {
353  no_match:
354 			e = ipt_next_entry(e);
355 			continue;
356 		}
357 
358 		xt_ematch_foreach(ematch, e) {
359 			acpar.match     = ematch->u.kernel.match;
360 			acpar.matchinfo = ematch->data;
361 			if (!acpar.match->match(skb, &acpar))
362 				goto no_match;
363 		}
364 
365 		ADD_COUNTER(e->counters, skb->len, 1);
366 
367 		t = ipt_get_target(e);
368 		IP_NF_ASSERT(t->u.kernel.target);
369 
370 #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
371 		/* The packet is traced: log it */
372 		if (unlikely(skb->nf_trace))
373 			trace_packet(skb, hook, in, out,
374 				     table->name, private, e);
375 #endif
376 		/* Standard target? */
377 		if (!t->u.kernel.target->target) {
378 			int v;
379 
380 			v = ((struct xt_standard_target *)t)->verdict;
381 			if (v < 0) {
382 				/* Pop from stack? */
383 				if (v != XT_RETURN) {
384 					verdict = (unsigned int)(-v) - 1;
385 					break;
386 				}
387 				if (*stackptr <= origptr) {
388 					e = get_entry(table_base,
389 					    private->underflow[hook]);
390 					pr_debug("Underflow (this is normal) "
391 						 "to %p\n", e);
392 				} else {
393 					e = jumpstack[--*stackptr];
394 					pr_debug("Pulled %p out from pos %u\n",
395 						 e, *stackptr);
396 					e = ipt_next_entry(e);
397 				}
398 				continue;
399 			}
400 			if (table_base + v != ipt_next_entry(e) &&
401 			    !(e->ip.flags & IPT_F_GOTO)) {
402 				if (*stackptr >= private->stacksize) {
403 					verdict = NF_DROP;
404 					break;
405 				}
406 				jumpstack[(*stackptr)++] = e;
407 				pr_debug("Pushed %p into pos %u\n",
408 					 e, *stackptr - 1);
409 			}
410 
411 			e = get_entry(table_base, v);
412 			continue;
413 		}
414 
415 		acpar.target   = t->u.kernel.target;
416 		acpar.targinfo = t->data;
417 
418 		verdict = t->u.kernel.target->target(skb, &acpar);
419 		/* Target might have changed stuff. */
420 		ip = ip_hdr(skb);
421 		if (verdict == XT_CONTINUE)
422 			e = ipt_next_entry(e);
423 		else
424 			/* Verdict */
425 			break;
426 	} while (!acpar.hotdrop);
427 	pr_debug("Exiting %s; resetting sp from %u to %u\n",
428 		 __func__, *stackptr, origptr);
429 	*stackptr = origptr;
430  	xt_write_recseq_end(addend);
431  	local_bh_enable();
432 
433 #ifdef DEBUG_ALLOW_ALL
434 	return NF_ACCEPT;
435 #else
436 	if (acpar.hotdrop)
437 		return NF_DROP;
438 	else return verdict;
439 #endif
440 }
441 
442 /* Figures out from what hook each rule can be called: returns 0 if
443    there are loops.  Puts hook bitmask in comefrom. */
444 static int
mark_source_chains(const struct xt_table_info * newinfo,unsigned int valid_hooks,void * entry0,unsigned int * offsets)445 mark_source_chains(const struct xt_table_info *newinfo,
446 		   unsigned int valid_hooks, void *entry0,
447 		   unsigned int *offsets)
448 {
449 	unsigned int hook;
450 
451 	/* No recursion; use packet counter to save back ptrs (reset
452 	   to 0 as we leave), and comefrom to save source hook bitmask */
453 	for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
454 		unsigned int pos = newinfo->hook_entry[hook];
455 		struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);
456 
457 		if (!(valid_hooks & (1 << hook)))
458 			continue;
459 
460 		/* Set initial back pointer. */
461 		e->counters.pcnt = pos;
462 
463 		for (;;) {
464 			const struct xt_standard_target *t
465 				= (void *)ipt_get_target_c(e);
466 			int visited = e->comefrom & (1 << hook);
467 
468 			if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
469 				pr_err("iptables: loop hook %u pos %u %08X.\n",
470 				       hook, pos, e->comefrom);
471 				return 0;
472 			}
473 			e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
474 
475 			/* Unconditional return/END. */
476 			if ((unconditional(e) &&
477 			     (strcmp(t->target.u.user.name,
478 				     XT_STANDARD_TARGET) == 0) &&
479 			     t->verdict < 0) || visited) {
480 				unsigned int oldpos, size;
481 
482 				if ((strcmp(t->target.u.user.name,
483 			    		    XT_STANDARD_TARGET) == 0) &&
484 				    t->verdict < -NF_MAX_VERDICT - 1) {
485 					duprintf("mark_source_chains: bad "
486 						"negative verdict (%i)\n",
487 								t->verdict);
488 					return 0;
489 				}
490 
491 				/* Return: backtrack through the last
492 				   big jump. */
493 				do {
494 					e->comefrom ^= (1<<NF_INET_NUMHOOKS);
495 #ifdef DEBUG_IP_FIREWALL_USER
496 					if (e->comefrom
497 					    & (1 << NF_INET_NUMHOOKS)) {
498 						duprintf("Back unset "
499 							 "on hook %u "
500 							 "rule %u\n",
501 							 hook, pos);
502 					}
503 #endif
504 					oldpos = pos;
505 					pos = e->counters.pcnt;
506 					e->counters.pcnt = 0;
507 
508 					/* We're at the start. */
509 					if (pos == oldpos)
510 						goto next;
511 
512 					e = (struct ipt_entry *)
513 						(entry0 + pos);
514 				} while (oldpos == pos + e->next_offset);
515 
516 				/* Move along one */
517 				size = e->next_offset;
518 				e = (struct ipt_entry *)
519 					(entry0 + pos + size);
520 				if (pos + size >= newinfo->size)
521 					return 0;
522 				e->counters.pcnt = pos;
523 				pos += size;
524 			} else {
525 				int newpos = t->verdict;
526 
527 				if (strcmp(t->target.u.user.name,
528 					   XT_STANDARD_TARGET) == 0 &&
529 				    newpos >= 0) {
530 					if (newpos > newinfo->size -
531 						sizeof(struct ipt_entry)) {
532 						duprintf("mark_source_chains: "
533 							"bad verdict (%i)\n",
534 								newpos);
535 						return 0;
536 					}
537 					/* This a jump; chase it. */
538 					duprintf("Jump rule %u -> %u\n",
539 						 pos, newpos);
540 					if (!xt_find_jump_offset(offsets, newpos,
541 								 newinfo->number))
542 						return 0;
543 					e = (struct ipt_entry *)
544 						(entry0 + newpos);
545 				} else {
546 					/* ... this is a fallthru */
547 					newpos = pos + e->next_offset;
548 					if (newpos >= newinfo->size)
549 						return 0;
550 				}
551 				e = (struct ipt_entry *)
552 					(entry0 + newpos);
553 				e->counters.pcnt = pos;
554 				pos = newpos;
555 			}
556 		}
557 		next:
558 		duprintf("Finished chain %u\n", hook);
559 	}
560 	return 1;
561 }
562 
cleanup_match(struct xt_entry_match * m,struct net * net)563 static void cleanup_match(struct xt_entry_match *m, struct net *net)
564 {
565 	struct xt_mtdtor_param par;
566 
567 	par.net       = net;
568 	par.match     = m->u.kernel.match;
569 	par.matchinfo = m->data;
570 	par.family    = NFPROTO_IPV4;
571 	if (par.match->destroy != NULL)
572 		par.match->destroy(&par);
573 	module_put(par.match->me);
574 }
575 
576 static int
check_entry(const struct ipt_entry * e)577 check_entry(const struct ipt_entry *e)
578 {
579 	const struct xt_entry_target *t;
580 
581 	if (!ip_checkentry(&e->ip))
582 		return -EINVAL;
583 
584 	if (e->target_offset + sizeof(struct xt_entry_target) >
585 	    e->next_offset)
586 		return -EINVAL;
587 
588 	t = ipt_get_target_c(e);
589 	if (e->target_offset + t->u.target_size > e->next_offset)
590 		return -EINVAL;
591 
592 	return 0;
593 }
594 
595 static int
check_match(struct xt_entry_match * m,struct xt_mtchk_param * par)596 check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
597 {
598 	const struct ipt_ip *ip = par->entryinfo;
599 	int ret;
600 
601 	par->match     = m->u.kernel.match;
602 	par->matchinfo = m->data;
603 
604 	ret = xt_check_match(par, m->u.match_size - sizeof(*m),
605 	      ip->proto, ip->invflags & IPT_INV_PROTO);
606 	if (ret < 0) {
607 		duprintf("check failed for `%s'.\n", par->match->name);
608 		return ret;
609 	}
610 	return 0;
611 }
612 
613 static int
find_check_match(struct xt_entry_match * m,struct xt_mtchk_param * par)614 find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
615 {
616 	struct xt_match *match;
617 	int ret;
618 
619 	match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
620 				      m->u.user.revision);
621 	if (IS_ERR(match)) {
622 		duprintf("find_check_match: `%s' not found\n", m->u.user.name);
623 		return PTR_ERR(match);
624 	}
625 	m->u.kernel.match = match;
626 
627 	ret = check_match(m, par);
628 	if (ret)
629 		goto err;
630 
631 	return 0;
632 err:
633 	module_put(m->u.kernel.match->me);
634 	return ret;
635 }
636 
check_target(struct ipt_entry * e,struct net * net,const char * name)637 static int check_target(struct ipt_entry *e, struct net *net, const char *name)
638 {
639 	struct xt_entry_target *t = ipt_get_target(e);
640 	struct xt_tgchk_param par = {
641 		.net       = net,
642 		.table     = name,
643 		.entryinfo = e,
644 		.target    = t->u.kernel.target,
645 		.targinfo  = t->data,
646 		.hook_mask = e->comefrom,
647 		.family    = NFPROTO_IPV4,
648 	};
649 	int ret;
650 
651 	ret = xt_check_target(&par, t->u.target_size - sizeof(*t),
652 	      e->ip.proto, e->ip.invflags & IPT_INV_PROTO);
653 	if (ret < 0) {
654 		duprintf("check failed for `%s'.\n",
655 			 t->u.kernel.target->name);
656 		return ret;
657 	}
658 	return 0;
659 }
660 
661 static int
find_check_entry(struct ipt_entry * e,struct net * net,const char * name,unsigned int size)662 find_check_entry(struct ipt_entry *e, struct net *net, const char *name,
663 		 unsigned int size)
664 {
665 	struct xt_entry_target *t;
666 	struct xt_target *target;
667 	int ret;
668 	unsigned int j;
669 	struct xt_mtchk_param mtpar;
670 	struct xt_entry_match *ematch;
671 
672 	j = 0;
673 	mtpar.net	= net;
674 	mtpar.table     = name;
675 	mtpar.entryinfo = &e->ip;
676 	mtpar.hook_mask = e->comefrom;
677 	mtpar.family    = NFPROTO_IPV4;
678 	xt_ematch_foreach(ematch, e) {
679 		ret = find_check_match(ematch, &mtpar);
680 		if (ret != 0)
681 			goto cleanup_matches;
682 		++j;
683 	}
684 
685 	t = ipt_get_target(e);
686 	target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
687 					t->u.user.revision);
688 	if (IS_ERR(target)) {
689 		duprintf("find_check_entry: `%s' not found\n", t->u.user.name);
690 		ret = PTR_ERR(target);
691 		goto cleanup_matches;
692 	}
693 	t->u.kernel.target = target;
694 
695 	ret = check_target(e, net, name);
696 	if (ret)
697 		goto err;
698 	return 0;
699  err:
700 	module_put(t->u.kernel.target->me);
701  cleanup_matches:
702 	xt_ematch_foreach(ematch, e) {
703 		if (j-- == 0)
704 			break;
705 		cleanup_match(ematch, net);
706 	}
707 	return ret;
708 }
709 
check_underflow(const struct ipt_entry * e)710 static bool check_underflow(const struct ipt_entry *e)
711 {
712 	const struct xt_entry_target *t;
713 	unsigned int verdict;
714 
715 	if (!unconditional(e))
716 		return false;
717 	t = ipt_get_target_c(e);
718 	if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
719 		return false;
720 	verdict = ((struct xt_standard_target *)t)->verdict;
721 	verdict = -verdict - 1;
722 	return verdict == NF_DROP || verdict == NF_ACCEPT;
723 }
724 
725 static int
check_entry_size_and_hooks(struct ipt_entry * e,struct xt_table_info * newinfo,const unsigned char * base,const unsigned char * limit,const unsigned int * hook_entries,const unsigned int * underflows,unsigned int valid_hooks)726 check_entry_size_and_hooks(struct ipt_entry *e,
727 			   struct xt_table_info *newinfo,
728 			   const unsigned char *base,
729 			   const unsigned char *limit,
730 			   const unsigned int *hook_entries,
731 			   const unsigned int *underflows,
732 			   unsigned int valid_hooks)
733 {
734 	unsigned int h;
735 	int err;
736 
737 	if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
738 	    (unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
739 	    (unsigned char *)e + e->next_offset > limit) {
740 		duprintf("Bad offset %p\n", e);
741 		return -EINVAL;
742 	}
743 
744 	if (e->next_offset
745 	    < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
746 		duprintf("checking: element %p size %u\n",
747 			 e, e->next_offset);
748 		return -EINVAL;
749 	}
750 
751 	err = check_entry(e);
752 	if (err)
753 		return err;
754 
755 	/* Check hooks & underflows */
756 	for (h = 0; h < NF_INET_NUMHOOKS; h++) {
757 		if (!(valid_hooks & (1 << h)))
758 			continue;
759 		if ((unsigned char *)e - base == hook_entries[h])
760 			newinfo->hook_entry[h] = hook_entries[h];
761 		if ((unsigned char *)e - base == underflows[h]) {
762 			if (!check_underflow(e)) {
763 				pr_debug("Underflows must be unconditional and "
764 					 "use the STANDARD target with "
765 					 "ACCEPT/DROP\n");
766 				return -EINVAL;
767 			}
768 			newinfo->underflow[h] = underflows[h];
769 		}
770 	}
771 
772 	/* Clear counters and comefrom */
773 	e->counters = ((struct xt_counters) { 0, 0 });
774 	e->comefrom = 0;
775 	return 0;
776 }
777 
778 static void
cleanup_entry(struct ipt_entry * e,struct net * net)779 cleanup_entry(struct ipt_entry *e, struct net *net)
780 {
781 	struct xt_tgdtor_param par;
782 	struct xt_entry_target *t;
783 	struct xt_entry_match *ematch;
784 
785 	/* Cleanup all matches */
786 	xt_ematch_foreach(ematch, e)
787 		cleanup_match(ematch, net);
788 	t = ipt_get_target(e);
789 
790 	par.net      = net;
791 	par.target   = t->u.kernel.target;
792 	par.targinfo = t->data;
793 	par.family   = NFPROTO_IPV4;
794 	if (par.target->destroy != NULL)
795 		par.target->destroy(&par);
796 	module_put(par.target->me);
797 }
798 
799 /* Checks and translates the user-supplied table segment (held in
800    newinfo) */
801 static int
translate_table(struct net * net,struct xt_table_info * newinfo,void * entry0,const struct ipt_replace * repl)802 translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
803                 const struct ipt_replace *repl)
804 {
805 	struct ipt_entry *iter;
806 	unsigned int *offsets;
807 	unsigned int i;
808 	int ret = 0;
809 
810 	newinfo->size = repl->size;
811 	newinfo->number = repl->num_entries;
812 
813 	/* Init all hooks to impossible value. */
814 	for (i = 0; i < NF_INET_NUMHOOKS; i++) {
815 		newinfo->hook_entry[i] = 0xFFFFFFFF;
816 		newinfo->underflow[i] = 0xFFFFFFFF;
817 	}
818 
819 	duprintf("translate_table: size %u\n", newinfo->size);
820 	offsets = xt_alloc_entry_offsets(newinfo->number);
821 	if (!offsets)
822 		return -ENOMEM;
823 	i = 0;
824 	/* Walk through entries, checking offsets. */
825 	xt_entry_foreach(iter, entry0, newinfo->size) {
826 		ret = check_entry_size_and_hooks(iter, newinfo, entry0,
827 						 entry0 + repl->size,
828 						 repl->hook_entry,
829 						 repl->underflow,
830 						 repl->valid_hooks);
831 		if (ret != 0)
832 			goto out_free;
833 		if (i < repl->num_entries)
834 			offsets[i] = (void *)iter - entry0;
835 		++i;
836 		if (strcmp(ipt_get_target(iter)->u.user.name,
837 		    XT_ERROR_TARGET) == 0)
838 			++newinfo->stacksize;
839 	}
840 
841 	ret = -EINVAL;
842 	if (i != repl->num_entries) {
843 		duprintf("translate_table: %u not %u entries\n",
844 			 i, repl->num_entries);
845 		goto out_free;
846 	}
847 
848 	/* Check hooks all assigned */
849 	for (i = 0; i < NF_INET_NUMHOOKS; i++) {
850 		/* Only hooks which are valid */
851 		if (!(repl->valid_hooks & (1 << i)))
852 			continue;
853 		if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
854 			duprintf("Invalid hook entry %u %u\n",
855 				 i, repl->hook_entry[i]);
856 			goto out_free;
857 		}
858 		if (newinfo->underflow[i] == 0xFFFFFFFF) {
859 			duprintf("Invalid underflow %u %u\n",
860 				 i, repl->underflow[i]);
861 			goto out_free;
862 		}
863 	}
864 
865 	if (!mark_source_chains(newinfo, repl->valid_hooks, entry0, offsets)) {
866 		ret = -ELOOP;
867 		goto out_free;
868 	}
869 	kvfree(offsets);
870 
871 	/* Finally, each sanity check must pass */
872 	i = 0;
873 	xt_entry_foreach(iter, entry0, newinfo->size) {
874 		ret = find_check_entry(iter, net, repl->name, repl->size);
875 		if (ret != 0)
876 			break;
877 		++i;
878 	}
879 
880 	if (ret != 0) {
881 		xt_entry_foreach(iter, entry0, newinfo->size) {
882 			if (i-- == 0)
883 				break;
884 			cleanup_entry(iter, net);
885 		}
886 		return ret;
887 	}
888 
889 	/* And one copy for every other CPU */
890 	for_each_possible_cpu(i) {
891 		if (newinfo->entries[i] && newinfo->entries[i] != entry0)
892 			memcpy(newinfo->entries[i], entry0, newinfo->size);
893 	}
894 
895 	return ret;
896  out_free:
897 	kvfree(offsets);
898 	return ret;
899 }
900 
901 static void
get_counters(const struct xt_table_info * t,struct xt_counters counters[])902 get_counters(const struct xt_table_info *t,
903 	     struct xt_counters counters[])
904 {
905 	struct ipt_entry *iter;
906 	unsigned int cpu;
907 	unsigned int i;
908 
909 	for_each_possible_cpu(cpu) {
910 		seqcount_t *s = &per_cpu(xt_recseq, cpu);
911 
912 		i = 0;
913 		xt_entry_foreach(iter, t->entries[cpu], t->size) {
914 			u64 bcnt, pcnt;
915 			unsigned int start;
916 
917 			do {
918 				start = read_seqcount_begin(s);
919 				bcnt = iter->counters.bcnt;
920 				pcnt = iter->counters.pcnt;
921 			} while (read_seqcount_retry(s, start));
922 
923 			ADD_COUNTER(counters[i], bcnt, pcnt);
924 			++i; /* macro does multi eval of i */
925 		}
926 	}
927 }
928 
alloc_counters(const struct xt_table * table)929 static struct xt_counters *alloc_counters(const struct xt_table *table)
930 {
931 	unsigned int countersize;
932 	struct xt_counters *counters;
933 	const struct xt_table_info *private = table->private;
934 
935 	/* We need atomic snapshot of counters: rest doesn't change
936 	   (other than comefrom, which userspace doesn't care
937 	   about). */
938 	countersize = sizeof(struct xt_counters) * private->number;
939 	counters = vzalloc(countersize);
940 
941 	if (counters == NULL)
942 		return ERR_PTR(-ENOMEM);
943 
944 	get_counters(private, counters);
945 
946 	return counters;
947 }
948 
949 static int
copy_entries_to_user(unsigned int total_size,const struct xt_table * table,void __user * userptr)950 copy_entries_to_user(unsigned int total_size,
951 		     const struct xt_table *table,
952 		     void __user *userptr)
953 {
954 	unsigned int off, num;
955 	const struct ipt_entry *e;
956 	struct xt_counters *counters;
957 	const struct xt_table_info *private = table->private;
958 	int ret = 0;
959 	const void *loc_cpu_entry;
960 
961 	counters = alloc_counters(table);
962 	if (IS_ERR(counters))
963 		return PTR_ERR(counters);
964 
965 	/* choose the copy that is on our node/cpu, ...
966 	 * This choice is lazy (because current thread is
967 	 * allowed to migrate to another cpu)
968 	 */
969 	loc_cpu_entry = private->entries[raw_smp_processor_id()];
970 	if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
971 		ret = -EFAULT;
972 		goto free_counters;
973 	}
974 
975 	/* FIXME: use iterator macros --RR */
976 	/* ... then go back and fix counters and names */
977 	for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
978 		unsigned int i;
979 		const struct xt_entry_match *m;
980 		const struct xt_entry_target *t;
981 
982 		e = (struct ipt_entry *)(loc_cpu_entry + off);
983 		if (copy_to_user(userptr + off
984 				 + offsetof(struct ipt_entry, counters),
985 				 &counters[num],
986 				 sizeof(counters[num])) != 0) {
987 			ret = -EFAULT;
988 			goto free_counters;
989 		}
990 
991 		for (i = sizeof(struct ipt_entry);
992 		     i < e->target_offset;
993 		     i += m->u.match_size) {
994 			m = (void *)e + i;
995 
996 			if (copy_to_user(userptr + off + i
997 					 + offsetof(struct xt_entry_match,
998 						    u.user.name),
999 					 m->u.kernel.match->name,
1000 					 strlen(m->u.kernel.match->name)+1)
1001 			    != 0) {
1002 				ret = -EFAULT;
1003 				goto free_counters;
1004 			}
1005 		}
1006 
1007 		t = ipt_get_target_c(e);
1008 		if (copy_to_user(userptr + off + e->target_offset
1009 				 + offsetof(struct xt_entry_target,
1010 					    u.user.name),
1011 				 t->u.kernel.target->name,
1012 				 strlen(t->u.kernel.target->name)+1) != 0) {
1013 			ret = -EFAULT;
1014 			goto free_counters;
1015 		}
1016 	}
1017 
1018  free_counters:
1019 	vfree(counters);
1020 	return ret;
1021 }
1022 
1023 #ifdef CONFIG_COMPAT
compat_standard_from_user(void * dst,const void * src)1024 static void compat_standard_from_user(void *dst, const void *src)
1025 {
1026 	int v = *(compat_int_t *)src;
1027 
1028 	if (v > 0)
1029 		v += xt_compat_calc_jump(AF_INET, v);
1030 	memcpy(dst, &v, sizeof(v));
1031 }
1032 
compat_standard_to_user(void __user * dst,const void * src)1033 static int compat_standard_to_user(void __user *dst, const void *src)
1034 {
1035 	compat_int_t cv = *(int *)src;
1036 
1037 	if (cv > 0)
1038 		cv -= xt_compat_calc_jump(AF_INET, cv);
1039 	return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
1040 }
1041 
compat_calc_entry(const struct ipt_entry * e,const struct xt_table_info * info,const void * base,struct xt_table_info * newinfo)1042 static int compat_calc_entry(const struct ipt_entry *e,
1043 			     const struct xt_table_info *info,
1044 			     const void *base, struct xt_table_info *newinfo)
1045 {
1046 	const struct xt_entry_match *ematch;
1047 	const struct xt_entry_target *t;
1048 	unsigned int entry_offset;
1049 	int off, i, ret;
1050 
1051 	off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1052 	entry_offset = (void *)e - base;
1053 	xt_ematch_foreach(ematch, e)
1054 		off += xt_compat_match_offset(ematch->u.kernel.match);
1055 	t = ipt_get_target_c(e);
1056 	off += xt_compat_target_offset(t->u.kernel.target);
1057 	newinfo->size -= off;
1058 	ret = xt_compat_add_offset(AF_INET, entry_offset, off);
1059 	if (ret)
1060 		return ret;
1061 
1062 	for (i = 0; i < NF_INET_NUMHOOKS; i++) {
1063 		if (info->hook_entry[i] &&
1064 		    (e < (struct ipt_entry *)(base + info->hook_entry[i])))
1065 			newinfo->hook_entry[i] -= off;
1066 		if (info->underflow[i] &&
1067 		    (e < (struct ipt_entry *)(base + info->underflow[i])))
1068 			newinfo->underflow[i] -= off;
1069 	}
1070 	return 0;
1071 }
1072 
compat_table_info(const struct xt_table_info * info,struct xt_table_info * newinfo)1073 static int compat_table_info(const struct xt_table_info *info,
1074 			     struct xt_table_info *newinfo)
1075 {
1076 	struct ipt_entry *iter;
1077 	void *loc_cpu_entry;
1078 	int ret;
1079 
1080 	if (!newinfo || !info)
1081 		return -EINVAL;
1082 
1083 	/* we dont care about newinfo->entries[] */
1084 	memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
1085 	newinfo->initial_entries = 0;
1086 	loc_cpu_entry = info->entries[raw_smp_processor_id()];
1087 	xt_compat_init_offsets(AF_INET, info->number);
1088 	xt_entry_foreach(iter, loc_cpu_entry, info->size) {
1089 		ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
1090 		if (ret != 0)
1091 			return ret;
1092 	}
1093 	return 0;
1094 }
1095 #endif
1096 
get_info(struct net * net,void __user * user,const int * len,int compat)1097 static int get_info(struct net *net, void __user *user,
1098                     const int *len, int compat)
1099 {
1100 	char name[XT_TABLE_MAXNAMELEN];
1101 	struct xt_table *t;
1102 	int ret;
1103 
1104 	if (*len != sizeof(struct ipt_getinfo)) {
1105 		duprintf("length %u != %zu\n", *len,
1106 			 sizeof(struct ipt_getinfo));
1107 		return -EINVAL;
1108 	}
1109 
1110 	if (copy_from_user(name, user, sizeof(name)) != 0)
1111 		return -EFAULT;
1112 
1113 	name[XT_TABLE_MAXNAMELEN-1] = '\0';
1114 #ifdef CONFIG_COMPAT
1115 	if (compat)
1116 		xt_compat_lock(AF_INET);
1117 #endif
1118 	t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
1119 				    "iptable_%s", name);
1120 	if (!IS_ERR_OR_NULL(t)) {
1121 		struct ipt_getinfo info;
1122 		const struct xt_table_info *private = t->private;
1123 #ifdef CONFIG_COMPAT
1124 		struct xt_table_info tmp;
1125 
1126 		if (compat) {
1127 			ret = compat_table_info(private, &tmp);
1128 			xt_compat_flush_offsets(AF_INET);
1129 			private = &tmp;
1130 		}
1131 #endif
1132 		memset(&info, 0, sizeof(info));
1133 		info.valid_hooks = t->valid_hooks;
1134 		memcpy(info.hook_entry, private->hook_entry,
1135 		       sizeof(info.hook_entry));
1136 		memcpy(info.underflow, private->underflow,
1137 		       sizeof(info.underflow));
1138 		info.num_entries = private->number;
1139 		info.size = private->size;
1140 		strcpy(info.name, name);
1141 
1142 		if (copy_to_user(user, &info, *len) != 0)
1143 			ret = -EFAULT;
1144 		else
1145 			ret = 0;
1146 
1147 		xt_table_unlock(t);
1148 		module_put(t->me);
1149 	} else
1150 		ret = t ? PTR_ERR(t) : -ENOENT;
1151 #ifdef CONFIG_COMPAT
1152 	if (compat)
1153 		xt_compat_unlock(AF_INET);
1154 #endif
1155 	return ret;
1156 }
1157 
1158 static int
get_entries(struct net * net,struct ipt_get_entries __user * uptr,const int * len)1159 get_entries(struct net *net, struct ipt_get_entries __user *uptr,
1160 	    const int *len)
1161 {
1162 	int ret;
1163 	struct ipt_get_entries get;
1164 	struct xt_table *t;
1165 
1166 	if (*len < sizeof(get)) {
1167 		duprintf("get_entries: %u < %zu\n", *len, sizeof(get));
1168 		return -EINVAL;
1169 	}
1170 	if (copy_from_user(&get, uptr, sizeof(get)) != 0)
1171 		return -EFAULT;
1172 	if (*len != sizeof(struct ipt_get_entries) + get.size) {
1173 		duprintf("get_entries: %u != %zu\n",
1174 			 *len, sizeof(get) + get.size);
1175 		return -EINVAL;
1176 	}
1177 
1178 	t = xt_find_table_lock(net, AF_INET, get.name);
1179 	if (!IS_ERR_OR_NULL(t)) {
1180 		const struct xt_table_info *private = t->private;
1181 		duprintf("t->private->number = %u\n", private->number);
1182 		if (get.size == private->size)
1183 			ret = copy_entries_to_user(private->size,
1184 						   t, uptr->entrytable);
1185 		else {
1186 			duprintf("get_entries: I've got %u not %u!\n",
1187 				 private->size, get.size);
1188 			ret = -EAGAIN;
1189 		}
1190 		module_put(t->me);
1191 		xt_table_unlock(t);
1192 	} else
1193 		ret = t ? PTR_ERR(t) : -ENOENT;
1194 
1195 	return ret;
1196 }
1197 
1198 static int
__do_replace(struct net * net,const char * name,unsigned int valid_hooks,struct xt_table_info * newinfo,unsigned int num_counters,void __user * counters_ptr)1199 __do_replace(struct net *net, const char *name, unsigned int valid_hooks,
1200 	     struct xt_table_info *newinfo, unsigned int num_counters,
1201 	     void __user *counters_ptr)
1202 {
1203 	int ret;
1204 	struct xt_table *t;
1205 	struct xt_table_info *oldinfo;
1206 	struct xt_counters *counters;
1207 	void *loc_cpu_old_entry;
1208 	struct ipt_entry *iter;
1209 
1210 	ret = 0;
1211 	counters = vzalloc(num_counters * sizeof(struct xt_counters));
1212 	if (!counters) {
1213 		ret = -ENOMEM;
1214 		goto out;
1215 	}
1216 
1217 	t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
1218 				    "iptable_%s", name);
1219 	if (IS_ERR_OR_NULL(t)) {
1220 		ret = t ? PTR_ERR(t) : -ENOENT;
1221 		goto free_newinfo_counters_untrans;
1222 	}
1223 
1224 	/* You lied! */
1225 	if (valid_hooks != t->valid_hooks) {
1226 		duprintf("Valid hook crap: %08X vs %08X\n",
1227 			 valid_hooks, t->valid_hooks);
1228 		ret = -EINVAL;
1229 		goto put_module;
1230 	}
1231 
1232 	oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
1233 	if (!oldinfo)
1234 		goto put_module;
1235 
1236 	/* Update module usage count based on number of rules */
1237 	duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
1238 		oldinfo->number, oldinfo->initial_entries, newinfo->number);
1239 	if ((oldinfo->number > oldinfo->initial_entries) ||
1240 	    (newinfo->number <= oldinfo->initial_entries))
1241 		module_put(t->me);
1242 	if ((oldinfo->number > oldinfo->initial_entries) &&
1243 	    (newinfo->number <= oldinfo->initial_entries))
1244 		module_put(t->me);
1245 
1246 	/* Get the old counters, and synchronize with replace */
1247 	get_counters(oldinfo, counters);
1248 
1249 	/* Decrease module usage counts and free resource */
1250 	loc_cpu_old_entry = oldinfo->entries[raw_smp_processor_id()];
1251 	xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
1252 		cleanup_entry(iter, net);
1253 
1254 	xt_free_table_info(oldinfo);
1255 	if (copy_to_user(counters_ptr, counters,
1256 			 sizeof(struct xt_counters) * num_counters) != 0) {
1257 		/* Silent error, can't fail, new table is already in place */
1258 		net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n");
1259 	}
1260 	vfree(counters);
1261 	xt_table_unlock(t);
1262 	return ret;
1263 
1264  put_module:
1265 	module_put(t->me);
1266 	xt_table_unlock(t);
1267  free_newinfo_counters_untrans:
1268 	vfree(counters);
1269  out:
1270 	return ret;
1271 }
1272 
1273 static int
do_replace(struct net * net,const void __user * user,unsigned int len)1274 do_replace(struct net *net, const void __user *user, unsigned int len)
1275 {
1276 	int ret;
1277 	struct ipt_replace tmp;
1278 	struct xt_table_info *newinfo;
1279 	void *loc_cpu_entry;
1280 	struct ipt_entry *iter;
1281 
1282 	if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
1283 		return -EFAULT;
1284 
1285 	/* overflow check */
1286 	if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
1287 		return -ENOMEM;
1288 	tmp.name[sizeof(tmp.name)-1] = 0;
1289 
1290 	newinfo = xt_alloc_table_info(tmp.size);
1291 	if (!newinfo)
1292 		return -ENOMEM;
1293 
1294 	/* choose the copy that is on our node/cpu */
1295 	loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
1296 	if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
1297 			   tmp.size) != 0) {
1298 		ret = -EFAULT;
1299 		goto free_newinfo;
1300 	}
1301 
1302 	ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
1303 	if (ret != 0)
1304 		goto free_newinfo;
1305 
1306 	duprintf("Translated table\n");
1307 
1308 	ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
1309 			   tmp.num_counters, tmp.counters);
1310 	if (ret)
1311 		goto free_newinfo_untrans;
1312 	return 0;
1313 
1314  free_newinfo_untrans:
1315 	xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
1316 		cleanup_entry(iter, net);
1317  free_newinfo:
1318 	xt_free_table_info(newinfo);
1319 	return ret;
1320 }
1321 
1322 static int
do_add_counters(struct net * net,const void __user * user,unsigned int len,int compat)1323 do_add_counters(struct net *net, const void __user *user,
1324                 unsigned int len, int compat)
1325 {
1326 	unsigned int i, curcpu;
1327 	struct xt_counters_info tmp;
1328 	struct xt_counters *paddc;
1329 	struct xt_table *t;
1330 	const struct xt_table_info *private;
1331 	int ret = 0;
1332 	void *loc_cpu_entry;
1333 	struct ipt_entry *iter;
1334 	unsigned int addend;
1335 
1336 	paddc = xt_copy_counters_from_user(user, len, &tmp, compat);
1337 	if (IS_ERR(paddc))
1338 		return PTR_ERR(paddc);
1339 
1340 	t = xt_find_table_lock(net, AF_INET, tmp.name);
1341 	if (IS_ERR_OR_NULL(t)) {
1342 		ret = t ? PTR_ERR(t) : -ENOENT;
1343 		goto free;
1344 	}
1345 
1346 	local_bh_disable();
1347 	private = t->private;
1348 	if (private->number != tmp.num_counters) {
1349 		ret = -EINVAL;
1350 		goto unlock_up_free;
1351 	}
1352 
1353 	i = 0;
1354 	/* Choose the copy that is on our node */
1355 	curcpu = smp_processor_id();
1356 	loc_cpu_entry = private->entries[curcpu];
1357 	addend = xt_write_recseq_begin();
1358 	xt_entry_foreach(iter, loc_cpu_entry, private->size) {
1359 		ADD_COUNTER(iter->counters, paddc[i].bcnt, paddc[i].pcnt);
1360 		++i;
1361 	}
1362 	xt_write_recseq_end(addend);
1363  unlock_up_free:
1364 	local_bh_enable();
1365 	xt_table_unlock(t);
1366 	module_put(t->me);
1367  free:
1368 	vfree(paddc);
1369 
1370 	return ret;
1371 }
1372 
1373 #ifdef CONFIG_COMPAT
1374 struct compat_ipt_replace {
1375 	char			name[XT_TABLE_MAXNAMELEN];
1376 	u32			valid_hooks;
1377 	u32			num_entries;
1378 	u32			size;
1379 	u32			hook_entry[NF_INET_NUMHOOKS];
1380 	u32			underflow[NF_INET_NUMHOOKS];
1381 	u32			num_counters;
1382 	compat_uptr_t		counters;	/* struct xt_counters * */
1383 	struct compat_ipt_entry	entries[0];
1384 };
1385 
1386 static int
compat_copy_entry_to_user(struct ipt_entry * e,void __user ** dstptr,unsigned int * size,struct xt_counters * counters,unsigned int i)1387 compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr,
1388 			  unsigned int *size, struct xt_counters *counters,
1389 			  unsigned int i)
1390 {
1391 	struct xt_entry_target *t;
1392 	struct compat_ipt_entry __user *ce;
1393 	u_int16_t target_offset, next_offset;
1394 	compat_uint_t origsize;
1395 	const struct xt_entry_match *ematch;
1396 	int ret = 0;
1397 
1398 	origsize = *size;
1399 	ce = (struct compat_ipt_entry __user *)*dstptr;
1400 	if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 ||
1401 	    copy_to_user(&ce->counters, &counters[i],
1402 	    sizeof(counters[i])) != 0)
1403 		return -EFAULT;
1404 
1405 	*dstptr += sizeof(struct compat_ipt_entry);
1406 	*size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1407 
1408 	xt_ematch_foreach(ematch, e) {
1409 		ret = xt_compat_match_to_user(ematch, dstptr, size);
1410 		if (ret != 0)
1411 			return ret;
1412 	}
1413 	target_offset = e->target_offset - (origsize - *size);
1414 	t = ipt_get_target(e);
1415 	ret = xt_compat_target_to_user(t, dstptr, size);
1416 	if (ret)
1417 		return ret;
1418 	next_offset = e->next_offset - (origsize - *size);
1419 	if (put_user(target_offset, &ce->target_offset) != 0 ||
1420 	    put_user(next_offset, &ce->next_offset) != 0)
1421 		return -EFAULT;
1422 	return 0;
1423 }
1424 
1425 static int
compat_find_calc_match(struct xt_entry_match * m,const struct ipt_ip * ip,unsigned int hookmask,int * size)1426 compat_find_calc_match(struct xt_entry_match *m,
1427 		       const struct ipt_ip *ip,
1428 		       unsigned int hookmask,
1429 		       int *size)
1430 {
1431 	struct xt_match *match;
1432 
1433 	match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
1434 				      m->u.user.revision);
1435 	if (IS_ERR(match)) {
1436 		duprintf("compat_check_calc_match: `%s' not found\n",
1437 			 m->u.user.name);
1438 		return PTR_ERR(match);
1439 	}
1440 	m->u.kernel.match = match;
1441 	*size += xt_compat_match_offset(match);
1442 	return 0;
1443 }
1444 
compat_release_entry(struct compat_ipt_entry * e)1445 static void compat_release_entry(struct compat_ipt_entry *e)
1446 {
1447 	struct xt_entry_target *t;
1448 	struct xt_entry_match *ematch;
1449 
1450 	/* Cleanup all matches */
1451 	xt_ematch_foreach(ematch, e)
1452 		module_put(ematch->u.kernel.match->me);
1453 	t = compat_ipt_get_target(e);
1454 	module_put(t->u.kernel.target->me);
1455 }
1456 
1457 static int
check_compat_entry_size_and_hooks(struct compat_ipt_entry * e,struct xt_table_info * newinfo,unsigned int * size,const unsigned char * base,const unsigned char * limit)1458 check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
1459 				  struct xt_table_info *newinfo,
1460 				  unsigned int *size,
1461 				  const unsigned char *base,
1462 				  const unsigned char *limit)
1463 {
1464 	struct xt_entry_match *ematch;
1465 	struct xt_entry_target *t;
1466 	struct xt_target *target;
1467 	unsigned int entry_offset;
1468 	unsigned int j;
1469 	int ret, off;
1470 
1471 	duprintf("check_compat_entry_size_and_hooks %p\n", e);
1472 	if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
1473 	    (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
1474 	    (unsigned char *)e + e->next_offset > limit) {
1475 		duprintf("Bad offset %p, limit = %p\n", e, limit);
1476 		return -EINVAL;
1477 	}
1478 
1479 	if (e->next_offset < sizeof(struct compat_ipt_entry) +
1480 			     sizeof(struct compat_xt_entry_target)) {
1481 		duprintf("checking: element %p size %u\n",
1482 			 e, e->next_offset);
1483 		return -EINVAL;
1484 	}
1485 
1486 	/* For purposes of check_entry casting the compat entry is fine */
1487 	ret = check_entry((struct ipt_entry *)e);
1488 	if (ret)
1489 		return ret;
1490 
1491 	off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1492 	entry_offset = (void *)e - (void *)base;
1493 	j = 0;
1494 	xt_ematch_foreach(ematch, e) {
1495 		ret = compat_find_calc_match(ematch, &e->ip, e->comefrom,
1496 					     &off);
1497 		if (ret != 0)
1498 			goto release_matches;
1499 		++j;
1500 	}
1501 
1502 	t = compat_ipt_get_target(e);
1503 	target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
1504 					t->u.user.revision);
1505 	if (IS_ERR(target)) {
1506 		duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
1507 			 t->u.user.name);
1508 		ret = PTR_ERR(target);
1509 		goto release_matches;
1510 	}
1511 	t->u.kernel.target = target;
1512 
1513 	off += xt_compat_target_offset(target);
1514 	*size += off;
1515 	ret = xt_compat_add_offset(AF_INET, entry_offset, off);
1516 	if (ret)
1517 		goto out;
1518 
1519 	return 0;
1520 
1521 out:
1522 	module_put(t->u.kernel.target->me);
1523 release_matches:
1524 	xt_ematch_foreach(ematch, e) {
1525 		if (j-- == 0)
1526 			break;
1527 		module_put(ematch->u.kernel.match->me);
1528 	}
1529 	return ret;
1530 }
1531 
1532 static void
compat_copy_entry_from_user(struct compat_ipt_entry * e,void ** dstptr,unsigned int * size,struct xt_table_info * newinfo,unsigned char * base)1533 compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr,
1534 			    unsigned int *size,
1535 			    struct xt_table_info *newinfo, unsigned char *base)
1536 {
1537 	struct xt_entry_target *t;
1538 	struct xt_target *target;
1539 	struct ipt_entry *de;
1540 	unsigned int origsize;
1541 	int h;
1542 	struct xt_entry_match *ematch;
1543 
1544 	origsize = *size;
1545 	de = (struct ipt_entry *)*dstptr;
1546 	memcpy(de, e, sizeof(struct ipt_entry));
1547 	memcpy(&de->counters, &e->counters, sizeof(e->counters));
1548 
1549 	*dstptr += sizeof(struct ipt_entry);
1550 	*size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1551 
1552 	xt_ematch_foreach(ematch, e)
1553 		xt_compat_match_from_user(ematch, dstptr, size);
1554 
1555 	de->target_offset = e->target_offset - (origsize - *size);
1556 	t = compat_ipt_get_target(e);
1557 	target = t->u.kernel.target;
1558 	xt_compat_target_from_user(t, dstptr, size);
1559 
1560 	de->next_offset = e->next_offset - (origsize - *size);
1561 
1562 	for (h = 0; h < NF_INET_NUMHOOKS; h++) {
1563 		if ((unsigned char *)de - base < newinfo->hook_entry[h])
1564 			newinfo->hook_entry[h] -= origsize - *size;
1565 		if ((unsigned char *)de - base < newinfo->underflow[h])
1566 			newinfo->underflow[h] -= origsize - *size;
1567 	}
1568 }
1569 
1570 static int
translate_compat_table(struct net * net,struct xt_table_info ** pinfo,void ** pentry0,const struct compat_ipt_replace * compatr)1571 translate_compat_table(struct net *net,
1572 		       struct xt_table_info **pinfo,
1573 		       void **pentry0,
1574 		       const struct compat_ipt_replace *compatr)
1575 {
1576 	unsigned int i, j;
1577 	struct xt_table_info *newinfo, *info;
1578 	void *pos, *entry0, *entry1;
1579 	struct compat_ipt_entry *iter0;
1580 	struct ipt_replace repl;
1581 	unsigned int size;
1582 	int ret;
1583 
1584 	info = *pinfo;
1585 	entry0 = *pentry0;
1586 	size = compatr->size;
1587 	info->number = compatr->num_entries;
1588 
1589 	duprintf("translate_compat_table: size %u\n", info->size);
1590 	j = 0;
1591 	xt_compat_lock(AF_INET);
1592 	xt_compat_init_offsets(AF_INET, compatr->num_entries);
1593 	/* Walk through entries, checking offsets. */
1594 	xt_entry_foreach(iter0, entry0, compatr->size) {
1595 		ret = check_compat_entry_size_and_hooks(iter0, info, &size,
1596 							entry0,
1597 							entry0 + compatr->size);
1598 		if (ret != 0)
1599 			goto out_unlock;
1600 		++j;
1601 	}
1602 
1603 	ret = -EINVAL;
1604 	if (j != compatr->num_entries) {
1605 		duprintf("translate_compat_table: %u not %u entries\n",
1606 			 j, compatr->num_entries);
1607 		goto out_unlock;
1608 	}
1609 
1610 	ret = -ENOMEM;
1611 	newinfo = xt_alloc_table_info(size);
1612 	if (!newinfo)
1613 		goto out_unlock;
1614 
1615 	newinfo->number = compatr->num_entries;
1616 	for (i = 0; i < NF_INET_NUMHOOKS; i++) {
1617 		newinfo->hook_entry[i] = compatr->hook_entry[i];
1618 		newinfo->underflow[i] = compatr->underflow[i];
1619 	}
1620 	entry1 = newinfo->entries[raw_smp_processor_id()];
1621 	pos = entry1;
1622 	size = compatr->size;
1623 	xt_entry_foreach(iter0, entry0, compatr->size)
1624 		compat_copy_entry_from_user(iter0, &pos, &size,
1625 					    newinfo, entry1);
1626 
1627 	/* all module references in entry0 are now gone.
1628 	 * entry1/newinfo contains a 64bit ruleset that looks exactly as
1629 	 * generated by 64bit userspace.
1630 	 *
1631 	 * Call standard translate_table() to validate all hook_entrys,
1632 	 * underflows, check for loops, etc.
1633 	 */
1634 	xt_compat_flush_offsets(AF_INET);
1635 	xt_compat_unlock(AF_INET);
1636 
1637 	memcpy(&repl, compatr, sizeof(*compatr));
1638 
1639 	for (i = 0; i < NF_INET_NUMHOOKS; i++) {
1640 		repl.hook_entry[i] = newinfo->hook_entry[i];
1641 		repl.underflow[i] = newinfo->underflow[i];
1642 	}
1643 
1644 	repl.num_counters = 0;
1645 	repl.counters = NULL;
1646 	repl.size = newinfo->size;
1647 	ret = translate_table(net, newinfo, entry1, &repl);
1648 	if (ret)
1649 		goto free_newinfo;
1650 
1651 	*pinfo = newinfo;
1652 	*pentry0 = entry1;
1653 	xt_free_table_info(info);
1654 	return 0;
1655 
1656 free_newinfo:
1657 	xt_free_table_info(newinfo);
1658 	return ret;
1659 out_unlock:
1660 	xt_compat_flush_offsets(AF_INET);
1661 	xt_compat_unlock(AF_INET);
1662 	xt_entry_foreach(iter0, entry0, compatr->size) {
1663 		if (j-- == 0)
1664 			break;
1665 		compat_release_entry(iter0);
1666 	}
1667 	return ret;
1668 }
1669 
1670 static int
compat_do_replace(struct net * net,void __user * user,unsigned int len)1671 compat_do_replace(struct net *net, void __user *user, unsigned int len)
1672 {
1673 	int ret;
1674 	struct compat_ipt_replace tmp;
1675 	struct xt_table_info *newinfo;
1676 	void *loc_cpu_entry;
1677 	struct ipt_entry *iter;
1678 
1679 	if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
1680 		return -EFAULT;
1681 
1682 	/* overflow check */
1683 	if (tmp.size >= INT_MAX / num_possible_cpus())
1684 		return -ENOMEM;
1685 	if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
1686 		return -ENOMEM;
1687 	tmp.name[sizeof(tmp.name)-1] = 0;
1688 
1689 	newinfo = xt_alloc_table_info(tmp.size);
1690 	if (!newinfo)
1691 		return -ENOMEM;
1692 
1693 	/* choose the copy that is on our node/cpu */
1694 	loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
1695 	if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
1696 			   tmp.size) != 0) {
1697 		ret = -EFAULT;
1698 		goto free_newinfo;
1699 	}
1700 
1701 	ret = translate_compat_table(net, &newinfo, &loc_cpu_entry, &tmp);
1702 	if (ret != 0)
1703 		goto free_newinfo;
1704 
1705 	duprintf("compat_do_replace: Translated table\n");
1706 
1707 	ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
1708 			   tmp.num_counters, compat_ptr(tmp.counters));
1709 	if (ret)
1710 		goto free_newinfo_untrans;
1711 	return 0;
1712 
1713  free_newinfo_untrans:
1714 	xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
1715 		cleanup_entry(iter, net);
1716  free_newinfo:
1717 	xt_free_table_info(newinfo);
1718 	return ret;
1719 }
1720 
1721 static int
compat_do_ipt_set_ctl(struct sock * sk,int cmd,void __user * user,unsigned int len)1722 compat_do_ipt_set_ctl(struct sock *sk,	int cmd, void __user *user,
1723 		      unsigned int len)
1724 {
1725 	int ret;
1726 
1727 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1728 		return -EPERM;
1729 
1730 	switch (cmd) {
1731 	case IPT_SO_SET_REPLACE:
1732 		ret = compat_do_replace(sock_net(sk), user, len);
1733 		break;
1734 
1735 	case IPT_SO_SET_ADD_COUNTERS:
1736 		ret = do_add_counters(sock_net(sk), user, len, 1);
1737 		break;
1738 
1739 	default:
1740 		duprintf("do_ipt_set_ctl:  unknown request %i\n", cmd);
1741 		ret = -EINVAL;
1742 	}
1743 
1744 	return ret;
1745 }
1746 
1747 struct compat_ipt_get_entries {
1748 	char name[XT_TABLE_MAXNAMELEN];
1749 	compat_uint_t size;
1750 	struct compat_ipt_entry entrytable[0];
1751 };
1752 
1753 static int
compat_copy_entries_to_user(unsigned int total_size,struct xt_table * table,void __user * userptr)1754 compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
1755 			    void __user *userptr)
1756 {
1757 	struct xt_counters *counters;
1758 	const struct xt_table_info *private = table->private;
1759 	void __user *pos;
1760 	unsigned int size;
1761 	int ret = 0;
1762 	const void *loc_cpu_entry;
1763 	unsigned int i = 0;
1764 	struct ipt_entry *iter;
1765 
1766 	counters = alloc_counters(table);
1767 	if (IS_ERR(counters))
1768 		return PTR_ERR(counters);
1769 
1770 	/* choose the copy that is on our node/cpu, ...
1771 	 * This choice is lazy (because current thread is
1772 	 * allowed to migrate to another cpu)
1773 	 */
1774 	loc_cpu_entry = private->entries[raw_smp_processor_id()];
1775 	pos = userptr;
1776 	size = total_size;
1777 	xt_entry_foreach(iter, loc_cpu_entry, total_size) {
1778 		ret = compat_copy_entry_to_user(iter, &pos,
1779 						&size, counters, i++);
1780 		if (ret != 0)
1781 			break;
1782 	}
1783 
1784 	vfree(counters);
1785 	return ret;
1786 }
1787 
1788 static int
compat_get_entries(struct net * net,struct compat_ipt_get_entries __user * uptr,int * len)1789 compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr,
1790 		   int *len)
1791 {
1792 	int ret;
1793 	struct compat_ipt_get_entries get;
1794 	struct xt_table *t;
1795 
1796 	if (*len < sizeof(get)) {
1797 		duprintf("compat_get_entries: %u < %zu\n", *len, sizeof(get));
1798 		return -EINVAL;
1799 	}
1800 
1801 	if (copy_from_user(&get, uptr, sizeof(get)) != 0)
1802 		return -EFAULT;
1803 
1804 	if (*len != sizeof(struct compat_ipt_get_entries) + get.size) {
1805 		duprintf("compat_get_entries: %u != %zu\n",
1806 			 *len, sizeof(get) + get.size);
1807 		return -EINVAL;
1808 	}
1809 
1810 	xt_compat_lock(AF_INET);
1811 	t = xt_find_table_lock(net, AF_INET, get.name);
1812 	if (!IS_ERR_OR_NULL(t)) {
1813 		const struct xt_table_info *private = t->private;
1814 		struct xt_table_info info;
1815 		duprintf("t->private->number = %u\n", private->number);
1816 		ret = compat_table_info(private, &info);
1817 		if (!ret && get.size == info.size) {
1818 			ret = compat_copy_entries_to_user(private->size,
1819 							  t, uptr->entrytable);
1820 		} else if (!ret) {
1821 			duprintf("compat_get_entries: I've got %u not %u!\n",
1822 				 private->size, get.size);
1823 			ret = -EAGAIN;
1824 		}
1825 		xt_compat_flush_offsets(AF_INET);
1826 		module_put(t->me);
1827 		xt_table_unlock(t);
1828 	} else
1829 		ret = t ? PTR_ERR(t) : -ENOENT;
1830 
1831 	xt_compat_unlock(AF_INET);
1832 	return ret;
1833 }
1834 
1835 static int do_ipt_get_ctl(struct sock *, int, void __user *, int *);
1836 
1837 static int
compat_do_ipt_get_ctl(struct sock * sk,int cmd,void __user * user,int * len)1838 compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
1839 {
1840 	int ret;
1841 
1842 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1843 		return -EPERM;
1844 
1845 	switch (cmd) {
1846 	case IPT_SO_GET_INFO:
1847 		ret = get_info(sock_net(sk), user, len, 1);
1848 		break;
1849 	case IPT_SO_GET_ENTRIES:
1850 		ret = compat_get_entries(sock_net(sk), user, len);
1851 		break;
1852 	default:
1853 		ret = do_ipt_get_ctl(sk, cmd, user, len);
1854 	}
1855 	return ret;
1856 }
1857 #endif
1858 
1859 static int
do_ipt_set_ctl(struct sock * sk,int cmd,void __user * user,unsigned int len)1860 do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
1861 {
1862 	int ret;
1863 
1864 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1865 		return -EPERM;
1866 
1867 	switch (cmd) {
1868 	case IPT_SO_SET_REPLACE:
1869 		ret = do_replace(sock_net(sk), user, len);
1870 		break;
1871 
1872 	case IPT_SO_SET_ADD_COUNTERS:
1873 		ret = do_add_counters(sock_net(sk), user, len, 0);
1874 		break;
1875 
1876 	default:
1877 		duprintf("do_ipt_set_ctl:  unknown request %i\n", cmd);
1878 		ret = -EINVAL;
1879 	}
1880 
1881 	return ret;
1882 }
1883 
1884 static int
do_ipt_get_ctl(struct sock * sk,int cmd,void __user * user,int * len)1885 do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
1886 {
1887 	int ret;
1888 
1889 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1890 		return -EPERM;
1891 
1892 	switch (cmd) {
1893 	case IPT_SO_GET_INFO:
1894 		ret = get_info(sock_net(sk), user, len, 0);
1895 		break;
1896 
1897 	case IPT_SO_GET_ENTRIES:
1898 		ret = get_entries(sock_net(sk), user, len);
1899 		break;
1900 
1901 	case IPT_SO_GET_REVISION_MATCH:
1902 	case IPT_SO_GET_REVISION_TARGET: {
1903 		struct xt_get_revision rev;
1904 		int target;
1905 
1906 		if (*len != sizeof(rev)) {
1907 			ret = -EINVAL;
1908 			break;
1909 		}
1910 		if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
1911 			ret = -EFAULT;
1912 			break;
1913 		}
1914 		rev.name[sizeof(rev.name)-1] = 0;
1915 
1916 		if (cmd == IPT_SO_GET_REVISION_TARGET)
1917 			target = 1;
1918 		else
1919 			target = 0;
1920 
1921 		try_then_request_module(xt_find_revision(AF_INET, rev.name,
1922 							 rev.revision,
1923 							 target, &ret),
1924 					"ipt_%s", rev.name);
1925 		break;
1926 	}
1927 
1928 	default:
1929 		duprintf("do_ipt_get_ctl: unknown request %i\n", cmd);
1930 		ret = -EINVAL;
1931 	}
1932 
1933 	return ret;
1934 }
1935 
ipt_register_table(struct net * net,const struct xt_table * table,const struct ipt_replace * repl)1936 struct xt_table *ipt_register_table(struct net *net,
1937 				    const struct xt_table *table,
1938 				    const struct ipt_replace *repl)
1939 {
1940 	int ret;
1941 	struct xt_table_info *newinfo;
1942 	struct xt_table_info bootstrap = {0};
1943 	void *loc_cpu_entry;
1944 	struct xt_table *new_table;
1945 
1946 	newinfo = xt_alloc_table_info(repl->size);
1947 	if (!newinfo) {
1948 		ret = -ENOMEM;
1949 		goto out;
1950 	}
1951 
1952 	/* choose the copy on our node/cpu, but dont care about preemption */
1953 	loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
1954 	memcpy(loc_cpu_entry, repl->entries, repl->size);
1955 
1956 	ret = translate_table(net, newinfo, loc_cpu_entry, repl);
1957 	if (ret != 0)
1958 		goto out_free;
1959 
1960 	new_table = xt_register_table(net, table, &bootstrap, newinfo);
1961 	if (IS_ERR(new_table)) {
1962 		ret = PTR_ERR(new_table);
1963 		goto out_free;
1964 	}
1965 
1966 	return new_table;
1967 
1968 out_free:
1969 	xt_free_table_info(newinfo);
1970 out:
1971 	return ERR_PTR(ret);
1972 }
1973 
ipt_unregister_table(struct net * net,struct xt_table * table)1974 void ipt_unregister_table(struct net *net, struct xt_table *table)
1975 {
1976 	struct xt_table_info *private;
1977 	void *loc_cpu_entry;
1978 	struct module *table_owner = table->me;
1979 	struct ipt_entry *iter;
1980 
1981 	private = xt_unregister_table(table);
1982 
1983 	/* Decrease module usage counts and free resources */
1984 	loc_cpu_entry = private->entries[raw_smp_processor_id()];
1985 	xt_entry_foreach(iter, loc_cpu_entry, private->size)
1986 		cleanup_entry(iter, net);
1987 	if (private->number > private->initial_entries)
1988 		module_put(table_owner);
1989 	xt_free_table_info(private);
1990 }
1991 
1992 /* Returns 1 if the type and code is matched by the range, 0 otherwise */
1993 static inline bool
icmp_type_code_match(u_int8_t test_type,u_int8_t min_code,u_int8_t max_code,u_int8_t type,u_int8_t code,bool invert)1994 icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
1995 		     u_int8_t type, u_int8_t code,
1996 		     bool invert)
1997 {
1998 	return ((test_type == 0xFF) ||
1999 		(type == test_type && code >= min_code && code <= max_code))
2000 		^ invert;
2001 }
2002 
2003 static bool
icmp_match(const struct sk_buff * skb,struct xt_action_param * par)2004 icmp_match(const struct sk_buff *skb, struct xt_action_param *par)
2005 {
2006 	const struct icmphdr *ic;
2007 	struct icmphdr _icmph;
2008 	const struct ipt_icmp *icmpinfo = par->matchinfo;
2009 
2010 	/* Must not be a fragment. */
2011 	if (par->fragoff != 0)
2012 		return false;
2013 
2014 	ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
2015 	if (ic == NULL) {
2016 		/* We've been asked to examine this packet, and we
2017 		 * can't.  Hence, no choice but to drop.
2018 		 */
2019 		duprintf("Dropping evil ICMP tinygram.\n");
2020 		par->hotdrop = true;
2021 		return false;
2022 	}
2023 
2024 	return icmp_type_code_match(icmpinfo->type,
2025 				    icmpinfo->code[0],
2026 				    icmpinfo->code[1],
2027 				    ic->type, ic->code,
2028 				    !!(icmpinfo->invflags&IPT_ICMP_INV));
2029 }
2030 
icmp_checkentry(const struct xt_mtchk_param * par)2031 static int icmp_checkentry(const struct xt_mtchk_param *par)
2032 {
2033 	const struct ipt_icmp *icmpinfo = par->matchinfo;
2034 
2035 	/* Must specify no unknown invflags */
2036 	return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0;
2037 }
2038 
2039 static struct xt_target ipt_builtin_tg[] __read_mostly = {
2040 	{
2041 		.name             = XT_STANDARD_TARGET,
2042 		.targetsize       = sizeof(int),
2043 		.family           = NFPROTO_IPV4,
2044 #ifdef CONFIG_COMPAT
2045 		.compatsize       = sizeof(compat_int_t),
2046 		.compat_from_user = compat_standard_from_user,
2047 		.compat_to_user   = compat_standard_to_user,
2048 #endif
2049 	},
2050 	{
2051 		.name             = XT_ERROR_TARGET,
2052 		.target           = ipt_error,
2053 		.targetsize       = XT_FUNCTION_MAXNAMELEN,
2054 		.family           = NFPROTO_IPV4,
2055 	},
2056 };
2057 
2058 static struct nf_sockopt_ops ipt_sockopts = {
2059 	.pf		= PF_INET,
2060 	.set_optmin	= IPT_BASE_CTL,
2061 	.set_optmax	= IPT_SO_SET_MAX+1,
2062 	.set		= do_ipt_set_ctl,
2063 #ifdef CONFIG_COMPAT
2064 	.compat_set	= compat_do_ipt_set_ctl,
2065 #endif
2066 	.get_optmin	= IPT_BASE_CTL,
2067 	.get_optmax	= IPT_SO_GET_MAX+1,
2068 	.get		= do_ipt_get_ctl,
2069 #ifdef CONFIG_COMPAT
2070 	.compat_get	= compat_do_ipt_get_ctl,
2071 #endif
2072 	.owner		= THIS_MODULE,
2073 };
2074 
2075 static struct xt_match ipt_builtin_mt[] __read_mostly = {
2076 	{
2077 		.name       = "icmp",
2078 		.match      = icmp_match,
2079 		.matchsize  = sizeof(struct ipt_icmp),
2080 		.checkentry = icmp_checkentry,
2081 		.proto      = IPPROTO_ICMP,
2082 		.family     = NFPROTO_IPV4,
2083 	},
2084 };
2085 
ip_tables_net_init(struct net * net)2086 static int __net_init ip_tables_net_init(struct net *net)
2087 {
2088 	return xt_proto_init(net, NFPROTO_IPV4);
2089 }
2090 
ip_tables_net_exit(struct net * net)2091 static void __net_exit ip_tables_net_exit(struct net *net)
2092 {
2093 	xt_proto_fini(net, NFPROTO_IPV4);
2094 }
2095 
2096 static struct pernet_operations ip_tables_net_ops = {
2097 	.init = ip_tables_net_init,
2098 	.exit = ip_tables_net_exit,
2099 };
2100 
ip_tables_init(void)2101 static int __init ip_tables_init(void)
2102 {
2103 	int ret;
2104 
2105 	ret = register_pernet_subsys(&ip_tables_net_ops);
2106 	if (ret < 0)
2107 		goto err1;
2108 
2109 	/* No one else will be downing sem now, so we won't sleep */
2110 	ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
2111 	if (ret < 0)
2112 		goto err2;
2113 	ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
2114 	if (ret < 0)
2115 		goto err4;
2116 
2117 	/* Register setsockopt */
2118 	ret = nf_register_sockopt(&ipt_sockopts);
2119 	if (ret < 0)
2120 		goto err5;
2121 
2122 	pr_info("(C) 2000-2006 Netfilter Core Team\n");
2123 	return 0;
2124 
2125 err5:
2126 	xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
2127 err4:
2128 	xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
2129 err2:
2130 	unregister_pernet_subsys(&ip_tables_net_ops);
2131 err1:
2132 	return ret;
2133 }
2134 
ip_tables_fini(void)2135 static void __exit ip_tables_fini(void)
2136 {
2137 	nf_unregister_sockopt(&ipt_sockopts);
2138 
2139 	xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
2140 	xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
2141 	unregister_pernet_subsys(&ip_tables_net_ops);
2142 }
2143 
2144 EXPORT_SYMBOL(ipt_register_table);
2145 EXPORT_SYMBOL(ipt_unregister_table);
2146 EXPORT_SYMBOL(ipt_do_table);
2147 module_init(ip_tables_init);
2148 module_exit(ip_tables_fini);
2149