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