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