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