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