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