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