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