]> git.karo-electronics.de Git - karo-tx-linux.git/blob - net/ipv4/netfilter/ip_tables.c
308b456723f0d926514464a050cb9fbb46916ed3
[karo-tx-linux.git] / net / ipv4 / netfilter / ip_tables.c
1 /*
2  * Packet matching code.
3  *
4  * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
5  * Copyright (C) 2000-2005 Netfilter Core Team <coreteam@netfilter.org>
6  * Copyright (C) 2006-2010 Patrick McHardy <kaber@trash.net>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/cache.h>
14 #include <linux/capability.h>
15 #include <linux/skbuff.h>
16 #include <linux/kmod.h>
17 #include <linux/vmalloc.h>
18 #include <linux/netdevice.h>
19 #include <linux/module.h>
20 #include <linux/icmp.h>
21 #include <net/ip.h>
22 #include <net/compat.h>
23 #include <asm/uaccess.h>
24 #include <linux/mutex.h>
25 #include <linux/proc_fs.h>
26 #include <linux/err.h>
27 #include <linux/cpumask.h>
28
29 #include <linux/netfilter/x_tables.h>
30 #include <linux/netfilter_ipv4/ip_tables.h>
31 #include <net/netfilter/nf_log.h>
32 #include "../../netfilter/xt_repldata.h"
33
34 MODULE_LICENSE("GPL");
35 MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
36 MODULE_DESCRIPTION("IPv4 packet filter");
37
38 #ifdef CONFIG_NETFILTER_DEBUG
39 #define IP_NF_ASSERT(x)         WARN_ON(!(x))
40 #else
41 #define IP_NF_ASSERT(x)
42 #endif
43
44 void *ipt_alloc_initial_table(const struct xt_table *info)
45 {
46         return xt_alloc_initial_table(ipt, IPT);
47 }
48 EXPORT_SYMBOL_GPL(ipt_alloc_initial_table);
49
50 /* Returns whether matches rule or not. */
51 /* Performance critical - called for every packet */
52 static inline bool
53 ip_packet_match(const struct iphdr *ip,
54                 const char *indev,
55                 const char *outdev,
56                 const struct ipt_ip *ipinfo,
57                 int isfrag)
58 {
59         unsigned long ret;
60
61         if (NF_INVF(ipinfo, IPT_INV_SRCIP,
62                     (ip->saddr & ipinfo->smsk.s_addr) != ipinfo->src.s_addr) ||
63             NF_INVF(ipinfo, IPT_INV_DSTIP,
64                     (ip->daddr & ipinfo->dmsk.s_addr) != ipinfo->dst.s_addr))
65                 return false;
66
67         ret = ifname_compare_aligned(indev, ipinfo->iniface, ipinfo->iniface_mask);
68
69         if (NF_INVF(ipinfo, IPT_INV_VIA_IN, ret != 0))
70                 return false;
71
72         ret = ifname_compare_aligned(outdev, ipinfo->outiface, ipinfo->outiface_mask);
73
74         if (NF_INVF(ipinfo, IPT_INV_VIA_OUT, ret != 0))
75                 return false;
76
77         /* Check specific protocol */
78         if (ipinfo->proto &&
79             NF_INVF(ipinfo, IPT_INV_PROTO, ip->protocol != ipinfo->proto))
80                 return false;
81
82         /* If we have a fragment rule but the packet is not a fragment
83          * then we return zero */
84         if (NF_INVF(ipinfo, IPT_INV_FRAG,
85                     (ipinfo->flags & IPT_F_FRAG) && !isfrag))
86                 return false;
87
88         return true;
89 }
90
91 static bool
92 ip_checkentry(const struct ipt_ip *ip)
93 {
94         if (ip->flags & ~IPT_F_MASK)
95                 return false;
96         if (ip->invflags & ~IPT_INV_MASK)
97                 return false;
98         return true;
99 }
100
101 static unsigned int
102 ipt_error(struct sk_buff *skb, const struct xt_action_param *par)
103 {
104         net_info_ratelimited("error: `%s'\n", (const char *)par->targinfo);
105
106         return NF_DROP;
107 }
108
109 /* Performance critical */
110 static inline struct ipt_entry *
111 get_entry(const void *base, unsigned int offset)
112 {
113         return (struct ipt_entry *)(base + offset);
114 }
115
116 /* All zeroes == unconditional rule. */
117 /* Mildly perf critical (only if packet tracing is on) */
118 static inline bool unconditional(const struct ipt_entry *e)
119 {
120         static const struct ipt_ip uncond;
121
122         return e->target_offset == sizeof(struct ipt_entry) &&
123                memcmp(&e->ip, &uncond, sizeof(uncond)) == 0;
124 }
125
126 /* for const-correctness */
127 static inline const struct xt_entry_target *
128 ipt_get_target_c(const struct ipt_entry *e)
129 {
130         return ipt_get_target((struct ipt_entry *)e);
131 }
132
133 #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
134 static const char *const hooknames[] = {
135         [NF_INET_PRE_ROUTING]           = "PREROUTING",
136         [NF_INET_LOCAL_IN]              = "INPUT",
137         [NF_INET_FORWARD]               = "FORWARD",
138         [NF_INET_LOCAL_OUT]             = "OUTPUT",
139         [NF_INET_POST_ROUTING]          = "POSTROUTING",
140 };
141
142 enum nf_ip_trace_comments {
143         NF_IP_TRACE_COMMENT_RULE,
144         NF_IP_TRACE_COMMENT_RETURN,
145         NF_IP_TRACE_COMMENT_POLICY,
146 };
147
148 static const char *const comments[] = {
149         [NF_IP_TRACE_COMMENT_RULE]      = "rule",
150         [NF_IP_TRACE_COMMENT_RETURN]    = "return",
151         [NF_IP_TRACE_COMMENT_POLICY]    = "policy",
152 };
153
154 static struct nf_loginfo trace_loginfo = {
155         .type = NF_LOG_TYPE_LOG,
156         .u = {
157                 .log = {
158                         .level = 4,
159                         .logflags = NF_LOG_DEFAULT_MASK,
160                 },
161         },
162 };
163
164 /* Mildly perf critical (only if packet tracing is on) */
165 static inline int
166 get_chainname_rulenum(const struct ipt_entry *s, const struct ipt_entry *e,
167                       const char *hookname, const char **chainname,
168                       const char **comment, unsigned int *rulenum)
169 {
170         const struct xt_standard_target *t = (void *)ipt_get_target_c(s);
171
172         if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
173                 /* Head of user chain: ERROR target with chainname */
174                 *chainname = t->target.data;
175                 (*rulenum) = 0;
176         } else if (s == e) {
177                 (*rulenum)++;
178
179                 if (unconditional(s) &&
180                     strcmp(t->target.u.kernel.target->name,
181                            XT_STANDARD_TARGET) == 0 &&
182                    t->verdict < 0) {
183                         /* Tail of chains: STANDARD target (return/policy) */
184                         *comment = *chainname == hookname
185                                 ? comments[NF_IP_TRACE_COMMENT_POLICY]
186                                 : comments[NF_IP_TRACE_COMMENT_RETURN];
187                 }
188                 return 1;
189         } else
190                 (*rulenum)++;
191
192         return 0;
193 }
194
195 static void trace_packet(struct net *net,
196                          const struct sk_buff *skb,
197                          unsigned int hook,
198                          const struct net_device *in,
199                          const struct net_device *out,
200                          const char *tablename,
201                          const struct xt_table_info *private,
202                          const struct ipt_entry *e)
203 {
204         const struct ipt_entry *root;
205         const char *hookname, *chainname, *comment;
206         const struct ipt_entry *iter;
207         unsigned int rulenum = 0;
208
209         root = get_entry(private->entries, private->hook_entry[hook]);
210
211         hookname = chainname = hooknames[hook];
212         comment = comments[NF_IP_TRACE_COMMENT_RULE];
213
214         xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
215                 if (get_chainname_rulenum(iter, e, hookname,
216                     &chainname, &comment, &rulenum) != 0)
217                         break;
218
219         nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo,
220                      "TRACE: %s:%s:%s:%u ",
221                      tablename, chainname, comment, rulenum);
222 }
223 #endif
224
225 static inline
226 struct ipt_entry *ipt_next_entry(const struct ipt_entry *entry)
227 {
228         return (void *)entry + entry->next_offset;
229 }
230
231 /* Returns one of the generic firewall policies, like NF_ACCEPT. */
232 unsigned int
233 ipt_do_table(struct sk_buff *skb,
234              const struct nf_hook_state *state,
235              struct xt_table *table)
236 {
237         unsigned int hook = state->hook;
238         static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
239         const struct iphdr *ip;
240         /* Initializing verdict to NF_DROP keeps gcc happy. */
241         unsigned int verdict = NF_DROP;
242         const char *indev, *outdev;
243         const void *table_base;
244         struct ipt_entry *e, **jumpstack;
245         unsigned int stackidx, cpu;
246         const struct xt_table_info *private;
247         struct xt_action_param acpar;
248         unsigned int addend;
249
250         /* Initialization */
251         stackidx = 0;
252         ip = ip_hdr(skb);
253         indev = state->in ? state->in->name : nulldevname;
254         outdev = state->out ? state->out->name : nulldevname;
255         /* We handle fragments by dealing with the first fragment as
256          * if it was a normal packet.  All other fragments are treated
257          * normally, except that they will NEVER match rules that ask
258          * things we don't know, ie. tcp syn flag or ports).  If the
259          * rule is also a fragment-specific rule, non-fragments won't
260          * match it. */
261         acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
262         acpar.thoff   = ip_hdrlen(skb);
263         acpar.hotdrop = false;
264         acpar.state   = state;
265
266         IP_NF_ASSERT(table->valid_hooks & (1 << hook));
267         local_bh_disable();
268         addend = xt_write_recseq_begin();
269         private = table->private;
270         cpu        = smp_processor_id();
271         /*
272          * Ensure we load private-> members after we've fetched the base
273          * pointer.
274          */
275         smp_read_barrier_depends();
276         table_base = private->entries;
277         jumpstack  = (struct ipt_entry **)private->jumpstack[cpu];
278
279         /* Switch to alternate jumpstack if we're being invoked via TEE.
280          * TEE issues XT_CONTINUE verdict on original skb so we must not
281          * clobber the jumpstack.
282          *
283          * For recursion via REJECT or SYNPROXY the stack will be clobbered
284          * but it is no problem since absolute verdict is issued by these.
285          */
286         if (static_key_false(&xt_tee_enabled))
287                 jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
288
289         e = get_entry(table_base, private->hook_entry[hook]);
290
291         do {
292                 const struct xt_entry_target *t;
293                 const struct xt_entry_match *ematch;
294                 struct xt_counters *counter;
295
296                 IP_NF_ASSERT(e);
297                 if (!ip_packet_match(ip, indev, outdev,
298                     &e->ip, acpar.fragoff)) {
299  no_match:
300                         e = ipt_next_entry(e);
301                         continue;
302                 }
303
304                 xt_ematch_foreach(ematch, e) {
305                         acpar.match     = ematch->u.kernel.match;
306                         acpar.matchinfo = ematch->data;
307                         if (!acpar.match->match(skb, &acpar))
308                                 goto no_match;
309                 }
310
311                 counter = xt_get_this_cpu_counter(&e->counters);
312                 ADD_COUNTER(*counter, skb->len, 1);
313
314                 t = ipt_get_target(e);
315                 IP_NF_ASSERT(t->u.kernel.target);
316
317 #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
318                 /* The packet is traced: log it */
319                 if (unlikely(skb->nf_trace))
320                         trace_packet(state->net, skb, hook, state->in,
321                                      state->out, table->name, private, e);
322 #endif
323                 /* Standard target? */
324                 if (!t->u.kernel.target->target) {
325                         int v;
326
327                         v = ((struct xt_standard_target *)t)->verdict;
328                         if (v < 0) {
329                                 /* Pop from stack? */
330                                 if (v != XT_RETURN) {
331                                         verdict = (unsigned int)(-v) - 1;
332                                         break;
333                                 }
334                                 if (stackidx == 0) {
335                                         e = get_entry(table_base,
336                                             private->underflow[hook]);
337                                 } else {
338                                         e = jumpstack[--stackidx];
339                                         e = ipt_next_entry(e);
340                                 }
341                                 continue;
342                         }
343                         if (table_base + v != ipt_next_entry(e) &&
344                             !(e->ip.flags & IPT_F_GOTO))
345                                 jumpstack[stackidx++] = e;
346
347                         e = get_entry(table_base, v);
348                         continue;
349                 }
350
351                 acpar.target   = t->u.kernel.target;
352                 acpar.targinfo = t->data;
353
354                 verdict = t->u.kernel.target->target(skb, &acpar);
355                 /* Target might have changed stuff. */
356                 ip = ip_hdr(skb);
357                 if (verdict == XT_CONTINUE)
358                         e = ipt_next_entry(e);
359                 else
360                         /* Verdict */
361                         break;
362         } while (!acpar.hotdrop);
363
364         xt_write_recseq_end(addend);
365         local_bh_enable();
366
367         if (acpar.hotdrop)
368                 return NF_DROP;
369         else return verdict;
370 }
371
372 /* Figures out from what hook each rule can be called: returns 0 if
373    there are loops.  Puts hook bitmask in comefrom. */
374 static int
375 mark_source_chains(const struct xt_table_info *newinfo,
376                    unsigned int valid_hooks, void *entry0,
377                    unsigned int *offsets)
378 {
379         unsigned int hook;
380
381         /* No recursion; use packet counter to save back ptrs (reset
382            to 0 as we leave), and comefrom to save source hook bitmask */
383         for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
384                 unsigned int pos = newinfo->hook_entry[hook];
385                 struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos);
386
387                 if (!(valid_hooks & (1 << hook)))
388                         continue;
389
390                 /* Set initial back pointer. */
391                 e->counters.pcnt = pos;
392
393                 for (;;) {
394                         const struct xt_standard_target *t
395                                 = (void *)ipt_get_target_c(e);
396                         int visited = e->comefrom & (1 << hook);
397
398                         if (e->comefrom & (1 << NF_INET_NUMHOOKS))
399                                 return 0;
400
401                         e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
402
403                         /* Unconditional return/END. */
404                         if ((unconditional(e) &&
405                              (strcmp(t->target.u.user.name,
406                                      XT_STANDARD_TARGET) == 0) &&
407                              t->verdict < 0) || visited) {
408                                 unsigned int oldpos, size;
409
410                                 if ((strcmp(t->target.u.user.name,
411                                             XT_STANDARD_TARGET) == 0) &&
412                                     t->verdict < -NF_MAX_VERDICT - 1)
413                                         return 0;
414
415                                 /* Return: backtrack through the last
416                                    big jump. */
417                                 do {
418                                         e->comefrom ^= (1<<NF_INET_NUMHOOKS);
419                                         oldpos = pos;
420                                         pos = e->counters.pcnt;
421                                         e->counters.pcnt = 0;
422
423                                         /* We're at the start. */
424                                         if (pos == oldpos)
425                                                 goto next;
426
427                                         e = (struct ipt_entry *)
428                                                 (entry0 + pos);
429                                 } while (oldpos == pos + e->next_offset);
430
431                                 /* Move along one */
432                                 size = e->next_offset;
433                                 e = (struct ipt_entry *)
434                                         (entry0 + pos + size);
435                                 if (pos + size >= newinfo->size)
436                                         return 0;
437                                 e->counters.pcnt = pos;
438                                 pos += size;
439                         } else {
440                                 int newpos = t->verdict;
441
442                                 if (strcmp(t->target.u.user.name,
443                                            XT_STANDARD_TARGET) == 0 &&
444                                     newpos >= 0) {
445                                         /* This a jump; chase it. */
446                                         if (!xt_find_jump_offset(offsets, newpos,
447                                                                  newinfo->number))
448                                                 return 0;
449                                         e = (struct ipt_entry *)
450                                                 (entry0 + newpos);
451                                 } else {
452                                         /* ... this is a fallthru */
453                                         newpos = pos + e->next_offset;
454                                         if (newpos >= newinfo->size)
455                                                 return 0;
456                                 }
457                                 e = (struct ipt_entry *)
458                                         (entry0 + newpos);
459                                 e->counters.pcnt = pos;
460                                 pos = newpos;
461                         }
462                 }
463 next:           ;
464         }
465         return 1;
466 }
467
468 static void cleanup_match(struct xt_entry_match *m, struct net *net)
469 {
470         struct xt_mtdtor_param par;
471
472         par.net       = net;
473         par.match     = m->u.kernel.match;
474         par.matchinfo = m->data;
475         par.family    = NFPROTO_IPV4;
476         if (par.match->destroy != NULL)
477                 par.match->destroy(&par);
478         module_put(par.match->me);
479 }
480
481 static int
482 check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
483 {
484         const struct ipt_ip *ip = par->entryinfo;
485
486         par->match     = m->u.kernel.match;
487         par->matchinfo = m->data;
488
489         return xt_check_match(par, m->u.match_size - sizeof(*m),
490                               ip->proto, ip->invflags & IPT_INV_PROTO);
491 }
492
493 static int
494 find_check_match(struct xt_entry_match *m, struct xt_mtchk_param *par)
495 {
496         struct xt_match *match;
497         int ret;
498
499         match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
500                                       m->u.user.revision);
501         if (IS_ERR(match))
502                 return PTR_ERR(match);
503         m->u.kernel.match = match;
504
505         ret = check_match(m, par);
506         if (ret)
507                 goto err;
508
509         return 0;
510 err:
511         module_put(m->u.kernel.match->me);
512         return ret;
513 }
514
515 static int check_target(struct ipt_entry *e, struct net *net, const char *name)
516 {
517         struct xt_entry_target *t = ipt_get_target(e);
518         struct xt_tgchk_param par = {
519                 .net       = net,
520                 .table     = name,
521                 .entryinfo = e,
522                 .target    = t->u.kernel.target,
523                 .targinfo  = t->data,
524                 .hook_mask = e->comefrom,
525                 .family    = NFPROTO_IPV4,
526         };
527
528         return xt_check_target(&par, t->u.target_size - sizeof(*t),
529                                e->ip.proto, e->ip.invflags & IPT_INV_PROTO);
530 }
531
532 static int
533 find_check_entry(struct ipt_entry *e, struct net *net, const char *name,
534                  unsigned int size,
535                  struct xt_percpu_counter_alloc_state *alloc_state)
536 {
537         struct xt_entry_target *t;
538         struct xt_target *target;
539         int ret;
540         unsigned int j;
541         struct xt_mtchk_param mtpar;
542         struct xt_entry_match *ematch;
543
544         if (!xt_percpu_counter_alloc(alloc_state, &e->counters))
545                 return -ENOMEM;
546
547         j = 0;
548         mtpar.net       = net;
549         mtpar.table     = name;
550         mtpar.entryinfo = &e->ip;
551         mtpar.hook_mask = e->comefrom;
552         mtpar.family    = NFPROTO_IPV4;
553         xt_ematch_foreach(ematch, e) {
554                 ret = find_check_match(ematch, &mtpar);
555                 if (ret != 0)
556                         goto cleanup_matches;
557                 ++j;
558         }
559
560         t = ipt_get_target(e);
561         target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
562                                         t->u.user.revision);
563         if (IS_ERR(target)) {
564                 ret = PTR_ERR(target);
565                 goto cleanup_matches;
566         }
567         t->u.kernel.target = target;
568
569         ret = check_target(e, net, name);
570         if (ret)
571                 goto err;
572
573         return 0;
574  err:
575         module_put(t->u.kernel.target->me);
576  cleanup_matches:
577         xt_ematch_foreach(ematch, e) {
578                 if (j-- == 0)
579                         break;
580                 cleanup_match(ematch, net);
581         }
582
583         xt_percpu_counter_free(&e->counters);
584
585         return ret;
586 }
587
588 static bool check_underflow(const struct ipt_entry *e)
589 {
590         const struct xt_entry_target *t;
591         unsigned int verdict;
592
593         if (!unconditional(e))
594                 return false;
595         t = ipt_get_target_c(e);
596         if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
597                 return false;
598         verdict = ((struct xt_standard_target *)t)->verdict;
599         verdict = -verdict - 1;
600         return verdict == NF_DROP || verdict == NF_ACCEPT;
601 }
602
603 static int
604 check_entry_size_and_hooks(struct ipt_entry *e,
605                            struct xt_table_info *newinfo,
606                            const unsigned char *base,
607                            const unsigned char *limit,
608                            const unsigned int *hook_entries,
609                            const unsigned int *underflows,
610                            unsigned int valid_hooks)
611 {
612         unsigned int h;
613         int err;
614
615         if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
616             (unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
617             (unsigned char *)e + e->next_offset > limit)
618                 return -EINVAL;
619
620         if (e->next_offset
621             < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target))
622                 return -EINVAL;
623
624         if (!ip_checkentry(&e->ip))
625                 return -EINVAL;
626
627         err = xt_check_entry_offsets(e, e->elems, e->target_offset,
628                                      e->next_offset);
629         if (err)
630                 return err;
631
632         /* Check hooks & underflows */
633         for (h = 0; h < NF_INET_NUMHOOKS; h++) {
634                 if (!(valid_hooks & (1 << h)))
635                         continue;
636                 if ((unsigned char *)e - base == hook_entries[h])
637                         newinfo->hook_entry[h] = hook_entries[h];
638                 if ((unsigned char *)e - base == underflows[h]) {
639                         if (!check_underflow(e))
640                                 return -EINVAL;
641
642                         newinfo->underflow[h] = underflows[h];
643                 }
644         }
645
646         /* Clear counters and comefrom */
647         e->counters = ((struct xt_counters) { 0, 0 });
648         e->comefrom = 0;
649         return 0;
650 }
651
652 static void
653 cleanup_entry(struct ipt_entry *e, struct net *net)
654 {
655         struct xt_tgdtor_param par;
656         struct xt_entry_target *t;
657         struct xt_entry_match *ematch;
658
659         /* Cleanup all matches */
660         xt_ematch_foreach(ematch, e)
661                 cleanup_match(ematch, net);
662         t = ipt_get_target(e);
663
664         par.net      = net;
665         par.target   = t->u.kernel.target;
666         par.targinfo = t->data;
667         par.family   = NFPROTO_IPV4;
668         if (par.target->destroy != NULL)
669                 par.target->destroy(&par);
670         module_put(par.target->me);
671         xt_percpu_counter_free(&e->counters);
672 }
673
674 /* Checks and translates the user-supplied table segment (held in
675    newinfo) */
676 static int
677 translate_table(struct net *net, struct xt_table_info *newinfo, void *entry0,
678                 const struct ipt_replace *repl)
679 {
680         struct xt_percpu_counter_alloc_state alloc_state = { 0 };
681         struct ipt_entry *iter;
682         unsigned int *offsets;
683         unsigned int i;
684         int ret = 0;
685
686         newinfo->size = repl->size;
687         newinfo->number = repl->num_entries;
688
689         /* Init all hooks to impossible value. */
690         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
691                 newinfo->hook_entry[i] = 0xFFFFFFFF;
692                 newinfo->underflow[i] = 0xFFFFFFFF;
693         }
694
695         offsets = xt_alloc_entry_offsets(newinfo->number);
696         if (!offsets)
697                 return -ENOMEM;
698         i = 0;
699         /* Walk through entries, checking offsets. */
700         xt_entry_foreach(iter, entry0, newinfo->size) {
701                 ret = check_entry_size_and_hooks(iter, newinfo, entry0,
702                                                  entry0 + repl->size,
703                                                  repl->hook_entry,
704                                                  repl->underflow,
705                                                  repl->valid_hooks);
706                 if (ret != 0)
707                         goto out_free;
708                 if (i < repl->num_entries)
709                         offsets[i] = (void *)iter - entry0;
710                 ++i;
711                 if (strcmp(ipt_get_target(iter)->u.user.name,
712                     XT_ERROR_TARGET) == 0)
713                         ++newinfo->stacksize;
714         }
715
716         ret = -EINVAL;
717         if (i != repl->num_entries)
718                 goto out_free;
719
720         /* Check hooks all assigned */
721         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
722                 /* Only hooks which are valid */
723                 if (!(repl->valid_hooks & (1 << i)))
724                         continue;
725                 if (newinfo->hook_entry[i] == 0xFFFFFFFF)
726                         goto out_free;
727                 if (newinfo->underflow[i] == 0xFFFFFFFF)
728                         goto out_free;
729         }
730
731         if (!mark_source_chains(newinfo, repl->valid_hooks, entry0, offsets)) {
732                 ret = -ELOOP;
733                 goto out_free;
734         }
735         kvfree(offsets);
736
737         /* Finally, each sanity check must pass */
738         i = 0;
739         xt_entry_foreach(iter, entry0, newinfo->size) {
740                 ret = find_check_entry(iter, net, repl->name, repl->size,
741                                        &alloc_state);
742                 if (ret != 0)
743                         break;
744                 ++i;
745         }
746
747         if (ret != 0) {
748                 xt_entry_foreach(iter, entry0, newinfo->size) {
749                         if (i-- == 0)
750                                 break;
751                         cleanup_entry(iter, net);
752                 }
753                 return ret;
754         }
755
756         return ret;
757  out_free:
758         kvfree(offsets);
759         return ret;
760 }
761
762 static void
763 get_counters(const struct xt_table_info *t,
764              struct xt_counters counters[])
765 {
766         struct ipt_entry *iter;
767         unsigned int cpu;
768         unsigned int i;
769
770         for_each_possible_cpu(cpu) {
771                 seqcount_t *s = &per_cpu(xt_recseq, cpu);
772
773                 i = 0;
774                 xt_entry_foreach(iter, t->entries, t->size) {
775                         struct xt_counters *tmp;
776                         u64 bcnt, pcnt;
777                         unsigned int start;
778
779                         tmp = xt_get_per_cpu_counter(&iter->counters, cpu);
780                         do {
781                                 start = read_seqcount_begin(s);
782                                 bcnt = tmp->bcnt;
783                                 pcnt = tmp->pcnt;
784                         } while (read_seqcount_retry(s, start));
785
786                         ADD_COUNTER(counters[i], bcnt, pcnt);
787                         ++i; /* macro does multi eval of i */
788                 }
789         }
790 }
791
792 static struct xt_counters *alloc_counters(const struct xt_table *table)
793 {
794         unsigned int countersize;
795         struct xt_counters *counters;
796         const struct xt_table_info *private = table->private;
797
798         /* We need atomic snapshot of counters: rest doesn't change
799            (other than comefrom, which userspace doesn't care
800            about). */
801         countersize = sizeof(struct xt_counters) * private->number;
802         counters = vzalloc(countersize);
803
804         if (counters == NULL)
805                 return ERR_PTR(-ENOMEM);
806
807         get_counters(private, counters);
808
809         return counters;
810 }
811
812 static int
813 copy_entries_to_user(unsigned int total_size,
814                      const struct xt_table *table,
815                      void __user *userptr)
816 {
817         unsigned int off, num;
818         const struct ipt_entry *e;
819         struct xt_counters *counters;
820         const struct xt_table_info *private = table->private;
821         int ret = 0;
822         const void *loc_cpu_entry;
823
824         counters = alloc_counters(table);
825         if (IS_ERR(counters))
826                 return PTR_ERR(counters);
827
828         loc_cpu_entry = private->entries;
829         if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
830                 ret = -EFAULT;
831                 goto free_counters;
832         }
833
834         /* FIXME: use iterator macros --RR */
835         /* ... then go back and fix counters and names */
836         for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
837                 unsigned int i;
838                 const struct xt_entry_match *m;
839                 const struct xt_entry_target *t;
840
841                 e = (struct ipt_entry *)(loc_cpu_entry + off);
842                 if (copy_to_user(userptr + off
843                                  + offsetof(struct ipt_entry, counters),
844                                  &counters[num],
845                                  sizeof(counters[num])) != 0) {
846                         ret = -EFAULT;
847                         goto free_counters;
848                 }
849
850                 for (i = sizeof(struct ipt_entry);
851                      i < e->target_offset;
852                      i += m->u.match_size) {
853                         m = (void *)e + i;
854
855                         if (copy_to_user(userptr + off + i
856                                          + offsetof(struct xt_entry_match,
857                                                     u.user.name),
858                                          m->u.kernel.match->name,
859                                          strlen(m->u.kernel.match->name)+1)
860                             != 0) {
861                                 ret = -EFAULT;
862                                 goto free_counters;
863                         }
864                 }
865
866                 t = ipt_get_target_c(e);
867                 if (copy_to_user(userptr + off + e->target_offset
868                                  + offsetof(struct xt_entry_target,
869                                             u.user.name),
870                                  t->u.kernel.target->name,
871                                  strlen(t->u.kernel.target->name)+1) != 0) {
872                         ret = -EFAULT;
873                         goto free_counters;
874                 }
875         }
876
877  free_counters:
878         vfree(counters);
879         return ret;
880 }
881
882 #ifdef CONFIG_COMPAT
883 static void compat_standard_from_user(void *dst, const void *src)
884 {
885         int v = *(compat_int_t *)src;
886
887         if (v > 0)
888                 v += xt_compat_calc_jump(AF_INET, v);
889         memcpy(dst, &v, sizeof(v));
890 }
891
892 static int compat_standard_to_user(void __user *dst, const void *src)
893 {
894         compat_int_t cv = *(int *)src;
895
896         if (cv > 0)
897                 cv -= xt_compat_calc_jump(AF_INET, cv);
898         return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
899 }
900
901 static int compat_calc_entry(const struct ipt_entry *e,
902                              const struct xt_table_info *info,
903                              const void *base, struct xt_table_info *newinfo)
904 {
905         const struct xt_entry_match *ematch;
906         const struct xt_entry_target *t;
907         unsigned int entry_offset;
908         int off, i, ret;
909
910         off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
911         entry_offset = (void *)e - base;
912         xt_ematch_foreach(ematch, e)
913                 off += xt_compat_match_offset(ematch->u.kernel.match);
914         t = ipt_get_target_c(e);
915         off += xt_compat_target_offset(t->u.kernel.target);
916         newinfo->size -= off;
917         ret = xt_compat_add_offset(AF_INET, entry_offset, off);
918         if (ret)
919                 return ret;
920
921         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
922                 if (info->hook_entry[i] &&
923                     (e < (struct ipt_entry *)(base + info->hook_entry[i])))
924                         newinfo->hook_entry[i] -= off;
925                 if (info->underflow[i] &&
926                     (e < (struct ipt_entry *)(base + info->underflow[i])))
927                         newinfo->underflow[i] -= off;
928         }
929         return 0;
930 }
931
932 static int compat_table_info(const struct xt_table_info *info,
933                              struct xt_table_info *newinfo)
934 {
935         struct ipt_entry *iter;
936         const void *loc_cpu_entry;
937         int ret;
938
939         if (!newinfo || !info)
940                 return -EINVAL;
941
942         /* we dont care about newinfo->entries */
943         memcpy(newinfo, info, offsetof(struct xt_table_info, entries));
944         newinfo->initial_entries = 0;
945         loc_cpu_entry = info->entries;
946         xt_compat_init_offsets(AF_INET, info->number);
947         xt_entry_foreach(iter, loc_cpu_entry, info->size) {
948                 ret = compat_calc_entry(iter, info, loc_cpu_entry, newinfo);
949                 if (ret != 0)
950                         return ret;
951         }
952         return 0;
953 }
954 #endif
955
956 static int get_info(struct net *net, void __user *user,
957                     const int *len, int compat)
958 {
959         char name[XT_TABLE_MAXNAMELEN];
960         struct xt_table *t;
961         int ret;
962
963         if (*len != sizeof(struct ipt_getinfo))
964                 return -EINVAL;
965
966         if (copy_from_user(name, user, sizeof(name)) != 0)
967                 return -EFAULT;
968
969         name[XT_TABLE_MAXNAMELEN-1] = '\0';
970 #ifdef CONFIG_COMPAT
971         if (compat)
972                 xt_compat_lock(AF_INET);
973 #endif
974         t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
975                                     "iptable_%s", name);
976         if (t) {
977                 struct ipt_getinfo info;
978                 const struct xt_table_info *private = t->private;
979 #ifdef CONFIG_COMPAT
980                 struct xt_table_info tmp;
981
982                 if (compat) {
983                         ret = compat_table_info(private, &tmp);
984                         xt_compat_flush_offsets(AF_INET);
985                         private = &tmp;
986                 }
987 #endif
988                 memset(&info, 0, sizeof(info));
989                 info.valid_hooks = t->valid_hooks;
990                 memcpy(info.hook_entry, private->hook_entry,
991                        sizeof(info.hook_entry));
992                 memcpy(info.underflow, private->underflow,
993                        sizeof(info.underflow));
994                 info.num_entries = private->number;
995                 info.size = private->size;
996                 strcpy(info.name, name);
997
998                 if (copy_to_user(user, &info, *len) != 0)
999                         ret = -EFAULT;
1000                 else
1001                         ret = 0;
1002
1003                 xt_table_unlock(t);
1004                 module_put(t->me);
1005         } else
1006                 ret = -ENOENT;
1007 #ifdef CONFIG_COMPAT
1008         if (compat)
1009                 xt_compat_unlock(AF_INET);
1010 #endif
1011         return ret;
1012 }
1013
1014 static int
1015 get_entries(struct net *net, struct ipt_get_entries __user *uptr,
1016             const int *len)
1017 {
1018         int ret;
1019         struct ipt_get_entries get;
1020         struct xt_table *t;
1021
1022         if (*len < sizeof(get))
1023                 return -EINVAL;
1024         if (copy_from_user(&get, uptr, sizeof(get)) != 0)
1025                 return -EFAULT;
1026         if (*len != sizeof(struct ipt_get_entries) + get.size)
1027                 return -EINVAL;
1028         get.name[sizeof(get.name) - 1] = '\0';
1029
1030         t = xt_find_table_lock(net, AF_INET, get.name);
1031         if (t) {
1032                 const struct xt_table_info *private = t->private;
1033                 if (get.size == private->size)
1034                         ret = copy_entries_to_user(private->size,
1035                                                    t, uptr->entrytable);
1036                 else
1037                         ret = -EAGAIN;
1038
1039                 module_put(t->me);
1040                 xt_table_unlock(t);
1041         } else
1042                 ret = -ENOENT;
1043
1044         return ret;
1045 }
1046
1047 static int
1048 __do_replace(struct net *net, const char *name, unsigned int valid_hooks,
1049              struct xt_table_info *newinfo, unsigned int num_counters,
1050              void __user *counters_ptr)
1051 {
1052         int ret;
1053         struct xt_table *t;
1054         struct xt_table_info *oldinfo;
1055         struct xt_counters *counters;
1056         struct ipt_entry *iter;
1057
1058         ret = 0;
1059         counters = vzalloc(num_counters * sizeof(struct xt_counters));
1060         if (!counters) {
1061                 ret = -ENOMEM;
1062                 goto out;
1063         }
1064
1065         t = try_then_request_module(xt_find_table_lock(net, AF_INET, name),
1066                                     "iptable_%s", name);
1067         if (!t) {
1068                 ret = -ENOENT;
1069                 goto free_newinfo_counters_untrans;
1070         }
1071
1072         /* You lied! */
1073         if (valid_hooks != t->valid_hooks) {
1074                 ret = -EINVAL;
1075                 goto put_module;
1076         }
1077
1078         oldinfo = xt_replace_table(t, num_counters, newinfo, &ret);
1079         if (!oldinfo)
1080                 goto put_module;
1081
1082         /* Update module usage count based on number of rules */
1083         if ((oldinfo->number > oldinfo->initial_entries) ||
1084             (newinfo->number <= oldinfo->initial_entries))
1085                 module_put(t->me);
1086         if ((oldinfo->number > oldinfo->initial_entries) &&
1087             (newinfo->number <= oldinfo->initial_entries))
1088                 module_put(t->me);
1089
1090         /* Get the old counters, and synchronize with replace */
1091         get_counters(oldinfo, counters);
1092
1093         /* Decrease module usage counts and free resource */
1094         xt_entry_foreach(iter, oldinfo->entries, oldinfo->size)
1095                 cleanup_entry(iter, net);
1096
1097         xt_free_table_info(oldinfo);
1098         if (copy_to_user(counters_ptr, counters,
1099                          sizeof(struct xt_counters) * num_counters) != 0) {
1100                 /* Silent error, can't fail, new table is already in place */
1101                 net_warn_ratelimited("iptables: counters copy to user failed while replacing table\n");
1102         }
1103         vfree(counters);
1104         xt_table_unlock(t);
1105         return ret;
1106
1107  put_module:
1108         module_put(t->me);
1109         xt_table_unlock(t);
1110  free_newinfo_counters_untrans:
1111         vfree(counters);
1112  out:
1113         return ret;
1114 }
1115
1116 static int
1117 do_replace(struct net *net, const void __user *user, unsigned int len)
1118 {
1119         int ret;
1120         struct ipt_replace tmp;
1121         struct xt_table_info *newinfo;
1122         void *loc_cpu_entry;
1123         struct ipt_entry *iter;
1124
1125         if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
1126                 return -EFAULT;
1127
1128         /* overflow check */
1129         if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
1130                 return -ENOMEM;
1131         if (tmp.num_counters == 0)
1132                 return -EINVAL;
1133
1134         tmp.name[sizeof(tmp.name)-1] = 0;
1135
1136         newinfo = xt_alloc_table_info(tmp.size);
1137         if (!newinfo)
1138                 return -ENOMEM;
1139
1140         loc_cpu_entry = newinfo->entries;
1141         if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
1142                            tmp.size) != 0) {
1143                 ret = -EFAULT;
1144                 goto free_newinfo;
1145         }
1146
1147         ret = translate_table(net, newinfo, loc_cpu_entry, &tmp);
1148         if (ret != 0)
1149                 goto free_newinfo;
1150
1151         ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
1152                            tmp.num_counters, tmp.counters);
1153         if (ret)
1154                 goto free_newinfo_untrans;
1155         return 0;
1156
1157  free_newinfo_untrans:
1158         xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
1159                 cleanup_entry(iter, net);
1160  free_newinfo:
1161         xt_free_table_info(newinfo);
1162         return ret;
1163 }
1164
1165 static int
1166 do_add_counters(struct net *net, const void __user *user,
1167                 unsigned int len, int compat)
1168 {
1169         unsigned int i;
1170         struct xt_counters_info tmp;
1171         struct xt_counters *paddc;
1172         struct xt_table *t;
1173         const struct xt_table_info *private;
1174         int ret = 0;
1175         struct ipt_entry *iter;
1176         unsigned int addend;
1177
1178         paddc = xt_copy_counters_from_user(user, len, &tmp, compat);
1179         if (IS_ERR(paddc))
1180                 return PTR_ERR(paddc);
1181
1182         t = xt_find_table_lock(net, AF_INET, tmp.name);
1183         if (!t) {
1184                 ret = -ENOENT;
1185                 goto free;
1186         }
1187
1188         local_bh_disable();
1189         private = t->private;
1190         if (private->number != tmp.num_counters) {
1191                 ret = -EINVAL;
1192                 goto unlock_up_free;
1193         }
1194
1195         i = 0;
1196         addend = xt_write_recseq_begin();
1197         xt_entry_foreach(iter, private->entries, private->size) {
1198                 struct xt_counters *tmp;
1199
1200                 tmp = xt_get_this_cpu_counter(&iter->counters);
1201                 ADD_COUNTER(*tmp, paddc[i].bcnt, paddc[i].pcnt);
1202                 ++i;
1203         }
1204         xt_write_recseq_end(addend);
1205  unlock_up_free:
1206         local_bh_enable();
1207         xt_table_unlock(t);
1208         module_put(t->me);
1209  free:
1210         vfree(paddc);
1211
1212         return ret;
1213 }
1214
1215 #ifdef CONFIG_COMPAT
1216 struct compat_ipt_replace {
1217         char                    name[XT_TABLE_MAXNAMELEN];
1218         u32                     valid_hooks;
1219         u32                     num_entries;
1220         u32                     size;
1221         u32                     hook_entry[NF_INET_NUMHOOKS];
1222         u32                     underflow[NF_INET_NUMHOOKS];
1223         u32                     num_counters;
1224         compat_uptr_t           counters;       /* struct xt_counters * */
1225         struct compat_ipt_entry entries[0];
1226 };
1227
1228 static int
1229 compat_copy_entry_to_user(struct ipt_entry *e, void __user **dstptr,
1230                           unsigned int *size, struct xt_counters *counters,
1231                           unsigned int i)
1232 {
1233         struct xt_entry_target *t;
1234         struct compat_ipt_entry __user *ce;
1235         u_int16_t target_offset, next_offset;
1236         compat_uint_t origsize;
1237         const struct xt_entry_match *ematch;
1238         int ret = 0;
1239
1240         origsize = *size;
1241         ce = (struct compat_ipt_entry __user *)*dstptr;
1242         if (copy_to_user(ce, e, sizeof(struct ipt_entry)) != 0 ||
1243             copy_to_user(&ce->counters, &counters[i],
1244             sizeof(counters[i])) != 0)
1245                 return -EFAULT;
1246
1247         *dstptr += sizeof(struct compat_ipt_entry);
1248         *size -= sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1249
1250         xt_ematch_foreach(ematch, e) {
1251                 ret = xt_compat_match_to_user(ematch, dstptr, size);
1252                 if (ret != 0)
1253                         return ret;
1254         }
1255         target_offset = e->target_offset - (origsize - *size);
1256         t = ipt_get_target(e);
1257         ret = xt_compat_target_to_user(t, dstptr, size);
1258         if (ret)
1259                 return ret;
1260         next_offset = e->next_offset - (origsize - *size);
1261         if (put_user(target_offset, &ce->target_offset) != 0 ||
1262             put_user(next_offset, &ce->next_offset) != 0)
1263                 return -EFAULT;
1264         return 0;
1265 }
1266
1267 static int
1268 compat_find_calc_match(struct xt_entry_match *m,
1269                        const struct ipt_ip *ip,
1270                        int *size)
1271 {
1272         struct xt_match *match;
1273
1274         match = xt_request_find_match(NFPROTO_IPV4, m->u.user.name,
1275                                       m->u.user.revision);
1276         if (IS_ERR(match))
1277                 return PTR_ERR(match);
1278
1279         m->u.kernel.match = match;
1280         *size += xt_compat_match_offset(match);
1281         return 0;
1282 }
1283
1284 static void compat_release_entry(struct compat_ipt_entry *e)
1285 {
1286         struct xt_entry_target *t;
1287         struct xt_entry_match *ematch;
1288
1289         /* Cleanup all matches */
1290         xt_ematch_foreach(ematch, e)
1291                 module_put(ematch->u.kernel.match->me);
1292         t = compat_ipt_get_target(e);
1293         module_put(t->u.kernel.target->me);
1294 }
1295
1296 static int
1297 check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
1298                                   struct xt_table_info *newinfo,
1299                                   unsigned int *size,
1300                                   const unsigned char *base,
1301                                   const unsigned char *limit)
1302 {
1303         struct xt_entry_match *ematch;
1304         struct xt_entry_target *t;
1305         struct xt_target *target;
1306         unsigned int entry_offset;
1307         unsigned int j;
1308         int ret, off;
1309
1310         if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
1311             (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
1312             (unsigned char *)e + e->next_offset > limit)
1313                 return -EINVAL;
1314
1315         if (e->next_offset < sizeof(struct compat_ipt_entry) +
1316                              sizeof(struct compat_xt_entry_target))
1317                 return -EINVAL;
1318
1319         if (!ip_checkentry(&e->ip))
1320                 return -EINVAL;
1321
1322         ret = xt_compat_check_entry_offsets(e, e->elems,
1323                                             e->target_offset, e->next_offset);
1324         if (ret)
1325                 return ret;
1326
1327         off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1328         entry_offset = (void *)e - (void *)base;
1329         j = 0;
1330         xt_ematch_foreach(ematch, e) {
1331                 ret = compat_find_calc_match(ematch, &e->ip, &off);
1332                 if (ret != 0)
1333                         goto release_matches;
1334                 ++j;
1335         }
1336
1337         t = compat_ipt_get_target(e);
1338         target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
1339                                         t->u.user.revision);
1340         if (IS_ERR(target)) {
1341                 ret = PTR_ERR(target);
1342                 goto release_matches;
1343         }
1344         t->u.kernel.target = target;
1345
1346         off += xt_compat_target_offset(target);
1347         *size += off;
1348         ret = xt_compat_add_offset(AF_INET, entry_offset, off);
1349         if (ret)
1350                 goto out;
1351
1352         return 0;
1353
1354 out:
1355         module_put(t->u.kernel.target->me);
1356 release_matches:
1357         xt_ematch_foreach(ematch, e) {
1358                 if (j-- == 0)
1359                         break;
1360                 module_put(ematch->u.kernel.match->me);
1361         }
1362         return ret;
1363 }
1364
1365 static void
1366 compat_copy_entry_from_user(struct compat_ipt_entry *e, void **dstptr,
1367                             unsigned int *size,
1368                             struct xt_table_info *newinfo, unsigned char *base)
1369 {
1370         struct xt_entry_target *t;
1371         struct xt_target *target;
1372         struct ipt_entry *de;
1373         unsigned int origsize;
1374         int h;
1375         struct xt_entry_match *ematch;
1376
1377         origsize = *size;
1378         de = (struct ipt_entry *)*dstptr;
1379         memcpy(de, e, sizeof(struct ipt_entry));
1380         memcpy(&de->counters, &e->counters, sizeof(e->counters));
1381
1382         *dstptr += sizeof(struct ipt_entry);
1383         *size += sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
1384
1385         xt_ematch_foreach(ematch, e)
1386                 xt_compat_match_from_user(ematch, dstptr, size);
1387
1388         de->target_offset = e->target_offset - (origsize - *size);
1389         t = compat_ipt_get_target(e);
1390         target = t->u.kernel.target;
1391         xt_compat_target_from_user(t, dstptr, size);
1392
1393         de->next_offset = e->next_offset - (origsize - *size);
1394
1395         for (h = 0; h < NF_INET_NUMHOOKS; h++) {
1396                 if ((unsigned char *)de - base < newinfo->hook_entry[h])
1397                         newinfo->hook_entry[h] -= origsize - *size;
1398                 if ((unsigned char *)de - base < newinfo->underflow[h])
1399                         newinfo->underflow[h] -= origsize - *size;
1400         }
1401 }
1402
1403 static int
1404 translate_compat_table(struct net *net,
1405                        struct xt_table_info **pinfo,
1406                        void **pentry0,
1407                        const struct compat_ipt_replace *compatr)
1408 {
1409         unsigned int i, j;
1410         struct xt_table_info *newinfo, *info;
1411         void *pos, *entry0, *entry1;
1412         struct compat_ipt_entry *iter0;
1413         struct ipt_replace repl;
1414         unsigned int size;
1415         int ret;
1416
1417         info = *pinfo;
1418         entry0 = *pentry0;
1419         size = compatr->size;
1420         info->number = compatr->num_entries;
1421
1422         j = 0;
1423         xt_compat_lock(AF_INET);
1424         xt_compat_init_offsets(AF_INET, compatr->num_entries);
1425         /* Walk through entries, checking offsets. */
1426         xt_entry_foreach(iter0, entry0, compatr->size) {
1427                 ret = check_compat_entry_size_and_hooks(iter0, info, &size,
1428                                                         entry0,
1429                                                         entry0 + compatr->size);
1430                 if (ret != 0)
1431                         goto out_unlock;
1432                 ++j;
1433         }
1434
1435         ret = -EINVAL;
1436         if (j != compatr->num_entries)
1437                 goto out_unlock;
1438
1439         ret = -ENOMEM;
1440         newinfo = xt_alloc_table_info(size);
1441         if (!newinfo)
1442                 goto out_unlock;
1443
1444         newinfo->number = compatr->num_entries;
1445         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
1446                 newinfo->hook_entry[i] = compatr->hook_entry[i];
1447                 newinfo->underflow[i] = compatr->underflow[i];
1448         }
1449         entry1 = newinfo->entries;
1450         pos = entry1;
1451         size = compatr->size;
1452         xt_entry_foreach(iter0, entry0, compatr->size)
1453                 compat_copy_entry_from_user(iter0, &pos, &size,
1454                                             newinfo, entry1);
1455
1456         /* all module references in entry0 are now gone.
1457          * entry1/newinfo contains a 64bit ruleset that looks exactly as
1458          * generated by 64bit userspace.
1459          *
1460          * Call standard translate_table() to validate all hook_entrys,
1461          * underflows, check for loops, etc.
1462          */
1463         xt_compat_flush_offsets(AF_INET);
1464         xt_compat_unlock(AF_INET);
1465
1466         memcpy(&repl, compatr, sizeof(*compatr));
1467
1468         for (i = 0; i < NF_INET_NUMHOOKS; i++) {
1469                 repl.hook_entry[i] = newinfo->hook_entry[i];
1470                 repl.underflow[i] = newinfo->underflow[i];
1471         }
1472
1473         repl.num_counters = 0;
1474         repl.counters = NULL;
1475         repl.size = newinfo->size;
1476         ret = translate_table(net, newinfo, entry1, &repl);
1477         if (ret)
1478                 goto free_newinfo;
1479
1480         *pinfo = newinfo;
1481         *pentry0 = entry1;
1482         xt_free_table_info(info);
1483         return 0;
1484
1485 free_newinfo:
1486         xt_free_table_info(newinfo);
1487         return ret;
1488 out_unlock:
1489         xt_compat_flush_offsets(AF_INET);
1490         xt_compat_unlock(AF_INET);
1491         xt_entry_foreach(iter0, entry0, compatr->size) {
1492                 if (j-- == 0)
1493                         break;
1494                 compat_release_entry(iter0);
1495         }
1496         return ret;
1497 }
1498
1499 static int
1500 compat_do_replace(struct net *net, void __user *user, unsigned int len)
1501 {
1502         int ret;
1503         struct compat_ipt_replace tmp;
1504         struct xt_table_info *newinfo;
1505         void *loc_cpu_entry;
1506         struct ipt_entry *iter;
1507
1508         if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
1509                 return -EFAULT;
1510
1511         /* overflow check */
1512         if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
1513                 return -ENOMEM;
1514         if (tmp.num_counters == 0)
1515                 return -EINVAL;
1516
1517         tmp.name[sizeof(tmp.name)-1] = 0;
1518
1519         newinfo = xt_alloc_table_info(tmp.size);
1520         if (!newinfo)
1521                 return -ENOMEM;
1522
1523         loc_cpu_entry = newinfo->entries;
1524         if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
1525                            tmp.size) != 0) {
1526                 ret = -EFAULT;
1527                 goto free_newinfo;
1528         }
1529
1530         ret = translate_compat_table(net, &newinfo, &loc_cpu_entry, &tmp);
1531         if (ret != 0)
1532                 goto free_newinfo;
1533
1534         ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
1535                            tmp.num_counters, compat_ptr(tmp.counters));
1536         if (ret)
1537                 goto free_newinfo_untrans;
1538         return 0;
1539
1540  free_newinfo_untrans:
1541         xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
1542                 cleanup_entry(iter, net);
1543  free_newinfo:
1544         xt_free_table_info(newinfo);
1545         return ret;
1546 }
1547
1548 static int
1549 compat_do_ipt_set_ctl(struct sock *sk,  int cmd, void __user *user,
1550                       unsigned int len)
1551 {
1552         int ret;
1553
1554         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1555                 return -EPERM;
1556
1557         switch (cmd) {
1558         case IPT_SO_SET_REPLACE:
1559                 ret = compat_do_replace(sock_net(sk), user, len);
1560                 break;
1561
1562         case IPT_SO_SET_ADD_COUNTERS:
1563                 ret = do_add_counters(sock_net(sk), user, len, 1);
1564                 break;
1565
1566         default:
1567                 ret = -EINVAL;
1568         }
1569
1570         return ret;
1571 }
1572
1573 struct compat_ipt_get_entries {
1574         char name[XT_TABLE_MAXNAMELEN];
1575         compat_uint_t size;
1576         struct compat_ipt_entry entrytable[0];
1577 };
1578
1579 static int
1580 compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
1581                             void __user *userptr)
1582 {
1583         struct xt_counters *counters;
1584         const struct xt_table_info *private = table->private;
1585         void __user *pos;
1586         unsigned int size;
1587         int ret = 0;
1588         unsigned int i = 0;
1589         struct ipt_entry *iter;
1590
1591         counters = alloc_counters(table);
1592         if (IS_ERR(counters))
1593                 return PTR_ERR(counters);
1594
1595         pos = userptr;
1596         size = total_size;
1597         xt_entry_foreach(iter, private->entries, total_size) {
1598                 ret = compat_copy_entry_to_user(iter, &pos,
1599                                                 &size, counters, i++);
1600                 if (ret != 0)
1601                         break;
1602         }
1603
1604         vfree(counters);
1605         return ret;
1606 }
1607
1608 static int
1609 compat_get_entries(struct net *net, struct compat_ipt_get_entries __user *uptr,
1610                    int *len)
1611 {
1612         int ret;
1613         struct compat_ipt_get_entries get;
1614         struct xt_table *t;
1615
1616         if (*len < sizeof(get))
1617                 return -EINVAL;
1618
1619         if (copy_from_user(&get, uptr, sizeof(get)) != 0)
1620                 return -EFAULT;
1621
1622         if (*len != sizeof(struct compat_ipt_get_entries) + get.size)
1623                 return -EINVAL;
1624
1625         get.name[sizeof(get.name) - 1] = '\0';
1626
1627         xt_compat_lock(AF_INET);
1628         t = xt_find_table_lock(net, AF_INET, get.name);
1629         if (t) {
1630                 const struct xt_table_info *private = t->private;
1631                 struct xt_table_info info;
1632                 ret = compat_table_info(private, &info);
1633                 if (!ret && get.size == info.size)
1634                         ret = compat_copy_entries_to_user(private->size,
1635                                                           t, uptr->entrytable);
1636                 else if (!ret)
1637                         ret = -EAGAIN;
1638
1639                 xt_compat_flush_offsets(AF_INET);
1640                 module_put(t->me);
1641                 xt_table_unlock(t);
1642         } else
1643                 ret = -ENOENT;
1644
1645         xt_compat_unlock(AF_INET);
1646         return ret;
1647 }
1648
1649 static int do_ipt_get_ctl(struct sock *, int, void __user *, int *);
1650
1651 static int
1652 compat_do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
1653 {
1654         int ret;
1655
1656         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1657                 return -EPERM;
1658
1659         switch (cmd) {
1660         case IPT_SO_GET_INFO:
1661                 ret = get_info(sock_net(sk), user, len, 1);
1662                 break;
1663         case IPT_SO_GET_ENTRIES:
1664                 ret = compat_get_entries(sock_net(sk), user, len);
1665                 break;
1666         default:
1667                 ret = do_ipt_get_ctl(sk, cmd, user, len);
1668         }
1669         return ret;
1670 }
1671 #endif
1672
1673 static int
1674 do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
1675 {
1676         int ret;
1677
1678         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1679                 return -EPERM;
1680
1681         switch (cmd) {
1682         case IPT_SO_SET_REPLACE:
1683                 ret = do_replace(sock_net(sk), user, len);
1684                 break;
1685
1686         case IPT_SO_SET_ADD_COUNTERS:
1687                 ret = do_add_counters(sock_net(sk), user, len, 0);
1688                 break;
1689
1690         default:
1691                 ret = -EINVAL;
1692         }
1693
1694         return ret;
1695 }
1696
1697 static int
1698 do_ipt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
1699 {
1700         int ret;
1701
1702         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1703                 return -EPERM;
1704
1705         switch (cmd) {
1706         case IPT_SO_GET_INFO:
1707                 ret = get_info(sock_net(sk), user, len, 0);
1708                 break;
1709
1710         case IPT_SO_GET_ENTRIES:
1711                 ret = get_entries(sock_net(sk), user, len);
1712                 break;
1713
1714         case IPT_SO_GET_REVISION_MATCH:
1715         case IPT_SO_GET_REVISION_TARGET: {
1716                 struct xt_get_revision rev;
1717                 int target;
1718
1719                 if (*len != sizeof(rev)) {
1720                         ret = -EINVAL;
1721                         break;
1722                 }
1723                 if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
1724                         ret = -EFAULT;
1725                         break;
1726                 }
1727                 rev.name[sizeof(rev.name)-1] = 0;
1728
1729                 if (cmd == IPT_SO_GET_REVISION_TARGET)
1730                         target = 1;
1731                 else
1732                         target = 0;
1733
1734                 try_then_request_module(xt_find_revision(AF_INET, rev.name,
1735                                                          rev.revision,
1736                                                          target, &ret),
1737                                         "ipt_%s", rev.name);
1738                 break;
1739         }
1740
1741         default:
1742                 ret = -EINVAL;
1743         }
1744
1745         return ret;
1746 }
1747
1748 static void __ipt_unregister_table(struct net *net, struct xt_table *table)
1749 {
1750         struct xt_table_info *private;
1751         void *loc_cpu_entry;
1752         struct module *table_owner = table->me;
1753         struct ipt_entry *iter;
1754
1755         private = xt_unregister_table(table);
1756
1757         /* Decrease module usage counts and free resources */
1758         loc_cpu_entry = private->entries;
1759         xt_entry_foreach(iter, loc_cpu_entry, private->size)
1760                 cleanup_entry(iter, net);
1761         if (private->number > private->initial_entries)
1762                 module_put(table_owner);
1763         xt_free_table_info(private);
1764 }
1765
1766 int ipt_register_table(struct net *net, const struct xt_table *table,
1767                        const struct ipt_replace *repl,
1768                        const struct nf_hook_ops *ops, struct xt_table **res)
1769 {
1770         int ret;
1771         struct xt_table_info *newinfo;
1772         struct xt_table_info bootstrap = {0};
1773         void *loc_cpu_entry;
1774         struct xt_table *new_table;
1775
1776         newinfo = xt_alloc_table_info(repl->size);
1777         if (!newinfo)
1778                 return -ENOMEM;
1779
1780         loc_cpu_entry = newinfo->entries;
1781         memcpy(loc_cpu_entry, repl->entries, repl->size);
1782
1783         ret = translate_table(net, newinfo, loc_cpu_entry, repl);
1784         if (ret != 0)
1785                 goto out_free;
1786
1787         new_table = xt_register_table(net, table, &bootstrap, newinfo);
1788         if (IS_ERR(new_table)) {
1789                 ret = PTR_ERR(new_table);
1790                 goto out_free;
1791         }
1792
1793         /* set res now, will see skbs right after nf_register_net_hooks */
1794         WRITE_ONCE(*res, new_table);
1795
1796         ret = nf_register_net_hooks(net, ops, hweight32(table->valid_hooks));
1797         if (ret != 0) {
1798                 __ipt_unregister_table(net, new_table);
1799                 *res = NULL;
1800         }
1801
1802         return ret;
1803
1804 out_free:
1805         xt_free_table_info(newinfo);
1806         return ret;
1807 }
1808
1809 void ipt_unregister_table(struct net *net, struct xt_table *table,
1810                           const struct nf_hook_ops *ops)
1811 {
1812         nf_unregister_net_hooks(net, ops, hweight32(table->valid_hooks));
1813         __ipt_unregister_table(net, table);
1814 }
1815
1816 /* Returns 1 if the type and code is matched by the range, 0 otherwise */
1817 static inline bool
1818 icmp_type_code_match(u_int8_t test_type, u_int8_t min_code, u_int8_t max_code,
1819                      u_int8_t type, u_int8_t code,
1820                      bool invert)
1821 {
1822         return ((test_type == 0xFF) ||
1823                 (type == test_type && code >= min_code && code <= max_code))
1824                 ^ invert;
1825 }
1826
1827 static bool
1828 icmp_match(const struct sk_buff *skb, struct xt_action_param *par)
1829 {
1830         const struct icmphdr *ic;
1831         struct icmphdr _icmph;
1832         const struct ipt_icmp *icmpinfo = par->matchinfo;
1833
1834         /* Must not be a fragment. */
1835         if (par->fragoff != 0)
1836                 return false;
1837
1838         ic = skb_header_pointer(skb, par->thoff, sizeof(_icmph), &_icmph);
1839         if (ic == NULL) {
1840                 /* We've been asked to examine this packet, and we
1841                  * can't.  Hence, no choice but to drop.
1842                  */
1843                 par->hotdrop = true;
1844                 return false;
1845         }
1846
1847         return icmp_type_code_match(icmpinfo->type,
1848                                     icmpinfo->code[0],
1849                                     icmpinfo->code[1],
1850                                     ic->type, ic->code,
1851                                     !!(icmpinfo->invflags&IPT_ICMP_INV));
1852 }
1853
1854 static int icmp_checkentry(const struct xt_mtchk_param *par)
1855 {
1856         const struct ipt_icmp *icmpinfo = par->matchinfo;
1857
1858         /* Must specify no unknown invflags */
1859         return (icmpinfo->invflags & ~IPT_ICMP_INV) ? -EINVAL : 0;
1860 }
1861
1862 static struct xt_target ipt_builtin_tg[] __read_mostly = {
1863         {
1864                 .name             = XT_STANDARD_TARGET,
1865                 .targetsize       = sizeof(int),
1866                 .family           = NFPROTO_IPV4,
1867 #ifdef CONFIG_COMPAT
1868                 .compatsize       = sizeof(compat_int_t),
1869                 .compat_from_user = compat_standard_from_user,
1870                 .compat_to_user   = compat_standard_to_user,
1871 #endif
1872         },
1873         {
1874                 .name             = XT_ERROR_TARGET,
1875                 .target           = ipt_error,
1876                 .targetsize       = XT_FUNCTION_MAXNAMELEN,
1877                 .family           = NFPROTO_IPV4,
1878         },
1879 };
1880
1881 static struct nf_sockopt_ops ipt_sockopts = {
1882         .pf             = PF_INET,
1883         .set_optmin     = IPT_BASE_CTL,
1884         .set_optmax     = IPT_SO_SET_MAX+1,
1885         .set            = do_ipt_set_ctl,
1886 #ifdef CONFIG_COMPAT
1887         .compat_set     = compat_do_ipt_set_ctl,
1888 #endif
1889         .get_optmin     = IPT_BASE_CTL,
1890         .get_optmax     = IPT_SO_GET_MAX+1,
1891         .get            = do_ipt_get_ctl,
1892 #ifdef CONFIG_COMPAT
1893         .compat_get     = compat_do_ipt_get_ctl,
1894 #endif
1895         .owner          = THIS_MODULE,
1896 };
1897
1898 static struct xt_match ipt_builtin_mt[] __read_mostly = {
1899         {
1900                 .name       = "icmp",
1901                 .match      = icmp_match,
1902                 .matchsize  = sizeof(struct ipt_icmp),
1903                 .checkentry = icmp_checkentry,
1904                 .proto      = IPPROTO_ICMP,
1905                 .family     = NFPROTO_IPV4,
1906         },
1907 };
1908
1909 static int __net_init ip_tables_net_init(struct net *net)
1910 {
1911         return xt_proto_init(net, NFPROTO_IPV4);
1912 }
1913
1914 static void __net_exit ip_tables_net_exit(struct net *net)
1915 {
1916         xt_proto_fini(net, NFPROTO_IPV4);
1917 }
1918
1919 static struct pernet_operations ip_tables_net_ops = {
1920         .init = ip_tables_net_init,
1921         .exit = ip_tables_net_exit,
1922 };
1923
1924 static int __init ip_tables_init(void)
1925 {
1926         int ret;
1927
1928         ret = register_pernet_subsys(&ip_tables_net_ops);
1929         if (ret < 0)
1930                 goto err1;
1931
1932         /* No one else will be downing sem now, so we won't sleep */
1933         ret = xt_register_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
1934         if (ret < 0)
1935                 goto err2;
1936         ret = xt_register_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
1937         if (ret < 0)
1938                 goto err4;
1939
1940         /* Register setsockopt */
1941         ret = nf_register_sockopt(&ipt_sockopts);
1942         if (ret < 0)
1943                 goto err5;
1944
1945         pr_info("(C) 2000-2006 Netfilter Core Team\n");
1946         return 0;
1947
1948 err5:
1949         xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
1950 err4:
1951         xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
1952 err2:
1953         unregister_pernet_subsys(&ip_tables_net_ops);
1954 err1:
1955         return ret;
1956 }
1957
1958 static void __exit ip_tables_fini(void)
1959 {
1960         nf_unregister_sockopt(&ipt_sockopts);
1961
1962         xt_unregister_matches(ipt_builtin_mt, ARRAY_SIZE(ipt_builtin_mt));
1963         xt_unregister_targets(ipt_builtin_tg, ARRAY_SIZE(ipt_builtin_tg));
1964         unregister_pernet_subsys(&ip_tables_net_ops);
1965 }
1966
1967 EXPORT_SYMBOL(ipt_register_table);
1968 EXPORT_SYMBOL(ipt_unregister_table);
1969 EXPORT_SYMBOL(ipt_do_table);
1970 module_init(ip_tables_init);
1971 module_exit(ip_tables_fini);