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