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