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