Linux-libre 4.4.228-gnu
[librecmc/linux-libre.git] / net / netfilter / x_tables.c
1 /*
2  * x_tables core - Backend for {ip,ip6,arp}_tables
3  *
4  * Copyright (C) 2006-2006 Harald Welte <laforge@netfilter.org>
5  * Copyright (C) 2006-2012 Patrick McHardy <kaber@trash.net>
6  *
7  * Based on existing ip_tables code which is
8  *   Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
9  *   Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2 as
13  * published by the Free Software Foundation.
14  *
15  */
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/socket.h>
20 #include <linux/net.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/string.h>
24 #include <linux/vmalloc.h>
25 #include <linux/mutex.h>
26 #include <linux/mm.h>
27 #include <linux/slab.h>
28 #include <linux/audit.h>
29 #include <net/net_namespace.h>
30
31 #include <linux/netfilter/x_tables.h>
32 #include <linux/netfilter_arp.h>
33 #include <linux/netfilter_ipv4/ip_tables.h>
34 #include <linux/netfilter_ipv6/ip6_tables.h>
35 #include <linux/netfilter_arp/arp_tables.h>
36
37 MODULE_LICENSE("GPL");
38 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
39 MODULE_DESCRIPTION("{ip,ip6,arp,eb}_tables backend module");
40
41 #define XT_PCPU_BLOCK_SIZE 4096
42
43 struct compat_delta {
44         unsigned int offset; /* offset in kernel */
45         int delta; /* delta in 32bit user land */
46 };
47
48 struct xt_af {
49         struct mutex mutex;
50         struct list_head match;
51         struct list_head target;
52 #ifdef CONFIG_COMPAT
53         struct mutex compat_mutex;
54         struct compat_delta *compat_tab;
55         unsigned int number; /* number of slots in compat_tab[] */
56         unsigned int cur; /* number of used slots in compat_tab[] */
57 #endif
58 };
59
60 static struct xt_af *xt;
61
62 static const char *const xt_prefix[NFPROTO_NUMPROTO] = {
63         [NFPROTO_UNSPEC] = "x",
64         [NFPROTO_IPV4]   = "ip",
65         [NFPROTO_ARP]    = "arp",
66         [NFPROTO_BRIDGE] = "eb",
67         [NFPROTO_IPV6]   = "ip6",
68 };
69
70 /* Registration hooks for targets. */
71 int xt_register_target(struct xt_target *target)
72 {
73         u_int8_t af = target->family;
74
75         mutex_lock(&xt[af].mutex);
76         list_add(&target->list, &xt[af].target);
77         mutex_unlock(&xt[af].mutex);
78         return 0;
79 }
80 EXPORT_SYMBOL(xt_register_target);
81
82 void
83 xt_unregister_target(struct xt_target *target)
84 {
85         u_int8_t af = target->family;
86
87         mutex_lock(&xt[af].mutex);
88         list_del(&target->list);
89         mutex_unlock(&xt[af].mutex);
90 }
91 EXPORT_SYMBOL(xt_unregister_target);
92
93 int
94 xt_register_targets(struct xt_target *target, unsigned int n)
95 {
96         unsigned int i;
97         int err = 0;
98
99         for (i = 0; i < n; i++) {
100                 err = xt_register_target(&target[i]);
101                 if (err)
102                         goto err;
103         }
104         return err;
105
106 err:
107         if (i > 0)
108                 xt_unregister_targets(target, i);
109         return err;
110 }
111 EXPORT_SYMBOL(xt_register_targets);
112
113 void
114 xt_unregister_targets(struct xt_target *target, unsigned int n)
115 {
116         while (n-- > 0)
117                 xt_unregister_target(&target[n]);
118 }
119 EXPORT_SYMBOL(xt_unregister_targets);
120
121 int xt_register_match(struct xt_match *match)
122 {
123         u_int8_t af = match->family;
124
125         mutex_lock(&xt[af].mutex);
126         list_add(&match->list, &xt[af].match);
127         mutex_unlock(&xt[af].mutex);
128         return 0;
129 }
130 EXPORT_SYMBOL(xt_register_match);
131
132 void
133 xt_unregister_match(struct xt_match *match)
134 {
135         u_int8_t af = match->family;
136
137         mutex_lock(&xt[af].mutex);
138         list_del(&match->list);
139         mutex_unlock(&xt[af].mutex);
140 }
141 EXPORT_SYMBOL(xt_unregister_match);
142
143 int
144 xt_register_matches(struct xt_match *match, unsigned int n)
145 {
146         unsigned int i;
147         int err = 0;
148
149         for (i = 0; i < n; i++) {
150                 err = xt_register_match(&match[i]);
151                 if (err)
152                         goto err;
153         }
154         return err;
155
156 err:
157         if (i > 0)
158                 xt_unregister_matches(match, i);
159         return err;
160 }
161 EXPORT_SYMBOL(xt_register_matches);
162
163 void
164 xt_unregister_matches(struct xt_match *match, unsigned int n)
165 {
166         while (n-- > 0)
167                 xt_unregister_match(&match[n]);
168 }
169 EXPORT_SYMBOL(xt_unregister_matches);
170
171
172 /*
173  * These are weird, but module loading must not be done with mutex
174  * held (since they will register), and we have to have a single
175  * function to use.
176  */
177
178 /* Find match, grabs ref.  Returns ERR_PTR() on error. */
179 struct xt_match *xt_find_match(u8 af, const char *name, u8 revision)
180 {
181         struct xt_match *m;
182         int err = -ENOENT;
183
184         mutex_lock(&xt[af].mutex);
185         list_for_each_entry(m, &xt[af].match, list) {
186                 if (strcmp(m->name, name) == 0) {
187                         if (m->revision == revision) {
188                                 if (try_module_get(m->me)) {
189                                         mutex_unlock(&xt[af].mutex);
190                                         return m;
191                                 }
192                         } else
193                                 err = -EPROTOTYPE; /* Found something. */
194                 }
195         }
196         mutex_unlock(&xt[af].mutex);
197
198         if (af != NFPROTO_UNSPEC)
199                 /* Try searching again in the family-independent list */
200                 return xt_find_match(NFPROTO_UNSPEC, name, revision);
201
202         return ERR_PTR(err);
203 }
204 EXPORT_SYMBOL(xt_find_match);
205
206 struct xt_match *
207 xt_request_find_match(uint8_t nfproto, const char *name, uint8_t revision)
208 {
209         struct xt_match *match;
210
211         if (strnlen(name, XT_EXTENSION_MAXNAMELEN) == XT_EXTENSION_MAXNAMELEN)
212                 return ERR_PTR(-EINVAL);
213
214         match = xt_find_match(nfproto, name, revision);
215         if (IS_ERR(match)) {
216                 request_module("%st_%s", xt_prefix[nfproto], name);
217                 match = xt_find_match(nfproto, name, revision);
218         }
219
220         return match;
221 }
222 EXPORT_SYMBOL_GPL(xt_request_find_match);
223
224 /* Find target, grabs ref.  Returns ERR_PTR() on error. */
225 struct xt_target *xt_find_target(u8 af, const char *name, u8 revision)
226 {
227         struct xt_target *t;
228         int err = -ENOENT;
229
230         mutex_lock(&xt[af].mutex);
231         list_for_each_entry(t, &xt[af].target, list) {
232                 if (strcmp(t->name, name) == 0) {
233                         if (t->revision == revision) {
234                                 if (try_module_get(t->me)) {
235                                         mutex_unlock(&xt[af].mutex);
236                                         return t;
237                                 }
238                         } else
239                                 err = -EPROTOTYPE; /* Found something. */
240                 }
241         }
242         mutex_unlock(&xt[af].mutex);
243
244         if (af != NFPROTO_UNSPEC)
245                 /* Try searching again in the family-independent list */
246                 return xt_find_target(NFPROTO_UNSPEC, name, revision);
247
248         return ERR_PTR(err);
249 }
250 EXPORT_SYMBOL(xt_find_target);
251
252 struct xt_target *xt_request_find_target(u8 af, const char *name, u8 revision)
253 {
254         struct xt_target *target;
255
256         if (strnlen(name, XT_EXTENSION_MAXNAMELEN) == XT_EXTENSION_MAXNAMELEN)
257                 return ERR_PTR(-EINVAL);
258
259         target = xt_find_target(af, name, revision);
260         if (IS_ERR(target)) {
261                 request_module("%st_%s", xt_prefix[af], name);
262                 target = xt_find_target(af, name, revision);
263         }
264
265         return target;
266 }
267 EXPORT_SYMBOL_GPL(xt_request_find_target);
268
269 static int match_revfn(u8 af, const char *name, u8 revision, int *bestp)
270 {
271         const struct xt_match *m;
272         int have_rev = 0;
273
274         list_for_each_entry(m, &xt[af].match, list) {
275                 if (strcmp(m->name, name) == 0) {
276                         if (m->revision > *bestp)
277                                 *bestp = m->revision;
278                         if (m->revision == revision)
279                                 have_rev = 1;
280                 }
281         }
282
283         if (af != NFPROTO_UNSPEC && !have_rev)
284                 return match_revfn(NFPROTO_UNSPEC, name, revision, bestp);
285
286         return have_rev;
287 }
288
289 static int target_revfn(u8 af, const char *name, u8 revision, int *bestp)
290 {
291         const struct xt_target *t;
292         int have_rev = 0;
293
294         list_for_each_entry(t, &xt[af].target, list) {
295                 if (strcmp(t->name, name) == 0) {
296                         if (t->revision > *bestp)
297                                 *bestp = t->revision;
298                         if (t->revision == revision)
299                                 have_rev = 1;
300                 }
301         }
302
303         if (af != NFPROTO_UNSPEC && !have_rev)
304                 return target_revfn(NFPROTO_UNSPEC, name, revision, bestp);
305
306         return have_rev;
307 }
308
309 /* Returns true or false (if no such extension at all) */
310 int xt_find_revision(u8 af, const char *name, u8 revision, int target,
311                      int *err)
312 {
313         int have_rev, best = -1;
314
315         mutex_lock(&xt[af].mutex);
316         if (target == 1)
317                 have_rev = target_revfn(af, name, revision, &best);
318         else
319                 have_rev = match_revfn(af, name, revision, &best);
320         mutex_unlock(&xt[af].mutex);
321
322         /* Nothing at all?  Return 0 to try loading module. */
323         if (best == -1) {
324                 *err = -ENOENT;
325                 return 0;
326         }
327
328         *err = best;
329         if (!have_rev)
330                 *err = -EPROTONOSUPPORT;
331         return 1;
332 }
333 EXPORT_SYMBOL_GPL(xt_find_revision);
334
335 static char *
336 textify_hooks(char *buf, size_t size, unsigned int mask, uint8_t nfproto)
337 {
338         static const char *const inetbr_names[] = {
339                 "PREROUTING", "INPUT", "FORWARD",
340                 "OUTPUT", "POSTROUTING", "BROUTING",
341         };
342         static const char *const arp_names[] = {
343                 "INPUT", "FORWARD", "OUTPUT",
344         };
345         const char *const *names;
346         unsigned int i, max;
347         char *p = buf;
348         bool np = false;
349         int res;
350
351         names = (nfproto == NFPROTO_ARP) ? arp_names : inetbr_names;
352         max   = (nfproto == NFPROTO_ARP) ? ARRAY_SIZE(arp_names) :
353                                            ARRAY_SIZE(inetbr_names);
354         *p = '\0';
355         for (i = 0; i < max; ++i) {
356                 if (!(mask & (1 << i)))
357                         continue;
358                 res = snprintf(p, size, "%s%s", np ? "/" : "", names[i]);
359                 if (res > 0) {
360                         size -= res;
361                         p += res;
362                 }
363                 np = true;
364         }
365
366         return buf;
367 }
368
369 /**
370  * xt_check_proc_name - check that name is suitable for /proc file creation
371  *
372  * @name: file name candidate
373  * @size: length of buffer
374  *
375  * some x_tables modules wish to create a file in /proc.
376  * This function makes sure that the name is suitable for this
377  * purpose, it checks that name is NUL terminated and isn't a 'special'
378  * name, like "..".
379  *
380  * returns negative number on error or 0 if name is useable.
381  */
382 int xt_check_proc_name(const char *name, unsigned int size)
383 {
384         if (name[0] == '\0')
385                 return -EINVAL;
386
387         if (strnlen(name, size) == size)
388                 return -ENAMETOOLONG;
389
390         if (strcmp(name, ".") == 0 ||
391             strcmp(name, "..") == 0 ||
392             strchr(name, '/'))
393                 return -EINVAL;
394
395         return 0;
396 }
397 EXPORT_SYMBOL(xt_check_proc_name);
398
399 int xt_check_match(struct xt_mtchk_param *par,
400                    unsigned int size, u_int8_t proto, bool inv_proto)
401 {
402         int ret;
403
404         if (XT_ALIGN(par->match->matchsize) != size &&
405             par->match->matchsize != -1) {
406                 /*
407                  * ebt_among is exempt from centralized matchsize checking
408                  * because it uses a dynamic-size data set.
409                  */
410                 pr_err("%s_tables: %s.%u match: invalid size "
411                        "%u (kernel) != (user) %u\n",
412                        xt_prefix[par->family], par->match->name,
413                        par->match->revision,
414                        XT_ALIGN(par->match->matchsize), size);
415                 return -EINVAL;
416         }
417         if (par->match->table != NULL &&
418             strcmp(par->match->table, par->table) != 0) {
419                 pr_err("%s_tables: %s match: only valid in %s table, not %s\n",
420                        xt_prefix[par->family], par->match->name,
421                        par->match->table, par->table);
422                 return -EINVAL;
423         }
424         if (par->match->hooks && (par->hook_mask & ~par->match->hooks) != 0) {
425                 char used[64], allow[64];
426
427                 pr_err("%s_tables: %s match: used from hooks %s, but only "
428                        "valid from %s\n",
429                        xt_prefix[par->family], par->match->name,
430                        textify_hooks(used, sizeof(used), par->hook_mask,
431                                      par->family),
432                        textify_hooks(allow, sizeof(allow), par->match->hooks,
433                                      par->family));
434                 return -EINVAL;
435         }
436         if (par->match->proto && (par->match->proto != proto || inv_proto)) {
437                 pr_err("%s_tables: %s match: only valid for protocol %u\n",
438                        xt_prefix[par->family], par->match->name,
439                        par->match->proto);
440                 return -EINVAL;
441         }
442         if (par->match->checkentry != NULL) {
443                 ret = par->match->checkentry(par);
444                 if (ret < 0)
445                         return ret;
446                 else if (ret > 0)
447                         /* Flag up potential errors. */
448                         return -EIO;
449         }
450         return 0;
451 }
452 EXPORT_SYMBOL_GPL(xt_check_match);
453
454 /** xt_check_entry_match - check that matches end before start of target
455  *
456  * @match: beginning of xt_entry_match
457  * @target: beginning of this rules target (alleged end of matches)
458  * @alignment: alignment requirement of match structures
459  *
460  * Validates that all matches add up to the beginning of the target,
461  * and that each match covers at least the base structure size.
462  *
463  * Return: 0 on success, negative errno on failure.
464  */
465 static int xt_check_entry_match(const char *match, const char *target,
466                                 const size_t alignment)
467 {
468         const struct xt_entry_match *pos;
469         int length = target - match;
470
471         if (length == 0) /* no matches */
472                 return 0;
473
474         pos = (struct xt_entry_match *)match;
475         do {
476                 if ((unsigned long)pos % alignment)
477                         return -EINVAL;
478
479                 if (length < (int)sizeof(struct xt_entry_match))
480                         return -EINVAL;
481
482                 if (pos->u.match_size < sizeof(struct xt_entry_match))
483                         return -EINVAL;
484
485                 if (pos->u.match_size > length)
486                         return -EINVAL;
487
488                 length -= pos->u.match_size;
489                 pos = ((void *)((char *)(pos) + (pos)->u.match_size));
490         } while (length > 0);
491
492         return 0;
493 }
494
495 #ifdef CONFIG_COMPAT
496 int xt_compat_add_offset(u_int8_t af, unsigned int offset, int delta)
497 {
498         struct xt_af *xp = &xt[af];
499
500         if (!xp->compat_tab) {
501                 if (!xp->number)
502                         return -EINVAL;
503                 xp->compat_tab = vmalloc(sizeof(struct compat_delta) * xp->number);
504                 if (!xp->compat_tab)
505                         return -ENOMEM;
506                 xp->cur = 0;
507         }
508
509         if (xp->cur >= xp->number)
510                 return -EINVAL;
511
512         if (xp->cur)
513                 delta += xp->compat_tab[xp->cur - 1].delta;
514         xp->compat_tab[xp->cur].offset = offset;
515         xp->compat_tab[xp->cur].delta = delta;
516         xp->cur++;
517         return 0;
518 }
519 EXPORT_SYMBOL_GPL(xt_compat_add_offset);
520
521 void xt_compat_flush_offsets(u_int8_t af)
522 {
523         if (xt[af].compat_tab) {
524                 vfree(xt[af].compat_tab);
525                 xt[af].compat_tab = NULL;
526                 xt[af].number = 0;
527                 xt[af].cur = 0;
528         }
529 }
530 EXPORT_SYMBOL_GPL(xt_compat_flush_offsets);
531
532 int xt_compat_calc_jump(u_int8_t af, unsigned int offset)
533 {
534         struct compat_delta *tmp = xt[af].compat_tab;
535         int mid, left = 0, right = xt[af].cur - 1;
536
537         while (left <= right) {
538                 mid = (left + right) >> 1;
539                 if (offset > tmp[mid].offset)
540                         left = mid + 1;
541                 else if (offset < tmp[mid].offset)
542                         right = mid - 1;
543                 else
544                         return mid ? tmp[mid - 1].delta : 0;
545         }
546         return left ? tmp[left - 1].delta : 0;
547 }
548 EXPORT_SYMBOL_GPL(xt_compat_calc_jump);
549
550 void xt_compat_init_offsets(u_int8_t af, unsigned int number)
551 {
552         xt[af].number = number;
553         xt[af].cur = 0;
554 }
555 EXPORT_SYMBOL(xt_compat_init_offsets);
556
557 int xt_compat_match_offset(const struct xt_match *match)
558 {
559         u_int16_t csize = match->compatsize ? : match->matchsize;
560         return XT_ALIGN(match->matchsize) - COMPAT_XT_ALIGN(csize);
561 }
562 EXPORT_SYMBOL_GPL(xt_compat_match_offset);
563
564 void xt_compat_match_from_user(struct xt_entry_match *m, void **dstptr,
565                                unsigned int *size)
566 {
567         const struct xt_match *match = m->u.kernel.match;
568         struct compat_xt_entry_match *cm = (struct compat_xt_entry_match *)m;
569         int pad, off = xt_compat_match_offset(match);
570         u_int16_t msize = cm->u.user.match_size;
571         char name[sizeof(m->u.user.name)];
572
573         m = *dstptr;
574         memcpy(m, cm, sizeof(*cm));
575         if (match->compat_from_user)
576                 match->compat_from_user(m->data, cm->data);
577         else
578                 memcpy(m->data, cm->data, msize - sizeof(*cm));
579         pad = XT_ALIGN(match->matchsize) - match->matchsize;
580         if (pad > 0)
581                 memset(m->data + match->matchsize, 0, pad);
582
583         msize += off;
584         m->u.user.match_size = msize;
585         strlcpy(name, match->name, sizeof(name));
586         module_put(match->me);
587         strncpy(m->u.user.name, name, sizeof(m->u.user.name));
588
589         *size += off;
590         *dstptr += msize;
591 }
592 EXPORT_SYMBOL_GPL(xt_compat_match_from_user);
593
594 int xt_compat_match_to_user(const struct xt_entry_match *m,
595                             void __user **dstptr, unsigned int *size)
596 {
597         const struct xt_match *match = m->u.kernel.match;
598         struct compat_xt_entry_match __user *cm = *dstptr;
599         int off = xt_compat_match_offset(match);
600         u_int16_t msize = m->u.user.match_size - off;
601
602         if (copy_to_user(cm, m, sizeof(*cm)) ||
603             put_user(msize, &cm->u.user.match_size) ||
604             copy_to_user(cm->u.user.name, m->u.kernel.match->name,
605                          strlen(m->u.kernel.match->name) + 1))
606                 return -EFAULT;
607
608         if (match->compat_to_user) {
609                 if (match->compat_to_user((void __user *)cm->data, m->data))
610                         return -EFAULT;
611         } else {
612                 if (copy_to_user(cm->data, m->data, msize - sizeof(*cm)))
613                         return -EFAULT;
614         }
615
616         *size -= off;
617         *dstptr += msize;
618         return 0;
619 }
620 EXPORT_SYMBOL_GPL(xt_compat_match_to_user);
621
622 /* non-compat version may have padding after verdict */
623 struct compat_xt_standard_target {
624         struct compat_xt_entry_target t;
625         compat_uint_t verdict;
626 };
627
628 int xt_compat_check_entry_offsets(const void *base, const char *elems,
629                                   unsigned int target_offset,
630                                   unsigned int next_offset)
631 {
632         long size_of_base_struct = elems - (const char *)base;
633         const struct compat_xt_entry_target *t;
634         const char *e = base;
635
636         if (target_offset < size_of_base_struct)
637                 return -EINVAL;
638
639         if (target_offset + sizeof(*t) > next_offset)
640                 return -EINVAL;
641
642         t = (void *)(e + target_offset);
643         if (t->u.target_size < sizeof(*t))
644                 return -EINVAL;
645
646         if (target_offset + t->u.target_size > next_offset)
647                 return -EINVAL;
648
649         if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
650             COMPAT_XT_ALIGN(target_offset + sizeof(struct compat_xt_standard_target)) != next_offset)
651                 return -EINVAL;
652
653         /* compat_xt_entry match has less strict aligment requirements,
654          * otherwise they are identical.  In case of padding differences
655          * we need to add compat version of xt_check_entry_match.
656          */
657         BUILD_BUG_ON(sizeof(struct compat_xt_entry_match) != sizeof(struct xt_entry_match));
658
659         return xt_check_entry_match(elems, base + target_offset,
660                                     __alignof__(struct compat_xt_entry_match));
661 }
662 EXPORT_SYMBOL(xt_compat_check_entry_offsets);
663 #endif /* CONFIG_COMPAT */
664
665 /**
666  * xt_check_entry_offsets - validate arp/ip/ip6t_entry
667  *
668  * @base: pointer to arp/ip/ip6t_entry
669  * @elems: pointer to first xt_entry_match, i.e. ip(6)t_entry->elems
670  * @target_offset: the arp/ip/ip6_t->target_offset
671  * @next_offset: the arp/ip/ip6_t->next_offset
672  *
673  * validates that target_offset and next_offset are sane and that all
674  * match sizes (if any) align with the target offset.
675  *
676  * This function does not validate the targets or matches themselves, it
677  * only tests that all the offsets and sizes are correct, that all
678  * match structures are aligned, and that the last structure ends where
679  * the target structure begins.
680  *
681  * Also see xt_compat_check_entry_offsets for CONFIG_COMPAT version.
682  *
683  * The arp/ip/ip6t_entry structure @base must have passed following tests:
684  * - it must point to a valid memory location
685  * - base to base + next_offset must be accessible, i.e. not exceed allocated
686  *   length.
687  *
688  * A well-formed entry looks like this:
689  *
690  * ip(6)t_entry   match [mtdata]  match [mtdata] target [tgdata] ip(6)t_entry
691  * e->elems[]-----'                              |               |
692  *                matchsize                      |               |
693  *                                matchsize      |               |
694  *                                               |               |
695  * target_offset---------------------------------'               |
696  * next_offset---------------------------------------------------'
697  *
698  * elems[]: flexible array member at end of ip(6)/arpt_entry struct.
699  *          This is where matches (if any) and the target reside.
700  * target_offset: beginning of target.
701  * next_offset: start of the next rule; also: size of this rule.
702  * Since targets have a minimum size, target_offset + minlen <= next_offset.
703  *
704  * Every match stores its size, sum of sizes must not exceed target_offset.
705  *
706  * Return: 0 on success, negative errno on failure.
707  */
708 int xt_check_entry_offsets(const void *base,
709                            const char *elems,
710                            unsigned int target_offset,
711                            unsigned int next_offset)
712 {
713         long size_of_base_struct = elems - (const char *)base;
714         const struct xt_entry_target *t;
715         const char *e = base;
716
717         /* target start is within the ip/ip6/arpt_entry struct */
718         if (target_offset < size_of_base_struct)
719                 return -EINVAL;
720
721         if (target_offset + sizeof(*t) > next_offset)
722                 return -EINVAL;
723
724         t = (void *)(e + target_offset);
725         if (t->u.target_size < sizeof(*t))
726                 return -EINVAL;
727
728         if (target_offset + t->u.target_size > next_offset)
729                 return -EINVAL;
730
731         if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
732             XT_ALIGN(target_offset + sizeof(struct xt_standard_target)) != next_offset)
733                 return -EINVAL;
734
735         return xt_check_entry_match(elems, base + target_offset,
736                                     __alignof__(struct xt_entry_match));
737 }
738 EXPORT_SYMBOL(xt_check_entry_offsets);
739
740 /**
741  * xt_alloc_entry_offsets - allocate array to store rule head offsets
742  *
743  * @size: number of entries
744  *
745  * Return: NULL or kmalloc'd or vmalloc'd array
746  */
747 unsigned int *xt_alloc_entry_offsets(unsigned int size)
748 {
749         unsigned int *off;
750
751         off = kcalloc(size, sizeof(unsigned int), GFP_KERNEL | __GFP_NOWARN);
752
753         if (off)
754                 return off;
755
756         if (size < (SIZE_MAX / sizeof(unsigned int)))
757                 off = vmalloc(size * sizeof(unsigned int));
758
759         return off;
760 }
761 EXPORT_SYMBOL(xt_alloc_entry_offsets);
762
763 /**
764  * xt_find_jump_offset - check if target is a valid jump offset
765  *
766  * @offsets: array containing all valid rule start offsets of a rule blob
767  * @target: the jump target to search for
768  * @size: entries in @offset
769  */
770 bool xt_find_jump_offset(const unsigned int *offsets,
771                          unsigned int target, unsigned int size)
772 {
773         int m, low = 0, hi = size;
774
775         while (hi > low) {
776                 m = (low + hi) / 2u;
777
778                 if (offsets[m] > target)
779                         hi = m;
780                 else if (offsets[m] < target)
781                         low = m + 1;
782                 else
783                         return true;
784         }
785
786         return false;
787 }
788 EXPORT_SYMBOL(xt_find_jump_offset);
789
790 int xt_check_target(struct xt_tgchk_param *par,
791                     unsigned int size, u_int8_t proto, bool inv_proto)
792 {
793         int ret;
794
795         if (XT_ALIGN(par->target->targetsize) != size) {
796                 pr_err("%s_tables: %s.%u target: invalid size "
797                        "%u (kernel) != (user) %u\n",
798                        xt_prefix[par->family], par->target->name,
799                        par->target->revision,
800                        XT_ALIGN(par->target->targetsize), size);
801                 return -EINVAL;
802         }
803         if (par->target->table != NULL &&
804             strcmp(par->target->table, par->table) != 0) {
805                 pr_err("%s_tables: %s target: only valid in %s table, not %s\n",
806                        xt_prefix[par->family], par->target->name,
807                        par->target->table, par->table);
808                 return -EINVAL;
809         }
810         if (par->target->hooks && (par->hook_mask & ~par->target->hooks) != 0) {
811                 char used[64], allow[64];
812
813                 pr_err("%s_tables: %s target: used from hooks %s, but only "
814                        "usable from %s\n",
815                        xt_prefix[par->family], par->target->name,
816                        textify_hooks(used, sizeof(used), par->hook_mask,
817                                      par->family),
818                        textify_hooks(allow, sizeof(allow), par->target->hooks,
819                                      par->family));
820                 return -EINVAL;
821         }
822         if (par->target->proto && (par->target->proto != proto || inv_proto)) {
823                 pr_err("%s_tables: %s target: only valid for protocol %u\n",
824                        xt_prefix[par->family], par->target->name,
825                        par->target->proto);
826                 return -EINVAL;
827         }
828         if (par->target->checkentry != NULL) {
829                 ret = par->target->checkentry(par);
830                 if (ret < 0)
831                         return ret;
832                 else if (ret > 0)
833                         /* Flag up potential errors. */
834                         return -EIO;
835         }
836         return 0;
837 }
838 EXPORT_SYMBOL_GPL(xt_check_target);
839
840 /**
841  * xt_copy_counters_from_user - copy counters and metadata from userspace
842  *
843  * @user: src pointer to userspace memory
844  * @len: alleged size of userspace memory
845  * @info: where to store the xt_counters_info metadata
846  * @compat: true if we setsockopt call is done by 32bit task on 64bit kernel
847  *
848  * Copies counter meta data from @user and stores it in @info.
849  *
850  * vmallocs memory to hold the counters, then copies the counter data
851  * from @user to the new memory and returns a pointer to it.
852  *
853  * If @compat is true, @info gets converted automatically to the 64bit
854  * representation.
855  *
856  * The metadata associated with the counters is stored in @info.
857  *
858  * Return: returns pointer that caller has to test via IS_ERR().
859  * If IS_ERR is false, caller has to vfree the pointer.
860  */
861 void *xt_copy_counters_from_user(const void __user *user, unsigned int len,
862                                  struct xt_counters_info *info, bool compat)
863 {
864         void *mem;
865         u64 size;
866
867 #ifdef CONFIG_COMPAT
868         if (compat) {
869                 /* structures only differ in size due to alignment */
870                 struct compat_xt_counters_info compat_tmp;
871
872                 if (len <= sizeof(compat_tmp))
873                         return ERR_PTR(-EINVAL);
874
875                 len -= sizeof(compat_tmp);
876                 if (copy_from_user(&compat_tmp, user, sizeof(compat_tmp)) != 0)
877                         return ERR_PTR(-EFAULT);
878
879                 memcpy(info->name, compat_tmp.name, sizeof(info->name) - 1);
880                 info->num_counters = compat_tmp.num_counters;
881                 user += sizeof(compat_tmp);
882         } else
883 #endif
884         {
885                 if (len <= sizeof(*info))
886                         return ERR_PTR(-EINVAL);
887
888                 len -= sizeof(*info);
889                 if (copy_from_user(info, user, sizeof(*info)) != 0)
890                         return ERR_PTR(-EFAULT);
891
892                 user += sizeof(*info);
893         }
894         info->name[sizeof(info->name) - 1] = '\0';
895
896         size = sizeof(struct xt_counters);
897         size *= info->num_counters;
898
899         if (size != (u64)len)
900                 return ERR_PTR(-EINVAL);
901
902         mem = vmalloc(len);
903         if (!mem)
904                 return ERR_PTR(-ENOMEM);
905
906         if (copy_from_user(mem, user, len) == 0)
907                 return mem;
908
909         vfree(mem);
910         return ERR_PTR(-EFAULT);
911 }
912 EXPORT_SYMBOL_GPL(xt_copy_counters_from_user);
913
914 #ifdef CONFIG_COMPAT
915 int xt_compat_target_offset(const struct xt_target *target)
916 {
917         u_int16_t csize = target->compatsize ? : target->targetsize;
918         return XT_ALIGN(target->targetsize) - COMPAT_XT_ALIGN(csize);
919 }
920 EXPORT_SYMBOL_GPL(xt_compat_target_offset);
921
922 void xt_compat_target_from_user(struct xt_entry_target *t, void **dstptr,
923                                 unsigned int *size)
924 {
925         const struct xt_target *target = t->u.kernel.target;
926         struct compat_xt_entry_target *ct = (struct compat_xt_entry_target *)t;
927         int pad, off = xt_compat_target_offset(target);
928         u_int16_t tsize = ct->u.user.target_size;
929         char name[sizeof(t->u.user.name)];
930
931         t = *dstptr;
932         memcpy(t, ct, sizeof(*ct));
933         if (target->compat_from_user)
934                 target->compat_from_user(t->data, ct->data);
935         else
936                 memcpy(t->data, ct->data, tsize - sizeof(*ct));
937         pad = XT_ALIGN(target->targetsize) - target->targetsize;
938         if (pad > 0)
939                 memset(t->data + target->targetsize, 0, pad);
940
941         tsize += off;
942         t->u.user.target_size = tsize;
943         strlcpy(name, target->name, sizeof(name));
944         module_put(target->me);
945         strncpy(t->u.user.name, name, sizeof(t->u.user.name));
946
947         *size += off;
948         *dstptr += tsize;
949 }
950 EXPORT_SYMBOL_GPL(xt_compat_target_from_user);
951
952 int xt_compat_target_to_user(const struct xt_entry_target *t,
953                              void __user **dstptr, unsigned int *size)
954 {
955         const struct xt_target *target = t->u.kernel.target;
956         struct compat_xt_entry_target __user *ct = *dstptr;
957         int off = xt_compat_target_offset(target);
958         u_int16_t tsize = t->u.user.target_size - off;
959
960         if (copy_to_user(ct, t, sizeof(*ct)) ||
961             put_user(tsize, &ct->u.user.target_size) ||
962             copy_to_user(ct->u.user.name, t->u.kernel.target->name,
963                          strlen(t->u.kernel.target->name) + 1))
964                 return -EFAULT;
965
966         if (target->compat_to_user) {
967                 if (target->compat_to_user((void __user *)ct->data, t->data))
968                         return -EFAULT;
969         } else {
970                 if (copy_to_user(ct->data, t->data, tsize - sizeof(*ct)))
971                         return -EFAULT;
972         }
973
974         *size -= off;
975         *dstptr += tsize;
976         return 0;
977 }
978 EXPORT_SYMBOL_GPL(xt_compat_target_to_user);
979 #endif
980
981 struct xt_table_info *xt_alloc_table_info(unsigned int size)
982 {
983         struct xt_table_info *info = NULL;
984         size_t sz = sizeof(*info) + size;
985
986         if (sz < sizeof(*info))
987                 return NULL;
988
989         if (sz < sizeof(*info))
990                 return NULL;
991
992         /* Pedantry: prevent them from hitting BUG() in vmalloc.c --RR */
993         if ((size >> PAGE_SHIFT) + 2 > totalram_pages)
994                 return NULL;
995
996         if (sz <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
997                 info = kmalloc(sz, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
998         if (!info) {
999                 info = vmalloc(sz);
1000                 if (!info)
1001                         return NULL;
1002         }
1003         memset(info, 0, sizeof(*info));
1004         info->size = size;
1005         return info;
1006 }
1007 EXPORT_SYMBOL(xt_alloc_table_info);
1008
1009 void xt_free_table_info(struct xt_table_info *info)
1010 {
1011         int cpu;
1012
1013         if (info->jumpstack != NULL) {
1014                 for_each_possible_cpu(cpu)
1015                         kvfree(info->jumpstack[cpu]);
1016                 kvfree(info->jumpstack);
1017         }
1018
1019         kvfree(info);
1020 }
1021 EXPORT_SYMBOL(xt_free_table_info);
1022
1023 /* Find table by name, grabs mutex & ref.  Returns ERR_PTR() on error. */
1024 struct xt_table *xt_find_table_lock(struct net *net, u_int8_t af,
1025                                     const char *name)
1026 {
1027         struct xt_table *t;
1028
1029         mutex_lock(&xt[af].mutex);
1030         list_for_each_entry(t, &net->xt.tables[af], list)
1031                 if (strcmp(t->name, name) == 0 && try_module_get(t->me))
1032                         return t;
1033         mutex_unlock(&xt[af].mutex);
1034         return NULL;
1035 }
1036 EXPORT_SYMBOL_GPL(xt_find_table_lock);
1037
1038 void xt_table_unlock(struct xt_table *table)
1039 {
1040         mutex_unlock(&xt[table->af].mutex);
1041 }
1042 EXPORT_SYMBOL_GPL(xt_table_unlock);
1043
1044 #ifdef CONFIG_COMPAT
1045 void xt_compat_lock(u_int8_t af)
1046 {
1047         mutex_lock(&xt[af].compat_mutex);
1048 }
1049 EXPORT_SYMBOL_GPL(xt_compat_lock);
1050
1051 void xt_compat_unlock(u_int8_t af)
1052 {
1053         mutex_unlock(&xt[af].compat_mutex);
1054 }
1055 EXPORT_SYMBOL_GPL(xt_compat_unlock);
1056 #endif
1057
1058 DEFINE_PER_CPU(seqcount_t, xt_recseq);
1059 EXPORT_PER_CPU_SYMBOL_GPL(xt_recseq);
1060
1061 struct static_key xt_tee_enabled __read_mostly;
1062 EXPORT_SYMBOL_GPL(xt_tee_enabled);
1063
1064 static int xt_jumpstack_alloc(struct xt_table_info *i)
1065 {
1066         unsigned int size;
1067         int cpu;
1068
1069         size = sizeof(void **) * nr_cpu_ids;
1070         if (size > PAGE_SIZE)
1071                 i->jumpstack = vzalloc(size);
1072         else
1073                 i->jumpstack = kzalloc(size, GFP_KERNEL);
1074         if (i->jumpstack == NULL)
1075                 return -ENOMEM;
1076
1077         /* ruleset without jumps -- no stack needed */
1078         if (i->stacksize == 0)
1079                 return 0;
1080
1081         /* Jumpstack needs to be able to record two full callchains, one
1082          * from the first rule set traversal, plus one table reentrancy
1083          * via -j TEE without clobbering the callchain that brought us to
1084          * TEE target.
1085          *
1086          * This is done by allocating two jumpstacks per cpu, on reentry
1087          * the upper half of the stack is used.
1088          *
1089          * see the jumpstack setup in ipt_do_table() for more details.
1090          */
1091         size = sizeof(void *) * i->stacksize * 2u;
1092         for_each_possible_cpu(cpu) {
1093                 if (size > PAGE_SIZE)
1094                         i->jumpstack[cpu] = vmalloc_node(size,
1095                                 cpu_to_node(cpu));
1096                 else
1097                         i->jumpstack[cpu] = kmalloc_node(size,
1098                                 GFP_KERNEL, cpu_to_node(cpu));
1099                 if (i->jumpstack[cpu] == NULL)
1100                         /*
1101                          * Freeing will be done later on by the callers. The
1102                          * chain is: xt_replace_table -> __do_replace ->
1103                          * do_replace -> xt_free_table_info.
1104                          */
1105                         return -ENOMEM;
1106         }
1107
1108         return 0;
1109 }
1110
1111 struct xt_table_info *
1112 xt_replace_table(struct xt_table *table,
1113               unsigned int num_counters,
1114               struct xt_table_info *newinfo,
1115               int *error)
1116 {
1117         struct xt_table_info *private;
1118         int ret;
1119
1120         ret = xt_jumpstack_alloc(newinfo);
1121         if (ret < 0) {
1122                 *error = ret;
1123                 return NULL;
1124         }
1125
1126         /* Do the substitution. */
1127         local_bh_disable();
1128         private = table->private;
1129
1130         /* Check inside lock: is the old number correct? */
1131         if (num_counters != private->number) {
1132                 pr_debug("num_counters != table->private->number (%u/%u)\n",
1133                          num_counters, private->number);
1134                 local_bh_enable();
1135                 *error = -EAGAIN;
1136                 return NULL;
1137         }
1138
1139         newinfo->initial_entries = private->initial_entries;
1140         /*
1141          * Ensure contents of newinfo are visible before assigning to
1142          * private.
1143          */
1144         smp_wmb();
1145         table->private = newinfo;
1146
1147         /*
1148          * Even though table entries have now been swapped, other CPU's
1149          * may still be using the old entries. This is okay, because
1150          * resynchronization happens because of the locking done
1151          * during the get_counters() routine.
1152          */
1153         local_bh_enable();
1154
1155 #ifdef CONFIG_AUDIT
1156         if (audit_enabled) {
1157                 struct audit_buffer *ab;
1158
1159                 ab = audit_log_start(current->audit_context, GFP_KERNEL,
1160                                      AUDIT_NETFILTER_CFG);
1161                 if (ab) {
1162                         audit_log_format(ab, "table=%s family=%u entries=%u",
1163                                          table->name, table->af,
1164                                          private->number);
1165                         audit_log_end(ab);
1166                 }
1167         }
1168 #endif
1169
1170         return private;
1171 }
1172 EXPORT_SYMBOL_GPL(xt_replace_table);
1173
1174 struct xt_table *xt_register_table(struct net *net,
1175                                    const struct xt_table *input_table,
1176                                    struct xt_table_info *bootstrap,
1177                                    struct xt_table_info *newinfo)
1178 {
1179         int ret;
1180         struct xt_table_info *private;
1181         struct xt_table *t, *table;
1182
1183         /* Don't add one object to multiple lists. */
1184         table = kmemdup(input_table, sizeof(struct xt_table), GFP_KERNEL);
1185         if (!table) {
1186                 ret = -ENOMEM;
1187                 goto out;
1188         }
1189
1190         mutex_lock(&xt[table->af].mutex);
1191         /* Don't autoload: we'd eat our tail... */
1192         list_for_each_entry(t, &net->xt.tables[table->af], list) {
1193                 if (strcmp(t->name, table->name) == 0) {
1194                         ret = -EEXIST;
1195                         goto unlock;
1196                 }
1197         }
1198
1199         /* Simplifies replace_table code. */
1200         table->private = bootstrap;
1201
1202         if (!xt_replace_table(table, 0, newinfo, &ret))
1203                 goto unlock;
1204
1205         private = table->private;
1206         pr_debug("table->private->number = %u\n", private->number);
1207
1208         /* save number of initial entries */
1209         private->initial_entries = private->number;
1210
1211         list_add(&table->list, &net->xt.tables[table->af]);
1212         mutex_unlock(&xt[table->af].mutex);
1213         return table;
1214
1215 unlock:
1216         mutex_unlock(&xt[table->af].mutex);
1217         kfree(table);
1218 out:
1219         return ERR_PTR(ret);
1220 }
1221 EXPORT_SYMBOL_GPL(xt_register_table);
1222
1223 void *xt_unregister_table(struct xt_table *table)
1224 {
1225         struct xt_table_info *private;
1226
1227         mutex_lock(&xt[table->af].mutex);
1228         private = table->private;
1229         list_del(&table->list);
1230         mutex_unlock(&xt[table->af].mutex);
1231         kfree(table);
1232
1233         return private;
1234 }
1235 EXPORT_SYMBOL_GPL(xt_unregister_table);
1236
1237 #ifdef CONFIG_PROC_FS
1238 struct xt_names_priv {
1239         struct seq_net_private p;
1240         u_int8_t af;
1241 };
1242 static void *xt_table_seq_start(struct seq_file *seq, loff_t *pos)
1243 {
1244         struct xt_names_priv *priv = seq->private;
1245         struct net *net = seq_file_net(seq);
1246         u_int8_t af = priv->af;
1247
1248         mutex_lock(&xt[af].mutex);
1249         return seq_list_start(&net->xt.tables[af], *pos);
1250 }
1251
1252 static void *xt_table_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1253 {
1254         struct xt_names_priv *priv = seq->private;
1255         struct net *net = seq_file_net(seq);
1256         u_int8_t af = priv->af;
1257
1258         return seq_list_next(v, &net->xt.tables[af], pos);
1259 }
1260
1261 static void xt_table_seq_stop(struct seq_file *seq, void *v)
1262 {
1263         struct xt_names_priv *priv = seq->private;
1264         u_int8_t af = priv->af;
1265
1266         mutex_unlock(&xt[af].mutex);
1267 }
1268
1269 static int xt_table_seq_show(struct seq_file *seq, void *v)
1270 {
1271         struct xt_table *table = list_entry(v, struct xt_table, list);
1272
1273         if (*table->name)
1274                 seq_printf(seq, "%s\n", table->name);
1275         return 0;
1276 }
1277
1278 static const struct seq_operations xt_table_seq_ops = {
1279         .start  = xt_table_seq_start,
1280         .next   = xt_table_seq_next,
1281         .stop   = xt_table_seq_stop,
1282         .show   = xt_table_seq_show,
1283 };
1284
1285 static int xt_table_open(struct inode *inode, struct file *file)
1286 {
1287         int ret;
1288         struct xt_names_priv *priv;
1289
1290         ret = seq_open_net(inode, file, &xt_table_seq_ops,
1291                            sizeof(struct xt_names_priv));
1292         if (!ret) {
1293                 priv = ((struct seq_file *)file->private_data)->private;
1294                 priv->af = (unsigned long)PDE_DATA(inode);
1295         }
1296         return ret;
1297 }
1298
1299 static const struct file_operations xt_table_ops = {
1300         .owner   = THIS_MODULE,
1301         .open    = xt_table_open,
1302         .read    = seq_read,
1303         .llseek  = seq_lseek,
1304         .release = seq_release_net,
1305 };
1306
1307 /*
1308  * Traverse state for ip{,6}_{tables,matches} for helping crossing
1309  * the multi-AF mutexes.
1310  */
1311 struct nf_mttg_trav {
1312         struct list_head *head, *curr;
1313         uint8_t class, nfproto;
1314 };
1315
1316 enum {
1317         MTTG_TRAV_INIT,
1318         MTTG_TRAV_NFP_UNSPEC,
1319         MTTG_TRAV_NFP_SPEC,
1320         MTTG_TRAV_DONE,
1321 };
1322
1323 static void *xt_mttg_seq_next(struct seq_file *seq, void *v, loff_t *ppos,
1324     bool is_target)
1325 {
1326         static const uint8_t next_class[] = {
1327                 [MTTG_TRAV_NFP_UNSPEC] = MTTG_TRAV_NFP_SPEC,
1328                 [MTTG_TRAV_NFP_SPEC]   = MTTG_TRAV_DONE,
1329         };
1330         struct nf_mttg_trav *trav = seq->private;
1331
1332         switch (trav->class) {
1333         case MTTG_TRAV_INIT:
1334                 trav->class = MTTG_TRAV_NFP_UNSPEC;
1335                 mutex_lock(&xt[NFPROTO_UNSPEC].mutex);
1336                 trav->head = trav->curr = is_target ?
1337                         &xt[NFPROTO_UNSPEC].target : &xt[NFPROTO_UNSPEC].match;
1338                 break;
1339         case MTTG_TRAV_NFP_UNSPEC:
1340                 trav->curr = trav->curr->next;
1341                 if (trav->curr != trav->head)
1342                         break;
1343                 mutex_unlock(&xt[NFPROTO_UNSPEC].mutex);
1344                 mutex_lock(&xt[trav->nfproto].mutex);
1345                 trav->head = trav->curr = is_target ?
1346                         &xt[trav->nfproto].target : &xt[trav->nfproto].match;
1347                 trav->class = next_class[trav->class];
1348                 break;
1349         case MTTG_TRAV_NFP_SPEC:
1350                 trav->curr = trav->curr->next;
1351                 if (trav->curr != trav->head)
1352                         break;
1353                 /* fallthru, _stop will unlock */
1354         default:
1355                 return NULL;
1356         }
1357
1358         if (ppos != NULL)
1359                 ++*ppos;
1360         return trav;
1361 }
1362
1363 static void *xt_mttg_seq_start(struct seq_file *seq, loff_t *pos,
1364     bool is_target)
1365 {
1366         struct nf_mttg_trav *trav = seq->private;
1367         unsigned int j;
1368
1369         trav->class = MTTG_TRAV_INIT;
1370         for (j = 0; j < *pos; ++j)
1371                 if (xt_mttg_seq_next(seq, NULL, NULL, is_target) == NULL)
1372                         return NULL;
1373         return trav;
1374 }
1375
1376 static void xt_mttg_seq_stop(struct seq_file *seq, void *v)
1377 {
1378         struct nf_mttg_trav *trav = seq->private;
1379
1380         switch (trav->class) {
1381         case MTTG_TRAV_NFP_UNSPEC:
1382                 mutex_unlock(&xt[NFPROTO_UNSPEC].mutex);
1383                 break;
1384         case MTTG_TRAV_NFP_SPEC:
1385                 mutex_unlock(&xt[trav->nfproto].mutex);
1386                 break;
1387         }
1388 }
1389
1390 static void *xt_match_seq_start(struct seq_file *seq, loff_t *pos)
1391 {
1392         return xt_mttg_seq_start(seq, pos, false);
1393 }
1394
1395 static void *xt_match_seq_next(struct seq_file *seq, void *v, loff_t *ppos)
1396 {
1397         return xt_mttg_seq_next(seq, v, ppos, false);
1398 }
1399
1400 static int xt_match_seq_show(struct seq_file *seq, void *v)
1401 {
1402         const struct nf_mttg_trav *trav = seq->private;
1403         const struct xt_match *match;
1404
1405         switch (trav->class) {
1406         case MTTG_TRAV_NFP_UNSPEC:
1407         case MTTG_TRAV_NFP_SPEC:
1408                 if (trav->curr == trav->head)
1409                         return 0;
1410                 match = list_entry(trav->curr, struct xt_match, list);
1411                 if (*match->name)
1412                         seq_printf(seq, "%s\n", match->name);
1413         }
1414         return 0;
1415 }
1416
1417 static const struct seq_operations xt_match_seq_ops = {
1418         .start  = xt_match_seq_start,
1419         .next   = xt_match_seq_next,
1420         .stop   = xt_mttg_seq_stop,
1421         .show   = xt_match_seq_show,
1422 };
1423
1424 static int xt_match_open(struct inode *inode, struct file *file)
1425 {
1426         struct nf_mttg_trav *trav;
1427         trav = __seq_open_private(file, &xt_match_seq_ops, sizeof(*trav));
1428         if (!trav)
1429                 return -ENOMEM;
1430
1431         trav->nfproto = (unsigned long)PDE_DATA(inode);
1432         return 0;
1433 }
1434
1435 static const struct file_operations xt_match_ops = {
1436         .owner   = THIS_MODULE,
1437         .open    = xt_match_open,
1438         .read    = seq_read,
1439         .llseek  = seq_lseek,
1440         .release = seq_release_private,
1441 };
1442
1443 static void *xt_target_seq_start(struct seq_file *seq, loff_t *pos)
1444 {
1445         return xt_mttg_seq_start(seq, pos, true);
1446 }
1447
1448 static void *xt_target_seq_next(struct seq_file *seq, void *v, loff_t *ppos)
1449 {
1450         return xt_mttg_seq_next(seq, v, ppos, true);
1451 }
1452
1453 static int xt_target_seq_show(struct seq_file *seq, void *v)
1454 {
1455         const struct nf_mttg_trav *trav = seq->private;
1456         const struct xt_target *target;
1457
1458         switch (trav->class) {
1459         case MTTG_TRAV_NFP_UNSPEC:
1460         case MTTG_TRAV_NFP_SPEC:
1461                 if (trav->curr == trav->head)
1462                         return 0;
1463                 target = list_entry(trav->curr, struct xt_target, list);
1464                 if (*target->name)
1465                         seq_printf(seq, "%s\n", target->name);
1466         }
1467         return 0;
1468 }
1469
1470 static const struct seq_operations xt_target_seq_ops = {
1471         .start  = xt_target_seq_start,
1472         .next   = xt_target_seq_next,
1473         .stop   = xt_mttg_seq_stop,
1474         .show   = xt_target_seq_show,
1475 };
1476
1477 static int xt_target_open(struct inode *inode, struct file *file)
1478 {
1479         struct nf_mttg_trav *trav;
1480         trav = __seq_open_private(file, &xt_target_seq_ops, sizeof(*trav));
1481         if (!trav)
1482                 return -ENOMEM;
1483
1484         trav->nfproto = (unsigned long)PDE_DATA(inode);
1485         return 0;
1486 }
1487
1488 static const struct file_operations xt_target_ops = {
1489         .owner   = THIS_MODULE,
1490         .open    = xt_target_open,
1491         .read    = seq_read,
1492         .llseek  = seq_lseek,
1493         .release = seq_release_private,
1494 };
1495
1496 #define FORMAT_TABLES   "_tables_names"
1497 #define FORMAT_MATCHES  "_tables_matches"
1498 #define FORMAT_TARGETS  "_tables_targets"
1499
1500 #endif /* CONFIG_PROC_FS */
1501
1502 /**
1503  * xt_hook_link - set up hooks for a new table
1504  * @table:      table with metadata needed to set up hooks
1505  * @fn:         Hook function
1506  *
1507  * This function will take care of creating and registering the necessary
1508  * Netfilter hooks for XT tables.
1509  */
1510 struct nf_hook_ops *xt_hook_link(const struct xt_table *table, nf_hookfn *fn)
1511 {
1512         unsigned int hook_mask = table->valid_hooks;
1513         uint8_t i, num_hooks = hweight32(hook_mask);
1514         uint8_t hooknum;
1515         struct nf_hook_ops *ops;
1516         int ret;
1517
1518         ops = kmalloc(sizeof(*ops) * num_hooks, GFP_KERNEL);
1519         if (ops == NULL)
1520                 return ERR_PTR(-ENOMEM);
1521
1522         for (i = 0, hooknum = 0; i < num_hooks && hook_mask != 0;
1523              hook_mask >>= 1, ++hooknum) {
1524                 if (!(hook_mask & 1))
1525                         continue;
1526                 ops[i].hook     = fn;
1527                 ops[i].pf       = table->af;
1528                 ops[i].hooknum  = hooknum;
1529                 ops[i].priority = table->priority;
1530                 ++i;
1531         }
1532
1533         ret = nf_register_hooks(ops, num_hooks);
1534         if (ret < 0) {
1535                 kfree(ops);
1536                 return ERR_PTR(ret);
1537         }
1538
1539         return ops;
1540 }
1541 EXPORT_SYMBOL_GPL(xt_hook_link);
1542
1543 /**
1544  * xt_hook_unlink - remove hooks for a table
1545  * @ops:        nf_hook_ops array as returned by nf_hook_link
1546  * @hook_mask:  the very same mask that was passed to nf_hook_link
1547  */
1548 void xt_hook_unlink(const struct xt_table *table, struct nf_hook_ops *ops)
1549 {
1550         nf_unregister_hooks(ops, hweight32(table->valid_hooks));
1551         kfree(ops);
1552 }
1553 EXPORT_SYMBOL_GPL(xt_hook_unlink);
1554
1555 int xt_proto_init(struct net *net, u_int8_t af)
1556 {
1557 #ifdef CONFIG_PROC_FS
1558         char buf[XT_FUNCTION_MAXNAMELEN];
1559         struct proc_dir_entry *proc;
1560 #endif
1561
1562         if (af >= ARRAY_SIZE(xt_prefix))
1563                 return -EINVAL;
1564
1565
1566 #ifdef CONFIG_PROC_FS
1567         strlcpy(buf, xt_prefix[af], sizeof(buf));
1568         strlcat(buf, FORMAT_TABLES, sizeof(buf));
1569         proc = proc_create_data(buf, 0440, net->proc_net, &xt_table_ops,
1570                                 (void *)(unsigned long)af);
1571         if (!proc)
1572                 goto out;
1573
1574         strlcpy(buf, xt_prefix[af], sizeof(buf));
1575         strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1576         proc = proc_create_data(buf, 0440, net->proc_net, &xt_match_ops,
1577                                 (void *)(unsigned long)af);
1578         if (!proc)
1579                 goto out_remove_tables;
1580
1581         strlcpy(buf, xt_prefix[af], sizeof(buf));
1582         strlcat(buf, FORMAT_TARGETS, sizeof(buf));
1583         proc = proc_create_data(buf, 0440, net->proc_net, &xt_target_ops,
1584                                 (void *)(unsigned long)af);
1585         if (!proc)
1586                 goto out_remove_matches;
1587 #endif
1588
1589         return 0;
1590
1591 #ifdef CONFIG_PROC_FS
1592 out_remove_matches:
1593         strlcpy(buf, xt_prefix[af], sizeof(buf));
1594         strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1595         remove_proc_entry(buf, net->proc_net);
1596
1597 out_remove_tables:
1598         strlcpy(buf, xt_prefix[af], sizeof(buf));
1599         strlcat(buf, FORMAT_TABLES, sizeof(buf));
1600         remove_proc_entry(buf, net->proc_net);
1601 out:
1602         return -1;
1603 #endif
1604 }
1605 EXPORT_SYMBOL_GPL(xt_proto_init);
1606
1607 void xt_proto_fini(struct net *net, u_int8_t af)
1608 {
1609 #ifdef CONFIG_PROC_FS
1610         char buf[XT_FUNCTION_MAXNAMELEN];
1611
1612         strlcpy(buf, xt_prefix[af], sizeof(buf));
1613         strlcat(buf, FORMAT_TABLES, sizeof(buf));
1614         remove_proc_entry(buf, net->proc_net);
1615
1616         strlcpy(buf, xt_prefix[af], sizeof(buf));
1617         strlcat(buf, FORMAT_TARGETS, sizeof(buf));
1618         remove_proc_entry(buf, net->proc_net);
1619
1620         strlcpy(buf, xt_prefix[af], sizeof(buf));
1621         strlcat(buf, FORMAT_MATCHES, sizeof(buf));
1622         remove_proc_entry(buf, net->proc_net);
1623 #endif /*CONFIG_PROC_FS*/
1624 }
1625 EXPORT_SYMBOL_GPL(xt_proto_fini);
1626
1627 /**
1628  * xt_percpu_counter_alloc - allocate x_tables rule counter
1629  *
1630  * @state: pointer to xt_percpu allocation state
1631  * @counter: pointer to counter struct inside the ip(6)/arpt_entry struct
1632  *
1633  * On SMP, the packet counter [ ip(6)t_entry->counters.pcnt ] will then
1634  * contain the address of the real (percpu) counter.
1635  *
1636  * Rule evaluation needs to use xt_get_this_cpu_counter() helper
1637  * to fetch the real percpu counter.
1638  *
1639  * To speed up allocation and improve data locality, a 4kb block is
1640  * allocated.
1641  *
1642  * xt_percpu_counter_alloc_state contains the base address of the
1643  * allocated page and the current sub-offset.
1644  *
1645  * returns false on error.
1646  */
1647 bool xt_percpu_counter_alloc(struct xt_percpu_counter_alloc_state *state,
1648                              struct xt_counters *counter)
1649 {
1650         BUILD_BUG_ON(XT_PCPU_BLOCK_SIZE < (sizeof(*counter) * 2));
1651
1652         if (nr_cpu_ids <= 1)
1653                 return true;
1654
1655         if (!state->mem) {
1656                 state->mem = __alloc_percpu(XT_PCPU_BLOCK_SIZE,
1657                                             XT_PCPU_BLOCK_SIZE);
1658                 if (!state->mem)
1659                         return false;
1660         }
1661         counter->pcnt = (__force unsigned long)(state->mem + state->off);
1662         state->off += sizeof(*counter);
1663         if (state->off > (XT_PCPU_BLOCK_SIZE - sizeof(*counter))) {
1664                 state->mem = NULL;
1665                 state->off = 0;
1666         }
1667         return true;
1668 }
1669 EXPORT_SYMBOL_GPL(xt_percpu_counter_alloc);
1670
1671 void xt_percpu_counter_free(struct xt_counters *counters)
1672 {
1673         unsigned long pcnt = counters->pcnt;
1674
1675         if (nr_cpu_ids > 1 && (pcnt & (XT_PCPU_BLOCK_SIZE - 1)) == 0)
1676                 free_percpu((void __percpu *)pcnt);
1677 }
1678 EXPORT_SYMBOL_GPL(xt_percpu_counter_free);
1679
1680 static int __net_init xt_net_init(struct net *net)
1681 {
1682         int i;
1683
1684         for (i = 0; i < NFPROTO_NUMPROTO; i++)
1685                 INIT_LIST_HEAD(&net->xt.tables[i]);
1686         return 0;
1687 }
1688
1689 static struct pernet_operations xt_net_ops = {
1690         .init = xt_net_init,
1691 };
1692
1693 static int __init xt_init(void)
1694 {
1695         unsigned int i;
1696         int rv;
1697
1698         for_each_possible_cpu(i) {
1699                 seqcount_init(&per_cpu(xt_recseq, i));
1700         }
1701
1702         xt = kcalloc(NFPROTO_NUMPROTO, sizeof(struct xt_af), GFP_KERNEL);
1703         if (!xt)
1704                 return -ENOMEM;
1705
1706         for (i = 0; i < NFPROTO_NUMPROTO; i++) {
1707                 mutex_init(&xt[i].mutex);
1708 #ifdef CONFIG_COMPAT
1709                 mutex_init(&xt[i].compat_mutex);
1710                 xt[i].compat_tab = NULL;
1711 #endif
1712                 INIT_LIST_HEAD(&xt[i].target);
1713                 INIT_LIST_HEAD(&xt[i].match);
1714         }
1715         rv = register_pernet_subsys(&xt_net_ops);
1716         if (rv < 0)
1717                 kfree(xt);
1718         return rv;
1719 }
1720
1721 static void __exit xt_fini(void)
1722 {
1723         unregister_pernet_subsys(&xt_net_ops);
1724         kfree(xt);
1725 }
1726
1727 module_init(xt_init);
1728 module_exit(xt_fini);
1729