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