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