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