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