GNU Linux-libre 4.9.333-gnu1
[releases.git] / net / bridge / netfilter / ebtables.c
1 /*
2  *  ebtables
3  *
4  *  Author:
5  *  Bart De Schuymer            <bdschuym@pandora.be>
6  *
7  *  ebtables.c,v 2.0, July, 2002
8  *
9  *  This code is strongly inspired by the iptables code which is
10  *  Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
11  *
12  *  This program is free software; you can redistribute it and/or
13  *  modify it under the terms of the GNU General Public License
14  *  as published by the Free Software Foundation; either version
15  *  2 of the License, or (at your option) any later version.
16  */
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 #include <linux/kmod.h>
19 #include <linux/module.h>
20 #include <linux/vmalloc.h>
21 #include <linux/netfilter/x_tables.h>
22 #include <linux/netfilter_bridge/ebtables.h>
23 #include <linux/spinlock.h>
24 #include <linux/mutex.h>
25 #include <linux/slab.h>
26 #include <asm/uaccess.h>
27 #include <linux/smp.h>
28 #include <linux/cpumask.h>
29 #include <linux/audit.h>
30 #include <net/sock.h>
31 /* needed for logical [in,out]-dev filtering */
32 #include "../br_private.h"
33
34 #define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
35                                          "report to author: "format, ## args)
36 /* #define BUGPRINT(format, args...) */
37
38 /* Each cpu has its own set of counters, so there is no need for write_lock in
39  * the softirq
40  * For reading or updating the counters, the user context needs to
41  * get a write_lock
42  */
43
44 /* The size of each set of counters is altered to get cache alignment */
45 #define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
46 #define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
47 #define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
48                                  COUNTER_OFFSET(n) * cpu))
49
50
51
52 static DEFINE_MUTEX(ebt_mutex);
53
54 #ifdef CONFIG_COMPAT
55 static void ebt_standard_compat_from_user(void *dst, const void *src)
56 {
57         int v = *(compat_int_t *)src;
58
59         if (v >= 0)
60                 v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
61         memcpy(dst, &v, sizeof(v));
62 }
63
64 static int ebt_standard_compat_to_user(void __user *dst, const void *src)
65 {
66         compat_int_t cv = *(int *)src;
67
68         if (cv >= 0)
69                 cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
70         return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
71 }
72 #endif
73
74
75 static struct xt_target ebt_standard_target = {
76         .name       = "standard",
77         .revision   = 0,
78         .family     = NFPROTO_BRIDGE,
79         .targetsize = sizeof(int),
80 #ifdef CONFIG_COMPAT
81         .compatsize = sizeof(compat_int_t),
82         .compat_from_user = ebt_standard_compat_from_user,
83         .compat_to_user =  ebt_standard_compat_to_user,
84 #endif
85 };
86
87 static inline int
88 ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
89                struct xt_action_param *par)
90 {
91         par->target   = w->u.watcher;
92         par->targinfo = w->data;
93         w->u.watcher->target(skb, par);
94         /* watchers don't give a verdict */
95         return 0;
96 }
97
98 static inline int
99 ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
100              struct xt_action_param *par)
101 {
102         par->match     = m->u.match;
103         par->matchinfo = m->data;
104         return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
105 }
106
107 static inline int
108 ebt_dev_check(const char *entry, const struct net_device *device)
109 {
110         int i = 0;
111         const char *devname;
112
113         if (*entry == '\0')
114                 return 0;
115         if (!device)
116                 return 1;
117         devname = device->name;
118         /* 1 is the wildcard token */
119         while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
120                 i++;
121         return devname[i] != entry[i] && entry[i] != 1;
122 }
123
124 /* process standard matches */
125 static inline int
126 ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
127                 const struct net_device *in, const struct net_device *out)
128 {
129         const struct ethhdr *h = eth_hdr(skb);
130         const struct net_bridge_port *p;
131         __be16 ethproto;
132
133         if (skb_vlan_tag_present(skb))
134                 ethproto = htons(ETH_P_8021Q);
135         else
136                 ethproto = h->h_proto;
137
138         if (e->bitmask & EBT_802_3) {
139                 if (NF_INVF(e, EBT_IPROTO, eth_proto_is_802_3(ethproto)))
140                         return 1;
141         } else if (!(e->bitmask & EBT_NOPROTO) &&
142                    NF_INVF(e, EBT_IPROTO, e->ethproto != ethproto))
143                 return 1;
144
145         if (NF_INVF(e, EBT_IIN, ebt_dev_check(e->in, in)))
146                 return 1;
147         if (NF_INVF(e, EBT_IOUT, ebt_dev_check(e->out, out)))
148                 return 1;
149         /* rcu_read_lock()ed by nf_hook_thresh */
150         if (in && (p = br_port_get_rcu(in)) != NULL &&
151             NF_INVF(e, EBT_ILOGICALIN,
152                     ebt_dev_check(e->logical_in, p->br->dev)))
153                 return 1;
154         if (out && (p = br_port_get_rcu(out)) != NULL &&
155             NF_INVF(e, EBT_ILOGICALOUT,
156                     ebt_dev_check(e->logical_out, p->br->dev)))
157                 return 1;
158
159         if (e->bitmask & EBT_SOURCEMAC) {
160                 if (NF_INVF(e, EBT_ISOURCE,
161                             !ether_addr_equal_masked(h->h_source, e->sourcemac,
162                                                      e->sourcemsk)))
163                         return 1;
164         }
165         if (e->bitmask & EBT_DESTMAC) {
166                 if (NF_INVF(e, EBT_IDEST,
167                             !ether_addr_equal_masked(h->h_dest, e->destmac,
168                                                      e->destmsk)))
169                         return 1;
170         }
171         return 0;
172 }
173
174 static inline
175 struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
176 {
177         return (void *)entry + entry->next_offset;
178 }
179
180 /* Do some firewalling */
181 unsigned int ebt_do_table(struct sk_buff *skb,
182                           const struct nf_hook_state *state,
183                           struct ebt_table *table)
184 {
185         unsigned int hook = state->hook;
186         int i, nentries;
187         struct ebt_entry *point;
188         struct ebt_counter *counter_base, *cb_base;
189         const struct ebt_entry_target *t;
190         int verdict, sp = 0;
191         struct ebt_chainstack *cs;
192         struct ebt_entries *chaininfo;
193         const char *base;
194         const struct ebt_table_info *private;
195         struct xt_action_param acpar;
196
197         acpar.family  = NFPROTO_BRIDGE;
198         acpar.net     = state->net;
199         acpar.in      = state->in;
200         acpar.out     = state->out;
201         acpar.hotdrop = false;
202         acpar.hooknum = hook;
203
204         read_lock_bh(&table->lock);
205         private = table->private;
206         cb_base = COUNTER_BASE(private->counters, private->nentries,
207            smp_processor_id());
208         if (private->chainstack)
209                 cs = private->chainstack[smp_processor_id()];
210         else
211                 cs = NULL;
212         chaininfo = private->hook_entry[hook];
213         nentries = private->hook_entry[hook]->nentries;
214         point = (struct ebt_entry *)(private->hook_entry[hook]->data);
215         counter_base = cb_base + private->hook_entry[hook]->counter_offset;
216         /* base for chain jumps */
217         base = private->entries;
218         i = 0;
219         while (i < nentries) {
220                 if (ebt_basic_match(point, skb, state->in, state->out))
221                         goto letscontinue;
222
223                 if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
224                         goto letscontinue;
225                 if (acpar.hotdrop) {
226                         read_unlock_bh(&table->lock);
227                         return NF_DROP;
228                 }
229
230                 /* increase counter */
231                 (*(counter_base + i)).pcnt++;
232                 (*(counter_base + i)).bcnt += skb->len;
233
234                 /* these should only watch: not modify, nor tell us
235                  * what to do with the packet
236                  */
237                 EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
238
239                 t = (struct ebt_entry_target *)
240                    (((char *)point) + point->target_offset);
241                 /* standard target */
242                 if (!t->u.target->target)
243                         verdict = ((struct ebt_standard_target *)t)->verdict;
244                 else {
245                         acpar.target   = t->u.target;
246                         acpar.targinfo = t->data;
247                         verdict = t->u.target->target(skb, &acpar);
248                 }
249                 if (verdict == EBT_ACCEPT) {
250                         read_unlock_bh(&table->lock);
251                         return NF_ACCEPT;
252                 }
253                 if (verdict == EBT_DROP) {
254                         read_unlock_bh(&table->lock);
255                         return NF_DROP;
256                 }
257                 if (verdict == EBT_RETURN) {
258 letsreturn:
259 #ifdef CONFIG_NETFILTER_DEBUG
260                         if (sp == 0) {
261                                 BUGPRINT("RETURN on base chain");
262                                 /* act like this is EBT_CONTINUE */
263                                 goto letscontinue;
264                         }
265 #endif
266                         sp--;
267                         /* put all the local variables right */
268                         i = cs[sp].n;
269                         chaininfo = cs[sp].chaininfo;
270                         nentries = chaininfo->nentries;
271                         point = cs[sp].e;
272                         counter_base = cb_base +
273                            chaininfo->counter_offset;
274                         continue;
275                 }
276                 if (verdict == EBT_CONTINUE)
277                         goto letscontinue;
278 #ifdef CONFIG_NETFILTER_DEBUG
279                 if (verdict < 0) {
280                         BUGPRINT("bogus standard verdict\n");
281                         read_unlock_bh(&table->lock);
282                         return NF_DROP;
283                 }
284 #endif
285                 /* jump to a udc */
286                 cs[sp].n = i + 1;
287                 cs[sp].chaininfo = chaininfo;
288                 cs[sp].e = ebt_next_entry(point);
289                 i = 0;
290                 chaininfo = (struct ebt_entries *) (base + verdict);
291 #ifdef CONFIG_NETFILTER_DEBUG
292                 if (chaininfo->distinguisher) {
293                         BUGPRINT("jump to non-chain\n");
294                         read_unlock_bh(&table->lock);
295                         return NF_DROP;
296                 }
297 #endif
298                 nentries = chaininfo->nentries;
299                 point = (struct ebt_entry *)chaininfo->data;
300                 counter_base = cb_base + chaininfo->counter_offset;
301                 sp++;
302                 continue;
303 letscontinue:
304                 point = ebt_next_entry(point);
305                 i++;
306         }
307
308         /* I actually like this :) */
309         if (chaininfo->policy == EBT_RETURN)
310                 goto letsreturn;
311         if (chaininfo->policy == EBT_ACCEPT) {
312                 read_unlock_bh(&table->lock);
313                 return NF_ACCEPT;
314         }
315         read_unlock_bh(&table->lock);
316         return NF_DROP;
317 }
318
319 /* If it succeeds, returns element and locks mutex */
320 static inline void *
321 find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
322                         struct mutex *mutex)
323 {
324         struct {
325                 struct list_head list;
326                 char name[EBT_FUNCTION_MAXNAMELEN];
327         } *e;
328
329         mutex_lock(mutex);
330         list_for_each_entry(e, head, list) {
331                 if (strcmp(e->name, name) == 0)
332                         return e;
333         }
334         *error = -ENOENT;
335         mutex_unlock(mutex);
336         return NULL;
337 }
338
339 static void *
340 find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
341                  int *error, struct mutex *mutex)
342 {
343         return try_then_request_module(
344                         find_inlist_lock_noload(head, name, error, mutex),
345                         "%s%s", prefix, name);
346 }
347
348 static inline struct ebt_table *
349 find_table_lock(struct net *net, const char *name, int *error,
350                 struct mutex *mutex)
351 {
352         return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
353                                 "ebtable_", error, mutex);
354 }
355
356 static inline int
357 ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
358                 unsigned int *cnt)
359 {
360         const struct ebt_entry *e = par->entryinfo;
361         struct xt_match *match;
362         size_t left = ((char *)e + e->watchers_offset) - (char *)m;
363         int ret;
364
365         if (left < sizeof(struct ebt_entry_match) ||
366             left - sizeof(struct ebt_entry_match) < m->match_size)
367                 return -EINVAL;
368
369         match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0);
370         if (IS_ERR(match) || match->family != NFPROTO_BRIDGE) {
371                 if (!IS_ERR(match))
372                         module_put(match->me);
373                 request_module("ebt_%s", m->u.name);
374                 match = xt_find_match(NFPROTO_BRIDGE, m->u.name, 0);
375         }
376         if (IS_ERR(match))
377                 return PTR_ERR(match);
378         m->u.match = match;
379
380         par->match     = match;
381         par->matchinfo = m->data;
382         ret = xt_check_match(par, m->match_size,
383               e->ethproto, e->invflags & EBT_IPROTO);
384         if (ret < 0) {
385                 module_put(match->me);
386                 return ret;
387         }
388
389         (*cnt)++;
390         return 0;
391 }
392
393 static inline int
394 ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
395                   unsigned int *cnt)
396 {
397         const struct ebt_entry *e = par->entryinfo;
398         struct xt_target *watcher;
399         size_t left = ((char *)e + e->target_offset) - (char *)w;
400         int ret;
401
402         if (left < sizeof(struct ebt_entry_watcher) ||
403            left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
404                 return -EINVAL;
405
406         watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
407         if (IS_ERR(watcher))
408                 return PTR_ERR(watcher);
409
410         if (watcher->family != NFPROTO_BRIDGE) {
411                 module_put(watcher->me);
412                 return -ENOENT;
413         }
414
415         w->u.watcher = watcher;
416
417         par->target   = watcher;
418         par->targinfo = w->data;
419         ret = xt_check_target(par, w->watcher_size,
420               e->ethproto, e->invflags & EBT_IPROTO);
421         if (ret < 0) {
422                 module_put(watcher->me);
423                 return ret;
424         }
425
426         (*cnt)++;
427         return 0;
428 }
429
430 static int ebt_verify_pointers(const struct ebt_replace *repl,
431                                struct ebt_table_info *newinfo)
432 {
433         unsigned int limit = repl->entries_size;
434         unsigned int valid_hooks = repl->valid_hooks;
435         unsigned int offset = 0;
436         int i;
437
438         for (i = 0; i < NF_BR_NUMHOOKS; i++)
439                 newinfo->hook_entry[i] = NULL;
440
441         newinfo->entries_size = repl->entries_size;
442         newinfo->nentries = repl->nentries;
443
444         while (offset < limit) {
445                 size_t left = limit - offset;
446                 struct ebt_entry *e = (void *)newinfo->entries + offset;
447
448                 if (left < sizeof(unsigned int))
449                         break;
450
451                 for (i = 0; i < NF_BR_NUMHOOKS; i++) {
452                         if ((valid_hooks & (1 << i)) == 0)
453                                 continue;
454                         if ((char __user *)repl->hook_entry[i] ==
455                              repl->entries + offset)
456                                 break;
457                 }
458
459                 if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
460                         if (e->bitmask != 0) {
461                                 /* we make userspace set this right,
462                                  * so there is no misunderstanding
463                                  */
464                                 BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
465                                          "in distinguisher\n");
466                                 return -EINVAL;
467                         }
468                         if (i != NF_BR_NUMHOOKS)
469                                 newinfo->hook_entry[i] = (struct ebt_entries *)e;
470                         if (left < sizeof(struct ebt_entries))
471                                 break;
472                         offset += sizeof(struct ebt_entries);
473                 } else {
474                         if (left < sizeof(struct ebt_entry))
475                                 break;
476                         if (left < e->next_offset)
477                                 break;
478                         if (e->next_offset < sizeof(struct ebt_entry))
479                                 return -EINVAL;
480                         offset += e->next_offset;
481                 }
482         }
483         if (offset != limit) {
484                 BUGPRINT("entries_size too small\n");
485                 return -EINVAL;
486         }
487
488         /* check if all valid hooks have a chain */
489         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
490                 if (!newinfo->hook_entry[i] &&
491                    (valid_hooks & (1 << i))) {
492                         BUGPRINT("Valid hook without chain\n");
493                         return -EINVAL;
494                 }
495         }
496         return 0;
497 }
498
499 /* this one is very careful, as it is the first function
500  * to parse the userspace data
501  */
502 static inline int
503 ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
504                                const struct ebt_table_info *newinfo,
505                                unsigned int *n, unsigned int *cnt,
506                                unsigned int *totalcnt, unsigned int *udc_cnt)
507 {
508         int i;
509
510         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
511                 if ((void *)e == (void *)newinfo->hook_entry[i])
512                         break;
513         }
514         /* beginning of a new chain
515          * if i == NF_BR_NUMHOOKS it must be a user defined chain
516          */
517         if (i != NF_BR_NUMHOOKS || !e->bitmask) {
518                 /* this checks if the previous chain has as many entries
519                  * as it said it has
520                  */
521                 if (*n != *cnt) {
522                         BUGPRINT("nentries does not equal the nr of entries "
523                                  "in the chain\n");
524                         return -EINVAL;
525                 }
526                 if (((struct ebt_entries *)e)->policy != EBT_DROP &&
527                    ((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
528                         /* only RETURN from udc */
529                         if (i != NF_BR_NUMHOOKS ||
530                            ((struct ebt_entries *)e)->policy != EBT_RETURN) {
531                                 BUGPRINT("bad policy\n");
532                                 return -EINVAL;
533                         }
534                 }
535                 if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
536                         (*udc_cnt)++;
537                 if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
538                         BUGPRINT("counter_offset != totalcnt");
539                         return -EINVAL;
540                 }
541                 *n = ((struct ebt_entries *)e)->nentries;
542                 *cnt = 0;
543                 return 0;
544         }
545         /* a plain old entry, heh */
546         if (sizeof(struct ebt_entry) > e->watchers_offset ||
547            e->watchers_offset > e->target_offset ||
548            e->target_offset >= e->next_offset) {
549                 BUGPRINT("entry offsets not in right order\n");
550                 return -EINVAL;
551         }
552         /* this is not checked anywhere else */
553         if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
554                 BUGPRINT("target size too small\n");
555                 return -EINVAL;
556         }
557         (*cnt)++;
558         (*totalcnt)++;
559         return 0;
560 }
561
562 struct ebt_cl_stack {
563         struct ebt_chainstack cs;
564         int from;
565         unsigned int hookmask;
566 };
567
568 /* We need these positions to check that the jumps to a different part of the
569  * entries is a jump to the beginning of a new chain.
570  */
571 static inline int
572 ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
573                       unsigned int *n, struct ebt_cl_stack *udc)
574 {
575         int i;
576
577         /* we're only interested in chain starts */
578         if (e->bitmask)
579                 return 0;
580         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
581                 if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
582                         break;
583         }
584         /* only care about udc */
585         if (i != NF_BR_NUMHOOKS)
586                 return 0;
587
588         udc[*n].cs.chaininfo = (struct ebt_entries *)e;
589         /* these initialisations are depended on later in check_chainloops() */
590         udc[*n].cs.n = 0;
591         udc[*n].hookmask = 0;
592
593         (*n)++;
594         return 0;
595 }
596
597 static inline int
598 ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
599 {
600         struct xt_mtdtor_param par;
601
602         if (i && (*i)-- == 0)
603                 return 1;
604
605         par.net       = net;
606         par.match     = m->u.match;
607         par.matchinfo = m->data;
608         par.family    = NFPROTO_BRIDGE;
609         if (par.match->destroy != NULL)
610                 par.match->destroy(&par);
611         module_put(par.match->me);
612         return 0;
613 }
614
615 static inline int
616 ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
617 {
618         struct xt_tgdtor_param par;
619
620         if (i && (*i)-- == 0)
621                 return 1;
622
623         par.net      = net;
624         par.target   = w->u.watcher;
625         par.targinfo = w->data;
626         par.family   = NFPROTO_BRIDGE;
627         if (par.target->destroy != NULL)
628                 par.target->destroy(&par);
629         module_put(par.target->me);
630         return 0;
631 }
632
633 static inline int
634 ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
635 {
636         struct xt_tgdtor_param par;
637         struct ebt_entry_target *t;
638
639         if (e->bitmask == 0)
640                 return 0;
641         /* we're done */
642         if (cnt && (*cnt)-- == 0)
643                 return 1;
644         EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
645         EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
646         t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
647
648         par.net      = net;
649         par.target   = t->u.target;
650         par.targinfo = t->data;
651         par.family   = NFPROTO_BRIDGE;
652         if (par.target->destroy != NULL)
653                 par.target->destroy(&par);
654         module_put(par.target->me);
655         return 0;
656 }
657
658 static inline int
659 ebt_check_entry(struct ebt_entry *e, struct net *net,
660                 const struct ebt_table_info *newinfo,
661                 const char *name, unsigned int *cnt,
662                 struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
663 {
664         struct ebt_entry_target *t;
665         struct xt_target *target;
666         unsigned int i, j, hook = 0, hookmask = 0;
667         size_t gap;
668         int ret;
669         struct xt_mtchk_param mtpar;
670         struct xt_tgchk_param tgpar;
671
672         /* don't mess with the struct ebt_entries */
673         if (e->bitmask == 0)
674                 return 0;
675
676         if (e->bitmask & ~EBT_F_MASK) {
677                 BUGPRINT("Unknown flag for bitmask\n");
678                 return -EINVAL;
679         }
680         if (e->invflags & ~EBT_INV_MASK) {
681                 BUGPRINT("Unknown flag for inv bitmask\n");
682                 return -EINVAL;
683         }
684         if ((e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3)) {
685                 BUGPRINT("NOPROTO & 802_3 not allowed\n");
686                 return -EINVAL;
687         }
688         /* what hook do we belong to? */
689         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
690                 if (!newinfo->hook_entry[i])
691                         continue;
692                 if ((char *)newinfo->hook_entry[i] < (char *)e)
693                         hook = i;
694                 else
695                         break;
696         }
697         /* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
698          * a base chain
699          */
700         if (i < NF_BR_NUMHOOKS)
701                 hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
702         else {
703                 for (i = 0; i < udc_cnt; i++)
704                         if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
705                                 break;
706                 if (i == 0)
707                         hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
708                 else
709                         hookmask = cl_s[i - 1].hookmask;
710         }
711         i = 0;
712
713         memset(&mtpar, 0, sizeof(mtpar));
714         memset(&tgpar, 0, sizeof(tgpar));
715         mtpar.net       = tgpar.net       = net;
716         mtpar.table     = tgpar.table     = name;
717         mtpar.entryinfo = tgpar.entryinfo = e;
718         mtpar.hook_mask = tgpar.hook_mask = hookmask;
719         mtpar.family    = tgpar.family    = NFPROTO_BRIDGE;
720         ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
721         if (ret != 0)
722                 goto cleanup_matches;
723         j = 0;
724         ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
725         if (ret != 0)
726                 goto cleanup_watchers;
727         t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
728         gap = e->next_offset - e->target_offset;
729
730         target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
731         if (IS_ERR(target)) {
732                 ret = PTR_ERR(target);
733                 goto cleanup_watchers;
734         }
735
736         /* Reject UNSPEC, xtables verdicts/return values are incompatible */
737         if (target->family != NFPROTO_BRIDGE) {
738                 module_put(target->me);
739                 ret = -ENOENT;
740                 goto cleanup_watchers;
741         }
742
743         t->u.target = target;
744         if (t->u.target == &ebt_standard_target) {
745                 if (gap < sizeof(struct ebt_standard_target)) {
746                         BUGPRINT("Standard target size too big\n");
747                         ret = -EFAULT;
748                         goto cleanup_watchers;
749                 }
750                 if (((struct ebt_standard_target *)t)->verdict <
751                    -NUM_STANDARD_TARGETS) {
752                         BUGPRINT("Invalid standard target\n");
753                         ret = -EFAULT;
754                         goto cleanup_watchers;
755                 }
756         } else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
757                 module_put(t->u.target->me);
758                 ret = -EFAULT;
759                 goto cleanup_watchers;
760         }
761
762         tgpar.target   = target;
763         tgpar.targinfo = t->data;
764         ret = xt_check_target(&tgpar, t->target_size,
765               e->ethproto, e->invflags & EBT_IPROTO);
766         if (ret < 0) {
767                 module_put(target->me);
768                 goto cleanup_watchers;
769         }
770         (*cnt)++;
771         return 0;
772 cleanup_watchers:
773         EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
774 cleanup_matches:
775         EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
776         return ret;
777 }
778
779 /* checks for loops and sets the hook mask for udc
780  * the hook mask for udc tells us from which base chains the udc can be
781  * accessed. This mask is a parameter to the check() functions of the extensions
782  */
783 static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
784                             unsigned int udc_cnt, unsigned int hooknr, char *base)
785 {
786         int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
787         const struct ebt_entry *e = (struct ebt_entry *)chain->data;
788         const struct ebt_entry_target *t;
789
790         while (pos < nentries || chain_nr != -1) {
791                 /* end of udc, go back one 'recursion' step */
792                 if (pos == nentries) {
793                         /* put back values of the time when this chain was called */
794                         e = cl_s[chain_nr].cs.e;
795                         if (cl_s[chain_nr].from != -1)
796                                 nentries =
797                                 cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
798                         else
799                                 nentries = chain->nentries;
800                         pos = cl_s[chain_nr].cs.n;
801                         /* make sure we won't see a loop that isn't one */
802                         cl_s[chain_nr].cs.n = 0;
803                         chain_nr = cl_s[chain_nr].from;
804                         if (pos == nentries)
805                                 continue;
806                 }
807                 t = (struct ebt_entry_target *)
808                    (((char *)e) + e->target_offset);
809                 if (strcmp(t->u.name, EBT_STANDARD_TARGET))
810                         goto letscontinue;
811                 if (e->target_offset + sizeof(struct ebt_standard_target) >
812                    e->next_offset) {
813                         BUGPRINT("Standard target size too big\n");
814                         return -1;
815                 }
816                 verdict = ((struct ebt_standard_target *)t)->verdict;
817                 if (verdict >= 0) { /* jump to another chain */
818                         struct ebt_entries *hlp2 =
819                            (struct ebt_entries *)(base + verdict);
820                         for (i = 0; i < udc_cnt; i++)
821                                 if (hlp2 == cl_s[i].cs.chaininfo)
822                                         break;
823                         /* bad destination or loop */
824                         if (i == udc_cnt) {
825                                 BUGPRINT("bad destination\n");
826                                 return -1;
827                         }
828                         if (cl_s[i].cs.n) {
829                                 BUGPRINT("loop\n");
830                                 return -1;
831                         }
832                         if (cl_s[i].hookmask & (1 << hooknr))
833                                 goto letscontinue;
834                         /* this can't be 0, so the loop test is correct */
835                         cl_s[i].cs.n = pos + 1;
836                         pos = 0;
837                         cl_s[i].cs.e = ebt_next_entry(e);
838                         e = (struct ebt_entry *)(hlp2->data);
839                         nentries = hlp2->nentries;
840                         cl_s[i].from = chain_nr;
841                         chain_nr = i;
842                         /* this udc is accessible from the base chain for hooknr */
843                         cl_s[i].hookmask |= (1 << hooknr);
844                         continue;
845                 }
846 letscontinue:
847                 e = ebt_next_entry(e);
848                 pos++;
849         }
850         return 0;
851 }
852
853 /* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
854 static int translate_table(struct net *net, const char *name,
855                            struct ebt_table_info *newinfo)
856 {
857         unsigned int i, j, k, udc_cnt;
858         int ret;
859         struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
860
861         i = 0;
862         while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
863                 i++;
864         if (i == NF_BR_NUMHOOKS) {
865                 BUGPRINT("No valid hooks specified\n");
866                 return -EINVAL;
867         }
868         if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
869                 BUGPRINT("Chains don't start at beginning\n");
870                 return -EINVAL;
871         }
872         /* make sure chains are ordered after each other in same order
873          * as their corresponding hooks
874          */
875         for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
876                 if (!newinfo->hook_entry[j])
877                         continue;
878                 if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
879                         BUGPRINT("Hook order must be followed\n");
880                         return -EINVAL;
881                 }
882                 i = j;
883         }
884
885         /* do some early checkings and initialize some things */
886         i = 0; /* holds the expected nr. of entries for the chain */
887         j = 0; /* holds the up to now counted entries for the chain */
888         k = 0; /* holds the total nr. of entries, should equal
889                 * newinfo->nentries afterwards
890                 */
891         udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
892         ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
893            ebt_check_entry_size_and_hooks, newinfo,
894            &i, &j, &k, &udc_cnt);
895
896         if (ret != 0)
897                 return ret;
898
899         if (i != j) {
900                 BUGPRINT("nentries does not equal the nr of entries in the "
901                          "(last) chain\n");
902                 return -EINVAL;
903         }
904         if (k != newinfo->nentries) {
905                 BUGPRINT("Total nentries is wrong\n");
906                 return -EINVAL;
907         }
908
909         /* get the location of the udc, put them in an array
910          * while we're at it, allocate the chainstack
911          */
912         if (udc_cnt) {
913                 /* this will get free'd in do_replace()/ebt_register_table()
914                  * if an error occurs
915                  */
916                 newinfo->chainstack =
917                         vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
918                 if (!newinfo->chainstack)
919                         return -ENOMEM;
920                 for_each_possible_cpu(i) {
921                         newinfo->chainstack[i] =
922                           vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
923                         if (!newinfo->chainstack[i]) {
924                                 while (i)
925                                         vfree(newinfo->chainstack[--i]);
926                                 vfree(newinfo->chainstack);
927                                 newinfo->chainstack = NULL;
928                                 return -ENOMEM;
929                         }
930                 }
931
932                 cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
933                 if (!cl_s)
934                         return -ENOMEM;
935                 i = 0; /* the i'th udc */
936                 EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
937                    ebt_get_udc_positions, newinfo, &i, cl_s);
938                 /* sanity check */
939                 if (i != udc_cnt) {
940                         BUGPRINT("i != udc_cnt\n");
941                         vfree(cl_s);
942                         return -EFAULT;
943                 }
944         }
945
946         /* Check for loops */
947         for (i = 0; i < NF_BR_NUMHOOKS; i++)
948                 if (newinfo->hook_entry[i])
949                         if (check_chainloops(newinfo->hook_entry[i],
950                            cl_s, udc_cnt, i, newinfo->entries)) {
951                                 vfree(cl_s);
952                                 return -EINVAL;
953                         }
954
955         /* we now know the following (along with E=mc²):
956          *  - the nr of entries in each chain is right
957          *  - the size of the allocated space is right
958          *  - all valid hooks have a corresponding chain
959          *  - there are no loops
960          *  - wrong data can still be on the level of a single entry
961          *  - could be there are jumps to places that are not the
962          *    beginning of a chain. This can only occur in chains that
963          *    are not accessible from any base chains, so we don't care.
964          */
965
966         /* used to know what we need to clean up if something goes wrong */
967         i = 0;
968         ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
969            ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
970         if (ret != 0) {
971                 EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
972                                   ebt_cleanup_entry, net, &i);
973         }
974         vfree(cl_s);
975         return ret;
976 }
977
978 /* called under write_lock */
979 static void get_counters(const struct ebt_counter *oldcounters,
980                          struct ebt_counter *counters, unsigned int nentries)
981 {
982         int i, cpu;
983         struct ebt_counter *counter_base;
984
985         /* counters of cpu 0 */
986         memcpy(counters, oldcounters,
987                sizeof(struct ebt_counter) * nentries);
988
989         /* add other counters to those of cpu 0 */
990         for_each_possible_cpu(cpu) {
991                 if (cpu == 0)
992                         continue;
993                 counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
994                 for (i = 0; i < nentries; i++) {
995                         counters[i].pcnt += counter_base[i].pcnt;
996                         counters[i].bcnt += counter_base[i].bcnt;
997                 }
998         }
999 }
1000
1001 static int do_replace_finish(struct net *net, struct ebt_replace *repl,
1002                               struct ebt_table_info *newinfo)
1003 {
1004         int ret, i;
1005         struct ebt_counter *counterstmp = NULL;
1006         /* used to be able to unlock earlier */
1007         struct ebt_table_info *table;
1008         struct ebt_table *t;
1009
1010         /* the user wants counters back
1011          * the check on the size is done later, when we have the lock
1012          */
1013         if (repl->num_counters) {
1014                 unsigned long size = repl->num_counters * sizeof(*counterstmp);
1015                 counterstmp = vmalloc(size);
1016                 if (!counterstmp)
1017                         return -ENOMEM;
1018         }
1019
1020         newinfo->chainstack = NULL;
1021         ret = ebt_verify_pointers(repl, newinfo);
1022         if (ret != 0)
1023                 goto free_counterstmp;
1024
1025         ret = translate_table(net, repl->name, newinfo);
1026
1027         if (ret != 0)
1028                 goto free_counterstmp;
1029
1030         t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
1031         if (!t) {
1032                 ret = -ENOENT;
1033                 goto free_iterate;
1034         }
1035
1036         /* the table doesn't like it */
1037         if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
1038                 goto free_unlock;
1039
1040         if (repl->num_counters && repl->num_counters != t->private->nentries) {
1041                 BUGPRINT("Wrong nr. of counters requested\n");
1042                 ret = -EINVAL;
1043                 goto free_unlock;
1044         }
1045
1046         /* we have the mutex lock, so no danger in reading this pointer */
1047         table = t->private;
1048         /* make sure the table can only be rmmod'ed if it contains no rules */
1049         if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
1050                 ret = -ENOENT;
1051                 goto free_unlock;
1052         } else if (table->nentries && !newinfo->nentries)
1053                 module_put(t->me);
1054         /* we need an atomic snapshot of the counters */
1055         write_lock_bh(&t->lock);
1056         if (repl->num_counters)
1057                 get_counters(t->private->counters, counterstmp,
1058                    t->private->nentries);
1059
1060         t->private = newinfo;
1061         write_unlock_bh(&t->lock);
1062         mutex_unlock(&ebt_mutex);
1063         /* so, a user can change the chains while having messed up her counter
1064          * allocation. Only reason why this is done is because this way the lock
1065          * is held only once, while this doesn't bring the kernel into a
1066          * dangerous state.
1067          */
1068         if (repl->num_counters &&
1069            copy_to_user(repl->counters, counterstmp,
1070            repl->num_counters * sizeof(struct ebt_counter))) {
1071                 /* Silent error, can't fail, new table is already in place */
1072                 net_warn_ratelimited("ebtables: counters copy to user failed while replacing table\n");
1073         }
1074
1075         /* decrease module count and free resources */
1076         EBT_ENTRY_ITERATE(table->entries, table->entries_size,
1077                           ebt_cleanup_entry, net, NULL);
1078
1079         vfree(table->entries);
1080         if (table->chainstack) {
1081                 for_each_possible_cpu(i)
1082                         vfree(table->chainstack[i]);
1083                 vfree(table->chainstack);
1084         }
1085         vfree(table);
1086
1087         vfree(counterstmp);
1088
1089 #ifdef CONFIG_AUDIT
1090         if (audit_enabled) {
1091                 struct audit_buffer *ab;
1092
1093                 ab = audit_log_start(current->audit_context, GFP_KERNEL,
1094                                      AUDIT_NETFILTER_CFG);
1095                 if (ab) {
1096                         audit_log_format(ab, "table=%s family=%u entries=%u",
1097                                          repl->name, AF_BRIDGE, repl->nentries);
1098                         audit_log_end(ab);
1099                 }
1100         }
1101 #endif
1102         return ret;
1103
1104 free_unlock:
1105         mutex_unlock(&ebt_mutex);
1106 free_iterate:
1107         EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
1108                           ebt_cleanup_entry, net, NULL);
1109 free_counterstmp:
1110         vfree(counterstmp);
1111         /* can be initialized in translate_table() */
1112         if (newinfo->chainstack) {
1113                 for_each_possible_cpu(i)
1114                         vfree(newinfo->chainstack[i]);
1115                 vfree(newinfo->chainstack);
1116         }
1117         return ret;
1118 }
1119
1120 /* replace the table */
1121 static int do_replace(struct net *net, const void __user *user,
1122                       unsigned int len)
1123 {
1124         int ret, countersize;
1125         struct ebt_table_info *newinfo;
1126         struct ebt_replace tmp;
1127
1128         if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
1129                 return -EFAULT;
1130
1131         if (len != sizeof(tmp) + tmp.entries_size) {
1132                 BUGPRINT("Wrong len argument\n");
1133                 return -EINVAL;
1134         }
1135
1136         if (tmp.entries_size == 0) {
1137                 BUGPRINT("Entries_size never zero\n");
1138                 return -EINVAL;
1139         }
1140         /* overflow check */
1141         if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
1142                         NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
1143                 return -ENOMEM;
1144         if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
1145                 return -ENOMEM;
1146
1147         tmp.name[sizeof(tmp.name) - 1] = 0;
1148
1149         countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
1150         newinfo = __vmalloc(sizeof(*newinfo) + countersize, GFP_KERNEL_ACCOUNT,
1151                             PAGE_KERNEL);
1152         if (!newinfo)
1153                 return -ENOMEM;
1154
1155         if (countersize)
1156                 memset(newinfo->counters, 0, countersize);
1157
1158         newinfo->entries = __vmalloc(tmp.entries_size, GFP_KERNEL_ACCOUNT,
1159                                      PAGE_KERNEL);
1160         if (!newinfo->entries) {
1161                 ret = -ENOMEM;
1162                 goto free_newinfo;
1163         }
1164         if (copy_from_user(
1165            newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
1166                 BUGPRINT("Couldn't copy entries from userspace\n");
1167                 ret = -EFAULT;
1168                 goto free_entries;
1169         }
1170
1171         ret = do_replace_finish(net, &tmp, newinfo);
1172         if (ret == 0)
1173                 return ret;
1174 free_entries:
1175         vfree(newinfo->entries);
1176 free_newinfo:
1177         vfree(newinfo);
1178         return ret;
1179 }
1180
1181 struct ebt_table *
1182 ebt_register_table(struct net *net, const struct ebt_table *input_table)
1183 {
1184         struct ebt_table_info *newinfo;
1185         struct ebt_table *t, *table;
1186         struct ebt_replace_kernel *repl;
1187         int ret, i, countersize;
1188         void *p;
1189
1190         if (input_table == NULL || (repl = input_table->table) == NULL ||
1191             repl->entries == NULL || repl->entries_size == 0 ||
1192             repl->counters != NULL || input_table->private != NULL) {
1193                 BUGPRINT("Bad table data for ebt_register_table!!!\n");
1194                 return ERR_PTR(-EINVAL);
1195         }
1196
1197         /* Don't add one table to multiple lists. */
1198         table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
1199         if (!table) {
1200                 ret = -ENOMEM;
1201                 goto out;
1202         }
1203
1204         countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
1205         newinfo = vmalloc(sizeof(*newinfo) + countersize);
1206         ret = -ENOMEM;
1207         if (!newinfo)
1208                 goto free_table;
1209
1210         p = vmalloc(repl->entries_size);
1211         if (!p)
1212                 goto free_newinfo;
1213
1214         memcpy(p, repl->entries, repl->entries_size);
1215         newinfo->entries = p;
1216
1217         newinfo->entries_size = repl->entries_size;
1218         newinfo->nentries = repl->nentries;
1219
1220         if (countersize)
1221                 memset(newinfo->counters, 0, countersize);
1222
1223         /* fill in newinfo and parse the entries */
1224         newinfo->chainstack = NULL;
1225         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
1226                 if ((repl->valid_hooks & (1 << i)) == 0)
1227                         newinfo->hook_entry[i] = NULL;
1228                 else
1229                         newinfo->hook_entry[i] = p +
1230                                 ((char *)repl->hook_entry[i] - repl->entries);
1231         }
1232         ret = translate_table(net, repl->name, newinfo);
1233         if (ret != 0) {
1234                 BUGPRINT("Translate_table failed\n");
1235                 goto free_chainstack;
1236         }
1237
1238         if (table->check && table->check(newinfo, table->valid_hooks)) {
1239                 BUGPRINT("The table doesn't like its own initial data, lol\n");
1240                 ret = -EINVAL;
1241                 goto free_chainstack;
1242         }
1243
1244         table->private = newinfo;
1245         rwlock_init(&table->lock);
1246         mutex_lock(&ebt_mutex);
1247         list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
1248                 if (strcmp(t->name, table->name) == 0) {
1249                         ret = -EEXIST;
1250                         BUGPRINT("Table name already exists\n");
1251                         goto free_unlock;
1252                 }
1253         }
1254
1255         /* Hold a reference count if the chains aren't empty */
1256         if (newinfo->nentries && !try_module_get(table->me)) {
1257                 ret = -ENOENT;
1258                 goto free_unlock;
1259         }
1260         list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
1261         mutex_unlock(&ebt_mutex);
1262         return table;
1263 free_unlock:
1264         mutex_unlock(&ebt_mutex);
1265 free_chainstack:
1266         if (newinfo->chainstack) {
1267                 for_each_possible_cpu(i)
1268                         vfree(newinfo->chainstack[i]);
1269                 vfree(newinfo->chainstack);
1270         }
1271         vfree(newinfo->entries);
1272 free_newinfo:
1273         vfree(newinfo);
1274 free_table:
1275         kfree(table);
1276 out:
1277         return ERR_PTR(ret);
1278 }
1279
1280 void ebt_unregister_table(struct net *net, struct ebt_table *table)
1281 {
1282         int i;
1283
1284         if (!table) {
1285                 BUGPRINT("Request to unregister NULL table!!!\n");
1286                 return;
1287         }
1288         mutex_lock(&ebt_mutex);
1289         list_del(&table->list);
1290         mutex_unlock(&ebt_mutex);
1291         EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
1292                           ebt_cleanup_entry, net, NULL);
1293         if (table->private->nentries)
1294                 module_put(table->me);
1295         vfree(table->private->entries);
1296         if (table->private->chainstack) {
1297                 for_each_possible_cpu(i)
1298                         vfree(table->private->chainstack[i]);
1299                 vfree(table->private->chainstack);
1300         }
1301         vfree(table->private);
1302         kfree(table);
1303 }
1304
1305 /* userspace just supplied us with counters */
1306 static int do_update_counters(struct net *net, const char *name,
1307                                 struct ebt_counter __user *counters,
1308                                 unsigned int num_counters,
1309                                 const void __user *user, unsigned int len)
1310 {
1311         int i, ret;
1312         struct ebt_counter *tmp;
1313         struct ebt_table *t;
1314
1315         if (num_counters == 0)
1316                 return -EINVAL;
1317
1318         tmp = vmalloc(num_counters * sizeof(*tmp));
1319         if (!tmp)
1320                 return -ENOMEM;
1321
1322         t = find_table_lock(net, name, &ret, &ebt_mutex);
1323         if (!t)
1324                 goto free_tmp;
1325
1326         if (num_counters != t->private->nentries) {
1327                 BUGPRINT("Wrong nr of counters\n");
1328                 ret = -EINVAL;
1329                 goto unlock_mutex;
1330         }
1331
1332         if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
1333                 ret = -EFAULT;
1334                 goto unlock_mutex;
1335         }
1336
1337         /* we want an atomic add of the counters */
1338         write_lock_bh(&t->lock);
1339
1340         /* we add to the counters of the first cpu */
1341         for (i = 0; i < num_counters; i++) {
1342                 t->private->counters[i].pcnt += tmp[i].pcnt;
1343                 t->private->counters[i].bcnt += tmp[i].bcnt;
1344         }
1345
1346         write_unlock_bh(&t->lock);
1347         ret = 0;
1348 unlock_mutex:
1349         mutex_unlock(&ebt_mutex);
1350 free_tmp:
1351         vfree(tmp);
1352         return ret;
1353 }
1354
1355 static int update_counters(struct net *net, const void __user *user,
1356                             unsigned int len)
1357 {
1358         struct ebt_replace hlp;
1359
1360         if (copy_from_user(&hlp, user, sizeof(hlp)))
1361                 return -EFAULT;
1362
1363         if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
1364                 return -EINVAL;
1365
1366         return do_update_counters(net, hlp.name, hlp.counters,
1367                                 hlp.num_counters, user, len);
1368 }
1369
1370 static inline int ebt_make_matchname(const struct ebt_entry_match *m,
1371                                      const char *base, char __user *ubase)
1372 {
1373         char __user *hlp = ubase + ((char *)m - base);
1374         char name[EBT_FUNCTION_MAXNAMELEN] = {};
1375
1376         /* ebtables expects 32 bytes long names but xt_match names are 29 bytes
1377          * long. Copy 29 bytes and fill remaining bytes with zeroes.
1378          */
1379         strlcpy(name, m->u.match->name, sizeof(name));
1380         if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN))
1381                 return -EFAULT;
1382         return 0;
1383 }
1384
1385 static inline int ebt_make_watchername(const struct ebt_entry_watcher *w,
1386                                        const char *base, char __user *ubase)
1387 {
1388         char __user *hlp = ubase + ((char *)w - base);
1389         char name[EBT_FUNCTION_MAXNAMELEN] = {};
1390
1391         strlcpy(name, w->u.watcher->name, sizeof(name));
1392         if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN))
1393                 return -EFAULT;
1394         return 0;
1395 }
1396
1397 static inline int ebt_make_names(struct ebt_entry *e, const char *base,
1398                                  char __user *ubase)
1399 {
1400         int ret;
1401         char __user *hlp;
1402         const struct ebt_entry_target *t;
1403         char name[EBT_FUNCTION_MAXNAMELEN] = {};
1404
1405         if (e->bitmask == 0)
1406                 return 0;
1407
1408         hlp = ubase + (((char *)e + e->target_offset) - base);
1409         t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
1410
1411         ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase);
1412         if (ret != 0)
1413                 return ret;
1414         ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase);
1415         if (ret != 0)
1416                 return ret;
1417         strlcpy(name, t->u.target->name, sizeof(name));
1418         if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN))
1419                 return -EFAULT;
1420         return 0;
1421 }
1422
1423 static int copy_counters_to_user(struct ebt_table *t,
1424                                  const struct ebt_counter *oldcounters,
1425                                  void __user *user, unsigned int num_counters,
1426                                  unsigned int nentries)
1427 {
1428         struct ebt_counter *counterstmp;
1429         int ret = 0;
1430
1431         /* userspace might not need the counters */
1432         if (num_counters == 0)
1433                 return 0;
1434
1435         if (num_counters != nentries) {
1436                 BUGPRINT("Num_counters wrong\n");
1437                 return -EINVAL;
1438         }
1439
1440         counterstmp = vmalloc(nentries * sizeof(*counterstmp));
1441         if (!counterstmp)
1442                 return -ENOMEM;
1443
1444         write_lock_bh(&t->lock);
1445         get_counters(oldcounters, counterstmp, nentries);
1446         write_unlock_bh(&t->lock);
1447
1448         if (copy_to_user(user, counterstmp,
1449            nentries * sizeof(struct ebt_counter)))
1450                 ret = -EFAULT;
1451         vfree(counterstmp);
1452         return ret;
1453 }
1454
1455 /* called with ebt_mutex locked */
1456 static int copy_everything_to_user(struct ebt_table *t, void __user *user,
1457                                    const int *len, int cmd)
1458 {
1459         struct ebt_replace tmp;
1460         const struct ebt_counter *oldcounters;
1461         unsigned int entries_size, nentries;
1462         int ret;
1463         char *entries;
1464
1465         if (cmd == EBT_SO_GET_ENTRIES) {
1466                 entries_size = t->private->entries_size;
1467                 nentries = t->private->nentries;
1468                 entries = t->private->entries;
1469                 oldcounters = t->private->counters;
1470         } else {
1471                 entries_size = t->table->entries_size;
1472                 nentries = t->table->nentries;
1473                 entries = t->table->entries;
1474                 oldcounters = t->table->counters;
1475         }
1476
1477         if (copy_from_user(&tmp, user, sizeof(tmp)))
1478                 return -EFAULT;
1479
1480         if (*len != sizeof(struct ebt_replace) + entries_size +
1481            (tmp.num_counters ? nentries * sizeof(struct ebt_counter) : 0))
1482                 return -EINVAL;
1483
1484         if (tmp.nentries != nentries) {
1485                 BUGPRINT("Nentries wrong\n");
1486                 return -EINVAL;
1487         }
1488
1489         if (tmp.entries_size != entries_size) {
1490                 BUGPRINT("Wrong size\n");
1491                 return -EINVAL;
1492         }
1493
1494         ret = copy_counters_to_user(t, oldcounters, tmp.counters,
1495                                         tmp.num_counters, nentries);
1496         if (ret)
1497                 return ret;
1498
1499         if (copy_to_user(tmp.entries, entries, entries_size)) {
1500                 BUGPRINT("Couldn't copy entries to userspace\n");
1501                 return -EFAULT;
1502         }
1503         /* set the match/watcher/target names right */
1504         return EBT_ENTRY_ITERATE(entries, entries_size,
1505            ebt_make_names, entries, tmp.entries);
1506 }
1507
1508 static int do_ebt_set_ctl(struct sock *sk,
1509         int cmd, void __user *user, unsigned int len)
1510 {
1511         int ret;
1512         struct net *net = sock_net(sk);
1513
1514         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1515                 return -EPERM;
1516
1517         switch (cmd) {
1518         case EBT_SO_SET_ENTRIES:
1519                 ret = do_replace(net, user, len);
1520                 break;
1521         case EBT_SO_SET_COUNTERS:
1522                 ret = update_counters(net, user, len);
1523                 break;
1524         default:
1525                 ret = -EINVAL;
1526         }
1527         return ret;
1528 }
1529
1530 static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
1531 {
1532         int ret;
1533         struct ebt_replace tmp;
1534         struct ebt_table *t;
1535         struct net *net = sock_net(sk);
1536
1537         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1538                 return -EPERM;
1539
1540         if (copy_from_user(&tmp, user, sizeof(tmp)))
1541                 return -EFAULT;
1542
1543         tmp.name[sizeof(tmp.name) - 1] = '\0';
1544
1545         t = find_table_lock(net, tmp.name, &ret, &ebt_mutex);
1546         if (!t)
1547                 return ret;
1548
1549         switch (cmd) {
1550         case EBT_SO_GET_INFO:
1551         case EBT_SO_GET_INIT_INFO:
1552                 if (*len != sizeof(struct ebt_replace)) {
1553                         ret = -EINVAL;
1554                         mutex_unlock(&ebt_mutex);
1555                         break;
1556                 }
1557                 if (cmd == EBT_SO_GET_INFO) {
1558                         tmp.nentries = t->private->nentries;
1559                         tmp.entries_size = t->private->entries_size;
1560                         tmp.valid_hooks = t->valid_hooks;
1561                 } else {
1562                         tmp.nentries = t->table->nentries;
1563                         tmp.entries_size = t->table->entries_size;
1564                         tmp.valid_hooks = t->table->valid_hooks;
1565                 }
1566                 mutex_unlock(&ebt_mutex);
1567                 if (copy_to_user(user, &tmp, *len) != 0) {
1568                         BUGPRINT("c2u Didn't work\n");
1569                         ret = -EFAULT;
1570                         break;
1571                 }
1572                 ret = 0;
1573                 break;
1574
1575         case EBT_SO_GET_ENTRIES:
1576         case EBT_SO_GET_INIT_ENTRIES:
1577                 ret = copy_everything_to_user(t, user, len, cmd);
1578                 mutex_unlock(&ebt_mutex);
1579                 break;
1580
1581         default:
1582                 mutex_unlock(&ebt_mutex);
1583                 ret = -EINVAL;
1584         }
1585
1586         return ret;
1587 }
1588
1589 #ifdef CONFIG_COMPAT
1590 /* 32 bit-userspace compatibility definitions. */
1591 struct compat_ebt_replace {
1592         char name[EBT_TABLE_MAXNAMELEN];
1593         compat_uint_t valid_hooks;
1594         compat_uint_t nentries;
1595         compat_uint_t entries_size;
1596         /* start of the chains */
1597         compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
1598         /* nr of counters userspace expects back */
1599         compat_uint_t num_counters;
1600         /* where the kernel will put the old counters. */
1601         compat_uptr_t counters;
1602         compat_uptr_t entries;
1603 };
1604
1605 /* struct ebt_entry_match, _target and _watcher have same layout */
1606 struct compat_ebt_entry_mwt {
1607         union {
1608                 char name[EBT_FUNCTION_MAXNAMELEN];
1609                 compat_uptr_t ptr;
1610         } u;
1611         compat_uint_t match_size;
1612         compat_uint_t data[0];
1613 };
1614
1615 /* account for possible padding between match_size and ->data */
1616 static int ebt_compat_entry_padsize(void)
1617 {
1618         BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
1619                         COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
1620         return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
1621                         COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
1622 }
1623
1624 static int ebt_compat_match_offset(const struct xt_match *match,
1625                                    unsigned int userlen)
1626 {
1627         /* ebt_among needs special handling. The kernel .matchsize is
1628          * set to -1 at registration time; at runtime an EBT_ALIGN()ed
1629          * value is expected.
1630          * Example: userspace sends 4500, ebt_among.c wants 4504.
1631          */
1632         if (unlikely(match->matchsize == -1))
1633                 return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
1634         return xt_compat_match_offset(match);
1635 }
1636
1637 static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
1638                                 unsigned int *size)
1639 {
1640         const struct xt_match *match = m->u.match;
1641         struct compat_ebt_entry_mwt __user *cm = *dstptr;
1642         int off = ebt_compat_match_offset(match, m->match_size);
1643         compat_uint_t msize = m->match_size - off;
1644
1645         if (WARN_ON(off >= m->match_size))
1646                 return -EINVAL;
1647
1648         if (copy_to_user(cm->u.name, match->name,
1649             strlen(match->name) + 1) || put_user(msize, &cm->match_size))
1650                 return -EFAULT;
1651
1652         if (match->compat_to_user) {
1653                 if (match->compat_to_user(cm->data, m->data))
1654                         return -EFAULT;
1655         } else if (copy_to_user(cm->data, m->data, msize))
1656                         return -EFAULT;
1657
1658         *size -= ebt_compat_entry_padsize() + off;
1659         *dstptr = cm->data;
1660         *dstptr += msize;
1661         return 0;
1662 }
1663
1664 static int compat_target_to_user(struct ebt_entry_target *t,
1665                                  void __user **dstptr,
1666                                  unsigned int *size)
1667 {
1668         const struct xt_target *target = t->u.target;
1669         struct compat_ebt_entry_mwt __user *cm = *dstptr;
1670         int off = xt_compat_target_offset(target);
1671         compat_uint_t tsize = t->target_size - off;
1672
1673         if (WARN_ON(off >= t->target_size))
1674                 return -EINVAL;
1675
1676         if (copy_to_user(cm->u.name, target->name,
1677             strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
1678                 return -EFAULT;
1679
1680         if (target->compat_to_user) {
1681                 if (target->compat_to_user(cm->data, t->data))
1682                         return -EFAULT;
1683         } else if (copy_to_user(cm->data, t->data, tsize))
1684                 return -EFAULT;
1685
1686         *size -= ebt_compat_entry_padsize() + off;
1687         *dstptr = cm->data;
1688         *dstptr += tsize;
1689         return 0;
1690 }
1691
1692 static int compat_watcher_to_user(struct ebt_entry_watcher *w,
1693                                   void __user **dstptr,
1694                                   unsigned int *size)
1695 {
1696         return compat_target_to_user((struct ebt_entry_target *)w,
1697                                                         dstptr, size);
1698 }
1699
1700 static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
1701                                 unsigned int *size)
1702 {
1703         struct ebt_entry_target *t;
1704         struct ebt_entry __user *ce;
1705         u32 watchers_offset, target_offset, next_offset;
1706         compat_uint_t origsize;
1707         int ret;
1708
1709         if (e->bitmask == 0) {
1710                 if (*size < sizeof(struct ebt_entries))
1711                         return -EINVAL;
1712                 if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
1713                         return -EFAULT;
1714
1715                 *dstptr += sizeof(struct ebt_entries);
1716                 *size -= sizeof(struct ebt_entries);
1717                 return 0;
1718         }
1719
1720         if (*size < sizeof(*ce))
1721                 return -EINVAL;
1722
1723         ce = (struct ebt_entry __user *)*dstptr;
1724         if (copy_to_user(ce, e, sizeof(*ce)))
1725                 return -EFAULT;
1726
1727         origsize = *size;
1728         *dstptr += sizeof(*ce);
1729
1730         ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
1731         if (ret)
1732                 return ret;
1733         watchers_offset = e->watchers_offset - (origsize - *size);
1734
1735         ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
1736         if (ret)
1737                 return ret;
1738         target_offset = e->target_offset - (origsize - *size);
1739
1740         t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
1741
1742         ret = compat_target_to_user(t, dstptr, size);
1743         if (ret)
1744                 return ret;
1745         next_offset = e->next_offset - (origsize - *size);
1746
1747         if (put_user(watchers_offset, &ce->watchers_offset) ||
1748             put_user(target_offset, &ce->target_offset) ||
1749             put_user(next_offset, &ce->next_offset))
1750                 return -EFAULT;
1751
1752         *size -= sizeof(*ce);
1753         return 0;
1754 }
1755
1756 static int compat_calc_match(struct ebt_entry_match *m, int *off)
1757 {
1758         *off += ebt_compat_match_offset(m->u.match, m->match_size);
1759         *off += ebt_compat_entry_padsize();
1760         return 0;
1761 }
1762
1763 static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
1764 {
1765         *off += xt_compat_target_offset(w->u.watcher);
1766         *off += ebt_compat_entry_padsize();
1767         return 0;
1768 }
1769
1770 static int compat_calc_entry(const struct ebt_entry *e,
1771                              const struct ebt_table_info *info,
1772                              const void *base,
1773                              struct compat_ebt_replace *newinfo)
1774 {
1775         const struct ebt_entry_target *t;
1776         unsigned int entry_offset;
1777         int off, ret, i;
1778
1779         if (e->bitmask == 0)
1780                 return 0;
1781
1782         off = 0;
1783         entry_offset = (void *)e - base;
1784
1785         EBT_MATCH_ITERATE(e, compat_calc_match, &off);
1786         EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
1787
1788         t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
1789
1790         off += xt_compat_target_offset(t->u.target);
1791         off += ebt_compat_entry_padsize();
1792
1793         newinfo->entries_size -= off;
1794
1795         ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
1796         if (ret)
1797                 return ret;
1798
1799         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
1800                 const void *hookptr = info->hook_entry[i];
1801                 if (info->hook_entry[i] &&
1802                     (e < (struct ebt_entry *)(base - hookptr))) {
1803                         newinfo->hook_entry[i] -= off;
1804                         pr_debug("0x%08X -> 0x%08X\n",
1805                                         newinfo->hook_entry[i] + off,
1806                                         newinfo->hook_entry[i]);
1807                 }
1808         }
1809
1810         return 0;
1811 }
1812
1813
1814 static int compat_table_info(const struct ebt_table_info *info,
1815                              struct compat_ebt_replace *newinfo)
1816 {
1817         unsigned int size = info->entries_size;
1818         const void *entries = info->entries;
1819
1820         newinfo->entries_size = size;
1821
1822         xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries);
1823         return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
1824                                                         entries, newinfo);
1825 }
1826
1827 static int compat_copy_everything_to_user(struct ebt_table *t,
1828                                           void __user *user, int *len, int cmd)
1829 {
1830         struct compat_ebt_replace repl, tmp;
1831         struct ebt_counter *oldcounters;
1832         struct ebt_table_info tinfo;
1833         int ret;
1834         void __user *pos;
1835
1836         memset(&tinfo, 0, sizeof(tinfo));
1837
1838         if (cmd == EBT_SO_GET_ENTRIES) {
1839                 tinfo.entries_size = t->private->entries_size;
1840                 tinfo.nentries = t->private->nentries;
1841                 tinfo.entries = t->private->entries;
1842                 oldcounters = t->private->counters;
1843         } else {
1844                 tinfo.entries_size = t->table->entries_size;
1845                 tinfo.nentries = t->table->nentries;
1846                 tinfo.entries = t->table->entries;
1847                 oldcounters = t->table->counters;
1848         }
1849
1850         if (copy_from_user(&tmp, user, sizeof(tmp)))
1851                 return -EFAULT;
1852
1853         if (tmp.nentries != tinfo.nentries ||
1854            (tmp.num_counters && tmp.num_counters != tinfo.nentries))
1855                 return -EINVAL;
1856
1857         memcpy(&repl, &tmp, sizeof(repl));
1858         if (cmd == EBT_SO_GET_ENTRIES)
1859                 ret = compat_table_info(t->private, &repl);
1860         else
1861                 ret = compat_table_info(&tinfo, &repl);
1862         if (ret)
1863                 return ret;
1864
1865         if (*len != sizeof(tmp) + repl.entries_size +
1866            (tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
1867                 pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
1868                                 *len, tinfo.entries_size, repl.entries_size);
1869                 return -EINVAL;
1870         }
1871
1872         /* userspace might not need the counters */
1873         ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
1874                                         tmp.num_counters, tinfo.nentries);
1875         if (ret)
1876                 return ret;
1877
1878         pos = compat_ptr(tmp.entries);
1879         return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
1880                         compat_copy_entry_to_user, &pos, &tmp.entries_size);
1881 }
1882
1883 struct ebt_entries_buf_state {
1884         char *buf_kern_start;   /* kernel buffer to copy (translated) data to */
1885         u32 buf_kern_len;       /* total size of kernel buffer */
1886         u32 buf_kern_offset;    /* amount of data copied so far */
1887         u32 buf_user_offset;    /* read position in userspace buffer */
1888 };
1889
1890 static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
1891 {
1892         state->buf_kern_offset += sz;
1893         return state->buf_kern_offset >= sz ? 0 : -EINVAL;
1894 }
1895
1896 static int ebt_buf_add(struct ebt_entries_buf_state *state,
1897                        const void *data, unsigned int sz)
1898 {
1899         if (state->buf_kern_start == NULL)
1900                 goto count_only;
1901
1902         if (WARN_ON(state->buf_kern_offset + sz > state->buf_kern_len))
1903                 return -EINVAL;
1904
1905         memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
1906
1907  count_only:
1908         state->buf_user_offset += sz;
1909         return ebt_buf_count(state, sz);
1910 }
1911
1912 static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
1913 {
1914         char *b = state->buf_kern_start;
1915
1916         if (WARN_ON(b && state->buf_kern_offset > state->buf_kern_len))
1917                 return -EINVAL;
1918
1919         if (b != NULL && sz > 0)
1920                 memset(b + state->buf_kern_offset, 0, sz);
1921         /* do not adjust ->buf_user_offset here, we added kernel-side padding */
1922         return ebt_buf_count(state, sz);
1923 }
1924
1925 enum compat_mwt {
1926         EBT_COMPAT_MATCH,
1927         EBT_COMPAT_WATCHER,
1928         EBT_COMPAT_TARGET,
1929 };
1930
1931 static int compat_mtw_from_user(const struct compat_ebt_entry_mwt *mwt,
1932                                 enum compat_mwt compat_mwt,
1933                                 struct ebt_entries_buf_state *state,
1934                                 const unsigned char *base)
1935 {
1936         char name[EBT_FUNCTION_MAXNAMELEN];
1937         struct xt_match *match;
1938         struct xt_target *wt;
1939         void *dst = NULL;
1940         int off, pad = 0;
1941         unsigned int size_kern, match_size = mwt->match_size;
1942
1943         if (strscpy(name, mwt->u.name, sizeof(name)) < 0)
1944                 return -EINVAL;
1945
1946         if (state->buf_kern_start)
1947                 dst = state->buf_kern_start + state->buf_kern_offset;
1948
1949         switch (compat_mwt) {
1950         case EBT_COMPAT_MATCH:
1951                 match = xt_request_find_match(NFPROTO_BRIDGE, name, 0);
1952                 if (IS_ERR(match))
1953                         return PTR_ERR(match);
1954
1955                 off = ebt_compat_match_offset(match, match_size);
1956                 if (dst) {
1957                         if (match->compat_from_user)
1958                                 match->compat_from_user(dst, mwt->data);
1959                         else
1960                                 memcpy(dst, mwt->data, match_size);
1961                 }
1962
1963                 size_kern = match->matchsize;
1964                 if (unlikely(size_kern == -1))
1965                         size_kern = match_size;
1966                 module_put(match->me);
1967                 break;
1968         case EBT_COMPAT_WATCHER: /* fallthrough */
1969         case EBT_COMPAT_TARGET:
1970                 wt = xt_request_find_target(NFPROTO_BRIDGE, name, 0);
1971                 if (IS_ERR(wt))
1972                         return PTR_ERR(wt);
1973                 off = xt_compat_target_offset(wt);
1974
1975                 if (dst) {
1976                         if (wt->compat_from_user)
1977                                 wt->compat_from_user(dst, mwt->data);
1978                         else
1979                                 memcpy(dst, mwt->data, match_size);
1980                 }
1981
1982                 size_kern = wt->targetsize;
1983                 module_put(wt->me);
1984                 break;
1985
1986         default:
1987                 return -EINVAL;
1988         }
1989
1990         state->buf_kern_offset += match_size + off;
1991         state->buf_user_offset += match_size;
1992         pad = XT_ALIGN(size_kern) - size_kern;
1993
1994         if (pad > 0 && dst) {
1995                 if (WARN_ON(state->buf_kern_len <= pad))
1996                         return -EINVAL;
1997                 if (WARN_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad))
1998                         return -EINVAL;
1999                 memset(dst + size_kern, 0, pad);
2000         }
2001         return off + match_size;
2002 }
2003
2004 /* return size of all matches, watchers or target, including necessary
2005  * alignment and padding.
2006  */
2007 static int ebt_size_mwt(const struct compat_ebt_entry_mwt *match32,
2008                         unsigned int size_left, enum compat_mwt type,
2009                         struct ebt_entries_buf_state *state, const void *base)
2010 {
2011         const char *buf = (const char *)match32;
2012         int growth = 0;
2013
2014         if (size_left == 0)
2015                 return 0;
2016
2017         do {
2018                 struct ebt_entry_match *match_kern;
2019                 int ret;
2020
2021                 if (size_left < sizeof(*match32))
2022                         return -EINVAL;
2023
2024                 match_kern = (struct ebt_entry_match *) state->buf_kern_start;
2025                 if (match_kern) {
2026                         char *tmp;
2027                         tmp = state->buf_kern_start + state->buf_kern_offset;
2028                         match_kern = (struct ebt_entry_match *) tmp;
2029                 }
2030                 ret = ebt_buf_add(state, buf, sizeof(*match32));
2031                 if (ret < 0)
2032                         return ret;
2033                 size_left -= sizeof(*match32);
2034
2035                 /* add padding before match->data (if any) */
2036                 ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
2037                 if (ret < 0)
2038                         return ret;
2039
2040                 if (match32->match_size > size_left)
2041                         return -EINVAL;
2042
2043                 size_left -= match32->match_size;
2044
2045                 ret = compat_mtw_from_user(match32, type, state, base);
2046                 if (ret < 0)
2047                         return ret;
2048
2049                 if (WARN_ON(ret < match32->match_size))
2050                         return -EINVAL;
2051                 growth += ret - match32->match_size;
2052                 growth += ebt_compat_entry_padsize();
2053
2054                 buf += sizeof(*match32);
2055                 buf += match32->match_size;
2056
2057                 if (match_kern)
2058                         match_kern->match_size = ret;
2059
2060                 match32 = (struct compat_ebt_entry_mwt *) buf;
2061         } while (size_left);
2062
2063         return growth;
2064 }
2065
2066 /* called for all ebt_entry structures. */
2067 static int size_entry_mwt(const struct ebt_entry *entry, const unsigned char *base,
2068                           unsigned int *total,
2069                           struct ebt_entries_buf_state *state)
2070 {
2071         unsigned int i, j, startoff, next_expected_off, new_offset = 0;
2072         /* stores match/watchers/targets & offset of next struct ebt_entry: */
2073         unsigned int offsets[4];
2074         unsigned int *offsets_update = NULL;
2075         int ret;
2076         char *buf_start;
2077
2078         if (*total < sizeof(struct ebt_entries))
2079                 return -EINVAL;
2080
2081         if (!entry->bitmask) {
2082                 *total -= sizeof(struct ebt_entries);
2083                 return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
2084         }
2085         if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
2086                 return -EINVAL;
2087
2088         startoff = state->buf_user_offset;
2089         /* pull in most part of ebt_entry, it does not need to be changed. */
2090         ret = ebt_buf_add(state, entry,
2091                         offsetof(struct ebt_entry, watchers_offset));
2092         if (ret < 0)
2093                 return ret;
2094
2095         offsets[0] = sizeof(struct ebt_entry); /* matches come first */
2096         memcpy(&offsets[1], &entry->watchers_offset,
2097                         sizeof(offsets) - sizeof(offsets[0]));
2098
2099         if (state->buf_kern_start) {
2100                 buf_start = state->buf_kern_start + state->buf_kern_offset;
2101                 offsets_update = (unsigned int *) buf_start;
2102         }
2103         ret = ebt_buf_add(state, &offsets[1],
2104                         sizeof(offsets) - sizeof(offsets[0]));
2105         if (ret < 0)
2106                 return ret;
2107         buf_start = (char *) entry;
2108         /* 0: matches offset, always follows ebt_entry.
2109          * 1: watchers offset, from ebt_entry structure
2110          * 2: target offset, from ebt_entry structure
2111          * 3: next ebt_entry offset, from ebt_entry structure
2112          *
2113          * offsets are relative to beginning of struct ebt_entry (i.e., 0).
2114          */
2115         for (i = 0; i < 4 ; ++i) {
2116                 if (offsets[i] > *total)
2117                         return -EINVAL;
2118
2119                 if (i < 3 && offsets[i] == *total)
2120                         return -EINVAL;
2121
2122                 if (i == 0)
2123                         continue;
2124                 if (offsets[i-1] > offsets[i])
2125                         return -EINVAL;
2126         }
2127
2128         for (i = 0, j = 1 ; j < 4 ; j++, i++) {
2129                 struct compat_ebt_entry_mwt *match32;
2130                 unsigned int size;
2131                 char *buf = buf_start;
2132
2133                 buf = buf_start + offsets[i];
2134                 if (offsets[i] > offsets[j])
2135                         return -EINVAL;
2136
2137                 match32 = (struct compat_ebt_entry_mwt *) buf;
2138                 size = offsets[j] - offsets[i];
2139                 ret = ebt_size_mwt(match32, size, i, state, base);
2140                 if (ret < 0)
2141                         return ret;
2142                 new_offset += ret;
2143                 if (offsets_update && new_offset) {
2144                         pr_debug("change offset %d to %d\n",
2145                                 offsets_update[i], offsets[j] + new_offset);
2146                         offsets_update[i] = offsets[j] + new_offset;
2147                 }
2148         }
2149
2150         if (state->buf_kern_start == NULL) {
2151                 unsigned int offset = buf_start - (char *) base;
2152
2153                 ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
2154                 if (ret < 0)
2155                         return ret;
2156         }
2157
2158         next_expected_off = state->buf_user_offset - startoff;
2159         if (next_expected_off != entry->next_offset)
2160                 return -EINVAL;
2161
2162         if (*total < entry->next_offset)
2163                 return -EINVAL;
2164         *total -= entry->next_offset;
2165         return 0;
2166 }
2167
2168 /* repl->entries_size is the size of the ebt_entry blob in userspace.
2169  * It might need more memory when copied to a 64 bit kernel in case
2170  * userspace is 32-bit. So, first task: find out how much memory is needed.
2171  *
2172  * Called before validation is performed.
2173  */
2174 static int compat_copy_entries(unsigned char *data, unsigned int size_user,
2175                                 struct ebt_entries_buf_state *state)
2176 {
2177         unsigned int size_remaining = size_user;
2178         int ret;
2179
2180         ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
2181                                         &size_remaining, state);
2182         if (ret < 0)
2183                 return ret;
2184
2185         if (size_remaining)
2186                 return -EINVAL;
2187
2188         return state->buf_kern_offset;
2189 }
2190
2191
2192 static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
2193                                             void __user *user, unsigned int len)
2194 {
2195         struct compat_ebt_replace tmp;
2196         int i;
2197
2198         if (len < sizeof(tmp))
2199                 return -EINVAL;
2200
2201         if (copy_from_user(&tmp, user, sizeof(tmp)))
2202                 return -EFAULT;
2203
2204         if (len != sizeof(tmp) + tmp.entries_size)
2205                 return -EINVAL;
2206
2207         if (tmp.entries_size == 0)
2208                 return -EINVAL;
2209
2210         if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
2211                         NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
2212                 return -ENOMEM;
2213         if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
2214                 return -ENOMEM;
2215
2216         memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
2217
2218         /* starting with hook_entry, 32 vs. 64 bit structures are different */
2219         for (i = 0; i < NF_BR_NUMHOOKS; i++)
2220                 repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
2221
2222         repl->num_counters = tmp.num_counters;
2223         repl->counters = compat_ptr(tmp.counters);
2224         repl->entries = compat_ptr(tmp.entries);
2225         return 0;
2226 }
2227
2228 static int compat_do_replace(struct net *net, void __user *user,
2229                              unsigned int len)
2230 {
2231         int ret, i, countersize, size64;
2232         struct ebt_table_info *newinfo;
2233         struct ebt_replace tmp;
2234         struct ebt_entries_buf_state state;
2235         void *entries_tmp;
2236
2237         ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
2238         if (ret) {
2239                 /* try real handler in case userland supplied needed padding */
2240                 if (ret == -EINVAL && do_replace(net, user, len) == 0)
2241                         ret = 0;
2242                 return ret;
2243         }
2244
2245         countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
2246         newinfo = vmalloc(sizeof(*newinfo) + countersize);
2247         if (!newinfo)
2248                 return -ENOMEM;
2249
2250         if (countersize)
2251                 memset(newinfo->counters, 0, countersize);
2252
2253         memset(&state, 0, sizeof(state));
2254
2255         newinfo->entries = vmalloc(tmp.entries_size);
2256         if (!newinfo->entries) {
2257                 ret = -ENOMEM;
2258                 goto free_newinfo;
2259         }
2260         if (copy_from_user(
2261            newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
2262                 ret = -EFAULT;
2263                 goto free_entries;
2264         }
2265
2266         entries_tmp = newinfo->entries;
2267
2268         xt_compat_lock(NFPROTO_BRIDGE);
2269
2270         xt_compat_init_offsets(NFPROTO_BRIDGE, tmp.nentries);
2271         ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
2272         if (ret < 0)
2273                 goto out_unlock;
2274
2275         pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
2276                 tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
2277                 xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
2278
2279         size64 = ret;
2280         newinfo->entries = vmalloc(size64);
2281         if (!newinfo->entries) {
2282                 vfree(entries_tmp);
2283                 ret = -ENOMEM;
2284                 goto out_unlock;
2285         }
2286
2287         memset(&state, 0, sizeof(state));
2288         state.buf_kern_start = newinfo->entries;
2289         state.buf_kern_len = size64;
2290
2291         ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
2292         if (WARN_ON(ret < 0)) {
2293                 vfree(entries_tmp);
2294                 goto out_unlock;
2295         }
2296
2297         vfree(entries_tmp);
2298         tmp.entries_size = size64;
2299
2300         for (i = 0; i < NF_BR_NUMHOOKS; i++) {
2301                 char __user *usrptr;
2302                 if (tmp.hook_entry[i]) {
2303                         unsigned int delta;
2304                         usrptr = (char __user *) tmp.hook_entry[i];
2305                         delta = usrptr - tmp.entries;
2306                         usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
2307                         tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
2308                 }
2309         }
2310
2311         xt_compat_flush_offsets(NFPROTO_BRIDGE);
2312         xt_compat_unlock(NFPROTO_BRIDGE);
2313
2314         ret = do_replace_finish(net, &tmp, newinfo);
2315         if (ret == 0)
2316                 return ret;
2317 free_entries:
2318         vfree(newinfo->entries);
2319 free_newinfo:
2320         vfree(newinfo);
2321         return ret;
2322 out_unlock:
2323         xt_compat_flush_offsets(NFPROTO_BRIDGE);
2324         xt_compat_unlock(NFPROTO_BRIDGE);
2325         goto free_entries;
2326 }
2327
2328 static int compat_update_counters(struct net *net, void __user *user,
2329                                   unsigned int len)
2330 {
2331         struct compat_ebt_replace hlp;
2332
2333         if (copy_from_user(&hlp, user, sizeof(hlp)))
2334                 return -EFAULT;
2335
2336         /* try real handler in case userland supplied needed padding */
2337         if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
2338                 return update_counters(net, user, len);
2339
2340         return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
2341                                         hlp.num_counters, user, len);
2342 }
2343
2344 static int compat_do_ebt_set_ctl(struct sock *sk,
2345                 int cmd, void __user *user, unsigned int len)
2346 {
2347         int ret;
2348         struct net *net = sock_net(sk);
2349
2350         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2351                 return -EPERM;
2352
2353         switch (cmd) {
2354         case EBT_SO_SET_ENTRIES:
2355                 ret = compat_do_replace(net, user, len);
2356                 break;
2357         case EBT_SO_SET_COUNTERS:
2358                 ret = compat_update_counters(net, user, len);
2359                 break;
2360         default:
2361                 ret = -EINVAL;
2362         }
2363         return ret;
2364 }
2365
2366 static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
2367                 void __user *user, int *len)
2368 {
2369         int ret;
2370         struct compat_ebt_replace tmp;
2371         struct ebt_table *t;
2372         struct net *net = sock_net(sk);
2373
2374         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2375                 return -EPERM;
2376
2377         /* try real handler in case userland supplied needed padding */
2378         if ((cmd == EBT_SO_GET_INFO ||
2379              cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
2380                         return do_ebt_get_ctl(sk, cmd, user, len);
2381
2382         if (copy_from_user(&tmp, user, sizeof(tmp)))
2383                 return -EFAULT;
2384
2385         tmp.name[sizeof(tmp.name) - 1] = '\0';
2386
2387         t = find_table_lock(net, tmp.name, &ret, &ebt_mutex);
2388         if (!t)
2389                 return ret;
2390
2391         xt_compat_lock(NFPROTO_BRIDGE);
2392         switch (cmd) {
2393         case EBT_SO_GET_INFO:
2394                 tmp.nentries = t->private->nentries;
2395                 ret = compat_table_info(t->private, &tmp);
2396                 if (ret)
2397                         goto out;
2398                 tmp.valid_hooks = t->valid_hooks;
2399
2400                 if (copy_to_user(user, &tmp, *len) != 0) {
2401                         ret = -EFAULT;
2402                         break;
2403                 }
2404                 ret = 0;
2405                 break;
2406         case EBT_SO_GET_INIT_INFO:
2407                 tmp.nentries = t->table->nentries;
2408                 tmp.entries_size = t->table->entries_size;
2409                 tmp.valid_hooks = t->table->valid_hooks;
2410
2411                 if (copy_to_user(user, &tmp, *len) != 0) {
2412                         ret = -EFAULT;
2413                         break;
2414                 }
2415                 ret = 0;
2416                 break;
2417         case EBT_SO_GET_ENTRIES:
2418         case EBT_SO_GET_INIT_ENTRIES:
2419                 /* try real handler first in case of userland-side padding.
2420                  * in case we are dealing with an 'ordinary' 32 bit binary
2421                  * without 64bit compatibility padding, this will fail right
2422                  * after copy_from_user when the *len argument is validated.
2423                  *
2424                  * the compat_ variant needs to do one pass over the kernel
2425                  * data set to adjust for size differences before it the check.
2426                  */
2427                 if (copy_everything_to_user(t, user, len, cmd) == 0)
2428                         ret = 0;
2429                 else
2430                         ret = compat_copy_everything_to_user(t, user, len, cmd);
2431                 break;
2432         default:
2433                 ret = -EINVAL;
2434         }
2435  out:
2436         xt_compat_flush_offsets(NFPROTO_BRIDGE);
2437         xt_compat_unlock(NFPROTO_BRIDGE);
2438         mutex_unlock(&ebt_mutex);
2439         return ret;
2440 }
2441 #endif
2442
2443 static struct nf_sockopt_ops ebt_sockopts = {
2444         .pf             = PF_INET,
2445         .set_optmin     = EBT_BASE_CTL,
2446         .set_optmax     = EBT_SO_SET_MAX + 1,
2447         .set            = do_ebt_set_ctl,
2448 #ifdef CONFIG_COMPAT
2449         .compat_set     = compat_do_ebt_set_ctl,
2450 #endif
2451         .get_optmin     = EBT_BASE_CTL,
2452         .get_optmax     = EBT_SO_GET_MAX + 1,
2453         .get            = do_ebt_get_ctl,
2454 #ifdef CONFIG_COMPAT
2455         .compat_get     = compat_do_ebt_get_ctl,
2456 #endif
2457         .owner          = THIS_MODULE,
2458 };
2459
2460 static int __init ebtables_init(void)
2461 {
2462         int ret;
2463
2464         ret = xt_register_target(&ebt_standard_target);
2465         if (ret < 0)
2466                 return ret;
2467         ret = nf_register_sockopt(&ebt_sockopts);
2468         if (ret < 0) {
2469                 xt_unregister_target(&ebt_standard_target);
2470                 return ret;
2471         }
2472
2473         printk(KERN_INFO "Ebtables v2.0 registered\n");
2474         return 0;
2475 }
2476
2477 static void __exit ebtables_fini(void)
2478 {
2479         nf_unregister_sockopt(&ebt_sockopts);
2480         xt_unregister_target(&ebt_standard_target);
2481         printk(KERN_INFO "Ebtables v2.0 unregistered\n");
2482 }
2483
2484 EXPORT_SYMBOL(ebt_register_table);
2485 EXPORT_SYMBOL(ebt_unregister_table);
2486 EXPORT_SYMBOL(ebt_do_table);
2487 module_init(ebtables_init);
2488 module_exit(ebtables_fini);
2489 MODULE_LICENSE("GPL");