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