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