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