linux/net/netfilter/nf_tables_api.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (c) 2007-2009 Patrick McHardy <kaber@trash.net>
   4 *
   5 * Development of this code funded by Astaro AG (http://www.astaro.com/)
   6 */
   7
   8#include <linux/module.h>
   9#include <linux/init.h>
  10#include <linux/list.h>
  11#include <linux/skbuff.h>
  12#include <linux/netlink.h>
  13#include <linux/vmalloc.h>
  14#include <linux/rhashtable.h>
  15#include <linux/netfilter.h>
  16#include <linux/netfilter/nfnetlink.h>
  17#include <linux/netfilter/nf_tables.h>
  18#include <net/netfilter/nf_flow_table.h>
  19#include <net/netfilter/nf_tables_core.h>
  20#include <net/netfilter/nf_tables.h>
  21#include <net/netfilter/nf_tables_offload.h>
  22#include <net/net_namespace.h>
  23#include <net/sock.h>
  24
  25static LIST_HEAD(nf_tables_expressions);
  26static LIST_HEAD(nf_tables_objects);
  27static LIST_HEAD(nf_tables_flowtables);
  28static LIST_HEAD(nf_tables_destroy_list);
  29static DEFINE_SPINLOCK(nf_tables_destroy_list_lock);
  30static u64 table_handle;
  31
  32enum {
  33        NFT_VALIDATE_SKIP       = 0,
  34        NFT_VALIDATE_NEED,
  35        NFT_VALIDATE_DO,
  36};
  37
  38static struct rhltable nft_objname_ht;
  39
  40static u32 nft_chain_hash(const void *data, u32 len, u32 seed);
  41static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed);
  42static int nft_chain_hash_cmp(struct rhashtable_compare_arg *, const void *);
  43
  44static u32 nft_objname_hash(const void *data, u32 len, u32 seed);
  45static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed);
  46static int nft_objname_hash_cmp(struct rhashtable_compare_arg *, const void *);
  47
  48static const struct rhashtable_params nft_chain_ht_params = {
  49        .head_offset            = offsetof(struct nft_chain, rhlhead),
  50        .key_offset             = offsetof(struct nft_chain, name),
  51        .hashfn                 = nft_chain_hash,
  52        .obj_hashfn             = nft_chain_hash_obj,
  53        .obj_cmpfn              = nft_chain_hash_cmp,
  54        .automatic_shrinking    = true,
  55};
  56
  57static const struct rhashtable_params nft_objname_ht_params = {
  58        .head_offset            = offsetof(struct nft_object, rhlhead),
  59        .key_offset             = offsetof(struct nft_object, key),
  60        .hashfn                 = nft_objname_hash,
  61        .obj_hashfn             = nft_objname_hash_obj,
  62        .obj_cmpfn              = nft_objname_hash_cmp,
  63        .automatic_shrinking    = true,
  64};
  65
  66static void nft_validate_state_update(struct net *net, u8 new_validate_state)
  67{
  68        switch (net->nft.validate_state) {
  69        case NFT_VALIDATE_SKIP:
  70                WARN_ON_ONCE(new_validate_state == NFT_VALIDATE_DO);
  71                break;
  72        case NFT_VALIDATE_NEED:
  73                break;
  74        case NFT_VALIDATE_DO:
  75                if (new_validate_state == NFT_VALIDATE_NEED)
  76                        return;
  77        }
  78
  79        net->nft.validate_state = new_validate_state;
  80}
  81static void nf_tables_trans_destroy_work(struct work_struct *w);
  82static DECLARE_WORK(trans_destroy_work, nf_tables_trans_destroy_work);
  83
  84static void nft_ctx_init(struct nft_ctx *ctx,
  85                         struct net *net,
  86                         const struct sk_buff *skb,
  87                         const struct nlmsghdr *nlh,
  88                         u8 family,
  89                         struct nft_table *table,
  90                         struct nft_chain *chain,
  91                         const struct nlattr * const *nla)
  92{
  93        ctx->net        = net;
  94        ctx->family     = family;
  95        ctx->level      = 0;
  96        ctx->table      = table;
  97        ctx->chain      = chain;
  98        ctx->nla        = nla;
  99        ctx->portid     = NETLINK_CB(skb).portid;
 100        ctx->report     = nlmsg_report(nlh);
 101        ctx->flags      = nlh->nlmsg_flags;
 102        ctx->seq        = nlh->nlmsg_seq;
 103}
 104
 105static struct nft_trans *nft_trans_alloc_gfp(const struct nft_ctx *ctx,
 106                                             int msg_type, u32 size, gfp_t gfp)
 107{
 108        struct nft_trans *trans;
 109
 110        trans = kzalloc(sizeof(struct nft_trans) + size, gfp);
 111        if (trans == NULL)
 112                return NULL;
 113
 114        trans->msg_type = msg_type;
 115        trans->ctx      = *ctx;
 116
 117        return trans;
 118}
 119
 120static struct nft_trans *nft_trans_alloc(const struct nft_ctx *ctx,
 121                                         int msg_type, u32 size)
 122{
 123        return nft_trans_alloc_gfp(ctx, msg_type, size, GFP_KERNEL);
 124}
 125
 126static void nft_trans_destroy(struct nft_trans *trans)
 127{
 128        list_del(&trans->list);
 129        kfree(trans);
 130}
 131
 132static void nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set)
 133{
 134        struct net *net = ctx->net;
 135        struct nft_trans *trans;
 136
 137        if (!nft_set_is_anonymous(set))
 138                return;
 139
 140        list_for_each_entry_reverse(trans, &net->nft.commit_list, list) {
 141                switch (trans->msg_type) {
 142                case NFT_MSG_NEWSET:
 143                        if (nft_trans_set(trans) == set)
 144                                nft_trans_set_bound(trans) = true;
 145                        break;
 146                case NFT_MSG_NEWSETELEM:
 147                        if (nft_trans_elem_set(trans) == set)
 148                                nft_trans_elem_set_bound(trans) = true;
 149                        break;
 150                }
 151        }
 152}
 153
 154static int nf_tables_register_hook(struct net *net,
 155                                   const struct nft_table *table,
 156                                   struct nft_chain *chain)
 157{
 158        const struct nft_base_chain *basechain;
 159        const struct nf_hook_ops *ops;
 160
 161        if (table->flags & NFT_TABLE_F_DORMANT ||
 162            !nft_is_base_chain(chain))
 163                return 0;
 164
 165        basechain = nft_base_chain(chain);
 166        ops = &basechain->ops;
 167
 168        if (basechain->type->ops_register)
 169                return basechain->type->ops_register(net, ops);
 170
 171        return nf_register_net_hook(net, ops);
 172}
 173
 174static void nf_tables_unregister_hook(struct net *net,
 175                                      const struct nft_table *table,
 176                                      struct nft_chain *chain)
 177{
 178        const struct nft_base_chain *basechain;
 179        const struct nf_hook_ops *ops;
 180
 181        if (table->flags & NFT_TABLE_F_DORMANT ||
 182            !nft_is_base_chain(chain))
 183                return;
 184        basechain = nft_base_chain(chain);
 185        ops = &basechain->ops;
 186
 187        if (basechain->type->ops_unregister)
 188                return basechain->type->ops_unregister(net, ops);
 189
 190        nf_unregister_net_hook(net, ops);
 191}
 192
 193static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
 194{
 195        struct nft_trans *trans;
 196
 197        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
 198        if (trans == NULL)
 199                return -ENOMEM;
 200
 201        if (msg_type == NFT_MSG_NEWTABLE)
 202                nft_activate_next(ctx->net, ctx->table);
 203
 204        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 205        return 0;
 206}
 207
 208static int nft_deltable(struct nft_ctx *ctx)
 209{
 210        int err;
 211
 212        err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
 213        if (err < 0)
 214                return err;
 215
 216        nft_deactivate_next(ctx->net, ctx->table);
 217        return err;
 218}
 219
 220static struct nft_trans *nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
 221{
 222        struct nft_trans *trans;
 223
 224        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
 225        if (trans == NULL)
 226                return ERR_PTR(-ENOMEM);
 227
 228        if (msg_type == NFT_MSG_NEWCHAIN)
 229                nft_activate_next(ctx->net, ctx->chain);
 230
 231        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 232        return trans;
 233}
 234
 235static int nft_delchain(struct nft_ctx *ctx)
 236{
 237        struct nft_trans *trans;
 238
 239        trans = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
 240        if (IS_ERR(trans))
 241                return PTR_ERR(trans);
 242
 243        ctx->table->use--;
 244        nft_deactivate_next(ctx->net, ctx->chain);
 245
 246        return 0;
 247}
 248
 249static void nft_rule_expr_activate(const struct nft_ctx *ctx,
 250                                   struct nft_rule *rule)
 251{
 252        struct nft_expr *expr;
 253
 254        expr = nft_expr_first(rule);
 255        while (expr != nft_expr_last(rule) && expr->ops) {
 256                if (expr->ops->activate)
 257                        expr->ops->activate(ctx, expr);
 258
 259                expr = nft_expr_next(expr);
 260        }
 261}
 262
 263static void nft_rule_expr_deactivate(const struct nft_ctx *ctx,
 264                                     struct nft_rule *rule,
 265                                     enum nft_trans_phase phase)
 266{
 267        struct nft_expr *expr;
 268
 269        expr = nft_expr_first(rule);
 270        while (expr != nft_expr_last(rule) && expr->ops) {
 271                if (expr->ops->deactivate)
 272                        expr->ops->deactivate(ctx, expr, phase);
 273
 274                expr = nft_expr_next(expr);
 275        }
 276}
 277
 278static int
 279nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
 280{
 281        /* You cannot delete the same rule twice */
 282        if (nft_is_active_next(ctx->net, rule)) {
 283                nft_deactivate_next(ctx->net, rule);
 284                ctx->chain->use--;
 285                return 0;
 286        }
 287        return -ENOENT;
 288}
 289
 290static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
 291                                            struct nft_rule *rule)
 292{
 293        struct nft_trans *trans;
 294
 295        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
 296        if (trans == NULL)
 297                return NULL;
 298
 299        if (msg_type == NFT_MSG_NEWRULE && ctx->nla[NFTA_RULE_ID] != NULL) {
 300                nft_trans_rule_id(trans) =
 301                        ntohl(nla_get_be32(ctx->nla[NFTA_RULE_ID]));
 302        }
 303        nft_trans_rule(trans) = rule;
 304        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 305
 306        return trans;
 307}
 308
 309static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
 310{
 311        struct nft_trans *trans;
 312        int err;
 313
 314        trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
 315        if (trans == NULL)
 316                return -ENOMEM;
 317
 318        err = nf_tables_delrule_deactivate(ctx, rule);
 319        if (err < 0) {
 320                nft_trans_destroy(trans);
 321                return err;
 322        }
 323        nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
 324
 325        return 0;
 326}
 327
 328static int nft_delrule_by_chain(struct nft_ctx *ctx)
 329{
 330        struct nft_rule *rule;
 331        int err;
 332
 333        list_for_each_entry(rule, &ctx->chain->rules, list) {
 334                if (!nft_is_active_next(ctx->net, rule))
 335                        continue;
 336
 337                err = nft_delrule(ctx, rule);
 338                if (err < 0)
 339                        return err;
 340        }
 341        return 0;
 342}
 343
 344static int nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
 345                             struct nft_set *set)
 346{
 347        struct nft_trans *trans;
 348
 349        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
 350        if (trans == NULL)
 351                return -ENOMEM;
 352
 353        if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] != NULL) {
 354                nft_trans_set_id(trans) =
 355                        ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
 356                nft_activate_next(ctx->net, set);
 357        }
 358        nft_trans_set(trans) = set;
 359        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 360
 361        return 0;
 362}
 363
 364static int nft_delset(const struct nft_ctx *ctx, struct nft_set *set)
 365{
 366        int err;
 367
 368        err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
 369        if (err < 0)
 370                return err;
 371
 372        nft_deactivate_next(ctx->net, set);
 373        ctx->table->use--;
 374
 375        return err;
 376}
 377
 378static int nft_trans_obj_add(struct nft_ctx *ctx, int msg_type,
 379                             struct nft_object *obj)
 380{
 381        struct nft_trans *trans;
 382
 383        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_obj));
 384        if (trans == NULL)
 385                return -ENOMEM;
 386
 387        if (msg_type == NFT_MSG_NEWOBJ)
 388                nft_activate_next(ctx->net, obj);
 389
 390        nft_trans_obj(trans) = obj;
 391        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 392
 393        return 0;
 394}
 395
 396static int nft_delobj(struct nft_ctx *ctx, struct nft_object *obj)
 397{
 398        int err;
 399
 400        err = nft_trans_obj_add(ctx, NFT_MSG_DELOBJ, obj);
 401        if (err < 0)
 402                return err;
 403
 404        nft_deactivate_next(ctx->net, obj);
 405        ctx->table->use--;
 406
 407        return err;
 408}
 409
 410static int nft_trans_flowtable_add(struct nft_ctx *ctx, int msg_type,
 411                                   struct nft_flowtable *flowtable)
 412{
 413        struct nft_trans *trans;
 414
 415        trans = nft_trans_alloc(ctx, msg_type,
 416                                sizeof(struct nft_trans_flowtable));
 417        if (trans == NULL)
 418                return -ENOMEM;
 419
 420        if (msg_type == NFT_MSG_NEWFLOWTABLE)
 421                nft_activate_next(ctx->net, flowtable);
 422
 423        nft_trans_flowtable(trans) = flowtable;
 424        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 425
 426        return 0;
 427}
 428
 429static int nft_delflowtable(struct nft_ctx *ctx,
 430                            struct nft_flowtable *flowtable)
 431{
 432        int err;
 433
 434        err = nft_trans_flowtable_add(ctx, NFT_MSG_DELFLOWTABLE, flowtable);
 435        if (err < 0)
 436                return err;
 437
 438        nft_deactivate_next(ctx->net, flowtable);
 439        ctx->table->use--;
 440
 441        return err;
 442}
 443
 444/*
 445 * Tables
 446 */
 447
 448static struct nft_table *nft_table_lookup(const struct net *net,
 449                                          const struct nlattr *nla,
 450                                          u8 family, u8 genmask)
 451{
 452        struct nft_table *table;
 453
 454        if (nla == NULL)
 455                return ERR_PTR(-EINVAL);
 456
 457        list_for_each_entry_rcu(table, &net->nft.tables, list) {
 458                if (!nla_strcmp(nla, table->name) &&
 459                    table->family == family &&
 460                    nft_active_genmask(table, genmask))
 461                        return table;
 462        }
 463
 464        return ERR_PTR(-ENOENT);
 465}
 466
 467static struct nft_table *nft_table_lookup_byhandle(const struct net *net,
 468                                                   const struct nlattr *nla,
 469                                                   u8 genmask)
 470{
 471        struct nft_table *table;
 472
 473        list_for_each_entry(table, &net->nft.tables, list) {
 474                if (be64_to_cpu(nla_get_be64(nla)) == table->handle &&
 475                    nft_active_genmask(table, genmask))
 476                        return table;
 477        }
 478
 479        return ERR_PTR(-ENOENT);
 480}
 481
 482static inline u64 nf_tables_alloc_handle(struct nft_table *table)
 483{
 484        return ++table->hgenerator;
 485}
 486
 487static const struct nft_chain_type *chain_type[NFPROTO_NUMPROTO][NFT_CHAIN_T_MAX];
 488
 489static const struct nft_chain_type *
 490__nf_tables_chain_type_lookup(const struct nlattr *nla, u8 family)
 491{
 492        int i;
 493
 494        for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
 495                if (chain_type[family][i] != NULL &&
 496                    !nla_strcmp(nla, chain_type[family][i]->name))
 497                        return chain_type[family][i];
 498        }
 499        return NULL;
 500}
 501
 502/*
 503 * Loading a module requires dropping mutex that guards the
 504 * transaction.
 505 * We first need to abort any pending transactions as once
 506 * mutex is unlocked a different client could start a new
 507 * transaction.  It must not see any 'future generation'
 508 * changes * as these changes will never happen.
 509 */
 510#ifdef CONFIG_MODULES
 511static int __nf_tables_abort(struct net *net);
 512
 513static void nft_request_module(struct net *net, const char *fmt, ...)
 514{
 515        char module_name[MODULE_NAME_LEN];
 516        va_list args;
 517        int ret;
 518
 519        __nf_tables_abort(net);
 520
 521        va_start(args, fmt);
 522        ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
 523        va_end(args);
 524        if (WARN(ret >= MODULE_NAME_LEN, "truncated: '%s' (len %d)", module_name, ret))
 525                return;
 526
 527        mutex_unlock(&net->nft.commit_mutex);
 528        request_module("%s", module_name);
 529        mutex_lock(&net->nft.commit_mutex);
 530}
 531#endif
 532
 533static void lockdep_nfnl_nft_mutex_not_held(void)
 534{
 535#ifdef CONFIG_PROVE_LOCKING
 536        WARN_ON_ONCE(lockdep_nfnl_is_held(NFNL_SUBSYS_NFTABLES));
 537#endif
 538}
 539
 540static const struct nft_chain_type *
 541nf_tables_chain_type_lookup(struct net *net, const struct nlattr *nla,
 542                            u8 family, bool autoload)
 543{
 544        const struct nft_chain_type *type;
 545
 546        type = __nf_tables_chain_type_lookup(nla, family);
 547        if (type != NULL)
 548                return type;
 549
 550        lockdep_nfnl_nft_mutex_not_held();
 551#ifdef CONFIG_MODULES
 552        if (autoload) {
 553                nft_request_module(net, "nft-chain-%u-%.*s", family,
 554                                   nla_len(nla), (const char *)nla_data(nla));
 555                type = __nf_tables_chain_type_lookup(nla, family);
 556                if (type != NULL)
 557                        return ERR_PTR(-EAGAIN);
 558        }
 559#endif
 560        return ERR_PTR(-ENOENT);
 561}
 562
 563static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
 564        [NFTA_TABLE_NAME]       = { .type = NLA_STRING,
 565                                    .len = NFT_TABLE_MAXNAMELEN - 1 },
 566        [NFTA_TABLE_FLAGS]      = { .type = NLA_U32 },
 567        [NFTA_TABLE_HANDLE]     = { .type = NLA_U64 },
 568};
 569
 570static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
 571                                     u32 portid, u32 seq, int event, u32 flags,
 572                                     int family, const struct nft_table *table)
 573{
 574        struct nlmsghdr *nlh;
 575        struct nfgenmsg *nfmsg;
 576
 577        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
 578        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
 579        if (nlh == NULL)
 580                goto nla_put_failure;
 581
 582        nfmsg = nlmsg_data(nlh);
 583        nfmsg->nfgen_family     = family;
 584        nfmsg->version          = NFNETLINK_V0;
 585        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
 586
 587        if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
 588            nla_put_be32(skb, NFTA_TABLE_FLAGS, htonl(table->flags)) ||
 589            nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)) ||
 590            nla_put_be64(skb, NFTA_TABLE_HANDLE, cpu_to_be64(table->handle),
 591                         NFTA_TABLE_PAD))
 592                goto nla_put_failure;
 593
 594        nlmsg_end(skb, nlh);
 595        return 0;
 596
 597nla_put_failure:
 598        nlmsg_trim(skb, nlh);
 599        return -1;
 600}
 601
 602static void nf_tables_table_notify(const struct nft_ctx *ctx, int event)
 603{
 604        struct sk_buff *skb;
 605        int err;
 606
 607        if (!ctx->report &&
 608            !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
 609                return;
 610
 611        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
 612        if (skb == NULL)
 613                goto err;
 614
 615        err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
 616                                        event, 0, ctx->family, ctx->table);
 617        if (err < 0) {
 618                kfree_skb(skb);
 619                goto err;
 620        }
 621
 622        nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
 623                       ctx->report, GFP_KERNEL);
 624        return;
 625err:
 626        nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
 627}
 628
 629static int nf_tables_dump_tables(struct sk_buff *skb,
 630                                 struct netlink_callback *cb)
 631{
 632        const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
 633        const struct nft_table *table;
 634        unsigned int idx = 0, s_idx = cb->args[0];
 635        struct net *net = sock_net(skb->sk);
 636        int family = nfmsg->nfgen_family;
 637
 638        rcu_read_lock();
 639        cb->seq = net->nft.base_seq;
 640
 641        list_for_each_entry_rcu(table, &net->nft.tables, list) {
 642                if (family != NFPROTO_UNSPEC && family != table->family)
 643                        continue;
 644
 645                if (idx < s_idx)
 646                        goto cont;
 647                if (idx > s_idx)
 648                        memset(&cb->args[1], 0,
 649                               sizeof(cb->args) - sizeof(cb->args[0]));
 650                if (!nft_is_active(net, table))
 651                        continue;
 652                if (nf_tables_fill_table_info(skb, net,
 653                                              NETLINK_CB(cb->skb).portid,
 654                                              cb->nlh->nlmsg_seq,
 655                                              NFT_MSG_NEWTABLE, NLM_F_MULTI,
 656                                              table->family, table) < 0)
 657                        goto done;
 658
 659                nl_dump_check_consistent(cb, nlmsg_hdr(skb));
 660cont:
 661                idx++;
 662        }
 663done:
 664        rcu_read_unlock();
 665        cb->args[0] = idx;
 666        return skb->len;
 667}
 668
 669static int nft_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb,
 670                                      const struct nlmsghdr *nlh,
 671                                      struct netlink_dump_control *c)
 672{
 673        int err;
 674
 675        if (!try_module_get(THIS_MODULE))
 676                return -EINVAL;
 677
 678        rcu_read_unlock();
 679        err = netlink_dump_start(nlsk, skb, nlh, c);
 680        rcu_read_lock();
 681        module_put(THIS_MODULE);
 682
 683        return err;
 684}
 685
 686/* called with rcu_read_lock held */
 687static int nf_tables_gettable(struct net *net, struct sock *nlsk,
 688                              struct sk_buff *skb, const struct nlmsghdr *nlh,
 689                              const struct nlattr * const nla[],
 690                              struct netlink_ext_ack *extack)
 691{
 692        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
 693        u8 genmask = nft_genmask_cur(net);
 694        const struct nft_table *table;
 695        struct sk_buff *skb2;
 696        int family = nfmsg->nfgen_family;
 697        int err;
 698
 699        if (nlh->nlmsg_flags & NLM_F_DUMP) {
 700                struct netlink_dump_control c = {
 701                        .dump = nf_tables_dump_tables,
 702                        .module = THIS_MODULE,
 703                };
 704
 705                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
 706        }
 707
 708        table = nft_table_lookup(net, nla[NFTA_TABLE_NAME], family, genmask);
 709        if (IS_ERR(table)) {
 710                NL_SET_BAD_ATTR(extack, nla[NFTA_TABLE_NAME]);
 711                return PTR_ERR(table);
 712        }
 713
 714        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
 715        if (!skb2)
 716                return -ENOMEM;
 717
 718        err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
 719                                        nlh->nlmsg_seq, NFT_MSG_NEWTABLE, 0,
 720                                        family, table);
 721        if (err < 0)
 722                goto err;
 723
 724        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
 725
 726err:
 727        kfree_skb(skb2);
 728        return err;
 729}
 730
 731static void nft_table_disable(struct net *net, struct nft_table *table, u32 cnt)
 732{
 733        struct nft_chain *chain;
 734        u32 i = 0;
 735
 736        list_for_each_entry(chain, &table->chains, list) {
 737                if (!nft_is_active_next(net, chain))
 738                        continue;
 739                if (!nft_is_base_chain(chain))
 740                        continue;
 741
 742                if (cnt && i++ == cnt)
 743                        break;
 744
 745                nf_unregister_net_hook(net, &nft_base_chain(chain)->ops);
 746        }
 747}
 748
 749static int nf_tables_table_enable(struct net *net, struct nft_table *table)
 750{
 751        struct nft_chain *chain;
 752        int err, i = 0;
 753
 754        list_for_each_entry(chain, &table->chains, list) {
 755                if (!nft_is_active_next(net, chain))
 756                        continue;
 757                if (!nft_is_base_chain(chain))
 758                        continue;
 759
 760                err = nf_register_net_hook(net, &nft_base_chain(chain)->ops);
 761                if (err < 0)
 762                        goto err;
 763
 764                i++;
 765        }
 766        return 0;
 767err:
 768        if (i)
 769                nft_table_disable(net, table, i);
 770        return err;
 771}
 772
 773static void nf_tables_table_disable(struct net *net, struct nft_table *table)
 774{
 775        nft_table_disable(net, table, 0);
 776}
 777
 778static int nf_tables_updtable(struct nft_ctx *ctx)
 779{
 780        struct nft_trans *trans;
 781        u32 flags;
 782        int ret = 0;
 783
 784        if (!ctx->nla[NFTA_TABLE_FLAGS])
 785                return 0;
 786
 787        flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
 788        if (flags & ~NFT_TABLE_F_DORMANT)
 789                return -EINVAL;
 790
 791        if (flags == ctx->table->flags)
 792                return 0;
 793
 794        trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
 795                                sizeof(struct nft_trans_table));
 796        if (trans == NULL)
 797                return -ENOMEM;
 798
 799        if ((flags & NFT_TABLE_F_DORMANT) &&
 800            !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
 801                nft_trans_table_enable(trans) = false;
 802        } else if (!(flags & NFT_TABLE_F_DORMANT) &&
 803                   ctx->table->flags & NFT_TABLE_F_DORMANT) {
 804                ret = nf_tables_table_enable(ctx->net, ctx->table);
 805                if (ret >= 0) {
 806                        ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
 807                        nft_trans_table_enable(trans) = true;
 808                }
 809        }
 810        if (ret < 0)
 811                goto err;
 812
 813        nft_trans_table_update(trans) = true;
 814        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
 815        return 0;
 816err:
 817        nft_trans_destroy(trans);
 818        return ret;
 819}
 820
 821static u32 nft_chain_hash(const void *data, u32 len, u32 seed)
 822{
 823        const char *name = data;
 824
 825        return jhash(name, strlen(name), seed);
 826}
 827
 828static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed)
 829{
 830        const struct nft_chain *chain = data;
 831
 832        return nft_chain_hash(chain->name, 0, seed);
 833}
 834
 835static int nft_chain_hash_cmp(struct rhashtable_compare_arg *arg,
 836                              const void *ptr)
 837{
 838        const struct nft_chain *chain = ptr;
 839        const char *name = arg->key;
 840
 841        return strcmp(chain->name, name);
 842}
 843
 844static u32 nft_objname_hash(const void *data, u32 len, u32 seed)
 845{
 846        const struct nft_object_hash_key *k = data;
 847
 848        seed ^= hash_ptr(k->table, 32);
 849
 850        return jhash(k->name, strlen(k->name), seed);
 851}
 852
 853static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed)
 854{
 855        const struct nft_object *obj = data;
 856
 857        return nft_objname_hash(&obj->key, 0, seed);
 858}
 859
 860static int nft_objname_hash_cmp(struct rhashtable_compare_arg *arg,
 861                                const void *ptr)
 862{
 863        const struct nft_object_hash_key *k = arg->key;
 864        const struct nft_object *obj = ptr;
 865
 866        if (obj->key.table != k->table)
 867                return -1;
 868
 869        return strcmp(obj->key.name, k->name);
 870}
 871
 872static int nf_tables_newtable(struct net *net, struct sock *nlsk,
 873                              struct sk_buff *skb, const struct nlmsghdr *nlh,
 874                              const struct nlattr * const nla[],
 875                              struct netlink_ext_ack *extack)
 876{
 877        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
 878        u8 genmask = nft_genmask_next(net);
 879        int family = nfmsg->nfgen_family;
 880        const struct nlattr *attr;
 881        struct nft_table *table;
 882        u32 flags = 0;
 883        struct nft_ctx ctx;
 884        int err;
 885
 886        lockdep_assert_held(&net->nft.commit_mutex);
 887        attr = nla[NFTA_TABLE_NAME];
 888        table = nft_table_lookup(net, attr, family, genmask);
 889        if (IS_ERR(table)) {
 890                if (PTR_ERR(table) != -ENOENT)
 891                        return PTR_ERR(table);
 892        } else {
 893                if (nlh->nlmsg_flags & NLM_F_EXCL) {
 894                        NL_SET_BAD_ATTR(extack, attr);
 895                        return -EEXIST;
 896                }
 897                if (nlh->nlmsg_flags & NLM_F_REPLACE)
 898                        return -EOPNOTSUPP;
 899
 900                nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
 901                return nf_tables_updtable(&ctx);
 902        }
 903
 904        if (nla[NFTA_TABLE_FLAGS]) {
 905                flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
 906                if (flags & ~NFT_TABLE_F_DORMANT)
 907                        return -EINVAL;
 908        }
 909
 910        err = -ENOMEM;
 911        table = kzalloc(sizeof(*table), GFP_KERNEL);
 912        if (table == NULL)
 913                goto err_kzalloc;
 914
 915        table->name = nla_strdup(attr, GFP_KERNEL);
 916        if (table->name == NULL)
 917                goto err_strdup;
 918
 919        err = rhltable_init(&table->chains_ht, &nft_chain_ht_params);
 920        if (err)
 921                goto err_chain_ht;
 922
 923        INIT_LIST_HEAD(&table->chains);
 924        INIT_LIST_HEAD(&table->sets);
 925        INIT_LIST_HEAD(&table->objects);
 926        INIT_LIST_HEAD(&table->flowtables);
 927        table->family = family;
 928        table->flags = flags;
 929        table->handle = ++table_handle;
 930
 931        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
 932        err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
 933        if (err < 0)
 934                goto err_trans;
 935
 936        list_add_tail_rcu(&table->list, &net->nft.tables);
 937        return 0;
 938err_trans:
 939        rhltable_destroy(&table->chains_ht);
 940err_chain_ht:
 941        kfree(table->name);
 942err_strdup:
 943        kfree(table);
 944err_kzalloc:
 945        return err;
 946}
 947
 948static int nft_flush_table(struct nft_ctx *ctx)
 949{
 950        struct nft_flowtable *flowtable, *nft;
 951        struct nft_chain *chain, *nc;
 952        struct nft_object *obj, *ne;
 953        struct nft_set *set, *ns;
 954        int err;
 955
 956        list_for_each_entry(chain, &ctx->table->chains, list) {
 957                if (!nft_is_active_next(ctx->net, chain))
 958                        continue;
 959
 960                ctx->chain = chain;
 961
 962                err = nft_delrule_by_chain(ctx);
 963                if (err < 0)
 964                        goto out;
 965        }
 966
 967        list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
 968                if (!nft_is_active_next(ctx->net, set))
 969                        continue;
 970
 971                if (nft_set_is_anonymous(set) &&
 972                    !list_empty(&set->bindings))
 973                        continue;
 974
 975                err = nft_delset(ctx, set);
 976                if (err < 0)
 977                        goto out;
 978        }
 979
 980        list_for_each_entry_safe(flowtable, nft, &ctx->table->flowtables, list) {
 981                err = nft_delflowtable(ctx, flowtable);
 982                if (err < 0)
 983                        goto out;
 984        }
 985
 986        list_for_each_entry_safe(obj, ne, &ctx->table->objects, list) {
 987                err = nft_delobj(ctx, obj);
 988                if (err < 0)
 989                        goto out;
 990        }
 991
 992        list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
 993                if (!nft_is_active_next(ctx->net, chain))
 994                        continue;
 995
 996                ctx->chain = chain;
 997
 998                err = nft_delchain(ctx);
 999                if (err < 0)
1000                        goto out;
1001        }
1002
1003        err = nft_deltable(ctx);
1004out:
1005        return err;
1006}
1007
1008static int nft_flush(struct nft_ctx *ctx, int family)
1009{
1010        struct nft_table *table, *nt;
1011        const struct nlattr * const *nla = ctx->nla;
1012        int err = 0;
1013
1014        list_for_each_entry_safe(table, nt, &ctx->net->nft.tables, list) {
1015                if (family != AF_UNSPEC && table->family != family)
1016                        continue;
1017
1018                ctx->family = table->family;
1019
1020                if (!nft_is_active_next(ctx->net, table))
1021                        continue;
1022
1023                if (nla[NFTA_TABLE_NAME] &&
1024                    nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
1025                        continue;
1026
1027                ctx->table = table;
1028
1029                err = nft_flush_table(ctx);
1030                if (err < 0)
1031                        goto out;
1032        }
1033out:
1034        return err;
1035}
1036
1037static int nf_tables_deltable(struct net *net, struct sock *nlsk,
1038                              struct sk_buff *skb, const struct nlmsghdr *nlh,
1039                              const struct nlattr * const nla[],
1040                              struct netlink_ext_ack *extack)
1041{
1042        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1043        u8 genmask = nft_genmask_next(net);
1044        int family = nfmsg->nfgen_family;
1045        const struct nlattr *attr;
1046        struct nft_table *table;
1047        struct nft_ctx ctx;
1048
1049        nft_ctx_init(&ctx, net, skb, nlh, 0, NULL, NULL, nla);
1050        if (family == AF_UNSPEC ||
1051            (!nla[NFTA_TABLE_NAME] && !nla[NFTA_TABLE_HANDLE]))
1052                return nft_flush(&ctx, family);
1053
1054        if (nla[NFTA_TABLE_HANDLE]) {
1055                attr = nla[NFTA_TABLE_HANDLE];
1056                table = nft_table_lookup_byhandle(net, attr, genmask);
1057        } else {
1058                attr = nla[NFTA_TABLE_NAME];
1059                table = nft_table_lookup(net, attr, family, genmask);
1060        }
1061
1062        if (IS_ERR(table)) {
1063                NL_SET_BAD_ATTR(extack, attr);
1064                return PTR_ERR(table);
1065        }
1066
1067        if (nlh->nlmsg_flags & NLM_F_NONREC &&
1068            table->use > 0)
1069                return -EBUSY;
1070
1071        ctx.family = family;
1072        ctx.table = table;
1073
1074        return nft_flush_table(&ctx);
1075}
1076
1077static void nf_tables_table_destroy(struct nft_ctx *ctx)
1078{
1079        if (WARN_ON(ctx->table->use > 0))
1080                return;
1081
1082        rhltable_destroy(&ctx->table->chains_ht);
1083        kfree(ctx->table->name);
1084        kfree(ctx->table);
1085}
1086
1087void nft_register_chain_type(const struct nft_chain_type *ctype)
1088{
1089        if (WARN_ON(ctype->family >= NFPROTO_NUMPROTO))
1090                return;
1091
1092        nfnl_lock(NFNL_SUBSYS_NFTABLES);
1093        if (WARN_ON(chain_type[ctype->family][ctype->type] != NULL)) {
1094                nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1095                return;
1096        }
1097        chain_type[ctype->family][ctype->type] = ctype;
1098        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1099}
1100EXPORT_SYMBOL_GPL(nft_register_chain_type);
1101
1102void nft_unregister_chain_type(const struct nft_chain_type *ctype)
1103{
1104        nfnl_lock(NFNL_SUBSYS_NFTABLES);
1105        chain_type[ctype->family][ctype->type] = NULL;
1106        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1107}
1108EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
1109
1110/*
1111 * Chains
1112 */
1113
1114static struct nft_chain *
1115nft_chain_lookup_byhandle(const struct nft_table *table, u64 handle, u8 genmask)
1116{
1117        struct nft_chain *chain;
1118
1119        list_for_each_entry(chain, &table->chains, list) {
1120                if (chain->handle == handle &&
1121                    nft_active_genmask(chain, genmask))
1122                        return chain;
1123        }
1124
1125        return ERR_PTR(-ENOENT);
1126}
1127
1128static bool lockdep_commit_lock_is_held(const struct net *net)
1129{
1130#ifdef CONFIG_PROVE_LOCKING
1131        return lockdep_is_held(&net->nft.commit_mutex);
1132#else
1133        return true;
1134#endif
1135}
1136
1137static struct nft_chain *nft_chain_lookup(struct net *net,
1138                                          struct nft_table *table,
1139                                          const struct nlattr *nla, u8 genmask)
1140{
1141        char search[NFT_CHAIN_MAXNAMELEN + 1];
1142        struct rhlist_head *tmp, *list;
1143        struct nft_chain *chain;
1144
1145        if (nla == NULL)
1146                return ERR_PTR(-EINVAL);
1147
1148        nla_strlcpy(search, nla, sizeof(search));
1149
1150        WARN_ON(!rcu_read_lock_held() &&
1151                !lockdep_commit_lock_is_held(net));
1152
1153        chain = ERR_PTR(-ENOENT);
1154        rcu_read_lock();
1155        list = rhltable_lookup(&table->chains_ht, search, nft_chain_ht_params);
1156        if (!list)
1157                goto out_unlock;
1158
1159        rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
1160                if (nft_active_genmask(chain, genmask))
1161                        goto out_unlock;
1162        }
1163        chain = ERR_PTR(-ENOENT);
1164out_unlock:
1165        rcu_read_unlock();
1166        return chain;
1167}
1168
1169static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
1170        [NFTA_CHAIN_TABLE]      = { .type = NLA_STRING,
1171                                    .len = NFT_TABLE_MAXNAMELEN - 1 },
1172        [NFTA_CHAIN_HANDLE]     = { .type = NLA_U64 },
1173        [NFTA_CHAIN_NAME]       = { .type = NLA_STRING,
1174                                    .len = NFT_CHAIN_MAXNAMELEN - 1 },
1175        [NFTA_CHAIN_HOOK]       = { .type = NLA_NESTED },
1176        [NFTA_CHAIN_POLICY]     = { .type = NLA_U32 },
1177        [NFTA_CHAIN_TYPE]       = { .type = NLA_STRING },
1178        [NFTA_CHAIN_COUNTERS]   = { .type = NLA_NESTED },
1179        [NFTA_CHAIN_FLAGS]      = { .type = NLA_U32 },
1180};
1181
1182static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
1183        [NFTA_HOOK_HOOKNUM]     = { .type = NLA_U32 },
1184        [NFTA_HOOK_PRIORITY]    = { .type = NLA_U32 },
1185        [NFTA_HOOK_DEV]         = { .type = NLA_STRING,
1186                                    .len = IFNAMSIZ - 1 },
1187};
1188
1189static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
1190{
1191        struct nft_stats *cpu_stats, total;
1192        struct nlattr *nest;
1193        unsigned int seq;
1194        u64 pkts, bytes;
1195        int cpu;
1196
1197        if (!stats)
1198                return 0;
1199
1200        memset(&total, 0, sizeof(total));
1201        for_each_possible_cpu(cpu) {
1202                cpu_stats = per_cpu_ptr(stats, cpu);
1203                do {
1204                        seq = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1205                        pkts = cpu_stats->pkts;
1206                        bytes = cpu_stats->bytes;
1207                } while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, seq));
1208                total.pkts += pkts;
1209                total.bytes += bytes;
1210        }
1211        nest = nla_nest_start_noflag(skb, NFTA_CHAIN_COUNTERS);
1212        if (nest == NULL)
1213                goto nla_put_failure;
1214
1215        if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts),
1216                         NFTA_COUNTER_PAD) ||
1217            nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes),
1218                         NFTA_COUNTER_PAD))
1219                goto nla_put_failure;
1220
1221        nla_nest_end(skb, nest);
1222        return 0;
1223
1224nla_put_failure:
1225        return -ENOSPC;
1226}
1227
1228static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
1229                                     u32 portid, u32 seq, int event, u32 flags,
1230                                     int family, const struct nft_table *table,
1231                                     const struct nft_chain *chain)
1232{
1233        struct nlmsghdr *nlh;
1234        struct nfgenmsg *nfmsg;
1235
1236        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
1237        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
1238        if (nlh == NULL)
1239                goto nla_put_failure;
1240
1241        nfmsg = nlmsg_data(nlh);
1242        nfmsg->nfgen_family     = family;
1243        nfmsg->version          = NFNETLINK_V0;
1244        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
1245
1246        if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name))
1247                goto nla_put_failure;
1248        if (nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle),
1249                         NFTA_CHAIN_PAD))
1250                goto nla_put_failure;
1251        if (nla_put_string(skb, NFTA_CHAIN_NAME, chain->name))
1252                goto nla_put_failure;
1253
1254        if (nft_is_base_chain(chain)) {
1255                const struct nft_base_chain *basechain = nft_base_chain(chain);
1256                const struct nf_hook_ops *ops = &basechain->ops;
1257                struct nft_stats __percpu *stats;
1258                struct nlattr *nest;
1259
1260                nest = nla_nest_start_noflag(skb, NFTA_CHAIN_HOOK);
1261                if (nest == NULL)
1262                        goto nla_put_failure;
1263                if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
1264                        goto nla_put_failure;
1265                if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
1266                        goto nla_put_failure;
1267                if (basechain->dev_name[0] &&
1268                    nla_put_string(skb, NFTA_HOOK_DEV, basechain->dev_name))
1269                        goto nla_put_failure;
1270                nla_nest_end(skb, nest);
1271
1272                if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
1273                                 htonl(basechain->policy)))
1274                        goto nla_put_failure;
1275
1276                if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
1277                        goto nla_put_failure;
1278
1279                stats = rcu_dereference_check(basechain->stats,
1280                                              lockdep_commit_lock_is_held(net));
1281                if (nft_dump_stats(skb, stats))
1282                        goto nla_put_failure;
1283        }
1284
1285        if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
1286                goto nla_put_failure;
1287
1288        nlmsg_end(skb, nlh);
1289        return 0;
1290
1291nla_put_failure:
1292        nlmsg_trim(skb, nlh);
1293        return -1;
1294}
1295
1296static void nf_tables_chain_notify(const struct nft_ctx *ctx, int event)
1297{
1298        struct sk_buff *skb;
1299        int err;
1300
1301        if (!ctx->report &&
1302            !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1303                return;
1304
1305        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1306        if (skb == NULL)
1307                goto err;
1308
1309        err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
1310                                        event, 0, ctx->family, ctx->table,
1311                                        ctx->chain);
1312        if (err < 0) {
1313                kfree_skb(skb);
1314                goto err;
1315        }
1316
1317        nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1318                       ctx->report, GFP_KERNEL);
1319        return;
1320err:
1321        nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1322}
1323
1324static int nf_tables_dump_chains(struct sk_buff *skb,
1325                                 struct netlink_callback *cb)
1326{
1327        const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1328        const struct nft_table *table;
1329        const struct nft_chain *chain;
1330        unsigned int idx = 0, s_idx = cb->args[0];
1331        struct net *net = sock_net(skb->sk);
1332        int family = nfmsg->nfgen_family;
1333
1334        rcu_read_lock();
1335        cb->seq = net->nft.base_seq;
1336
1337        list_for_each_entry_rcu(table, &net->nft.tables, list) {
1338                if (family != NFPROTO_UNSPEC && family != table->family)
1339                        continue;
1340
1341                list_for_each_entry_rcu(chain, &table->chains, list) {
1342                        if (idx < s_idx)
1343                                goto cont;
1344                        if (idx > s_idx)
1345                                memset(&cb->args[1], 0,
1346                                       sizeof(cb->args) - sizeof(cb->args[0]));
1347                        if (!nft_is_active(net, chain))
1348                                continue;
1349                        if (nf_tables_fill_chain_info(skb, net,
1350                                                      NETLINK_CB(cb->skb).portid,
1351                                                      cb->nlh->nlmsg_seq,
1352                                                      NFT_MSG_NEWCHAIN,
1353                                                      NLM_F_MULTI,
1354                                                      table->family, table,
1355                                                      chain) < 0)
1356                                goto done;
1357
1358                        nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1359cont:
1360                        idx++;
1361                }
1362        }
1363done:
1364        rcu_read_unlock();
1365        cb->args[0] = idx;
1366        return skb->len;
1367}
1368
1369/* called with rcu_read_lock held */
1370static int nf_tables_getchain(struct net *net, struct sock *nlsk,
1371                              struct sk_buff *skb, const struct nlmsghdr *nlh,
1372                              const struct nlattr * const nla[],
1373                              struct netlink_ext_ack *extack)
1374{
1375        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1376        u8 genmask = nft_genmask_cur(net);
1377        const struct nft_chain *chain;
1378        struct nft_table *table;
1379        struct sk_buff *skb2;
1380        int family = nfmsg->nfgen_family;
1381        int err;
1382
1383        if (nlh->nlmsg_flags & NLM_F_DUMP) {
1384                struct netlink_dump_control c = {
1385                        .dump = nf_tables_dump_chains,
1386                        .module = THIS_MODULE,
1387                };
1388
1389                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
1390        }
1391
1392        table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1393        if (IS_ERR(table)) {
1394                NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1395                return PTR_ERR(table);
1396        }
1397
1398        chain = nft_chain_lookup(net, table, nla[NFTA_CHAIN_NAME], genmask);
1399        if (IS_ERR(chain)) {
1400                NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
1401                return PTR_ERR(chain);
1402        }
1403
1404        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1405        if (!skb2)
1406                return -ENOMEM;
1407
1408        err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1409                                        nlh->nlmsg_seq, NFT_MSG_NEWCHAIN, 0,
1410                                        family, table, chain);
1411        if (err < 0)
1412                goto err;
1413
1414        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1415
1416err:
1417        kfree_skb(skb2);
1418        return err;
1419}
1420
1421static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
1422        [NFTA_COUNTER_PACKETS]  = { .type = NLA_U64 },
1423        [NFTA_COUNTER_BYTES]    = { .type = NLA_U64 },
1424};
1425
1426static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
1427{
1428        struct nlattr *tb[NFTA_COUNTER_MAX+1];
1429        struct nft_stats __percpu *newstats;
1430        struct nft_stats *stats;
1431        int err;
1432
1433        err = nla_parse_nested_deprecated(tb, NFTA_COUNTER_MAX, attr,
1434                                          nft_counter_policy, NULL);
1435        if (err < 0)
1436                return ERR_PTR(err);
1437
1438        if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
1439                return ERR_PTR(-EINVAL);
1440
1441        newstats = netdev_alloc_pcpu_stats(struct nft_stats);
1442        if (newstats == NULL)
1443                return ERR_PTR(-ENOMEM);
1444
1445        /* Restore old counters on this cpu, no problem. Per-cpu statistics
1446         * are not exposed to userspace.
1447         */
1448        preempt_disable();
1449        stats = this_cpu_ptr(newstats);
1450        stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
1451        stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
1452        preempt_enable();
1453
1454        return newstats;
1455}
1456
1457static void nft_chain_stats_replace(struct nft_trans *trans)
1458{
1459        struct nft_base_chain *chain = nft_base_chain(trans->ctx.chain);
1460
1461        if (!nft_trans_chain_stats(trans))
1462                return;
1463
1464        rcu_swap_protected(chain->stats, nft_trans_chain_stats(trans),
1465                           lockdep_commit_lock_is_held(trans->ctx.net));
1466
1467        if (!nft_trans_chain_stats(trans))
1468                static_branch_inc(&nft_counters_enabled);
1469}
1470
1471static void nf_tables_chain_free_chain_rules(struct nft_chain *chain)
1472{
1473        struct nft_rule **g0 = rcu_dereference_raw(chain->rules_gen_0);
1474        struct nft_rule **g1 = rcu_dereference_raw(chain->rules_gen_1);
1475
1476        if (g0 != g1)
1477                kvfree(g1);
1478        kvfree(g0);
1479
1480        /* should be NULL either via abort or via successful commit */
1481        WARN_ON_ONCE(chain->rules_next);
1482        kvfree(chain->rules_next);
1483}
1484
1485static void nf_tables_chain_destroy(struct nft_ctx *ctx)
1486{
1487        struct nft_chain *chain = ctx->chain;
1488
1489        if (WARN_ON(chain->use > 0))
1490                return;
1491
1492        /* no concurrent access possible anymore */
1493        nf_tables_chain_free_chain_rules(chain);
1494
1495        if (nft_is_base_chain(chain)) {
1496                struct nft_base_chain *basechain = nft_base_chain(chain);
1497
1498                module_put(basechain->type->owner);
1499                if (rcu_access_pointer(basechain->stats)) {
1500                        static_branch_dec(&nft_counters_enabled);
1501                        free_percpu(rcu_dereference_raw(basechain->stats));
1502                }
1503                kfree(chain->name);
1504                kfree(basechain);
1505        } else {
1506                kfree(chain->name);
1507                kfree(chain);
1508        }
1509}
1510
1511struct nft_chain_hook {
1512        u32                             num;
1513        s32                             priority;
1514        const struct nft_chain_type     *type;
1515        struct net_device               *dev;
1516};
1517
1518static int nft_chain_parse_hook(struct net *net,
1519                                const struct nlattr * const nla[],
1520                                struct nft_chain_hook *hook, u8 family,
1521                                bool autoload)
1522{
1523        struct nlattr *ha[NFTA_HOOK_MAX + 1];
1524        const struct nft_chain_type *type;
1525        struct net_device *dev;
1526        int err;
1527
1528        lockdep_assert_held(&net->nft.commit_mutex);
1529        lockdep_nfnl_nft_mutex_not_held();
1530
1531        err = nla_parse_nested_deprecated(ha, NFTA_HOOK_MAX,
1532                                          nla[NFTA_CHAIN_HOOK],
1533                                          nft_hook_policy, NULL);
1534        if (err < 0)
1535                return err;
1536
1537        if (ha[NFTA_HOOK_HOOKNUM] == NULL ||
1538            ha[NFTA_HOOK_PRIORITY] == NULL)
1539                return -EINVAL;
1540
1541        hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
1542        hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
1543
1544        type = chain_type[family][NFT_CHAIN_T_DEFAULT];
1545        if (nla[NFTA_CHAIN_TYPE]) {
1546                type = nf_tables_chain_type_lookup(net, nla[NFTA_CHAIN_TYPE],
1547                                                   family, autoload);
1548                if (IS_ERR(type))
1549                        return PTR_ERR(type);
1550        }
1551        if (hook->num > NF_MAX_HOOKS || !(type->hook_mask & (1 << hook->num)))
1552                return -EOPNOTSUPP;
1553
1554        if (type->type == NFT_CHAIN_T_NAT &&
1555            hook->priority <= NF_IP_PRI_CONNTRACK)
1556                return -EOPNOTSUPP;
1557
1558        if (!try_module_get(type->owner))
1559                return -ENOENT;
1560
1561        hook->type = type;
1562
1563        hook->dev = NULL;
1564        if (family == NFPROTO_NETDEV) {
1565                char ifname[IFNAMSIZ];
1566
1567                if (!ha[NFTA_HOOK_DEV]) {
1568                        module_put(type->owner);
1569                        return -EOPNOTSUPP;
1570                }
1571
1572                nla_strlcpy(ifname, ha[NFTA_HOOK_DEV], IFNAMSIZ);
1573                dev = __dev_get_by_name(net, ifname);
1574                if (!dev) {
1575                        module_put(type->owner);
1576                        return -ENOENT;
1577                }
1578                hook->dev = dev;
1579        } else if (ha[NFTA_HOOK_DEV]) {
1580                module_put(type->owner);
1581                return -EOPNOTSUPP;
1582        }
1583
1584        return 0;
1585}
1586
1587static void nft_chain_release_hook(struct nft_chain_hook *hook)
1588{
1589        module_put(hook->type->owner);
1590}
1591
1592struct nft_rules_old {
1593        struct rcu_head h;
1594        struct nft_rule **start;
1595};
1596
1597static struct nft_rule **nf_tables_chain_alloc_rules(const struct nft_chain *chain,
1598                                                     unsigned int alloc)
1599{
1600        if (alloc > INT_MAX)
1601                return NULL;
1602
1603        alloc += 1;     /* NULL, ends rules */
1604        if (sizeof(struct nft_rule *) > INT_MAX / alloc)
1605                return NULL;
1606
1607        alloc *= sizeof(struct nft_rule *);
1608        alloc += sizeof(struct nft_rules_old);
1609
1610        return kvmalloc(alloc, GFP_KERNEL);
1611}
1612
1613static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask,
1614                              u8 policy, u32 flags)
1615{
1616        const struct nlattr * const *nla = ctx->nla;
1617        struct nft_table *table = ctx->table;
1618        struct nft_base_chain *basechain;
1619        struct nft_stats __percpu *stats;
1620        struct net *net = ctx->net;
1621        struct nft_trans *trans;
1622        struct nft_chain *chain;
1623        struct nft_rule **rules;
1624        int err;
1625
1626        if (table->use == UINT_MAX)
1627                return -EOVERFLOW;
1628
1629        if (nla[NFTA_CHAIN_HOOK]) {
1630                struct nft_chain_hook hook;
1631                struct nf_hook_ops *ops;
1632
1633                err = nft_chain_parse_hook(net, nla, &hook, family, true);
1634                if (err < 0)
1635                        return err;
1636
1637                basechain = kzalloc(sizeof(*basechain), GFP_KERNEL);
1638                if (basechain == NULL) {
1639                        nft_chain_release_hook(&hook);
1640                        return -ENOMEM;
1641                }
1642
1643                if (hook.dev != NULL)
1644                        strncpy(basechain->dev_name, hook.dev->name, IFNAMSIZ);
1645
1646                if (nla[NFTA_CHAIN_COUNTERS]) {
1647                        stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1648                        if (IS_ERR(stats)) {
1649                                nft_chain_release_hook(&hook);
1650                                kfree(basechain);
1651                                return PTR_ERR(stats);
1652                        }
1653                        rcu_assign_pointer(basechain->stats, stats);
1654                        static_branch_inc(&nft_counters_enabled);
1655                }
1656
1657                basechain->type = hook.type;
1658                chain = &basechain->chain;
1659
1660                ops             = &basechain->ops;
1661                ops->pf         = family;
1662                ops->hooknum    = hook.num;
1663                ops->priority   = hook.priority;
1664                ops->priv       = chain;
1665                ops->hook       = hook.type->hooks[ops->hooknum];
1666                ops->dev        = hook.dev;
1667
1668                chain->flags |= NFT_BASE_CHAIN | flags;
1669                basechain->policy = NF_ACCEPT;
1670                if (chain->flags & NFT_CHAIN_HW_OFFLOAD &&
1671                    nft_chain_offload_priority(basechain) < 0)
1672                        return -EOPNOTSUPP;
1673
1674                flow_block_init(&basechain->flow_block);
1675        } else {
1676                chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1677                if (chain == NULL)
1678                        return -ENOMEM;
1679        }
1680        ctx->chain = chain;
1681
1682        INIT_LIST_HEAD(&chain->rules);
1683        chain->handle = nf_tables_alloc_handle(table);
1684        chain->table = table;
1685        chain->name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1686        if (!chain->name) {
1687                err = -ENOMEM;
1688                goto err1;
1689        }
1690
1691        rules = nf_tables_chain_alloc_rules(chain, 0);
1692        if (!rules) {
1693                err = -ENOMEM;
1694                goto err1;
1695        }
1696
1697        *rules = NULL;
1698        rcu_assign_pointer(chain->rules_gen_0, rules);
1699        rcu_assign_pointer(chain->rules_gen_1, rules);
1700
1701        err = nf_tables_register_hook(net, table, chain);
1702        if (err < 0)
1703                goto err1;
1704
1705        err = rhltable_insert_key(&table->chains_ht, chain->name,
1706                                  &chain->rhlhead, nft_chain_ht_params);
1707        if (err)
1708                goto err2;
1709
1710        trans = nft_trans_chain_add(ctx, NFT_MSG_NEWCHAIN);
1711        if (IS_ERR(trans)) {
1712                err = PTR_ERR(trans);
1713                rhltable_remove(&table->chains_ht, &chain->rhlhead,
1714                                nft_chain_ht_params);
1715                goto err2;
1716        }
1717
1718        nft_trans_chain_policy(trans) = -1;
1719        if (nft_is_base_chain(chain))
1720                nft_trans_chain_policy(trans) = policy;
1721
1722        table->use++;
1723        list_add_tail_rcu(&chain->list, &table->chains);
1724
1725        return 0;
1726err2:
1727        nf_tables_unregister_hook(net, table, chain);
1728err1:
1729        nf_tables_chain_destroy(ctx);
1730
1731        return err;
1732}
1733
1734static int nf_tables_updchain(struct nft_ctx *ctx, u8 genmask, u8 policy,
1735                              u32 flags)
1736{
1737        const struct nlattr * const *nla = ctx->nla;
1738        struct nft_table *table = ctx->table;
1739        struct nft_chain *chain = ctx->chain;
1740        struct nft_base_chain *basechain;
1741        struct nft_stats *stats = NULL;
1742        struct nft_chain_hook hook;
1743        struct nf_hook_ops *ops;
1744        struct nft_trans *trans;
1745        int err;
1746
1747        if (chain->flags ^ flags)
1748                return -EOPNOTSUPP;
1749
1750        if (nla[NFTA_CHAIN_HOOK]) {
1751                if (!nft_is_base_chain(chain))
1752                        return -EBUSY;
1753
1754                err = nft_chain_parse_hook(ctx->net, nla, &hook, ctx->family,
1755                                           false);
1756                if (err < 0)
1757                        return err;
1758
1759                basechain = nft_base_chain(chain);
1760                if (basechain->type != hook.type) {
1761                        nft_chain_release_hook(&hook);
1762                        return -EBUSY;
1763                }
1764
1765                ops = &basechain->ops;
1766                if (ops->hooknum != hook.num ||
1767                    ops->priority != hook.priority ||
1768                    ops->dev != hook.dev) {
1769                        nft_chain_release_hook(&hook);
1770                        return -EBUSY;
1771                }
1772                nft_chain_release_hook(&hook);
1773        }
1774
1775        if (nla[NFTA_CHAIN_HANDLE] &&
1776            nla[NFTA_CHAIN_NAME]) {
1777                struct nft_chain *chain2;
1778
1779                chain2 = nft_chain_lookup(ctx->net, table,
1780                                          nla[NFTA_CHAIN_NAME], genmask);
1781                if (!IS_ERR(chain2))
1782                        return -EEXIST;
1783        }
1784
1785        if (nla[NFTA_CHAIN_COUNTERS]) {
1786                if (!nft_is_base_chain(chain))
1787                        return -EOPNOTSUPP;
1788
1789                stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1790                if (IS_ERR(stats))
1791                        return PTR_ERR(stats);
1792        }
1793
1794        err = -ENOMEM;
1795        trans = nft_trans_alloc(ctx, NFT_MSG_NEWCHAIN,
1796                                sizeof(struct nft_trans_chain));
1797        if (trans == NULL)
1798                goto err;
1799
1800        nft_trans_chain_stats(trans) = stats;
1801        nft_trans_chain_update(trans) = true;
1802
1803        if (nla[NFTA_CHAIN_POLICY])
1804                nft_trans_chain_policy(trans) = policy;
1805        else
1806                nft_trans_chain_policy(trans) = -1;
1807
1808        if (nla[NFTA_CHAIN_HANDLE] &&
1809            nla[NFTA_CHAIN_NAME]) {
1810                struct nft_trans *tmp;
1811                char *name;
1812
1813                err = -ENOMEM;
1814                name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1815                if (!name)
1816                        goto err;
1817
1818                err = -EEXIST;
1819                list_for_each_entry(tmp, &ctx->net->nft.commit_list, list) {
1820                        if (tmp->msg_type == NFT_MSG_NEWCHAIN &&
1821                            tmp->ctx.table == table &&
1822                            nft_trans_chain_update(tmp) &&
1823                            nft_trans_chain_name(tmp) &&
1824                            strcmp(name, nft_trans_chain_name(tmp)) == 0) {
1825                                kfree(name);
1826                                goto err;
1827                        }
1828                }
1829
1830                nft_trans_chain_name(trans) = name;
1831        }
1832        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
1833
1834        return 0;
1835err:
1836        free_percpu(stats);
1837        kfree(trans);
1838        return err;
1839}
1840
1841static int nf_tables_newchain(struct net *net, struct sock *nlsk,
1842                              struct sk_buff *skb, const struct nlmsghdr *nlh,
1843                              const struct nlattr * const nla[],
1844                              struct netlink_ext_ack *extack)
1845{
1846        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1847        u8 genmask = nft_genmask_next(net);
1848        int family = nfmsg->nfgen_family;
1849        const struct nlattr *attr;
1850        struct nft_table *table;
1851        struct nft_chain *chain;
1852        u8 policy = NF_ACCEPT;
1853        struct nft_ctx ctx;
1854        u64 handle = 0;
1855        u32 flags = 0;
1856
1857        lockdep_assert_held(&net->nft.commit_mutex);
1858
1859        table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1860        if (IS_ERR(table)) {
1861                NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1862                return PTR_ERR(table);
1863        }
1864
1865        chain = NULL;
1866        attr = nla[NFTA_CHAIN_NAME];
1867
1868        if (nla[NFTA_CHAIN_HANDLE]) {
1869                handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
1870                chain = nft_chain_lookup_byhandle(table, handle, genmask);
1871                if (IS_ERR(chain)) {
1872                        NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_HANDLE]);
1873                        return PTR_ERR(chain);
1874                }
1875                attr = nla[NFTA_CHAIN_HANDLE];
1876        } else {
1877                chain = nft_chain_lookup(net, table, attr, genmask);
1878                if (IS_ERR(chain)) {
1879                        if (PTR_ERR(chain) != -ENOENT) {
1880                                NL_SET_BAD_ATTR(extack, attr);
1881                                return PTR_ERR(chain);
1882                        }
1883                        chain = NULL;
1884                }
1885        }
1886
1887        if (nla[NFTA_CHAIN_POLICY]) {
1888                if (chain != NULL &&
1889                    !nft_is_base_chain(chain)) {
1890                        NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1891                        return -EOPNOTSUPP;
1892                }
1893
1894                if (chain == NULL &&
1895                    nla[NFTA_CHAIN_HOOK] == NULL) {
1896                        NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1897                        return -EOPNOTSUPP;
1898                }
1899
1900                policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
1901                switch (policy) {
1902                case NF_DROP:
1903                case NF_ACCEPT:
1904                        break;
1905                default:
1906                        return -EINVAL;
1907                }
1908        }
1909
1910        if (nla[NFTA_CHAIN_FLAGS])
1911                flags = ntohl(nla_get_be32(nla[NFTA_CHAIN_FLAGS]));
1912        else if (chain)
1913                flags = chain->flags;
1914
1915        nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1916
1917        if (chain != NULL) {
1918                if (nlh->nlmsg_flags & NLM_F_EXCL) {
1919                        NL_SET_BAD_ATTR(extack, attr);
1920                        return -EEXIST;
1921                }
1922                if (nlh->nlmsg_flags & NLM_F_REPLACE)
1923                        return -EOPNOTSUPP;
1924
1925                return nf_tables_updchain(&ctx, genmask, policy, flags);
1926        }
1927
1928        return nf_tables_addchain(&ctx, family, genmask, policy, flags);
1929}
1930
1931static int nf_tables_delchain(struct net *net, struct sock *nlsk,
1932                              struct sk_buff *skb, const struct nlmsghdr *nlh,
1933                              const struct nlattr * const nla[],
1934                              struct netlink_ext_ack *extack)
1935{
1936        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1937        u8 genmask = nft_genmask_next(net);
1938        int family = nfmsg->nfgen_family;
1939        const struct nlattr *attr;
1940        struct nft_table *table;
1941        struct nft_chain *chain;
1942        struct nft_rule *rule;
1943        struct nft_ctx ctx;
1944        u64 handle;
1945        u32 use;
1946        int err;
1947
1948        table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1949        if (IS_ERR(table)) {
1950                NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1951                return PTR_ERR(table);
1952        }
1953
1954        if (nla[NFTA_CHAIN_HANDLE]) {
1955                attr = nla[NFTA_CHAIN_HANDLE];
1956                handle = be64_to_cpu(nla_get_be64(attr));
1957                chain = nft_chain_lookup_byhandle(table, handle, genmask);
1958        } else {
1959                attr = nla[NFTA_CHAIN_NAME];
1960                chain = nft_chain_lookup(net, table, attr, genmask);
1961        }
1962        if (IS_ERR(chain)) {
1963                NL_SET_BAD_ATTR(extack, attr);
1964                return PTR_ERR(chain);
1965        }
1966
1967        if (nlh->nlmsg_flags & NLM_F_NONREC &&
1968            chain->use > 0)
1969                return -EBUSY;
1970
1971        nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1972
1973        use = chain->use;
1974        list_for_each_entry(rule, &chain->rules, list) {
1975                if (!nft_is_active_next(net, rule))
1976                        continue;
1977                use--;
1978
1979                err = nft_delrule(&ctx, rule);
1980                if (err < 0)
1981                        return err;
1982        }
1983
1984        /* There are rules and elements that are still holding references to us,
1985         * we cannot do a recursive removal in this case.
1986         */
1987        if (use > 0) {
1988                NL_SET_BAD_ATTR(extack, attr);
1989                return -EBUSY;
1990        }
1991
1992        return nft_delchain(&ctx);
1993}
1994
1995/*
1996 * Expressions
1997 */
1998
1999/**
2000 *      nft_register_expr - register nf_tables expr type
2001 *      @ops: expr type
2002 *
2003 *      Registers the expr type for use with nf_tables. Returns zero on
2004 *      success or a negative errno code otherwise.
2005 */
2006int nft_register_expr(struct nft_expr_type *type)
2007{
2008        nfnl_lock(NFNL_SUBSYS_NFTABLES);
2009        if (type->family == NFPROTO_UNSPEC)
2010                list_add_tail_rcu(&type->list, &nf_tables_expressions);
2011        else
2012                list_add_rcu(&type->list, &nf_tables_expressions);
2013        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2014        return 0;
2015}
2016EXPORT_SYMBOL_GPL(nft_register_expr);
2017
2018/**
2019 *      nft_unregister_expr - unregister nf_tables expr type
2020 *      @ops: expr type
2021 *
2022 *      Unregisters the expr typefor use with nf_tables.
2023 */
2024void nft_unregister_expr(struct nft_expr_type *type)
2025{
2026        nfnl_lock(NFNL_SUBSYS_NFTABLES);
2027        list_del_rcu(&type->list);
2028        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2029}
2030EXPORT_SYMBOL_GPL(nft_unregister_expr);
2031
2032static const struct nft_expr_type *__nft_expr_type_get(u8 family,
2033                                                       struct nlattr *nla)
2034{
2035        const struct nft_expr_type *type, *candidate = NULL;
2036
2037        list_for_each_entry(type, &nf_tables_expressions, list) {
2038                if (!nla_strcmp(nla, type->name)) {
2039                        if (!type->family && !candidate)
2040                                candidate = type;
2041                        else if (type->family == family)
2042                                candidate = type;
2043                }
2044        }
2045        return candidate;
2046}
2047
2048#ifdef CONFIG_MODULES
2049static int nft_expr_type_request_module(struct net *net, u8 family,
2050                                        struct nlattr *nla)
2051{
2052        nft_request_module(net, "nft-expr-%u-%.*s", family,
2053                           nla_len(nla), (char *)nla_data(nla));
2054        if (__nft_expr_type_get(family, nla))
2055                return -EAGAIN;
2056
2057        return 0;
2058}
2059#endif
2060
2061static const struct nft_expr_type *nft_expr_type_get(struct net *net,
2062                                                     u8 family,
2063                                                     struct nlattr *nla)
2064{
2065        const struct nft_expr_type *type;
2066
2067        if (nla == NULL)
2068                return ERR_PTR(-EINVAL);
2069
2070        type = __nft_expr_type_get(family, nla);
2071        if (type != NULL && try_module_get(type->owner))
2072                return type;
2073
2074        lockdep_nfnl_nft_mutex_not_held();
2075#ifdef CONFIG_MODULES
2076        if (type == NULL) {
2077                if (nft_expr_type_request_module(net, family, nla) == -EAGAIN)
2078                        return ERR_PTR(-EAGAIN);
2079
2080                nft_request_module(net, "nft-expr-%.*s",
2081                                   nla_len(nla), (char *)nla_data(nla));
2082                if (__nft_expr_type_get(family, nla))
2083                        return ERR_PTR(-EAGAIN);
2084        }
2085#endif
2086        return ERR_PTR(-ENOENT);
2087}
2088
2089static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
2090        [NFTA_EXPR_NAME]        = { .type = NLA_STRING },
2091        [NFTA_EXPR_DATA]        = { .type = NLA_NESTED },
2092};
2093
2094static int nf_tables_fill_expr_info(struct sk_buff *skb,
2095                                    const struct nft_expr *expr)
2096{
2097        if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
2098                goto nla_put_failure;
2099
2100        if (expr->ops->dump) {
2101                struct nlattr *data = nla_nest_start_noflag(skb,
2102                                                            NFTA_EXPR_DATA);
2103                if (data == NULL)
2104                        goto nla_put_failure;
2105                if (expr->ops->dump(skb, expr) < 0)
2106                        goto nla_put_failure;
2107                nla_nest_end(skb, data);
2108        }
2109
2110        return skb->len;
2111
2112nla_put_failure:
2113        return -1;
2114};
2115
2116int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
2117                  const struct nft_expr *expr)
2118{
2119        struct nlattr *nest;
2120
2121        nest = nla_nest_start_noflag(skb, attr);
2122        if (!nest)
2123                goto nla_put_failure;
2124        if (nf_tables_fill_expr_info(skb, expr) < 0)
2125                goto nla_put_failure;
2126        nla_nest_end(skb, nest);
2127        return 0;
2128
2129nla_put_failure:
2130        return -1;
2131}
2132
2133struct nft_expr_info {
2134        const struct nft_expr_ops       *ops;
2135        struct nlattr                   *tb[NFT_EXPR_MAXATTR + 1];
2136};
2137
2138static int nf_tables_expr_parse(const struct nft_ctx *ctx,
2139                                const struct nlattr *nla,
2140                                struct nft_expr_info *info)
2141{
2142        const struct nft_expr_type *type;
2143        const struct nft_expr_ops *ops;
2144        struct nlattr *tb[NFTA_EXPR_MAX + 1];
2145        int err;
2146
2147        err = nla_parse_nested_deprecated(tb, NFTA_EXPR_MAX, nla,
2148                                          nft_expr_policy, NULL);
2149        if (err < 0)
2150                return err;
2151
2152        type = nft_expr_type_get(ctx->net, ctx->family, tb[NFTA_EXPR_NAME]);
2153        if (IS_ERR(type))
2154                return PTR_ERR(type);
2155
2156        if (tb[NFTA_EXPR_DATA]) {
2157                err = nla_parse_nested_deprecated(info->tb, type->maxattr,
2158                                                  tb[NFTA_EXPR_DATA],
2159                                                  type->policy, NULL);
2160                if (err < 0)
2161                        goto err1;
2162        } else
2163                memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
2164
2165        if (type->select_ops != NULL) {
2166                ops = type->select_ops(ctx,
2167                                       (const struct nlattr * const *)info->tb);
2168                if (IS_ERR(ops)) {
2169                        err = PTR_ERR(ops);
2170#ifdef CONFIG_MODULES
2171                        if (err == -EAGAIN)
2172                                nft_expr_type_request_module(ctx->net,
2173                                                             ctx->family,
2174                                                             tb[NFTA_EXPR_NAME]);
2175#endif
2176                        goto err1;
2177                }
2178        } else
2179                ops = type->ops;
2180
2181        info->ops = ops;
2182        return 0;
2183
2184err1:
2185        module_put(type->owner);
2186        return err;
2187}
2188
2189static int nf_tables_newexpr(const struct nft_ctx *ctx,
2190                             const struct nft_expr_info *info,
2191                             struct nft_expr *expr)
2192{
2193        const struct nft_expr_ops *ops = info->ops;
2194        int err;
2195
2196        expr->ops = ops;
2197        if (ops->init) {
2198                err = ops->init(ctx, expr, (const struct nlattr **)info->tb);
2199                if (err < 0)
2200                        goto err1;
2201        }
2202
2203        return 0;
2204err1:
2205        expr->ops = NULL;
2206        return err;
2207}
2208
2209static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
2210                                   struct nft_expr *expr)
2211{
2212        const struct nft_expr_type *type = expr->ops->type;
2213
2214        if (expr->ops->destroy)
2215                expr->ops->destroy(ctx, expr);
2216        module_put(type->owner);
2217}
2218
2219struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
2220                               const struct nlattr *nla)
2221{
2222        struct nft_expr_info info;
2223        struct nft_expr *expr;
2224        struct module *owner;
2225        int err;
2226
2227        err = nf_tables_expr_parse(ctx, nla, &info);
2228        if (err < 0)
2229                goto err1;
2230
2231        err = -ENOMEM;
2232        expr = kzalloc(info.ops->size, GFP_KERNEL);
2233        if (expr == NULL)
2234                goto err2;
2235
2236        err = nf_tables_newexpr(ctx, &info, expr);
2237        if (err < 0)
2238                goto err3;
2239
2240        return expr;
2241err3:
2242        kfree(expr);
2243err2:
2244        owner = info.ops->type->owner;
2245        if (info.ops->type->release_ops)
2246                info.ops->type->release_ops(info.ops);
2247
2248        module_put(owner);
2249err1:
2250        return ERR_PTR(err);
2251}
2252
2253void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr)
2254{
2255        nf_tables_expr_destroy(ctx, expr);
2256        kfree(expr);
2257}
2258
2259/*
2260 * Rules
2261 */
2262
2263static struct nft_rule *__nft_rule_lookup(const struct nft_chain *chain,
2264                                          u64 handle)
2265{
2266        struct nft_rule *rule;
2267
2268        // FIXME: this sucks
2269        list_for_each_entry_rcu(rule, &chain->rules, list) {
2270                if (handle == rule->handle)
2271                        return rule;
2272        }
2273
2274        return ERR_PTR(-ENOENT);
2275}
2276
2277static struct nft_rule *nft_rule_lookup(const struct nft_chain *chain,
2278                                        const struct nlattr *nla)
2279{
2280        if (nla == NULL)
2281                return ERR_PTR(-EINVAL);
2282
2283        return __nft_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
2284}
2285
2286static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
2287        [NFTA_RULE_TABLE]       = { .type = NLA_STRING,
2288                                    .len = NFT_TABLE_MAXNAMELEN - 1 },
2289        [NFTA_RULE_CHAIN]       = { .type = NLA_STRING,
2290                                    .len = NFT_CHAIN_MAXNAMELEN - 1 },
2291        [NFTA_RULE_HANDLE]      = { .type = NLA_U64 },
2292        [NFTA_RULE_EXPRESSIONS] = { .type = NLA_NESTED },
2293        [NFTA_RULE_COMPAT]      = { .type = NLA_NESTED },
2294        [NFTA_RULE_POSITION]    = { .type = NLA_U64 },
2295        [NFTA_RULE_USERDATA]    = { .type = NLA_BINARY,
2296                                    .len = NFT_USERDATA_MAXLEN },
2297        [NFTA_RULE_ID]          = { .type = NLA_U32 },
2298        [NFTA_RULE_POSITION_ID] = { .type = NLA_U32 },
2299};
2300
2301static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
2302                                    u32 portid, u32 seq, int event,
2303                                    u32 flags, int family,
2304                                    const struct nft_table *table,
2305                                    const struct nft_chain *chain,
2306                                    const struct nft_rule *rule,
2307                                    const struct nft_rule *prule)
2308{
2309        struct nlmsghdr *nlh;
2310        struct nfgenmsg *nfmsg;
2311        const struct nft_expr *expr, *next;
2312        struct nlattr *list;
2313        u16 type = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
2314
2315        nlh = nlmsg_put(skb, portid, seq, type, sizeof(struct nfgenmsg), flags);
2316        if (nlh == NULL)
2317                goto nla_put_failure;
2318
2319        nfmsg = nlmsg_data(nlh);
2320        nfmsg->nfgen_family     = family;
2321        nfmsg->version          = NFNETLINK_V0;
2322        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
2323
2324        if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
2325                goto nla_put_failure;
2326        if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
2327                goto nla_put_failure;
2328        if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle),
2329                         NFTA_RULE_PAD))
2330                goto nla_put_failure;
2331
2332        if (event != NFT_MSG_DELRULE && prule) {
2333                if (nla_put_be64(skb, NFTA_RULE_POSITION,
2334                                 cpu_to_be64(prule->handle),
2335                                 NFTA_RULE_PAD))
2336                        goto nla_put_failure;
2337        }
2338
2339        list = nla_nest_start_noflag(skb, NFTA_RULE_EXPRESSIONS);
2340        if (list == NULL)
2341                goto nla_put_failure;
2342        nft_rule_for_each_expr(expr, next, rule) {
2343                if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr) < 0)
2344                        goto nla_put_failure;
2345        }
2346        nla_nest_end(skb, list);
2347
2348        if (rule->udata) {
2349                struct nft_userdata *udata = nft_userdata(rule);
2350                if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
2351                            udata->data) < 0)
2352                        goto nla_put_failure;
2353        }
2354
2355        nlmsg_end(skb, nlh);
2356        return 0;
2357
2358nla_put_failure:
2359        nlmsg_trim(skb, nlh);
2360        return -1;
2361}
2362
2363static void nf_tables_rule_notify(const struct nft_ctx *ctx,
2364                                  const struct nft_rule *rule, int event)
2365{
2366        struct sk_buff *skb;
2367        int err;
2368
2369        if (!ctx->report &&
2370            !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
2371                return;
2372
2373        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
2374        if (skb == NULL)
2375                goto err;
2376
2377        err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
2378                                       event, 0, ctx->family, ctx->table,
2379                                       ctx->chain, rule, NULL);
2380        if (err < 0) {
2381                kfree_skb(skb);
2382                goto err;
2383        }
2384
2385        nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
2386                       ctx->report, GFP_KERNEL);
2387        return;
2388err:
2389        nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
2390}
2391
2392struct nft_rule_dump_ctx {
2393        char *table;
2394        char *chain;
2395};
2396
2397static int __nf_tables_dump_rules(struct sk_buff *skb,
2398                                  unsigned int *idx,
2399                                  struct netlink_callback *cb,
2400                                  const struct nft_table *table,
2401                                  const struct nft_chain *chain)
2402{
2403        struct net *net = sock_net(skb->sk);
2404        const struct nft_rule *rule, *prule;
2405        unsigned int s_idx = cb->args[0];
2406
2407        prule = NULL;
2408        list_for_each_entry_rcu(rule, &chain->rules, list) {
2409                if (!nft_is_active(net, rule))
2410                        goto cont_skip;
2411                if (*idx < s_idx)
2412                        goto cont;
2413                if (*idx > s_idx) {
2414                        memset(&cb->args[1], 0,
2415                                        sizeof(cb->args) - sizeof(cb->args[0]));
2416                }
2417                if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
2418                                        cb->nlh->nlmsg_seq,
2419                                        NFT_MSG_NEWRULE,
2420                                        NLM_F_MULTI | NLM_F_APPEND,
2421                                        table->family,
2422                                        table, chain, rule, prule) < 0)
2423                        return 1;
2424
2425                nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2426cont:
2427                prule = rule;
2428cont_skip:
2429                (*idx)++;
2430        }
2431        return 0;
2432}
2433
2434static int nf_tables_dump_rules(struct sk_buff *skb,
2435                                struct netlink_callback *cb)
2436{
2437        const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
2438        const struct nft_rule_dump_ctx *ctx = cb->data;
2439        struct nft_table *table;
2440        const struct nft_chain *chain;
2441        unsigned int idx = 0;
2442        struct net *net = sock_net(skb->sk);
2443        int family = nfmsg->nfgen_family;
2444
2445        rcu_read_lock();
2446        cb->seq = net->nft.base_seq;
2447
2448        list_for_each_entry_rcu(table, &net->nft.tables, list) {
2449                if (family != NFPROTO_UNSPEC && family != table->family)
2450                        continue;
2451
2452                if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
2453                        continue;
2454
2455                if (ctx && ctx->table && ctx->chain) {
2456                        struct rhlist_head *list, *tmp;
2457
2458                        list = rhltable_lookup(&table->chains_ht, ctx->chain,
2459                                               nft_chain_ht_params);
2460                        if (!list)
2461                                goto done;
2462
2463                        rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
2464                                if (!nft_is_active(net, chain))
2465                                        continue;
2466                                __nf_tables_dump_rules(skb, &idx,
2467                                                       cb, table, chain);
2468                                break;
2469                        }
2470                        goto done;
2471                }
2472
2473                list_for_each_entry_rcu(chain, &table->chains, list) {
2474                        if (__nf_tables_dump_rules(skb, &idx, cb, table, chain))
2475                                goto done;
2476                }
2477
2478                if (ctx && ctx->table)
2479                        break;
2480        }
2481done:
2482        rcu_read_unlock();
2483
2484        cb->args[0] = idx;
2485        return skb->len;
2486}
2487
2488static int nf_tables_dump_rules_start(struct netlink_callback *cb)
2489{
2490        const struct nlattr * const *nla = cb->data;
2491        struct nft_rule_dump_ctx *ctx = NULL;
2492
2493        if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
2494                ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
2495                if (!ctx)
2496                        return -ENOMEM;
2497
2498                if (nla[NFTA_RULE_TABLE]) {
2499                        ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
2500                                                        GFP_ATOMIC);
2501                        if (!ctx->table) {
2502                                kfree(ctx);
2503                                return -ENOMEM;
2504                        }
2505                }
2506                if (nla[NFTA_RULE_CHAIN]) {
2507                        ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
2508                                                GFP_ATOMIC);
2509                        if (!ctx->chain) {
2510                                kfree(ctx->table);
2511                                kfree(ctx);
2512                                return -ENOMEM;
2513                        }
2514                }
2515        }
2516
2517        cb->data = ctx;
2518        return 0;
2519}
2520
2521static int nf_tables_dump_rules_done(struct netlink_callback *cb)
2522{
2523        struct nft_rule_dump_ctx *ctx = cb->data;
2524
2525        if (ctx) {
2526                kfree(ctx->table);
2527                kfree(ctx->chain);
2528                kfree(ctx);
2529        }
2530        return 0;
2531}
2532
2533/* called with rcu_read_lock held */
2534static int nf_tables_getrule(struct net *net, struct sock *nlsk,
2535                             struct sk_buff *skb, const struct nlmsghdr *nlh,
2536                             const struct nlattr * const nla[],
2537                             struct netlink_ext_ack *extack)
2538{
2539        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2540        u8 genmask = nft_genmask_cur(net);
2541        const struct nft_chain *chain;
2542        const struct nft_rule *rule;
2543        struct nft_table *table;
2544        struct sk_buff *skb2;
2545        int family = nfmsg->nfgen_family;
2546        int err;
2547
2548        if (nlh->nlmsg_flags & NLM_F_DUMP) {
2549                struct netlink_dump_control c = {
2550                        .start= nf_tables_dump_rules_start,
2551                        .dump = nf_tables_dump_rules,
2552                        .done = nf_tables_dump_rules_done,
2553                        .module = THIS_MODULE,
2554                        .data = (void *)nla,
2555                };
2556
2557                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
2558        }
2559
2560        table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2561        if (IS_ERR(table)) {
2562                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2563                return PTR_ERR(table);
2564        }
2565
2566        chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2567        if (IS_ERR(chain)) {
2568                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2569                return PTR_ERR(chain);
2570        }
2571
2572        rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2573        if (IS_ERR(rule)) {
2574                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2575                return PTR_ERR(rule);
2576        }
2577
2578        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
2579        if (!skb2)
2580                return -ENOMEM;
2581
2582        err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
2583                                       nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
2584                                       family, table, chain, rule, NULL);
2585        if (err < 0)
2586                goto err;
2587
2588        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2589
2590err:
2591        kfree_skb(skb2);
2592        return err;
2593}
2594
2595static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
2596                                   struct nft_rule *rule)
2597{
2598        struct nft_expr *expr, *next;
2599
2600        /*
2601         * Careful: some expressions might not be initialized in case this
2602         * is called on error from nf_tables_newrule().
2603         */
2604        expr = nft_expr_first(rule);
2605        while (expr != nft_expr_last(rule) && expr->ops) {
2606                next = nft_expr_next(expr);
2607                nf_tables_expr_destroy(ctx, expr);
2608                expr = next;
2609        }
2610        kfree(rule);
2611}
2612
2613static void nf_tables_rule_release(const struct nft_ctx *ctx,
2614                                   struct nft_rule *rule)
2615{
2616        nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_RELEASE);
2617        nf_tables_rule_destroy(ctx, rule);
2618}
2619
2620int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
2621{
2622        struct nft_expr *expr, *last;
2623        const struct nft_data *data;
2624        struct nft_rule *rule;
2625        int err;
2626
2627        if (ctx->level == NFT_JUMP_STACK_SIZE)
2628                return -EMLINK;
2629
2630        list_for_each_entry(rule, &chain->rules, list) {
2631                if (!nft_is_active_next(ctx->net, rule))
2632                        continue;
2633
2634                nft_rule_for_each_expr(expr, last, rule) {
2635                        if (!expr->ops->validate)
2636                                continue;
2637
2638                        err = expr->ops->validate(ctx, expr, &data);
2639                        if (err < 0)
2640                                return err;
2641                }
2642        }
2643
2644        return 0;
2645}
2646EXPORT_SYMBOL_GPL(nft_chain_validate);
2647
2648static int nft_table_validate(struct net *net, const struct nft_table *table)
2649{
2650        struct nft_chain *chain;
2651        struct nft_ctx ctx = {
2652                .net    = net,
2653                .family = table->family,
2654        };
2655        int err;
2656
2657        list_for_each_entry(chain, &table->chains, list) {
2658                if (!nft_is_base_chain(chain))
2659                        continue;
2660
2661                ctx.chain = chain;
2662                err = nft_chain_validate(&ctx, chain);
2663                if (err < 0)
2664                        return err;
2665        }
2666
2667        return 0;
2668}
2669
2670static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2671                                             const struct nlattr *nla);
2672
2673#define NFT_RULE_MAXEXPRS       128
2674
2675static int nf_tables_newrule(struct net *net, struct sock *nlsk,
2676                             struct sk_buff *skb, const struct nlmsghdr *nlh,
2677                             const struct nlattr * const nla[],
2678                             struct netlink_ext_ack *extack)
2679{
2680        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2681        u8 genmask = nft_genmask_next(net);
2682        struct nft_expr_info *info = NULL;
2683        int family = nfmsg->nfgen_family;
2684        struct nft_flow_rule *flow;
2685        struct nft_table *table;
2686        struct nft_chain *chain;
2687        struct nft_rule *rule, *old_rule = NULL;
2688        struct nft_userdata *udata;
2689        struct nft_trans *trans = NULL;
2690        struct nft_expr *expr;
2691        struct nft_ctx ctx;
2692        struct nlattr *tmp;
2693        unsigned int size, i, n, ulen = 0, usize = 0;
2694        int err, rem;
2695        u64 handle, pos_handle;
2696
2697        lockdep_assert_held(&net->nft.commit_mutex);
2698
2699        table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2700        if (IS_ERR(table)) {
2701                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2702                return PTR_ERR(table);
2703        }
2704
2705        chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2706        if (IS_ERR(chain)) {
2707                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2708                return PTR_ERR(chain);
2709        }
2710
2711        if (nla[NFTA_RULE_HANDLE]) {
2712                handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
2713                rule = __nft_rule_lookup(chain, handle);
2714                if (IS_ERR(rule)) {
2715                        NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2716                        return PTR_ERR(rule);
2717                }
2718
2719                if (nlh->nlmsg_flags & NLM_F_EXCL) {
2720                        NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2721                        return -EEXIST;
2722                }
2723                if (nlh->nlmsg_flags & NLM_F_REPLACE)
2724                        old_rule = rule;
2725                else
2726                        return -EOPNOTSUPP;
2727        } else {
2728                if (!(nlh->nlmsg_flags & NLM_F_CREATE) ||
2729                    nlh->nlmsg_flags & NLM_F_REPLACE)
2730                        return -EINVAL;
2731                handle = nf_tables_alloc_handle(table);
2732
2733                if (chain->use == UINT_MAX)
2734                        return -EOVERFLOW;
2735
2736                if (nla[NFTA_RULE_POSITION]) {
2737                        pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
2738                        old_rule = __nft_rule_lookup(chain, pos_handle);
2739                        if (IS_ERR(old_rule)) {
2740                                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
2741                                return PTR_ERR(old_rule);
2742                        }
2743                } else if (nla[NFTA_RULE_POSITION_ID]) {
2744                        old_rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_POSITION_ID]);
2745                        if (IS_ERR(old_rule)) {
2746                                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION_ID]);
2747                                return PTR_ERR(old_rule);
2748                        }
2749                }
2750        }
2751
2752        nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2753
2754        n = 0;
2755        size = 0;
2756        if (nla[NFTA_RULE_EXPRESSIONS]) {
2757                info = kvmalloc_array(NFT_RULE_MAXEXPRS,
2758                                      sizeof(struct nft_expr_info),
2759                                      GFP_KERNEL);
2760                if (!info)
2761                        return -ENOMEM;
2762
2763                nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
2764                        err = -EINVAL;
2765                        if (nla_type(tmp) != NFTA_LIST_ELEM)
2766                                goto err1;
2767                        if (n == NFT_RULE_MAXEXPRS)
2768                                goto err1;
2769                        err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
2770                        if (err < 0)
2771                                goto err1;
2772                        size += info[n].ops->size;
2773                        n++;
2774                }
2775        }
2776        /* Check for overflow of dlen field */
2777        err = -EFBIG;
2778        if (size >= 1 << 12)
2779                goto err1;
2780
2781        if (nla[NFTA_RULE_USERDATA]) {
2782                ulen = nla_len(nla[NFTA_RULE_USERDATA]);
2783                if (ulen > 0)
2784                        usize = sizeof(struct nft_userdata) + ulen;
2785        }
2786
2787        err = -ENOMEM;
2788        rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
2789        if (rule == NULL)
2790                goto err1;
2791
2792        nft_activate_next(net, rule);
2793
2794        rule->handle = handle;
2795        rule->dlen   = size;
2796        rule->udata  = ulen ? 1 : 0;
2797
2798        if (ulen) {
2799                udata = nft_userdata(rule);
2800                udata->len = ulen - 1;
2801                nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
2802        }
2803
2804        expr = nft_expr_first(rule);
2805        for (i = 0; i < n; i++) {
2806                err = nf_tables_newexpr(&ctx, &info[i], expr);
2807                if (err < 0)
2808                        goto err2;
2809
2810                if (info[i].ops->validate)
2811                        nft_validate_state_update(net, NFT_VALIDATE_NEED);
2812
2813                info[i].ops = NULL;
2814                expr = nft_expr_next(expr);
2815        }
2816
2817        if (nlh->nlmsg_flags & NLM_F_REPLACE) {
2818                trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2819                if (trans == NULL) {
2820                        err = -ENOMEM;
2821                        goto err2;
2822                }
2823                err = nft_delrule(&ctx, old_rule);
2824                if (err < 0) {
2825                        nft_trans_destroy(trans);
2826                        goto err2;
2827                }
2828
2829                list_add_tail_rcu(&rule->list, &old_rule->list);
2830        } else {
2831                trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2832                if (!trans) {
2833                        err = -ENOMEM;
2834                        goto err2;
2835                }
2836
2837                if (nlh->nlmsg_flags & NLM_F_APPEND) {
2838                        if (old_rule)
2839                                list_add_rcu(&rule->list, &old_rule->list);
2840                        else
2841                                list_add_tail_rcu(&rule->list, &chain->rules);
2842                 } else {
2843                        if (old_rule)
2844                                list_add_tail_rcu(&rule->list, &old_rule->list);
2845                        else
2846                                list_add_rcu(&rule->list, &chain->rules);
2847                }
2848        }
2849        kvfree(info);
2850        chain->use++;
2851
2852        if (net->nft.validate_state == NFT_VALIDATE_DO)
2853                return nft_table_validate(net, table);
2854
2855        if (chain->flags & NFT_CHAIN_HW_OFFLOAD) {
2856                flow = nft_flow_rule_create(rule);
2857                if (IS_ERR(flow))
2858                        return PTR_ERR(flow);
2859
2860                nft_trans_flow_rule(trans) = flow;
2861        }
2862
2863        return 0;
2864err2:
2865        nf_tables_rule_release(&ctx, rule);
2866err1:
2867        for (i = 0; i < n; i++) {
2868                if (info[i].ops) {
2869                        module_put(info[i].ops->type->owner);
2870                        if (info[i].ops->type->release_ops)
2871                                info[i].ops->type->release_ops(info[i].ops);
2872                }
2873        }
2874        kvfree(info);
2875        return err;
2876}
2877
2878static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2879                                             const struct nlattr *nla)
2880{
2881        u32 id = ntohl(nla_get_be32(nla));
2882        struct nft_trans *trans;
2883
2884        list_for_each_entry(trans, &net->nft.commit_list, list) {
2885                struct nft_rule *rule = nft_trans_rule(trans);
2886
2887                if (trans->msg_type == NFT_MSG_NEWRULE &&
2888                    id == nft_trans_rule_id(trans))
2889                        return rule;
2890        }
2891        return ERR_PTR(-ENOENT);
2892}
2893
2894static int nf_tables_delrule(struct net *net, struct sock *nlsk,
2895                             struct sk_buff *skb, const struct nlmsghdr *nlh,
2896                             const struct nlattr * const nla[],
2897                             struct netlink_ext_ack *extack)
2898{
2899        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2900        u8 genmask = nft_genmask_next(net);
2901        struct nft_table *table;
2902        struct nft_chain *chain = NULL;
2903        struct nft_rule *rule;
2904        int family = nfmsg->nfgen_family, err = 0;
2905        struct nft_ctx ctx;
2906
2907        table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2908        if (IS_ERR(table)) {
2909                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2910                return PTR_ERR(table);
2911        }
2912
2913        if (nla[NFTA_RULE_CHAIN]) {
2914                chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
2915                                         genmask);
2916                if (IS_ERR(chain)) {
2917                        NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2918                        return PTR_ERR(chain);
2919                }
2920        }
2921
2922        nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2923
2924        if (chain) {
2925                if (nla[NFTA_RULE_HANDLE]) {
2926                        rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2927                        if (IS_ERR(rule)) {
2928                                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2929                                return PTR_ERR(rule);
2930                        }
2931
2932                        err = nft_delrule(&ctx, rule);
2933                } else if (nla[NFTA_RULE_ID]) {
2934                        rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_ID]);
2935                        if (IS_ERR(rule)) {
2936                                NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
2937                                return PTR_ERR(rule);
2938                        }
2939
2940                        err = nft_delrule(&ctx, rule);
2941                } else {
2942                        err = nft_delrule_by_chain(&ctx);
2943                }
2944        } else {
2945                list_for_each_entry(chain, &table->chains, list) {
2946                        if (!nft_is_active_next(net, chain))
2947                                continue;
2948
2949                        ctx.chain = chain;
2950                        err = nft_delrule_by_chain(&ctx);
2951                        if (err < 0)
2952                                break;
2953                }
2954        }
2955
2956        return err;
2957}
2958
2959/*
2960 * Sets
2961 */
2962
2963static LIST_HEAD(nf_tables_set_types);
2964
2965int nft_register_set(struct nft_set_type *type)
2966{
2967        nfnl_lock(NFNL_SUBSYS_NFTABLES);
2968        list_add_tail_rcu(&type->list, &nf_tables_set_types);
2969        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2970        return 0;
2971}
2972EXPORT_SYMBOL_GPL(nft_register_set);
2973
2974void nft_unregister_set(struct nft_set_type *type)
2975{
2976        nfnl_lock(NFNL_SUBSYS_NFTABLES);
2977        list_del_rcu(&type->list);
2978        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2979}
2980EXPORT_SYMBOL_GPL(nft_unregister_set);
2981
2982#define NFT_SET_FEATURES        (NFT_SET_INTERVAL | NFT_SET_MAP | \
2983                                 NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
2984                                 NFT_SET_EVAL)
2985
2986static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
2987{
2988        return (flags & type->features) == (flags & NFT_SET_FEATURES);
2989}
2990
2991/*
2992 * Select a set implementation based on the data characteristics and the
2993 * given policy. The total memory use might not be known if no size is
2994 * given, in that case the amount of memory per element is used.
2995 */
2996static const struct nft_set_ops *
2997nft_select_set_ops(const struct nft_ctx *ctx,
2998                   const struct nlattr * const nla[],
2999                   const struct nft_set_desc *desc,
3000                   enum nft_set_policies policy)
3001{
3002        const struct nft_set_ops *ops, *bops;
3003        struct nft_set_estimate est, best;
3004        const struct nft_set_type *type;
3005        u32 flags = 0;
3006
3007        lockdep_assert_held(&ctx->net->nft.commit_mutex);
3008        lockdep_nfnl_nft_mutex_not_held();
3009#ifdef CONFIG_MODULES
3010        if (list_empty(&nf_tables_set_types)) {
3011                nft_request_module(ctx->net, "nft-set");
3012                if (!list_empty(&nf_tables_set_types))
3013                        return ERR_PTR(-EAGAIN);
3014        }
3015#endif
3016        if (nla[NFTA_SET_FLAGS] != NULL)
3017                flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3018
3019        bops        = NULL;
3020        best.size   = ~0;
3021        best.lookup = ~0;
3022        best.space  = ~0;
3023
3024        list_for_each_entry(type, &nf_tables_set_types, list) {
3025                ops = &type->ops;
3026
3027                if (!nft_set_ops_candidate(type, flags))
3028                        continue;
3029                if (!ops->estimate(desc, flags, &est))
3030                        continue;
3031
3032                switch (policy) {
3033                case NFT_SET_POL_PERFORMANCE:
3034                        if (est.lookup < best.lookup)
3035                                break;
3036                        if (est.lookup == best.lookup &&
3037                            est.space < best.space)
3038                                break;
3039                        continue;
3040                case NFT_SET_POL_MEMORY:
3041                        if (!desc->size) {
3042                                if (est.space < best.space)
3043                                        break;
3044                                if (est.space == best.space &&
3045                                    est.lookup < best.lookup)
3046                                        break;
3047                        } else if (est.size < best.size || !bops) {
3048                                break;
3049                        }
3050                        continue;
3051                default:
3052                        break;
3053                }
3054
3055                if (!try_module_get(type->owner))
3056                        continue;
3057                if (bops != NULL)
3058                        module_put(to_set_type(bops)->owner);
3059
3060                bops = ops;
3061                best = est;
3062        }
3063
3064        if (bops != NULL)
3065                return bops;
3066
3067        return ERR_PTR(-EOPNOTSUPP);
3068}
3069
3070static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
3071        [NFTA_SET_TABLE]                = { .type = NLA_STRING,
3072                                            .len = NFT_TABLE_MAXNAMELEN - 1 },
3073        [NFTA_SET_NAME]                 = { .type = NLA_STRING,
3074                                            .len = NFT_SET_MAXNAMELEN - 1 },
3075        [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
3076        [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
3077        [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
3078        [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
3079        [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
3080        [NFTA_SET_POLICY]               = { .type = NLA_U32 },
3081        [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
3082        [NFTA_SET_ID]                   = { .type = NLA_U32 },
3083        [NFTA_SET_TIMEOUT]              = { .type = NLA_U64 },
3084        [NFTA_SET_GC_INTERVAL]          = { .type = NLA_U32 },
3085        [NFTA_SET_USERDATA]             = { .type = NLA_BINARY,
3086                                            .len  = NFT_USERDATA_MAXLEN },
3087        [NFTA_SET_OBJ_TYPE]             = { .type = NLA_U32 },
3088        [NFTA_SET_HANDLE]               = { .type = NLA_U64 },
3089};
3090
3091static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
3092        [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
3093};
3094
3095static int nft_ctx_init_from_setattr(struct nft_ctx *ctx, struct net *net,
3096                                     const struct sk_buff *skb,
3097                                     const struct nlmsghdr *nlh,
3098                                     const struct nlattr * const nla[],
3099                                     struct netlink_ext_ack *extack,
3100                                     u8 genmask)
3101{
3102        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3103        int family = nfmsg->nfgen_family;
3104        struct nft_table *table = NULL;
3105
3106        if (nla[NFTA_SET_TABLE] != NULL) {
3107                table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
3108                                         genmask);
3109                if (IS_ERR(table)) {
3110                        NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3111                        return PTR_ERR(table);
3112                }
3113        }
3114
3115        nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3116        return 0;
3117}
3118
3119static struct nft_set *nft_set_lookup(const struct nft_table *table,
3120                                      const struct nlattr *nla, u8 genmask)
3121{
3122        struct nft_set *set;
3123
3124        if (nla == NULL)
3125                return ERR_PTR(-EINVAL);
3126
3127        list_for_each_entry_rcu(set, &table->sets, list) {
3128                if (!nla_strcmp(nla, set->name) &&
3129                    nft_active_genmask(set, genmask))
3130                        return set;
3131        }
3132        return ERR_PTR(-ENOENT);
3133}
3134
3135static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
3136                                               const struct nlattr *nla,
3137                                               u8 genmask)
3138{
3139        struct nft_set *set;
3140
3141        list_for_each_entry(set, &table->sets, list) {
3142                if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
3143                    nft_active_genmask(set, genmask))
3144                        return set;
3145        }
3146        return ERR_PTR(-ENOENT);
3147}
3148
3149static struct nft_set *nft_set_lookup_byid(const struct net *net,
3150                                           const struct nlattr *nla, u8 genmask)
3151{
3152        struct nft_trans *trans;
3153        u32 id = ntohl(nla_get_be32(nla));
3154
3155        list_for_each_entry(trans, &net->nft.commit_list, list) {
3156                if (trans->msg_type == NFT_MSG_NEWSET) {
3157                        struct nft_set *set = nft_trans_set(trans);
3158
3159                        if (id == nft_trans_set_id(trans) &&
3160                            nft_active_genmask(set, genmask))
3161                                return set;
3162                }
3163        }
3164        return ERR_PTR(-ENOENT);
3165}
3166
3167struct nft_set *nft_set_lookup_global(const struct net *net,
3168                                      const struct nft_table *table,
3169                                      const struct nlattr *nla_set_name,
3170                                      const struct nlattr *nla_set_id,
3171                                      u8 genmask)
3172{
3173        struct nft_set *set;
3174
3175        set = nft_set_lookup(table, nla_set_name, genmask);
3176        if (IS_ERR(set)) {
3177                if (!nla_set_id)
3178                        return set;
3179
3180                set = nft_set_lookup_byid(net, nla_set_id, genmask);
3181        }
3182        return set;
3183}
3184EXPORT_SYMBOL_GPL(nft_set_lookup_global);
3185
3186static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
3187                                    const char *name)
3188{
3189        const struct nft_set *i;
3190        const char *p;
3191        unsigned long *inuse;
3192        unsigned int n = 0, min = 0;
3193
3194        p = strchr(name, '%');
3195        if (p != NULL) {
3196                if (p[1] != 'd' || strchr(p + 2, '%'))
3197                        return -EINVAL;
3198
3199                inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
3200                if (inuse == NULL)
3201                        return -ENOMEM;
3202cont:
3203                list_for_each_entry(i, &ctx->table->sets, list) {
3204                        int tmp;
3205
3206                        if (!nft_is_active_next(ctx->net, set))
3207                                continue;
3208                        if (!sscanf(i->name, name, &tmp))
3209                                continue;
3210                        if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
3211                                continue;
3212
3213                        set_bit(tmp - min, inuse);
3214                }
3215
3216                n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
3217                if (n >= BITS_PER_BYTE * PAGE_SIZE) {
3218                        min += BITS_PER_BYTE * PAGE_SIZE;
3219                        memset(inuse, 0, PAGE_SIZE);
3220                        goto cont;
3221                }
3222                free_page((unsigned long)inuse);
3223        }
3224
3225        set->name = kasprintf(GFP_KERNEL, name, min + n);
3226        if (!set->name)
3227                return -ENOMEM;
3228
3229        list_for_each_entry(i, &ctx->table->sets, list) {
3230                if (!nft_is_active_next(ctx->net, i))
3231                        continue;
3232                if (!strcmp(set->name, i->name)) {
3233                        kfree(set->name);
3234                        return -ENFILE;
3235                }
3236        }
3237        return 0;
3238}
3239
3240static int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
3241{
3242        u64 ms = be64_to_cpu(nla_get_be64(nla));
3243        u64 max = (u64)(~((u64)0));
3244
3245        max = div_u64(max, NSEC_PER_MSEC);
3246        if (ms >= max)
3247                return -ERANGE;
3248
3249        ms *= NSEC_PER_MSEC;
3250        *result = nsecs_to_jiffies64(ms);
3251        return 0;
3252}
3253
3254static __be64 nf_jiffies64_to_msecs(u64 input)
3255{
3256        return cpu_to_be64(jiffies64_to_msecs(input));
3257}
3258
3259static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
3260                              const struct nft_set *set, u16 event, u16 flags)
3261{
3262        struct nfgenmsg *nfmsg;
3263        struct nlmsghdr *nlh;
3264        struct nlattr *desc;
3265        u32 portid = ctx->portid;
3266        u32 seq = ctx->seq;
3267
3268        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3269        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3270                        flags);
3271        if (nlh == NULL)
3272                goto nla_put_failure;
3273
3274        nfmsg = nlmsg_data(nlh);
3275        nfmsg->nfgen_family     = ctx->family;
3276        nfmsg->version          = NFNETLINK_V0;
3277        nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3278
3279        if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3280                goto nla_put_failure;
3281        if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3282                goto nla_put_failure;
3283        if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
3284                         NFTA_SET_PAD))
3285                goto nla_put_failure;
3286        if (set->flags != 0)
3287                if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
3288                        goto nla_put_failure;
3289
3290        if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
3291                goto nla_put_failure;
3292        if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
3293                goto nla_put_failure;
3294        if (set->flags & NFT_SET_MAP) {
3295                if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
3296                        goto nla_put_failure;
3297                if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
3298                        goto nla_put_failure;
3299        }
3300        if (set->flags & NFT_SET_OBJECT &&
3301            nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
3302                goto nla_put_failure;
3303
3304        if (set->timeout &&
3305            nla_put_be64(skb, NFTA_SET_TIMEOUT,
3306                         nf_jiffies64_to_msecs(set->timeout),
3307                         NFTA_SET_PAD))
3308                goto nla_put_failure;
3309        if (set->gc_int &&
3310            nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(set->gc_int)))
3311                goto nla_put_failure;
3312
3313        if (set->policy != NFT_SET_POL_PERFORMANCE) {
3314                if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
3315                        goto nla_put_failure;
3316        }
3317
3318        if (nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
3319                goto nla_put_failure;
3320
3321        desc = nla_nest_start_noflag(skb, NFTA_SET_DESC);
3322        if (desc == NULL)
3323                goto nla_put_failure;
3324        if (set->size &&
3325            nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
3326                goto nla_put_failure;
3327        nla_nest_end(skb, desc);
3328
3329        nlmsg_end(skb, nlh);
3330        return 0;
3331
3332nla_put_failure:
3333        nlmsg_trim(skb, nlh);
3334        return -1;
3335}
3336
3337static void nf_tables_set_notify(const struct nft_ctx *ctx,
3338                                 const struct nft_set *set, int event,
3339                                 gfp_t gfp_flags)
3340{
3341        struct sk_buff *skb;
3342        u32 portid = ctx->portid;
3343        int err;
3344
3345        if (!ctx->report &&
3346            !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3347                return;
3348
3349        skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
3350        if (skb == NULL)
3351                goto err;
3352
3353        err = nf_tables_fill_set(skb, ctx, set, event, 0);
3354        if (err < 0) {
3355                kfree_skb(skb);
3356                goto err;
3357        }
3358
3359        nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES, ctx->report,
3360                       gfp_flags);
3361        return;
3362err:
3363        nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
3364}
3365
3366static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
3367{
3368        const struct nft_set *set;
3369        unsigned int idx, s_idx = cb->args[0];
3370        struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
3371        struct net *net = sock_net(skb->sk);
3372        struct nft_ctx *ctx = cb->data, ctx_set;
3373
3374        if (cb->args[1])
3375                return skb->len;
3376
3377        rcu_read_lock();
3378        cb->seq = net->nft.base_seq;
3379
3380        list_for_each_entry_rcu(table, &net->nft.tables, list) {
3381                if (ctx->family != NFPROTO_UNSPEC &&
3382                    ctx->family != table->family)
3383                        continue;
3384
3385                if (ctx->table && ctx->table != table)
3386                        continue;
3387
3388                if (cur_table) {
3389                        if (cur_table != table)
3390                                continue;
3391
3392                        cur_table = NULL;
3393                }
3394                idx = 0;
3395                list_for_each_entry_rcu(set, &table->sets, list) {
3396                        if (idx < s_idx)
3397                                goto cont;
3398                        if (!nft_is_active(net, set))
3399                                goto cont;
3400
3401                        ctx_set = *ctx;
3402                        ctx_set.table = table;
3403                        ctx_set.family = table->family;
3404
3405                        if (nf_tables_fill_set(skb, &ctx_set, set,
3406                                               NFT_MSG_NEWSET,
3407                                               NLM_F_MULTI) < 0) {
3408                                cb->args[0] = idx;
3409                                cb->args[2] = (unsigned long) table;
3410                                goto done;
3411                        }
3412                        nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3413cont:
3414                        idx++;
3415                }
3416                if (s_idx)
3417                        s_idx = 0;
3418        }
3419        cb->args[1] = 1;
3420done:
3421        rcu_read_unlock();
3422        return skb->len;
3423}
3424
3425static int nf_tables_dump_sets_start(struct netlink_callback *cb)
3426{
3427        struct nft_ctx *ctx_dump = NULL;
3428
3429        ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
3430        if (ctx_dump == NULL)
3431                return -ENOMEM;
3432
3433        cb->data = ctx_dump;
3434        return 0;
3435}
3436
3437static int nf_tables_dump_sets_done(struct netlink_callback *cb)
3438{
3439        kfree(cb->data);
3440        return 0;
3441}
3442
3443/* called with rcu_read_lock held */
3444static int nf_tables_getset(struct net *net, struct sock *nlsk,
3445                            struct sk_buff *skb, const struct nlmsghdr *nlh,
3446                            const struct nlattr * const nla[],
3447                            struct netlink_ext_ack *extack)
3448{
3449        u8 genmask = nft_genmask_cur(net);
3450        const struct nft_set *set;
3451        struct nft_ctx ctx;
3452        struct sk_buff *skb2;
3453        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3454        int err;
3455
3456        /* Verify existence before starting dump */
3457        err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3458                                        genmask);
3459        if (err < 0)
3460                return err;
3461
3462        if (nlh->nlmsg_flags & NLM_F_DUMP) {
3463                struct netlink_dump_control c = {
3464                        .start = nf_tables_dump_sets_start,
3465                        .dump = nf_tables_dump_sets,
3466                        .done = nf_tables_dump_sets_done,
3467                        .data = &ctx,
3468                        .module = THIS_MODULE,
3469                };
3470
3471                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
3472        }
3473
3474        /* Only accept unspec with dump */
3475        if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3476                return -EAFNOSUPPORT;
3477        if (!nla[NFTA_SET_TABLE])
3478                return -EINVAL;
3479
3480        set = nft_set_lookup(ctx.table, nla[NFTA_SET_NAME], genmask);
3481        if (IS_ERR(set))
3482                return PTR_ERR(set);
3483
3484        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3485        if (skb2 == NULL)
3486                return -ENOMEM;
3487
3488        err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
3489        if (err < 0)
3490                goto err;
3491
3492        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3493
3494err:
3495        kfree_skb(skb2);
3496        return err;
3497}
3498
3499static int nf_tables_set_desc_parse(struct nft_set_desc *desc,
3500                                    const struct nlattr *nla)
3501{
3502        struct nlattr *da[NFTA_SET_DESC_MAX + 1];
3503        int err;
3504
3505        err = nla_parse_nested_deprecated(da, NFTA_SET_DESC_MAX, nla,
3506                                          nft_set_desc_policy, NULL);
3507        if (err < 0)
3508                return err;
3509
3510        if (da[NFTA_SET_DESC_SIZE] != NULL)
3511                desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
3512
3513        return 0;
3514}
3515
3516static int nf_tables_newset(struct net *net, struct sock *nlsk,
3517                            struct sk_buff *skb, const struct nlmsghdr *nlh,
3518                            const struct nlattr * const nla[],
3519                            struct netlink_ext_ack *extack)
3520{
3521        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3522        u8 genmask = nft_genmask_next(net);
3523        int family = nfmsg->nfgen_family;
3524        const struct nft_set_ops *ops;
3525        struct nft_table *table;
3526        struct nft_set *set;
3527        struct nft_ctx ctx;
3528        char *name;
3529        u64 size;
3530        u64 timeout;
3531        u32 ktype, dtype, flags, policy, gc_int, objtype;
3532        struct nft_set_desc desc;
3533        unsigned char *udata;
3534        u16 udlen;
3535        int err;
3536
3537        if (nla[NFTA_SET_TABLE] == NULL ||
3538            nla[NFTA_SET_NAME] == NULL ||
3539            nla[NFTA_SET_KEY_LEN] == NULL ||
3540            nla[NFTA_SET_ID] == NULL)
3541                return -EINVAL;
3542
3543        memset(&desc, 0, sizeof(desc));
3544
3545        ktype = NFT_DATA_VALUE;
3546        if (nla[NFTA_SET_KEY_TYPE] != NULL) {
3547                ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
3548                if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
3549                        return -EINVAL;
3550        }
3551
3552        desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
3553        if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
3554                return -EINVAL;
3555
3556        flags = 0;
3557        if (nla[NFTA_SET_FLAGS] != NULL) {
3558                flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3559                if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
3560                              NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
3561                              NFT_SET_MAP | NFT_SET_EVAL |
3562                              NFT_SET_OBJECT))
3563                        return -EINVAL;
3564                /* Only one of these operations is supported */
3565                if ((flags & (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT)) ==
3566                             (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT))
3567                        return -EOPNOTSUPP;
3568        }
3569
3570        dtype = 0;
3571        if (nla[NFTA_SET_DATA_TYPE] != NULL) {
3572                if (!(flags & NFT_SET_MAP))
3573                        return -EINVAL;
3574
3575                dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
3576                if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
3577                    dtype != NFT_DATA_VERDICT)
3578                        return -EINVAL;
3579
3580                if (dtype != NFT_DATA_VERDICT) {
3581                        if (nla[NFTA_SET_DATA_LEN] == NULL)
3582                                return -EINVAL;
3583                        desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
3584                        if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
3585                                return -EINVAL;
3586                } else
3587                        desc.dlen = sizeof(struct nft_verdict);
3588        } else if (flags & NFT_SET_MAP)
3589                return -EINVAL;
3590
3591        if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
3592                if (!(flags & NFT_SET_OBJECT))
3593                        return -EINVAL;
3594
3595                objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
3596                if (objtype == NFT_OBJECT_UNSPEC ||
3597                    objtype > NFT_OBJECT_MAX)
3598                        return -EINVAL;
3599        } else if (flags & NFT_SET_OBJECT)
3600                return -EINVAL;
3601        else
3602                objtype = NFT_OBJECT_UNSPEC;
3603
3604        timeout = 0;
3605        if (nla[NFTA_SET_TIMEOUT] != NULL) {
3606                if (!(flags & NFT_SET_TIMEOUT))
3607                        return -EINVAL;
3608
3609                err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);
3610                if (err)
3611                        return err;
3612        }
3613        gc_int = 0;
3614        if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
3615                if (!(flags & NFT_SET_TIMEOUT))
3616                        return -EINVAL;
3617                gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
3618        }
3619
3620        policy = NFT_SET_POL_PERFORMANCE;
3621        if (nla[NFTA_SET_POLICY] != NULL)
3622                policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
3623
3624        if (nla[NFTA_SET_DESC] != NULL) {
3625                err = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);
3626                if (err < 0)
3627                        return err;
3628        }
3629
3630        table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask);
3631        if (IS_ERR(table)) {
3632                NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3633                return PTR_ERR(table);
3634        }
3635
3636        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
3637
3638        set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
3639        if (IS_ERR(set)) {
3640                if (PTR_ERR(set) != -ENOENT) {
3641                        NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3642                        return PTR_ERR(set);
3643                }
3644        } else {
3645                if (nlh->nlmsg_flags & NLM_F_EXCL) {
3646                        NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3647                        return -EEXIST;
3648                }
3649                if (nlh->nlmsg_flags & NLM_F_REPLACE)
3650                        return -EOPNOTSUPP;
3651
3652                return 0;
3653        }
3654
3655        if (!(nlh->nlmsg_flags & NLM_F_CREATE))
3656                return -ENOENT;
3657
3658        ops = nft_select_set_ops(&ctx, nla, &desc, policy);
3659        if (IS_ERR(ops))
3660                return PTR_ERR(ops);
3661
3662        udlen = 0;
3663        if (nla[NFTA_SET_USERDATA])
3664                udlen = nla_len(nla[NFTA_SET_USERDATA]);
3665
3666        size = 0;
3667        if (ops->privsize != NULL)
3668                size = ops->privsize(nla, &desc);
3669
3670        set = kvzalloc(sizeof(*set) + size + udlen, GFP_KERNEL);
3671        if (!set) {
3672                err = -ENOMEM;
3673                goto err1;
3674        }
3675
3676        name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);
3677        if (!name) {
3678                err = -ENOMEM;
3679                goto err2;
3680        }
3681
3682        err = nf_tables_set_alloc_name(&ctx, set, name);
3683        kfree(name);
3684        if (err < 0)
3685                goto err2;
3686
3687        udata = NULL;
3688        if (udlen) {
3689                udata = set->data + size;
3690                nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
3691        }
3692
3693        INIT_LIST_HEAD(&set->bindings);
3694        set->table = table;
3695        write_pnet(&set->net, net);
3696        set->ops   = ops;
3697        set->ktype = ktype;
3698        set->klen  = desc.klen;
3699        set->dtype = dtype;
3700        set->objtype = objtype;
3701        set->dlen  = desc.dlen;
3702        set->flags = flags;
3703        set->size  = desc.size;
3704        set->policy = policy;
3705        set->udlen  = udlen;
3706        set->udata  = udata;
3707        set->timeout = timeout;
3708        set->gc_int = gc_int;
3709        set->handle = nf_tables_alloc_handle(table);
3710
3711        err = ops->init(set, &desc, nla);
3712        if (err < 0)
3713                goto err3;
3714
3715        err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
3716        if (err < 0)
3717                goto err4;
3718
3719        list_add_tail_rcu(&set->list, &table->sets);
3720        table->use++;
3721        return 0;
3722
3723err4:
3724        ops->destroy(set);
3725err3:
3726        kfree(set->name);
3727err2:
3728        kvfree(set);
3729err1:
3730        module_put(to_set_type(ops)->owner);
3731        return err;
3732}
3733
3734static void nft_set_destroy(struct nft_set *set)
3735{
3736        if (WARN_ON(set->use > 0))
3737                return;
3738
3739        set->ops->destroy(set);
3740        module_put(to_set_type(set->ops)->owner);
3741        kfree(set->name);
3742        kvfree(set);
3743}
3744
3745static int nf_tables_delset(struct net *net, struct sock *nlsk,
3746                            struct sk_buff *skb, const struct nlmsghdr *nlh,
3747                            const struct nlattr * const nla[],
3748                            struct netlink_ext_ack *extack)
3749{
3750        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3751        u8 genmask = nft_genmask_next(net);
3752        const struct nlattr *attr;
3753        struct nft_set *set;
3754        struct nft_ctx ctx;
3755        int err;
3756
3757        if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3758                return -EAFNOSUPPORT;
3759        if (nla[NFTA_SET_TABLE] == NULL)
3760                return -EINVAL;
3761
3762        err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3763                                        genmask);
3764        if (err < 0)
3765                return err;
3766
3767        if (nla[NFTA_SET_HANDLE]) {
3768                attr = nla[NFTA_SET_HANDLE];
3769                set = nft_set_lookup_byhandle(ctx.table, attr, genmask);
3770        } else {
3771                attr = nla[NFTA_SET_NAME];
3772                set = nft_set_lookup(ctx.table, attr, genmask);
3773        }
3774
3775        if (IS_ERR(set)) {
3776                NL_SET_BAD_ATTR(extack, attr);
3777                return PTR_ERR(set);
3778        }
3779        if (set->use ||
3780            (nlh->nlmsg_flags & NLM_F_NONREC && atomic_read(&set->nelems) > 0)) {
3781                NL_SET_BAD_ATTR(extack, attr);
3782                return -EBUSY;
3783        }
3784
3785        return nft_delset(&ctx, set);
3786}
3787
3788static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
3789                                        struct nft_set *set,
3790                                        const struct nft_set_iter *iter,
3791                                        struct nft_set_elem *elem)
3792{
3793        const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3794        enum nft_registers dreg;
3795
3796        dreg = nft_type_to_reg(set->dtype);
3797        return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
3798                                           set->dtype == NFT_DATA_VERDICT ?
3799                                           NFT_DATA_VERDICT : NFT_DATA_VALUE,
3800                                           set->dlen);
3801}
3802
3803int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
3804                       struct nft_set_binding *binding)
3805{
3806        struct nft_set_binding *i;
3807        struct nft_set_iter iter;
3808
3809        if (set->use == UINT_MAX)
3810                return -EOVERFLOW;
3811
3812        if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
3813                return -EBUSY;
3814
3815        if (binding->flags & NFT_SET_MAP) {
3816                /* If the set is already bound to the same chain all
3817                 * jumps are already validated for that chain.
3818                 */
3819                list_for_each_entry(i, &set->bindings, list) {
3820                        if (i->flags & NFT_SET_MAP &&
3821                            i->chain == binding->chain)
3822                                goto bind;
3823                }
3824
3825                iter.genmask    = nft_genmask_next(ctx->net);
3826                iter.skip       = 0;
3827                iter.count      = 0;
3828                iter.err        = 0;
3829                iter.fn         = nf_tables_bind_check_setelem;
3830
3831                set->ops->walk(ctx, set, &iter);
3832                if (iter.err < 0)
3833                        return iter.err;
3834        }
3835bind:
3836        binding->chain = ctx->chain;
3837        list_add_tail_rcu(&binding->list, &set->bindings);
3838        nft_set_trans_bind(ctx, set);
3839        set->use++;
3840
3841        return 0;
3842}
3843EXPORT_SYMBOL_GPL(nf_tables_bind_set);
3844
3845static void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
3846                                 struct nft_set_binding *binding, bool event)
3847{
3848        list_del_rcu(&binding->list);
3849
3850        if (list_empty(&set->bindings) && nft_set_is_anonymous(set)) {
3851                list_del_rcu(&set->list);
3852                if (event)
3853                        nf_tables_set_notify(ctx, set, NFT_MSG_DELSET,
3854                                             GFP_KERNEL);
3855        }
3856}
3857
3858void nf_tables_deactivate_set(const struct nft_ctx *ctx, struct nft_set *set,
3859                              struct nft_set_binding *binding,
3860                              enum nft_trans_phase phase)
3861{
3862        switch (phase) {
3863        case NFT_TRANS_PREPARE:
3864                set->use--;
3865                return;
3866        case NFT_TRANS_ABORT:
3867        case NFT_TRANS_RELEASE:
3868                set->use--;
3869                /* fall through */
3870        default:
3871                nf_tables_unbind_set(ctx, set, binding,
3872                                     phase == NFT_TRANS_COMMIT);
3873        }
3874}
3875EXPORT_SYMBOL_GPL(nf_tables_deactivate_set);
3876
3877void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
3878{
3879        if (list_empty(&set->bindings) && nft_set_is_anonymous(set))
3880                nft_set_destroy(set);
3881}
3882EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
3883
3884const struct nft_set_ext_type nft_set_ext_types[] = {
3885        [NFT_SET_EXT_KEY]               = {
3886                .align  = __alignof__(u32),
3887        },
3888        [NFT_SET_EXT_DATA]              = {
3889                .align  = __alignof__(u32),
3890        },
3891        [NFT_SET_EXT_EXPR]              = {
3892                .align  = __alignof__(struct nft_expr),
3893        },
3894        [NFT_SET_EXT_OBJREF]            = {
3895                .len    = sizeof(struct nft_object *),
3896                .align  = __alignof__(struct nft_object *),
3897        },
3898        [NFT_SET_EXT_FLAGS]             = {
3899                .len    = sizeof(u8),
3900                .align  = __alignof__(u8),
3901        },
3902        [NFT_SET_EXT_TIMEOUT]           = {
3903                .len    = sizeof(u64),
3904                .align  = __alignof__(u64),
3905        },
3906        [NFT_SET_EXT_EXPIRATION]        = {
3907                .len    = sizeof(u64),
3908                .align  = __alignof__(u64),
3909        },
3910        [NFT_SET_EXT_USERDATA]          = {
3911                .len    = sizeof(struct nft_userdata),
3912                .align  = __alignof__(struct nft_userdata),
3913        },
3914};
3915EXPORT_SYMBOL_GPL(nft_set_ext_types);
3916
3917/*
3918 * Set elements
3919 */
3920
3921static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
3922        [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
3923        [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
3924        [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
3925        [NFTA_SET_ELEM_TIMEOUT]         = { .type = NLA_U64 },
3926        [NFTA_SET_ELEM_EXPIRATION]      = { .type = NLA_U64 },
3927        [NFTA_SET_ELEM_USERDATA]        = { .type = NLA_BINARY,
3928                                            .len = NFT_USERDATA_MAXLEN },
3929        [NFTA_SET_ELEM_EXPR]            = { .type = NLA_NESTED },
3930        [NFTA_SET_ELEM_OBJREF]          = { .type = NLA_STRING },
3931};
3932
3933static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
3934        [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING,
3935                                            .len = NFT_TABLE_MAXNAMELEN - 1 },
3936        [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING,
3937                                            .len = NFT_SET_MAXNAMELEN - 1 },
3938        [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
3939        [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
3940};
3941
3942static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx, struct net *net,
3943                                      const struct sk_buff *skb,
3944                                      const struct nlmsghdr *nlh,
3945                                      const struct nlattr * const nla[],
3946                                      struct netlink_ext_ack *extack,
3947                                      u8 genmask)
3948{
3949        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3950        int family = nfmsg->nfgen_family;
3951        struct nft_table *table;
3952
3953        table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
3954                                 genmask);
3955        if (IS_ERR(table)) {
3956                NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
3957                return PTR_ERR(table);
3958        }
3959
3960        nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3961        return 0;
3962}
3963
3964static int nf_tables_fill_setelem(struct sk_buff *skb,
3965                                  const struct nft_set *set,
3966                                  const struct nft_set_elem *elem)
3967{
3968        const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3969        unsigned char *b = skb_tail_pointer(skb);
3970        struct nlattr *nest;
3971
3972        nest = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
3973        if (nest == NULL)
3974                goto nla_put_failure;
3975
3976        if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
3977                          NFT_DATA_VALUE, set->klen) < 0)
3978                goto nla_put_failure;
3979
3980        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
3981            nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
3982                          set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
3983                          set->dlen) < 0)
3984                goto nla_put_failure;
3985
3986        if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR) &&
3987            nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, nft_set_ext_expr(ext)) < 0)
3988                goto nla_put_failure;
3989
3990        if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
3991            nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
3992                           (*nft_set_ext_obj(ext))->key.name) < 0)
3993                goto nla_put_failure;
3994
3995        if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
3996            nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
3997                         htonl(*nft_set_ext_flags(ext))))
3998                goto nla_put_failure;
3999
4000        if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
4001            nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
4002                         nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
4003                         NFTA_SET_ELEM_PAD))
4004                goto nla_put_failure;
4005
4006        if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4007                u64 expires, now = get_jiffies_64();
4008
4009                expires = *nft_set_ext_expiration(ext);
4010                if (time_before64(now, expires))
4011                        expires -= now;
4012                else
4013                        expires = 0;
4014
4015                if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
4016                                 nf_jiffies64_to_msecs(expires),
4017                                 NFTA_SET_ELEM_PAD))
4018                        goto nla_put_failure;
4019        }
4020
4021        if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
4022                struct nft_userdata *udata;
4023
4024                udata = nft_set_ext_userdata(ext);
4025                if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
4026                            udata->len + 1, udata->data))
4027                        goto nla_put_failure;
4028        }
4029
4030        nla_nest_end(skb, nest);
4031        return 0;
4032
4033nla_put_failure:
4034        nlmsg_trim(skb, b);
4035        return -EMSGSIZE;
4036}
4037
4038struct nft_set_dump_args {
4039        const struct netlink_callback   *cb;
4040        struct nft_set_iter             iter;
4041        struct sk_buff                  *skb;
4042};
4043
4044static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
4045                                  struct nft_set *set,
4046                                  const struct nft_set_iter *iter,
4047                                  struct nft_set_elem *elem)
4048{
4049        struct nft_set_dump_args *args;
4050
4051        args = container_of(iter, struct nft_set_dump_args, iter);
4052        return nf_tables_fill_setelem(args->skb, set, elem);
4053}
4054
4055struct nft_set_dump_ctx {
4056        const struct nft_set    *set;
4057        struct nft_ctx          ctx;
4058};
4059
4060static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
4061{
4062        struct nft_set_dump_ctx *dump_ctx = cb->data;
4063        struct net *net = sock_net(skb->sk);
4064        struct nft_table *table;
4065        struct nft_set *set;
4066        struct nft_set_dump_args args;
4067        bool set_found = false;
4068        struct nfgenmsg *nfmsg;
4069        struct nlmsghdr *nlh;
4070        struct nlattr *nest;
4071        u32 portid, seq;
4072        int event;
4073
4074        rcu_read_lock();
4075        list_for_each_entry_rcu(table, &net->nft.tables, list) {
4076                if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
4077                    dump_ctx->ctx.family != table->family)
4078                        continue;
4079
4080                if (table != dump_ctx->ctx.table)
4081                        continue;
4082
4083                list_for_each_entry_rcu(set, &table->sets, list) {
4084                        if (set == dump_ctx->set) {
4085                                set_found = true;
4086                                break;
4087                        }
4088                }
4089                break;
4090        }
4091
4092        if (!set_found) {
4093                rcu_read_unlock();
4094                return -ENOENT;
4095        }
4096
4097        event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
4098        portid = NETLINK_CB(cb->skb).portid;
4099        seq    = cb->nlh->nlmsg_seq;
4100
4101        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4102                        NLM_F_MULTI);
4103        if (nlh == NULL)
4104                goto nla_put_failure;
4105
4106        nfmsg = nlmsg_data(nlh);
4107        nfmsg->nfgen_family = table->family;
4108        nfmsg->version      = NFNETLINK_V0;
4109        nfmsg->res_id       = htons(net->nft.base_seq & 0xffff);
4110
4111        if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
4112                goto nla_put_failure;
4113        if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
4114                goto nla_put_failure;
4115
4116        nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4117        if (nest == NULL)
4118                goto nla_put_failure;
4119
4120        args.cb                 = cb;
4121        args.skb                = skb;
4122        args.iter.genmask       = nft_genmask_cur(net);
4123        args.iter.skip          = cb->args[0];
4124        args.iter.count         = 0;
4125        args.iter.err           = 0;
4126        args.iter.fn            = nf_tables_dump_setelem;
4127        set->ops->walk(&dump_ctx->ctx, set, &args.iter);
4128        rcu_read_unlock();
4129
4130        nla_nest_end(skb, nest);
4131        nlmsg_end(skb, nlh);
4132
4133        if (args.iter.err && args.iter.err != -EMSGSIZE)
4134                return args.iter.err;
4135        if (args.iter.count == cb->args[0])
4136                return 0;
4137
4138        cb->args[0] = args.iter.count;
4139        return skb->len;
4140
4141nla_put_failure:
4142        rcu_read_unlock();
4143        return -ENOSPC;
4144}
4145
4146static int nf_tables_dump_set_start(struct netlink_callback *cb)
4147{
4148        struct nft_set_dump_ctx *dump_ctx = cb->data;
4149
4150        cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
4151
4152        return cb->data ? 0 : -ENOMEM;
4153}
4154
4155static int nf_tables_dump_set_done(struct netlink_callback *cb)
4156{
4157        kfree(cb->data);
4158        return 0;
4159}
4160
4161static int nf_tables_fill_setelem_info(struct sk_buff *skb,
4162                                       const struct nft_ctx *ctx, u32 seq,
4163                                       u32 portid, int event, u16 flags,
4164                                       const struct nft_set *set,
4165                                       const struct nft_set_elem *elem)
4166{
4167        struct nfgenmsg *nfmsg;
4168        struct nlmsghdr *nlh;
4169        struct nlattr *nest;
4170        int err;
4171
4172        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4173        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4174                        flags);
4175        if (nlh == NULL)
4176                goto nla_put_failure;
4177
4178        nfmsg = nlmsg_data(nlh);
4179        nfmsg->nfgen_family     = ctx->family;
4180        nfmsg->version          = NFNETLINK_V0;
4181        nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
4182
4183        if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4184                goto nla_put_failure;
4185        if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4186                goto nla_put_failure;
4187
4188        nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4189        if (nest == NULL)
4190                goto nla_put_failure;
4191
4192        err = nf_tables_fill_setelem(skb, set, elem);
4193        if (err < 0)
4194                goto nla_put_failure;
4195
4196        nla_nest_end(skb, nest);
4197
4198        nlmsg_end(skb, nlh);
4199        return 0;
4200
4201nla_put_failure:
4202        nlmsg_trim(skb, nlh);
4203        return -1;
4204}
4205
4206static int nft_setelem_parse_flags(const struct nft_set *set,
4207                                   const struct nlattr *attr, u32 *flags)
4208{
4209        if (attr == NULL)
4210                return 0;
4211
4212        *flags = ntohl(nla_get_be32(attr));
4213        if (*flags & ~NFT_SET_ELEM_INTERVAL_END)
4214                return -EINVAL;
4215        if (!(set->flags & NFT_SET_INTERVAL) &&
4216            *flags & NFT_SET_ELEM_INTERVAL_END)
4217                return -EINVAL;
4218
4219        return 0;
4220}
4221
4222static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4223                            const struct nlattr *attr)
4224{
4225        struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4226        struct nft_data_desc desc;
4227        struct nft_set_elem elem;
4228        struct sk_buff *skb;
4229        uint32_t flags = 0;
4230        void *priv;
4231        int err;
4232
4233        err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4234                                          nft_set_elem_policy, NULL);
4235        if (err < 0)
4236                return err;
4237
4238        if (!nla[NFTA_SET_ELEM_KEY])
4239                return -EINVAL;
4240
4241        err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4242        if (err < 0)
4243                return err;
4244
4245        err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4246                            nla[NFTA_SET_ELEM_KEY]);
4247        if (err < 0)
4248                return err;
4249
4250        err = -EINVAL;
4251        if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4252                return err;
4253
4254        priv = set->ops->get(ctx->net, set, &elem, flags);
4255        if (IS_ERR(priv))
4256                return PTR_ERR(priv);
4257
4258        elem.priv = priv;
4259
4260        err = -ENOMEM;
4261        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
4262        if (skb == NULL)
4263                goto err1;
4264
4265        err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
4266                                          NFT_MSG_NEWSETELEM, 0, set, &elem);
4267        if (err < 0)
4268                goto err2;
4269
4270        err = nfnetlink_unicast(skb, ctx->net, ctx->portid, MSG_DONTWAIT);
4271        /* This avoids a loop in nfnetlink. */
4272        if (err < 0)
4273                goto err1;
4274
4275        return 0;
4276err2:
4277        kfree_skb(skb);
4278err1:
4279        /* this avoids a loop in nfnetlink. */
4280        return err == -EAGAIN ? -ENOBUFS : err;
4281}
4282
4283/* called with rcu_read_lock held */
4284static int nf_tables_getsetelem(struct net *net, struct sock *nlsk,
4285                                struct sk_buff *skb, const struct nlmsghdr *nlh,
4286                                const struct nlattr * const nla[],
4287                                struct netlink_ext_ack *extack)
4288{
4289        u8 genmask = nft_genmask_cur(net);
4290        struct nft_set *set;
4291        struct nlattr *attr;
4292        struct nft_ctx ctx;
4293        int rem, err = 0;
4294
4295        err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4296                                         genmask);
4297        if (err < 0)
4298                return err;
4299
4300        set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4301        if (IS_ERR(set))
4302                return PTR_ERR(set);
4303
4304        if (nlh->nlmsg_flags & NLM_F_DUMP) {
4305                struct netlink_dump_control c = {
4306                        .start = nf_tables_dump_set_start,
4307                        .dump = nf_tables_dump_set,
4308                        .done = nf_tables_dump_set_done,
4309                        .module = THIS_MODULE,
4310                };
4311                struct nft_set_dump_ctx dump_ctx = {
4312                        .set = set,
4313                        .ctx = ctx,
4314                };
4315
4316                c.data = &dump_ctx;
4317                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
4318        }
4319
4320        if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
4321                return -EINVAL;
4322
4323        nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4324                err = nft_get_set_elem(&ctx, set, attr);
4325                if (err < 0)
4326                        break;
4327        }
4328
4329        return err;
4330}
4331
4332static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
4333                                     const struct nft_set *set,
4334                                     const struct nft_set_elem *elem,
4335                                     int event, u16 flags)
4336{
4337        struct net *net = ctx->net;
4338        u32 portid = ctx->portid;
4339        struct sk_buff *skb;
4340        int err;
4341
4342        if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
4343                return;
4344
4345        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
4346        if (skb == NULL)
4347                goto err;
4348
4349        err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
4350                                          set, elem);
4351        if (err < 0) {
4352                kfree_skb(skb);
4353                goto err;
4354        }
4355
4356        nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
4357                       GFP_KERNEL);
4358        return;
4359err:
4360        nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4361}
4362
4363static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
4364                                              int msg_type,
4365                                              struct nft_set *set)
4366{
4367        struct nft_trans *trans;
4368
4369        trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
4370        if (trans == NULL)
4371                return NULL;
4372
4373        nft_trans_elem_set(trans) = set;
4374        return trans;
4375}
4376
4377void *nft_set_elem_init(const struct nft_set *set,
4378                        const struct nft_set_ext_tmpl *tmpl,
4379                        const u32 *key, const u32 *data,
4380                        u64 timeout, u64 expiration, gfp_t gfp)
4381{
4382        struct nft_set_ext *ext;
4383        void *elem;
4384
4385        elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
4386        if (elem == NULL)
4387                return NULL;
4388
4389        ext = nft_set_elem_ext(set, elem);
4390        nft_set_ext_init(ext, tmpl);
4391
4392        memcpy(nft_set_ext_key(ext), key, set->klen);
4393        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4394                memcpy(nft_set_ext_data(ext), data, set->dlen);
4395        if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
4396                *nft_set_ext_expiration(ext) = get_jiffies_64() + expiration;
4397                if (expiration == 0)
4398                        *nft_set_ext_expiration(ext) += timeout;
4399        }
4400        if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
4401                *nft_set_ext_timeout(ext) = timeout;
4402
4403        return elem;
4404}
4405
4406void nft_set_elem_destroy(const struct nft_set *set, void *elem,
4407                          bool destroy_expr)
4408{
4409        struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4410        struct nft_ctx ctx = {
4411                .net    = read_pnet(&set->net),
4412                .family = set->table->family,
4413        };
4414
4415        nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
4416        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4417                nft_data_release(nft_set_ext_data(ext), set->dtype);
4418        if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPR)) {
4419                struct nft_expr *expr = nft_set_ext_expr(ext);
4420
4421                if (expr->ops->destroy_clone) {
4422                        expr->ops->destroy_clone(&ctx, expr);
4423                        module_put(expr->ops->type->owner);
4424                } else {
4425                        nf_tables_expr_destroy(&ctx, expr);
4426                }
4427        }
4428        if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4429                (*nft_set_ext_obj(ext))->use--;
4430        kfree(elem);
4431}
4432EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
4433
4434/* Only called from commit path, nft_set_elem_deactivate() already deals with
4435 * the refcounting from the preparation phase.
4436 */
4437static void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
4438                                       const struct nft_set *set, void *elem)
4439{
4440        struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4441
4442        if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR))
4443                nf_tables_expr_destroy(ctx, nft_set_ext_expr(ext));
4444        kfree(elem);
4445}
4446
4447static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4448                            const struct nlattr *attr, u32 nlmsg_flags)
4449{
4450        struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4451        u8 genmask = nft_genmask_next(ctx->net);
4452        struct nft_data_desc d1, d2;
4453        struct nft_set_ext_tmpl tmpl;
4454        struct nft_set_ext *ext, *ext2;
4455        struct nft_set_elem elem;
4456        struct nft_set_binding *binding;
4457        struct nft_object *obj = NULL;
4458        struct nft_userdata *udata;
4459        struct nft_data data;
4460        enum nft_registers dreg;
4461        struct nft_trans *trans;
4462        u32 flags = 0;
4463        u64 timeout;
4464        u64 expiration;
4465        u8 ulen;
4466        int err;
4467
4468        err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4469                                          nft_set_elem_policy, NULL);
4470        if (err < 0)
4471                return err;
4472
4473        if (nla[NFTA_SET_ELEM_KEY] == NULL)
4474                return -EINVAL;
4475
4476        nft_set_ext_prepare(&tmpl);
4477
4478        err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4479        if (err < 0)
4480                return err;
4481        if (flags != 0)
4482                nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4483
4484        if (set->flags & NFT_SET_MAP) {
4485                if (nla[NFTA_SET_ELEM_DATA] == NULL &&
4486                    !(flags & NFT_SET_ELEM_INTERVAL_END))
4487                        return -EINVAL;
4488                if (nla[NFTA_SET_ELEM_DATA] != NULL &&
4489                    flags & NFT_SET_ELEM_INTERVAL_END)
4490                        return -EINVAL;
4491        } else {
4492                if (nla[NFTA_SET_ELEM_DATA] != NULL)
4493                        return -EINVAL;
4494        }
4495
4496        timeout = 0;
4497        if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
4498                if (!(set->flags & NFT_SET_TIMEOUT))
4499                        return -EINVAL;
4500                err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
4501                                            &timeout);
4502                if (err)
4503                        return err;
4504        } else if (set->flags & NFT_SET_TIMEOUT) {
4505                timeout = set->timeout;
4506        }
4507
4508        expiration = 0;
4509        if (nla[NFTA_SET_ELEM_EXPIRATION] != NULL) {
4510                if (!(set->flags & NFT_SET_TIMEOUT))
4511                        return -EINVAL;
4512                err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_EXPIRATION],
4513                                            &expiration);
4514                if (err)
4515                        return err;
4516        }
4517
4518        err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &d1,
4519                            nla[NFTA_SET_ELEM_KEY]);
4520        if (err < 0)
4521                goto err1;
4522        err = -EINVAL;
4523        if (d1.type != NFT_DATA_VALUE || d1.len != set->klen)
4524                goto err2;
4525
4526        nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, d1.len);
4527        if (timeout > 0) {
4528                nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
4529                if (timeout != set->timeout)
4530                        nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
4531        }
4532
4533        if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
4534                if (!(set->flags & NFT_SET_OBJECT)) {
4535                        err = -EINVAL;
4536                        goto err2;
4537                }
4538                obj = nft_obj_lookup(ctx->net, ctx->table,
4539                                     nla[NFTA_SET_ELEM_OBJREF],
4540                                     set->objtype, genmask);
4541                if (IS_ERR(obj)) {
4542                        err = PTR_ERR(obj);
4543                        goto err2;
4544                }
4545                nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
4546        }
4547
4548        if (nla[NFTA_SET_ELEM_DATA] != NULL) {
4549                err = nft_data_init(ctx, &data, sizeof(data), &d2,
4550                                    nla[NFTA_SET_ELEM_DATA]);
4551                if (err < 0)
4552                        goto err2;
4553
4554                err = -EINVAL;
4555                if (set->dtype != NFT_DATA_VERDICT && d2.len != set->dlen)
4556                        goto err3;
4557
4558                dreg = nft_type_to_reg(set->dtype);
4559                list_for_each_entry(binding, &set->bindings, list) {
4560                        struct nft_ctx bind_ctx = {
4561                                .net    = ctx->net,
4562                                .family = ctx->family,
4563                                .table  = ctx->table,
4564                                .chain  = (struct nft_chain *)binding->chain,
4565                        };
4566
4567                        if (!(binding->flags & NFT_SET_MAP))
4568                                continue;
4569
4570                        err = nft_validate_register_store(&bind_ctx, dreg,
4571                                                          &data,
4572                                                          d2.type, d2.len);
4573                        if (err < 0)
4574                                goto err3;
4575
4576                        if (d2.type == NFT_DATA_VERDICT &&
4577                            (data.verdict.code == NFT_GOTO ||
4578                             data.verdict.code == NFT_JUMP))
4579                                nft_validate_state_update(ctx->net,
4580                                                          NFT_VALIDATE_NEED);
4581                }
4582
4583                nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, d2.len);
4584        }
4585
4586        /* The full maximum length of userdata can exceed the maximum
4587         * offset value (U8_MAX) for following extensions, therefor it
4588         * must be the last extension added.
4589         */
4590        ulen = 0;
4591        if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
4592                ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
4593                if (ulen > 0)
4594                        nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
4595                                               ulen);
4596        }
4597
4598        err = -ENOMEM;
4599        elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, data.data,
4600                                      timeout, expiration, GFP_KERNEL);
4601        if (elem.priv == NULL)
4602                goto err3;
4603
4604        ext = nft_set_elem_ext(set, elem.priv);
4605        if (flags)
4606                *nft_set_ext_flags(ext) = flags;
4607        if (ulen > 0) {
4608                udata = nft_set_ext_userdata(ext);
4609                udata->len = ulen - 1;
4610                nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
4611        }
4612        if (obj) {
4613                *nft_set_ext_obj(ext) = obj;
4614                obj->use++;
4615        }
4616
4617        trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
4618        if (trans == NULL)
4619                goto err4;
4620
4621        ext->genmask = nft_genmask_cur(ctx->net) | NFT_SET_ELEM_BUSY_MASK;
4622        err = set->ops->insert(ctx->net, set, &elem, &ext2);
4623        if (err) {
4624                if (err == -EEXIST) {
4625                        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
4626                            nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
4627                            nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
4628                            nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF)) {
4629                                err = -EBUSY;
4630                                goto err5;
4631                        }
4632                        if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
4633                             nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
4634                             memcmp(nft_set_ext_data(ext),
4635                                    nft_set_ext_data(ext2), set->dlen) != 0) ||
4636                            (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
4637                             nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
4638                             *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
4639                                err = -EBUSY;
4640                        else if (!(nlmsg_flags & NLM_F_EXCL))
4641                                err = 0;
4642                }
4643                goto err5;
4644        }
4645
4646        if (set->size &&
4647            !atomic_add_unless(&set->nelems, 1, set->size + set->ndeact)) {
4648                err = -ENFILE;
4649                goto err6;
4650        }
4651
4652        nft_trans_elem(trans) = elem;
4653        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4654        return 0;
4655
4656err6:
4657        set->ops->remove(ctx->net, set, &elem);
4658err5:
4659        kfree(trans);
4660err4:
4661        if (obj)
4662                obj->use--;
4663        kfree(elem.priv);
4664err3:
4665        if (nla[NFTA_SET_ELEM_DATA] != NULL)
4666                nft_data_release(&data, d2.type);
4667err2:
4668        nft_data_release(&elem.key.val, d1.type);
4669err1:
4670        return err;
4671}
4672
4673static int nf_tables_newsetelem(struct net *net, struct sock *nlsk,
4674                                struct sk_buff *skb, const struct nlmsghdr *nlh,
4675                                const struct nlattr * const nla[],
4676                                struct netlink_ext_ack *extack)
4677{
4678        u8 genmask = nft_genmask_next(net);
4679        const struct nlattr *attr;
4680        struct nft_set *set;
4681        struct nft_ctx ctx;
4682        int rem, err;
4683
4684        if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
4685                return -EINVAL;
4686
4687        err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4688                                         genmask);
4689        if (err < 0)
4690                return err;
4691
4692        set = nft_set_lookup_global(net, ctx.table, nla[NFTA_SET_ELEM_LIST_SET],
4693                                    nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
4694        if (IS_ERR(set))
4695                return PTR_ERR(set);
4696
4697        if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4698                return -EBUSY;
4699
4700        nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4701                err = nft_add_set_elem(&ctx, set, attr, nlh->nlmsg_flags);
4702                if (err < 0)
4703                        return err;
4704        }
4705
4706        if (net->nft.validate_state == NFT_VALIDATE_DO)
4707                return nft_table_validate(net, ctx.table);
4708
4709        return 0;
4710}
4711
4712/**
4713 *      nft_data_hold - hold a nft_data item
4714 *
4715 *      @data: struct nft_data to release
4716 *      @type: type of data
4717 *
4718 *      Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
4719 *      NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
4720 *      NFT_GOTO verdicts. This function must be called on active data objects
4721 *      from the second phase of the commit protocol.
4722 */
4723void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
4724{
4725        if (type == NFT_DATA_VERDICT) {
4726                switch (data->verdict.code) {
4727                case NFT_JUMP:
4728                case NFT_GOTO:
4729                        data->verdict.chain->use++;
4730                        break;
4731                }
4732        }
4733}
4734
4735static void nft_set_elem_activate(const struct net *net,
4736                                  const struct nft_set *set,
4737                                  struct nft_set_elem *elem)
4738{
4739        const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4740
4741        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4742                nft_data_hold(nft_set_ext_data(ext), set->dtype);
4743        if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4744                (*nft_set_ext_obj(ext))->use++;
4745}
4746
4747static void nft_set_elem_deactivate(const struct net *net,
4748                                    const struct nft_set *set,
4749                                    struct nft_set_elem *elem)
4750{
4751        const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4752
4753        if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4754                nft_data_release(nft_set_ext_data(ext), set->dtype);
4755        if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4756                (*nft_set_ext_obj(ext))->use--;
4757}
4758
4759static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
4760                           const struct nlattr *attr)
4761{
4762        struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4763        struct nft_set_ext_tmpl tmpl;
4764        struct nft_data_desc desc;
4765        struct nft_set_elem elem;
4766        struct nft_set_ext *ext;
4767        struct nft_trans *trans;
4768        u32 flags = 0;
4769        void *priv;
4770        int err;
4771
4772        err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
4773                                          nft_set_elem_policy, NULL);
4774        if (err < 0)
4775                goto err1;
4776
4777        err = -EINVAL;
4778        if (nla[NFTA_SET_ELEM_KEY] == NULL)
4779                goto err1;
4780
4781        nft_set_ext_prepare(&tmpl);
4782
4783        err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4784        if (err < 0)
4785                return err;
4786        if (flags != 0)
4787                nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4788
4789        err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4790                            nla[NFTA_SET_ELEM_KEY]);
4791        if (err < 0)
4792                goto err1;
4793
4794        err = -EINVAL;
4795        if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4796                goto err2;
4797
4798        nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, desc.len);
4799
4800        err = -ENOMEM;
4801        elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, NULL, 0,
4802                                      0, GFP_KERNEL);
4803        if (elem.priv == NULL)
4804                goto err2;
4805
4806        ext = nft_set_elem_ext(set, elem.priv);
4807        if (flags)
4808                *nft_set_ext_flags(ext) = flags;
4809
4810        trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
4811        if (trans == NULL) {
4812                err = -ENOMEM;
4813                goto err3;
4814        }
4815
4816        priv = set->ops->deactivate(ctx->net, set, &elem);
4817        if (priv == NULL) {
4818                err = -ENOENT;
4819                goto err4;
4820        }
4821        kfree(elem.priv);
4822        elem.priv = priv;
4823
4824        nft_set_elem_deactivate(ctx->net, set, &elem);
4825
4826        nft_trans_elem(trans) = elem;
4827        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4828        return 0;
4829
4830err4:
4831        kfree(trans);
4832err3:
4833        kfree(elem.priv);
4834err2:
4835        nft_data_release(&elem.key.val, desc.type);
4836err1:
4837        return err;
4838}
4839
4840static int nft_flush_set(const struct nft_ctx *ctx,
4841                         struct nft_set *set,
4842                         const struct nft_set_iter *iter,
4843                         struct nft_set_elem *elem)
4844{
4845        struct nft_trans *trans;
4846        int err;
4847
4848        trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
4849                                    sizeof(struct nft_trans_elem), GFP_ATOMIC);
4850        if (!trans)
4851                return -ENOMEM;
4852
4853        if (!set->ops->flush(ctx->net, set, elem->priv)) {
4854                err = -ENOENT;
4855                goto err1;
4856        }
4857        set->ndeact++;
4858
4859        nft_set_elem_deactivate(ctx->net, set, elem);
4860        nft_trans_elem_set(trans) = set;
4861        nft_trans_elem(trans) = *elem;
4862        list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4863
4864        return 0;
4865err1:
4866        kfree(trans);
4867        return err;
4868}
4869
4870static int nf_tables_delsetelem(struct net *net, struct sock *nlsk,
4871                                struct sk_buff *skb, const struct nlmsghdr *nlh,
4872                                const struct nlattr * const nla[],
4873                                struct netlink_ext_ack *extack)
4874{
4875        u8 genmask = nft_genmask_next(net);
4876        const struct nlattr *attr;
4877        struct nft_set *set;
4878        struct nft_ctx ctx;
4879        int rem, err = 0;
4880
4881        err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4882                                         genmask);
4883        if (err < 0)
4884                return err;
4885
4886        set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4887        if (IS_ERR(set))
4888                return PTR_ERR(set);
4889        if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4890                return -EBUSY;
4891
4892        if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL) {
4893                struct nft_set_iter iter = {
4894                        .genmask        = genmask,
4895                        .fn             = nft_flush_set,
4896                };
4897                set->ops->walk(&ctx, set, &iter);
4898
4899                return iter.err;
4900        }
4901
4902        nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4903                err = nft_del_setelem(&ctx, set, attr);
4904                if (err < 0)
4905                        break;
4906
4907                set->ndeact++;
4908        }
4909        return err;
4910}
4911
4912void nft_set_gc_batch_release(struct rcu_head *rcu)
4913{
4914        struct nft_set_gc_batch *gcb;
4915        unsigned int i;
4916
4917        gcb = container_of(rcu, struct nft_set_gc_batch, head.rcu);
4918        for (i = 0; i < gcb->head.cnt; i++)
4919                nft_set_elem_destroy(gcb->head.set, gcb->elems[i], true);
4920        kfree(gcb);
4921}
4922EXPORT_SYMBOL_GPL(nft_set_gc_batch_release);
4923
4924struct nft_set_gc_batch *nft_set_gc_batch_alloc(const struct nft_set *set,
4925                                                gfp_t gfp)
4926{
4927        struct nft_set_gc_batch *gcb;
4928
4929        gcb = kzalloc(sizeof(*gcb), gfp);
4930        if (gcb == NULL)
4931                return gcb;
4932        gcb->head.set = set;
4933        return gcb;
4934}
4935EXPORT_SYMBOL_GPL(nft_set_gc_batch_alloc);
4936
4937/*
4938 * Stateful objects
4939 */
4940
4941/**
4942 *      nft_register_obj- register nf_tables stateful object type
4943 *      @obj: object type
4944 *
4945 *      Registers the object type for use with nf_tables. Returns zero on
4946 *      success or a negative errno code otherwise.
4947 */
4948int nft_register_obj(struct nft_object_type *obj_type)
4949{
4950        if (obj_type->type == NFT_OBJECT_UNSPEC)
4951                return -EINVAL;
4952
4953        nfnl_lock(NFNL_SUBSYS_NFTABLES);
4954        list_add_rcu(&obj_type->list, &nf_tables_objects);
4955        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4956        return 0;
4957}
4958EXPORT_SYMBOL_GPL(nft_register_obj);
4959
4960/**
4961 *      nft_unregister_obj - unregister nf_tables object type
4962 *      @obj: object type
4963 *
4964 *      Unregisters the object type for use with nf_tables.
4965 */
4966void nft_unregister_obj(struct nft_object_type *obj_type)
4967{
4968        nfnl_lock(NFNL_SUBSYS_NFTABLES);
4969        list_del_rcu(&obj_type->list);
4970        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4971}
4972EXPORT_SYMBOL_GPL(nft_unregister_obj);
4973
4974struct nft_object *nft_obj_lookup(const struct net *net,
4975                                  const struct nft_table *table,
4976                                  const struct nlattr *nla, u32 objtype,
4977                                  u8 genmask)
4978{
4979        struct nft_object_hash_key k = { .table = table };
4980        char search[NFT_OBJ_MAXNAMELEN];
4981        struct rhlist_head *tmp, *list;
4982        struct nft_object *obj;
4983
4984        nla_strlcpy(search, nla, sizeof(search));
4985        k.name = search;
4986
4987        WARN_ON_ONCE(!rcu_read_lock_held() &&
4988                     !lockdep_commit_lock_is_held(net));
4989
4990        rcu_read_lock();
4991        list = rhltable_lookup(&nft_objname_ht, &k, nft_objname_ht_params);
4992        if (!list)
4993                goto out;
4994
4995        rhl_for_each_entry_rcu(obj, tmp, list, rhlhead) {
4996                if (objtype == obj->ops->type->type &&
4997                    nft_active_genmask(obj, genmask)) {
4998                        rcu_read_unlock();
4999                        return obj;
5000                }
5001        }
5002out:
5003        rcu_read_unlock();
5004        return ERR_PTR(-ENOENT);
5005}
5006EXPORT_SYMBOL_GPL(nft_obj_lookup);
5007
5008static struct nft_object *nft_obj_lookup_byhandle(const struct nft_table *table,
5009                                                  const struct nlattr *nla,
5010                                                  u32 objtype, u8 genmask)
5011{
5012        struct nft_object *obj;
5013
5014        list_for_each_entry(obj, &table->objects, list) {
5015                if (be64_to_cpu(nla_get_be64(nla)) == obj->handle &&
5016                    objtype == obj->ops->type->type &&
5017                    nft_active_genmask(obj, genmask))
5018                        return obj;
5019        }
5020        return ERR_PTR(-ENOENT);
5021}
5022
5023static const struct nla_policy nft_obj_policy[NFTA_OBJ_MAX + 1] = {
5024        [NFTA_OBJ_TABLE]        = { .type = NLA_STRING,
5025                                    .len = NFT_TABLE_MAXNAMELEN - 1 },
5026        [NFTA_OBJ_NAME]         = { .type = NLA_STRING,
5027                                    .len = NFT_OBJ_MAXNAMELEN - 1 },
5028        [NFTA_OBJ_TYPE]         = { .type = NLA_U32 },
5029        [NFTA_OBJ_DATA]         = { .type = NLA_NESTED },
5030        [NFTA_OBJ_HANDLE]       = { .type = NLA_U64},
5031};
5032
5033static struct nft_object *nft_obj_init(const struct nft_ctx *ctx,
5034                                       const struct nft_object_type *type,
5035                                       const struct nlattr *attr)
5036{
5037        struct nlattr **tb;
5038        const struct nft_object_ops *ops;
5039        struct nft_object *obj;
5040        int err = -ENOMEM;
5041
5042        tb = kmalloc_array(type->maxattr + 1, sizeof(*tb), GFP_KERNEL);
5043        if (!tb)
5044                goto err1;
5045
5046        if (attr) {
5047                err = nla_parse_nested_deprecated(tb, type->maxattr, attr,
5048                                                  type->policy, NULL);
5049                if (err < 0)
5050                        goto err2;
5051        } else {
5052                memset(tb, 0, sizeof(tb[0]) * (type->maxattr + 1));
5053        }
5054
5055        if (type->select_ops) {
5056                ops = type->select_ops(ctx, (const struct nlattr * const *)tb);
5057                if (IS_ERR(ops)) {
5058                        err = PTR_ERR(ops);
5059                        goto err2;
5060                }
5061        } else {
5062                ops = type->ops;
5063        }
5064
5065        err = -ENOMEM;
5066        obj = kzalloc(sizeof(*obj) + ops->size, GFP_KERNEL);
5067        if (!obj)
5068                goto err2;
5069
5070        err = ops->init(ctx, (const struct nlattr * const *)tb, obj);
5071        if (err < 0)
5072                goto err3;
5073
5074        obj->ops = ops;
5075
5076        kfree(tb);
5077        return obj;
5078err3:
5079        kfree(obj);
5080err2:
5081        kfree(tb);
5082err1:
5083        return ERR_PTR(err);
5084}
5085
5086static int nft_object_dump(struct sk_buff *skb, unsigned int attr,
5087                           struct nft_object *obj, bool reset)
5088{
5089        struct nlattr *nest;
5090
5091        nest = nla_nest_start_noflag(skb, attr);
5092        if (!nest)
5093                goto nla_put_failure;
5094        if (obj->ops->dump(skb, obj, reset) < 0)
5095                goto nla_put_failure;
5096        nla_nest_end(skb, nest);
5097        return 0;
5098
5099nla_put_failure:
5100        return -1;
5101}
5102
5103static const struct nft_object_type *__nft_obj_type_get(u32 objtype)
5104{
5105        const struct nft_object_type *type;
5106
5107        list_for_each_entry(type, &nf_tables_objects, list) {
5108                if (objtype == type->type)
5109                        return type;
5110        }
5111        return NULL;
5112}
5113
5114static const struct nft_object_type *
5115nft_obj_type_get(struct net *net, u32 objtype)
5116{
5117        const struct nft_object_type *type;
5118
5119        type = __nft_obj_type_get(objtype);
5120        if (type != NULL && try_module_get(type->owner))
5121                return type;
5122
5123        lockdep_nfnl_nft_mutex_not_held();
5124#ifdef CONFIG_MODULES
5125        if (type == NULL) {
5126                nft_request_module(net, "nft-obj-%u", objtype);
5127                if (__nft_obj_type_get(objtype))
5128                        return ERR_PTR(-EAGAIN);
5129        }
5130#endif
5131        return ERR_PTR(-ENOENT);
5132}
5133
5134static int nf_tables_newobj(struct net *net, struct sock *nlsk,
5135                            struct sk_buff *skb, const struct nlmsghdr *nlh,
5136                            const struct nlattr * const nla[],
5137                            struct netlink_ext_ack *extack)
5138{
5139        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5140        const struct nft_object_type *type;
5141        u8 genmask = nft_genmask_next(net);
5142        int family = nfmsg->nfgen_family;
5143        struct nft_table *table;
5144        struct nft_object *obj;
5145        struct nft_ctx ctx;
5146        u32 objtype;
5147        int err;
5148
5149        if (!nla[NFTA_OBJ_TYPE] ||
5150            !nla[NFTA_OBJ_NAME] ||
5151            !nla[NFTA_OBJ_DATA])
5152                return -EINVAL;
5153
5154        table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5155        if (IS_ERR(table)) {
5156                NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5157                return PTR_ERR(table);
5158        }
5159
5160        objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5161        obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
5162        if (IS_ERR(obj)) {
5163                err = PTR_ERR(obj);
5164                if (err != -ENOENT) {
5165                        NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5166                        return err;
5167                }
5168        } else {
5169                if (nlh->nlmsg_flags & NLM_F_EXCL) {
5170                        NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5171                        return -EEXIST;
5172                }
5173                return 0;
5174        }
5175
5176        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5177
5178        type = nft_obj_type_get(net, objtype);
5179        if (IS_ERR(type))
5180                return PTR_ERR(type);
5181
5182        obj = nft_obj_init(&ctx, type, nla[NFTA_OBJ_DATA]);
5183        if (IS_ERR(obj)) {
5184                err = PTR_ERR(obj);
5185                goto err1;
5186        }
5187        obj->key.table = table;
5188        obj->handle = nf_tables_alloc_handle(table);
5189
5190        obj->key.name = nla_strdup(nla[NFTA_OBJ_NAME], GFP_KERNEL);
5191        if (!obj->key.name) {
5192                err = -ENOMEM;
5193                goto err2;
5194        }
5195
5196        err = nft_trans_obj_add(&ctx, NFT_MSG_NEWOBJ, obj);
5197        if (err < 0)
5198                goto err3;
5199
5200        err = rhltable_insert(&nft_objname_ht, &obj->rhlhead,
5201                              nft_objname_ht_params);
5202        if (err < 0)
5203                goto err4;
5204
5205        list_add_tail_rcu(&obj->list, &table->objects);
5206        table->use++;
5207        return 0;
5208err4:
5209        /* queued in transaction log */
5210        INIT_LIST_HEAD(&obj->list);
5211        return err;
5212err3:
5213        kfree(obj->key.name);
5214err2:
5215        if (obj->ops->destroy)
5216                obj->ops->destroy(&ctx, obj);
5217        kfree(obj);
5218err1:
5219        module_put(type->owner);
5220        return err;
5221}
5222
5223static int nf_tables_fill_obj_info(struct sk_buff *skb, struct net *net,
5224                                   u32 portid, u32 seq, int event, u32 flags,
5225                                   int family, const struct nft_table *table,
5226                                   struct nft_object *obj, bool reset)
5227{
5228        struct nfgenmsg *nfmsg;
5229        struct nlmsghdr *nlh;
5230
5231        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5232        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5233        if (nlh == NULL)
5234                goto nla_put_failure;
5235
5236        nfmsg = nlmsg_data(nlh);
5237        nfmsg->nfgen_family     = family;
5238        nfmsg->version          = NFNETLINK_V0;
5239        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5240
5241        if (nla_put_string(skb, NFTA_OBJ_TABLE, table->name) ||
5242            nla_put_string(skb, NFTA_OBJ_NAME, obj->key.name) ||
5243            nla_put_be32(skb, NFTA_OBJ_TYPE, htonl(obj->ops->type->type)) ||
5244            nla_put_be32(skb, NFTA_OBJ_USE, htonl(obj->use)) ||
5245            nft_object_dump(skb, NFTA_OBJ_DATA, obj, reset) ||
5246            nla_put_be64(skb, NFTA_OBJ_HANDLE, cpu_to_be64(obj->handle),
5247                         NFTA_OBJ_PAD))
5248                goto nla_put_failure;
5249
5250        nlmsg_end(skb, nlh);
5251        return 0;
5252
5253nla_put_failure:
5254        nlmsg_trim(skb, nlh);
5255        return -1;
5256}
5257
5258struct nft_obj_filter {
5259        char            *table;
5260        u32             type;
5261};
5262
5263static int nf_tables_dump_obj(struct sk_buff *skb, struct netlink_callback *cb)
5264{
5265        const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5266        const struct nft_table *table;
5267        unsigned int idx = 0, s_idx = cb->args[0];
5268        struct nft_obj_filter *filter = cb->data;
5269        struct net *net = sock_net(skb->sk);
5270        int family = nfmsg->nfgen_family;
5271        struct nft_object *obj;
5272        bool reset = false;
5273
5274        if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5275                reset = true;
5276
5277        rcu_read_lock();
5278        cb->seq = net->nft.base_seq;
5279
5280        list_for_each_entry_rcu(table, &net->nft.tables, list) {
5281                if (family != NFPROTO_UNSPEC && family != table->family)
5282                        continue;
5283
5284                list_for_each_entry_rcu(obj, &table->objects, list) {
5285                        if (!nft_is_active(net, obj))
5286                                goto cont;
5287                        if (idx < s_idx)
5288                                goto cont;
5289                        if (idx > s_idx)
5290                                memset(&cb->args[1], 0,
5291                                       sizeof(cb->args) - sizeof(cb->args[0]));
5292                        if (filter && filter->table &&
5293                            strcmp(filter->table, table->name))
5294                                goto cont;
5295                        if (filter &&
5296                            filter->type != NFT_OBJECT_UNSPEC &&
5297                            obj->ops->type->type != filter->type)
5298                                goto cont;
5299
5300                        if (nf_tables_fill_obj_info(skb, net, NETLINK_CB(cb->skb).portid,
5301                                                    cb->nlh->nlmsg_seq,
5302                                                    NFT_MSG_NEWOBJ,
5303                                                    NLM_F_MULTI | NLM_F_APPEND,
5304                                                    table->family, table,
5305                                                    obj, reset) < 0)
5306                                goto done;
5307
5308                        nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5309cont:
5310                        idx++;
5311                }
5312        }
5313done:
5314        rcu_read_unlock();
5315
5316        cb->args[0] = idx;
5317        return skb->len;
5318}
5319
5320static int nf_tables_dump_obj_start(struct netlink_callback *cb)
5321{
5322        const struct nlattr * const *nla = cb->data;
5323        struct nft_obj_filter *filter = NULL;
5324
5325        if (nla[NFTA_OBJ_TABLE] || nla[NFTA_OBJ_TYPE]) {
5326                filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5327                if (!filter)
5328                        return -ENOMEM;
5329
5330                if (nla[NFTA_OBJ_TABLE]) {
5331                        filter->table = nla_strdup(nla[NFTA_OBJ_TABLE], GFP_ATOMIC);
5332                        if (!filter->table) {
5333                                kfree(filter);
5334                                return -ENOMEM;
5335                        }
5336                }
5337
5338                if (nla[NFTA_OBJ_TYPE])
5339                        filter->type = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5340        }
5341
5342        cb->data = filter;
5343        return 0;
5344}
5345
5346static int nf_tables_dump_obj_done(struct netlink_callback *cb)
5347{
5348        struct nft_obj_filter *filter = cb->data;
5349
5350        if (filter) {
5351                kfree(filter->table);
5352                kfree(filter);
5353        }
5354
5355        return 0;
5356}
5357
5358/* called with rcu_read_lock held */
5359static int nf_tables_getobj(struct net *net, struct sock *nlsk,
5360                            struct sk_buff *skb, const struct nlmsghdr *nlh,
5361                            const struct nlattr * const nla[],
5362                            struct netlink_ext_ack *extack)
5363{
5364        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5365        u8 genmask = nft_genmask_cur(net);
5366        int family = nfmsg->nfgen_family;
5367        const struct nft_table *table;
5368        struct nft_object *obj;
5369        struct sk_buff *skb2;
5370        bool reset = false;
5371        u32 objtype;
5372        int err;
5373
5374        if (nlh->nlmsg_flags & NLM_F_DUMP) {
5375                struct netlink_dump_control c = {
5376                        .start = nf_tables_dump_obj_start,
5377                        .dump = nf_tables_dump_obj,
5378                        .done = nf_tables_dump_obj_done,
5379                        .module = THIS_MODULE,
5380                        .data = (void *)nla,
5381                };
5382
5383                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5384        }
5385
5386        if (!nla[NFTA_OBJ_NAME] ||
5387            !nla[NFTA_OBJ_TYPE])
5388                return -EINVAL;
5389
5390        table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5391        if (IS_ERR(table)) {
5392                NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5393                return PTR_ERR(table);
5394        }
5395
5396        objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5397        obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
5398        if (IS_ERR(obj)) {
5399                NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5400                return PTR_ERR(obj);
5401        }
5402
5403        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5404        if (!skb2)
5405                return -ENOMEM;
5406
5407        if (NFNL_MSG_TYPE(nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5408                reset = true;
5409
5410        err = nf_tables_fill_obj_info(skb2, net, NETLINK_CB(skb).portid,
5411                                      nlh->nlmsg_seq, NFT_MSG_NEWOBJ, 0,
5412                                      family, table, obj, reset);
5413        if (err < 0)
5414                goto err;
5415
5416        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5417err:
5418        kfree_skb(skb2);
5419        return err;
5420}
5421
5422static void nft_obj_destroy(const struct nft_ctx *ctx, struct nft_object *obj)
5423{
5424        if (obj->ops->destroy)
5425                obj->ops->destroy(ctx, obj);
5426
5427        module_put(obj->ops->type->owner);
5428        kfree(obj->key.name);
5429        kfree(obj);
5430}
5431
5432static int nf_tables_delobj(struct net *net, struct sock *nlsk,
5433                            struct sk_buff *skb, const struct nlmsghdr *nlh,
5434                            const struct nlattr * const nla[],
5435                            struct netlink_ext_ack *extack)
5436{
5437        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5438        u8 genmask = nft_genmask_next(net);
5439        int family = nfmsg->nfgen_family;
5440        const struct nlattr *attr;
5441        struct nft_table *table;
5442        struct nft_object *obj;
5443        struct nft_ctx ctx;
5444        u32 objtype;
5445
5446        if (!nla[NFTA_OBJ_TYPE] ||
5447            (!nla[NFTA_OBJ_NAME] && !nla[NFTA_OBJ_HANDLE]))
5448                return -EINVAL;
5449
5450        table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5451        if (IS_ERR(table)) {
5452                NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5453                return PTR_ERR(table);
5454        }
5455
5456        objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5457        if (nla[NFTA_OBJ_HANDLE]) {
5458                attr = nla[NFTA_OBJ_HANDLE];
5459                obj = nft_obj_lookup_byhandle(table, attr, objtype, genmask);
5460        } else {
5461                attr = nla[NFTA_OBJ_NAME];
5462                obj = nft_obj_lookup(net, table, attr, objtype, genmask);
5463        }
5464
5465        if (IS_ERR(obj)) {
5466                NL_SET_BAD_ATTR(extack, attr);
5467                return PTR_ERR(obj);
5468        }
5469        if (obj->use > 0) {
5470                NL_SET_BAD_ATTR(extack, attr);
5471                return -EBUSY;
5472        }
5473
5474        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5475
5476        return nft_delobj(&ctx, obj);
5477}
5478
5479void nft_obj_notify(struct net *net, const struct nft_table *table,
5480                    struct nft_object *obj, u32 portid, u32 seq, int event,
5481                    int family, int report, gfp_t gfp)
5482{
5483        struct sk_buff *skb;
5484        int err;
5485
5486        if (!report &&
5487            !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
5488                return;
5489
5490        skb = nlmsg_new(NLMSG_GOODSIZE, gfp);
5491        if (skb == NULL)
5492                goto err;
5493
5494        err = nf_tables_fill_obj_info(skb, net, portid, seq, event, 0, family,
5495                                      table, obj, false);
5496        if (err < 0) {
5497                kfree_skb(skb);
5498                goto err;
5499        }
5500
5501        nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, report, gfp);
5502        return;
5503err:
5504        nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
5505}
5506EXPORT_SYMBOL_GPL(nft_obj_notify);
5507
5508static void nf_tables_obj_notify(const struct nft_ctx *ctx,
5509                                 struct nft_object *obj, int event)
5510{
5511        nft_obj_notify(ctx->net, ctx->table, obj, ctx->portid, ctx->seq, event,
5512                       ctx->family, ctx->report, GFP_KERNEL);
5513}
5514
5515/*
5516 * Flow tables
5517 */
5518void nft_register_flowtable_type(struct nf_flowtable_type *type)
5519{
5520        nfnl_lock(NFNL_SUBSYS_NFTABLES);
5521        list_add_tail_rcu(&type->list, &nf_tables_flowtables);
5522        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5523}
5524EXPORT_SYMBOL_GPL(nft_register_flowtable_type);
5525
5526void nft_unregister_flowtable_type(struct nf_flowtable_type *type)
5527{
5528        nfnl_lock(NFNL_SUBSYS_NFTABLES);
5529        list_del_rcu(&type->list);
5530        nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5531}
5532EXPORT_SYMBOL_GPL(nft_unregister_flowtable_type);
5533
5534static const struct nla_policy nft_flowtable_policy[NFTA_FLOWTABLE_MAX + 1] = {
5535        [NFTA_FLOWTABLE_TABLE]          = { .type = NLA_STRING,
5536                                            .len = NFT_NAME_MAXLEN - 1 },
5537        [NFTA_FLOWTABLE_NAME]           = { .type = NLA_STRING,
5538                                            .len = NFT_NAME_MAXLEN - 1 },
5539        [NFTA_FLOWTABLE_HOOK]           = { .type = NLA_NESTED },
5540        [NFTA_FLOWTABLE_HANDLE]         = { .type = NLA_U64 },
5541};
5542
5543struct nft_flowtable *nft_flowtable_lookup(const struct nft_table *table,
5544                                           const struct nlattr *nla, u8 genmask)
5545{
5546        struct nft_flowtable *flowtable;
5547
5548        list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5549                if (!nla_strcmp(nla, flowtable->name) &&
5550                    nft_active_genmask(flowtable, genmask))
5551                        return flowtable;
5552        }
5553        return ERR_PTR(-ENOENT);
5554}
5555EXPORT_SYMBOL_GPL(nft_flowtable_lookup);
5556
5557static struct nft_flowtable *
5558nft_flowtable_lookup_byhandle(const struct nft_table *table,
5559                              const struct nlattr *nla, u8 genmask)
5560{
5561       struct nft_flowtable *flowtable;
5562
5563       list_for_each_entry(flowtable, &table->flowtables, list) {
5564               if (be64_to_cpu(nla_get_be64(nla)) == flowtable->handle &&
5565                   nft_active_genmask(flowtable, genmask))
5566                       return flowtable;
5567       }
5568       return ERR_PTR(-ENOENT);
5569}
5570
5571static int nf_tables_parse_devices(const struct nft_ctx *ctx,
5572                                   const struct nlattr *attr,
5573                                   struct net_device *dev_array[], int *len)
5574{
5575        const struct nlattr *tmp;
5576        struct net_device *dev;
5577        char ifname[IFNAMSIZ];
5578        int rem, n = 0, err;
5579
5580        nla_for_each_nested(tmp, attr, rem) {
5581                if (nla_type(tmp) != NFTA_DEVICE_NAME) {
5582                        err = -EINVAL;
5583                        goto err1;
5584                }
5585
5586                nla_strlcpy(ifname, tmp, IFNAMSIZ);
5587                dev = __dev_get_by_name(ctx->net, ifname);
5588                if (!dev) {
5589                        err = -ENOENT;
5590                        goto err1;
5591                }
5592
5593                dev_array[n++] = dev;
5594                if (n == NFT_FLOWTABLE_DEVICE_MAX) {
5595                        err = -EFBIG;
5596                        goto err1;
5597                }
5598        }
5599        if (!len)
5600                return -EINVAL;
5601
5602        err = 0;
5603err1:
5604        *len = n;
5605        return err;
5606}
5607
5608static const struct nla_policy nft_flowtable_hook_policy[NFTA_FLOWTABLE_HOOK_MAX + 1] = {
5609        [NFTA_FLOWTABLE_HOOK_NUM]       = { .type = NLA_U32 },
5610        [NFTA_FLOWTABLE_HOOK_PRIORITY]  = { .type = NLA_U32 },
5611        [NFTA_FLOWTABLE_HOOK_DEVS]      = { .type = NLA_NESTED },
5612};
5613
5614static int nf_tables_flowtable_parse_hook(const struct nft_ctx *ctx,
5615                                          const struct nlattr *attr,
5616                                          struct nft_flowtable *flowtable)
5617{
5618        struct net_device *dev_array[NFT_FLOWTABLE_DEVICE_MAX];
5619        struct nlattr *tb[NFTA_FLOWTABLE_HOOK_MAX + 1];
5620        struct nf_hook_ops *ops;
5621        int hooknum, priority;
5622        int err, n = 0, i;
5623
5624        err = nla_parse_nested_deprecated(tb, NFTA_FLOWTABLE_HOOK_MAX, attr,
5625                                          nft_flowtable_hook_policy, NULL);
5626        if (err < 0)
5627                return err;
5628
5629        if (!tb[NFTA_FLOWTABLE_HOOK_NUM] ||
5630            !tb[NFTA_FLOWTABLE_HOOK_PRIORITY] ||
5631            !tb[NFTA_FLOWTABLE_HOOK_DEVS])
5632                return -EINVAL;
5633
5634        hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
5635        if (hooknum != NF_NETDEV_INGRESS)
5636                return -EINVAL;
5637
5638        priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
5639
5640        err = nf_tables_parse_devices(ctx, tb[NFTA_FLOWTABLE_HOOK_DEVS],
5641                                      dev_array, &n);
5642        if (err < 0)
5643                return err;
5644
5645        ops = kcalloc(n, sizeof(struct nf_hook_ops), GFP_KERNEL);
5646        if (!ops)
5647                return -ENOMEM;
5648
5649        flowtable->hooknum      = hooknum;
5650        flowtable->priority     = priority;
5651        flowtable->ops          = ops;
5652        flowtable->ops_len      = n;
5653
5654        for (i = 0; i < n; i++) {
5655                flowtable->ops[i].pf            = NFPROTO_NETDEV;
5656                flowtable->ops[i].hooknum       = hooknum;
5657                flowtable->ops[i].priority      = priority;
5658                flowtable->ops[i].priv          = &flowtable->data;
5659                flowtable->ops[i].hook          = flowtable->data.type->hook;
5660                flowtable->ops[i].dev           = dev_array[i];
5661        }
5662
5663        return err;
5664}
5665
5666static const struct nf_flowtable_type *__nft_flowtable_type_get(u8 family)
5667{
5668        const struct nf_flowtable_type *type;
5669
5670        list_for_each_entry(type, &nf_tables_flowtables, list) {
5671                if (family == type->family)
5672                        return type;
5673        }
5674        return NULL;
5675}
5676
5677static const struct nf_flowtable_type *
5678nft_flowtable_type_get(struct net *net, u8 family)
5679{
5680        const struct nf_flowtable_type *type;
5681
5682        type = __nft_flowtable_type_get(family);
5683        if (type != NULL && try_module_get(type->owner))
5684                return type;
5685
5686        lockdep_nfnl_nft_mutex_not_held();
5687#ifdef CONFIG_MODULES
5688        if (type == NULL) {
5689                nft_request_module(net, "nf-flowtable-%u", family);
5690                if (__nft_flowtable_type_get(family))
5691                        return ERR_PTR(-EAGAIN);
5692        }
5693#endif
5694        return ERR_PTR(-ENOENT);
5695}
5696
5697static void nft_unregister_flowtable_net_hooks(struct net *net,
5698                                               struct nft_flowtable *flowtable)
5699{
5700        int i;
5701
5702        for (i = 0; i < flowtable->ops_len; i++) {
5703                if (!flowtable->ops[i].dev)
5704                        continue;
5705
5706                nf_unregister_net_hook(net, &flowtable->ops[i]);
5707        }
5708}
5709
5710static int nf_tables_newflowtable(struct net *net, struct sock *nlsk,
5711                                  struct sk_buff *skb,
5712                                  const struct nlmsghdr *nlh,
5713                                  const struct nlattr * const nla[],
5714                                  struct netlink_ext_ack *extack)
5715{
5716        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5717        const struct nf_flowtable_type *type;
5718        struct nft_flowtable *flowtable, *ft;
5719        u8 genmask = nft_genmask_next(net);
5720        int family = nfmsg->nfgen_family;
5721        struct nft_table *table;
5722        struct nft_ctx ctx;
5723        int err, i, k;
5724
5725        if (!nla[NFTA_FLOWTABLE_TABLE] ||
5726            !nla[NFTA_FLOWTABLE_NAME] ||
5727            !nla[NFTA_FLOWTABLE_HOOK])
5728                return -EINVAL;
5729
5730        table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5731                                 genmask);
5732        if (IS_ERR(table)) {
5733                NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5734                return PTR_ERR(table);
5735        }
5736
5737        flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5738                                         genmask);
5739        if (IS_ERR(flowtable)) {
5740                err = PTR_ERR(flowtable);
5741                if (err != -ENOENT) {
5742                        NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5743                        return err;
5744                }
5745        } else {
5746                if (nlh->nlmsg_flags & NLM_F_EXCL) {
5747                        NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5748                        return -EEXIST;
5749                }
5750
5751                return 0;
5752        }
5753
5754        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5755
5756        flowtable = kzalloc(sizeof(*flowtable), GFP_KERNEL);
5757        if (!flowtable)
5758                return -ENOMEM;
5759
5760        flowtable->table = table;
5761        flowtable->handle = nf_tables_alloc_handle(table);
5762
5763        flowtable->name = nla_strdup(nla[NFTA_FLOWTABLE_NAME], GFP_KERNEL);
5764        if (!flowtable->name) {
5765                err = -ENOMEM;
5766                goto err1;
5767        }
5768
5769        type = nft_flowtable_type_get(net, family);
5770        if (IS_ERR(type)) {
5771                err = PTR_ERR(type);
5772                goto err2;
5773        }
5774
5775        flowtable->data.type = type;
5776        err = type->init(&flowtable->data);
5777        if (err < 0)
5778                goto err3;
5779
5780        err = nf_tables_flowtable_parse_hook(&ctx, nla[NFTA_FLOWTABLE_HOOK],
5781                                             flowtable);
5782        if (err < 0)
5783                goto err4;
5784
5785        for (i = 0; i < flowtable->ops_len; i++) {
5786                if (!flowtable->ops[i].dev)
5787                        continue;
5788
5789                list_for_each_entry(ft, &table->flowtables, list) {
5790                        for (k = 0; k < ft->ops_len; k++) {
5791                                if (!ft->ops[k].dev)
5792                                        continue;
5793
5794                                if (flowtable->ops[i].dev == ft->ops[k].dev &&
5795                                    flowtable->ops[i].pf == ft->ops[k].pf) {
5796                                        err = -EBUSY;
5797                                        goto err5;
5798                                }
5799                        }
5800                }
5801
5802                err = nf_register_net_hook(net, &flowtable->ops[i]);
5803                if (err < 0)
5804                        goto err5;
5805        }
5806
5807        err = nft_trans_flowtable_add(&ctx, NFT_MSG_NEWFLOWTABLE, flowtable);
5808        if (err < 0)
5809                goto err6;
5810
5811        list_add_tail_rcu(&flowtable->list, &table->flowtables);
5812        table->use++;
5813
5814        return 0;
5815err6:
5816        i = flowtable->ops_len;
5817err5:
5818        for (k = i - 1; k >= 0; k--)
5819                nf_unregister_net_hook(net, &flowtable->ops[k]);
5820
5821        kfree(flowtable->ops);
5822err4:
5823        flowtable->data.type->free(&flowtable->data);
5824err3:
5825        module_put(type->owner);
5826err2:
5827        kfree(flowtable->name);
5828err1:
5829        kfree(flowtable);
5830        return err;
5831}
5832
5833static int nf_tables_delflowtable(struct net *net, struct sock *nlsk,
5834                                  struct sk_buff *skb,
5835                                  const struct nlmsghdr *nlh,
5836                                  const struct nlattr * const nla[],
5837                                  struct netlink_ext_ack *extack)
5838{
5839        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5840        u8 genmask = nft_genmask_next(net);
5841        int family = nfmsg->nfgen_family;
5842        struct nft_flowtable *flowtable;
5843        const struct nlattr *attr;
5844        struct nft_table *table;
5845        struct nft_ctx ctx;
5846
5847        if (!nla[NFTA_FLOWTABLE_TABLE] ||
5848            (!nla[NFTA_FLOWTABLE_NAME] &&
5849             !nla[NFTA_FLOWTABLE_HANDLE]))
5850                return -EINVAL;
5851
5852        table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5853                                 genmask);
5854        if (IS_ERR(table)) {
5855                NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5856                return PTR_ERR(table);
5857        }
5858
5859        if (nla[NFTA_FLOWTABLE_HANDLE]) {
5860                attr = nla[NFTA_FLOWTABLE_HANDLE];
5861                flowtable = nft_flowtable_lookup_byhandle(table, attr, genmask);
5862        } else {
5863                attr = nla[NFTA_FLOWTABLE_NAME];
5864                flowtable = nft_flowtable_lookup(table, attr, genmask);
5865        }
5866
5867        if (IS_ERR(flowtable)) {
5868                NL_SET_BAD_ATTR(extack, attr);
5869                return PTR_ERR(flowtable);
5870        }
5871        if (flowtable->use > 0) {
5872                NL_SET_BAD_ATTR(extack, attr);
5873                return -EBUSY;
5874        }
5875
5876        nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5877
5878        return nft_delflowtable(&ctx, flowtable);
5879}
5880
5881static int nf_tables_fill_flowtable_info(struct sk_buff *skb, struct net *net,
5882                                         u32 portid, u32 seq, int event,
5883                                         u32 flags, int family,
5884                                         struct nft_flowtable *flowtable)
5885{
5886        struct nlattr *nest, *nest_devs;
5887        struct nfgenmsg *nfmsg;
5888        struct nlmsghdr *nlh;
5889        int i;
5890
5891        event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5892        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5893        if (nlh == NULL)
5894                goto nla_put_failure;
5895
5896        nfmsg = nlmsg_data(nlh);
5897        nfmsg->nfgen_family     = family;
5898        nfmsg->version          = NFNETLINK_V0;
5899        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5900
5901        if (nla_put_string(skb, NFTA_FLOWTABLE_TABLE, flowtable->table->name) ||
5902            nla_put_string(skb, NFTA_FLOWTABLE_NAME, flowtable->name) ||
5903            nla_put_be32(skb, NFTA_FLOWTABLE_USE, htonl(flowtable->use)) ||
5904            nla_put_be64(skb, NFTA_FLOWTABLE_HANDLE, cpu_to_be64(flowtable->handle),
5905                         NFTA_FLOWTABLE_PAD))
5906                goto nla_put_failure;
5907
5908        nest = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK);
5909        if (!nest)
5910                goto nla_put_failure;
5911        if (nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_NUM, htonl(flowtable->hooknum)) ||
5912            nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_PRIORITY, htonl(flowtable->priority)))
5913                goto nla_put_failure;
5914
5915        nest_devs = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK_DEVS);
5916        if (!nest_devs)
5917                goto nla_put_failure;
5918
5919        for (i = 0; i < flowtable->ops_len; i++) {
5920                const struct net_device *dev = READ_ONCE(flowtable->ops[i].dev);
5921
5922                if (dev &&
5923                    nla_put_string(skb, NFTA_DEVICE_NAME, dev->name))
5924                        goto nla_put_failure;
5925        }
5926        nla_nest_end(skb, nest_devs);
5927        nla_nest_end(skb, nest);
5928
5929        nlmsg_end(skb, nlh);
5930        return 0;
5931
5932nla_put_failure:
5933        nlmsg_trim(skb, nlh);
5934        return -1;
5935}
5936
5937struct nft_flowtable_filter {
5938        char            *table;
5939};
5940
5941static int nf_tables_dump_flowtable(struct sk_buff *skb,
5942                                    struct netlink_callback *cb)
5943{
5944        const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5945        struct nft_flowtable_filter *filter = cb->data;
5946        unsigned int idx = 0, s_idx = cb->args[0];
5947        struct net *net = sock_net(skb->sk);
5948        int family = nfmsg->nfgen_family;
5949        struct nft_flowtable *flowtable;
5950        const struct nft_table *table;
5951
5952        rcu_read_lock();
5953        cb->seq = net->nft.base_seq;
5954
5955        list_for_each_entry_rcu(table, &net->nft.tables, list) {
5956                if (family != NFPROTO_UNSPEC && family != table->family)
5957                        continue;
5958
5959                list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5960                        if (!nft_is_active(net, flowtable))
5961                                goto cont;
5962                        if (idx < s_idx)
5963                                goto cont;
5964                        if (idx > s_idx)
5965                                memset(&cb->args[1], 0,
5966                                       sizeof(cb->args) - sizeof(cb->args[0]));
5967                        if (filter && filter->table &&
5968                            strcmp(filter->table, table->name))
5969                                goto cont;
5970
5971                        if (nf_tables_fill_flowtable_info(skb, net, NETLINK_CB(cb->skb).portid,
5972                                                          cb->nlh->nlmsg_seq,
5973                                                          NFT_MSG_NEWFLOWTABLE,
5974                                                          NLM_F_MULTI | NLM_F_APPEND,
5975                                                          table->family, flowtable) < 0)
5976                                goto done;
5977
5978                        nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5979cont:
5980                        idx++;
5981                }
5982        }
5983done:
5984        rcu_read_unlock();
5985
5986        cb->args[0] = idx;
5987        return skb->len;
5988}
5989
5990static int nf_tables_dump_flowtable_start(struct netlink_callback *cb)
5991{
5992        const struct nlattr * const *nla = cb->data;
5993        struct nft_flowtable_filter *filter = NULL;
5994
5995        if (nla[NFTA_FLOWTABLE_TABLE]) {
5996                filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5997                if (!filter)
5998                        return -ENOMEM;
5999
6000                filter->table = nla_strdup(nla[NFTA_FLOWTABLE_TABLE],
6001                                           GFP_ATOMIC);
6002                if (!filter->table) {
6003                        kfree(filter);
6004                        return -ENOMEM;
6005                }
6006        }
6007
6008        cb->data = filter;
6009        return 0;
6010}
6011
6012static int nf_tables_dump_flowtable_done(struct netlink_callback *cb)
6013{
6014        struct nft_flowtable_filter *filter = cb->data;
6015
6016        if (!filter)
6017                return 0;
6018
6019        kfree(filter->table);
6020        kfree(filter);
6021
6022        return 0;
6023}
6024
6025/* called with rcu_read_lock held */
6026static int nf_tables_getflowtable(struct net *net, struct sock *nlsk,
6027                                  struct sk_buff *skb,
6028                                  const struct nlmsghdr *nlh,
6029                                  const struct nlattr * const nla[],
6030                                  struct netlink_ext_ack *extack)
6031{
6032        const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
6033        u8 genmask = nft_genmask_cur(net);
6034        int family = nfmsg->nfgen_family;
6035        struct nft_flowtable *flowtable;
6036        const struct nft_table *table;
6037        struct sk_buff *skb2;
6038        int err;
6039
6040        if (nlh->nlmsg_flags & NLM_F_DUMP) {
6041                struct netlink_dump_control c = {
6042                        .start = nf_tables_dump_flowtable_start,
6043                        .dump = nf_tables_dump_flowtable,
6044                        .done = nf_tables_dump_flowtable_done,
6045                        .module = THIS_MODULE,
6046                        .data = (void *)nla,
6047                };
6048
6049                return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
6050        }
6051
6052        if (!nla[NFTA_FLOWTABLE_NAME])
6053                return -EINVAL;
6054
6055        table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
6056                                 genmask);
6057        if (IS_ERR(table))
6058                return PTR_ERR(table);
6059
6060        flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
6061                                         genmask);
6062        if (IS_ERR(flowtable))
6063                return PTR_ERR(flowtable);
6064
6065        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6066        if (!skb2)
6067                return -ENOMEM;
6068
6069        err = nf_tables_fill_flowtable_info(skb2, net, NETLINK_CB(skb).portid,
6070                                            nlh->nlmsg_seq,
6071                                            NFT_MSG_NEWFLOWTABLE, 0, family,
6072                                            flowtable);
6073        if (err < 0)
6074                goto err;
6075
6076        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6077err:
6078        kfree_skb(skb2);
6079        return err;
6080}
6081
6082static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
6083                                       struct nft_flowtable *flowtable,
6084                                       int event)
6085{
6086        struct sk_buff *skb;
6087        int err;
6088
6089        if (ctx->report &&
6090            !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
6091                return;
6092
6093        skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6094        if (skb == NULL)
6095                goto err;
6096
6097        err = nf_tables_fill_flowtable_info(skb, ctx->net, ctx->portid,
6098                                            ctx->seq, event, 0,
6099                                            ctx->family, flowtable);
6100        if (err < 0) {
6101                kfree_skb(skb);
6102                goto err;
6103        }
6104
6105        nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
6106                       ctx->report, GFP_KERNEL);
6107        return;
6108err:
6109        nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
6110}
6111
6112static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
6113{
6114        kfree(flowtable->ops);
6115        kfree(flowtable->name);
6116        flowtable->data.type->free(&flowtable->data);
6117        module_put(flowtable->data.type->owner);
6118        kfree(flowtable);
6119}
6120
6121static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
6122                                   u32 portid, u32 seq)
6123{
6124        struct nlmsghdr *nlh;
6125        struct nfgenmsg *nfmsg;
6126        char buf[TASK_COMM_LEN];
6127        int event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWGEN);
6128
6129        nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0);
6130        if (nlh == NULL)
6131                goto nla_put_failure;
6132
6133        nfmsg = nlmsg_data(nlh);
6134        nfmsg->nfgen_family     = AF_UNSPEC;
6135        nfmsg->version          = NFNETLINK_V0;
6136        nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
6137
6138        if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq)) ||
6139            nla_put_be32(skb, NFTA_GEN_PROC_PID, htonl(task_pid_nr(current))) ||
6140            nla_put_string(skb, NFTA_GEN_PROC_NAME, get_task_comm(buf, current)))
6141                goto nla_put_failure;
6142
6143        nlmsg_end(skb, nlh);
6144        return 0;
6145
6146nla_put_failure:
6147        nlmsg_trim(skb, nlh);
6148        return -EMSGSIZE;
6149}
6150
6151static void nft_flowtable_event(unsigned long event, struct net_device *dev,
6152                                struct nft_flowtable *flowtable)
6153{
6154        int i;
6155
6156        for (i = 0; i < flowtable->ops_len; i++) {
6157                if (flowtable->ops[i].dev != dev)
6158                        continue;
6159
6160                nf_unregister_net_hook(dev_net(dev), &flowtable->ops[i]);
6161                flowtable->ops[i].dev = NULL;
6162                break;
6163        }
6164}
6165
6166static int nf_tables_flowtable_event(struct notifier_block *this,
6167                                     unsigned long event, void *ptr)
6168{
6169        struct net_device *dev = netdev_notifier_info_to_dev(ptr);
6170        struct nft_flowtable *flowtable;
6171        struct nft_table *table;
6172        struct net *net;
6173
6174        if (event != NETDEV_UNREGISTER)
6175                return 0;
6176
6177        net = dev_net(dev);
6178        mutex_lock(&net->nft.commit_mutex);
6179        list_for_each_entry(table, &net->nft.tables, list) {
6180                list_for_each_entry(flowtable, &table->flowtables, list) {
6181                        nft_flowtable_event(event, dev, flowtable);
6182                }
6183        }
6184        mutex_unlock(&net->nft.commit_mutex);
6185
6186        return NOTIFY_DONE;
6187}
6188
6189static struct notifier_block nf_tables_flowtable_notifier = {
6190        .notifier_call  = nf_tables_flowtable_event,
6191};
6192
6193static void nf_tables_gen_notify(struct net *net, struct sk_buff *skb,
6194                                 int event)
6195{
6196        struct nlmsghdr *nlh = nlmsg_hdr(skb);
6197        struct sk_buff *skb2;
6198        int err;
6199
6200        if (nlmsg_report(nlh) &&
6201            !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
6202                return;
6203
6204        skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6205        if (skb2 == NULL)
6206                goto err;
6207
6208        err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6209                                      nlh->nlmsg_seq);
6210        if (err < 0) {
6211                kfree_skb(skb2);
6212                goto err;
6213        }
6214
6215        nfnetlink_send(skb2, net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6216                       nlmsg_report(nlh), GFP_KERNEL);
6217        return;
6218err:
6219        nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6220                          -ENOBUFS);
6221}
6222
6223static int nf_tables_getgen(struct net *net, struct sock *nlsk,
6224                            struct sk_buff *skb, const struct nlmsghdr *nlh,
6225                            const struct nlattr * const nla[],
6226                            struct netlink_ext_ack *extack)
6227{
6228        struct sk_buff *skb2;
6229        int err;
6230
6231        skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6232        if (skb2 == NULL)
6233                return -ENOMEM;
6234
6235        err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6236                                      nlh->nlmsg_seq);
6237        if (err < 0)
6238                goto err;
6239
6240        return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6241err:
6242        kfree_skb(skb2);
6243        return err;
6244}
6245
6246static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
6247        [NFT_MSG_NEWTABLE] = {
6248                .call_batch     = nf_tables_newtable,
6249                .attr_count     = NFTA_TABLE_MAX,
6250                .policy         = nft_table_policy,
6251        },
6252        [NFT_MSG_GETTABLE] = {
6253                .call_rcu       = nf_tables_gettable,
6254                .attr_count     = NFTA_TABLE_MAX,
6255                .policy         = nft_table_policy,
6256        },
6257        [NFT_MSG_DELTABLE] = {
6258                .call_batch     = nf_tables_deltable,
6259                .attr_count     = NFTA_TABLE_MAX,
6260                .policy         = nft_table_policy,
6261        },
6262        [NFT_MSG_NEWCHAIN] = {
6263                .call_batch     = nf_tables_newchain,
6264                .attr_count     = NFTA_CHAIN_MAX,
6265                .policy         = nft_chain_policy,
6266        },
6267        [NFT_MSG_GETCHAIN] = {
6268                .call_rcu       = nf_tables_getchain,
6269                .attr_count     = NFTA_CHAIN_MAX,
6270                .policy         = nft_chain_policy,
6271        },
6272        [NFT_MSG_DELCHAIN] = {
6273                .call_batch     = nf_tables_delchain,
6274                .attr_count     = NFTA_CHAIN_MAX,
6275                .policy         = nft_chain_policy,
6276        },
6277        [NFT_MSG_NEWRULE] = {
6278                .call_batch     = nf_tables_newrule,
6279                .attr_count     = NFTA_RULE_MAX,
6280                .policy         = nft_rule_policy,
6281        },
6282        [NFT_MSG_GETRULE] = {
6283                .call_rcu       = nf_tables_getrule,
6284                .attr_count     = NFTA_RULE_MAX,
6285                .policy         = nft_rule_policy,
6286        },
6287        [NFT_MSG_DELRULE] = {
6288                .call_batch     = nf_tables_delrule,
6289                .attr_count     = NFTA_RULE_MAX,
6290                .policy         = nft_rule_policy,
6291        },
6292        [NFT_MSG_NEWSET] = {
6293                .call_batch     = nf_tables_newset,
6294                .attr_count     = NFTA_SET_MAX,
6295                .policy         = nft_set_policy,
6296        },
6297        [NFT_MSG_GETSET] = {
6298                .call_rcu       = nf_tables_getset,
6299                .attr_count     = NFTA_SET_MAX,
6300                .policy         = nft_set_policy,
6301        },
6302        [NFT_MSG_DELSET] = {
6303                .call_batch     = nf_tables_delset,
6304                .attr_count     = NFTA_SET_MAX,
6305                .policy         = nft_set_policy,
6306        },
6307        [NFT_MSG_NEWSETELEM] = {
6308                .call_batch     = nf_tables_newsetelem,
6309                .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6310                .policy         = nft_set_elem_list_policy,
6311        },
6312        [NFT_MSG_GETSETELEM] = {
6313                .call_rcu       = nf_tables_getsetelem,
6314                .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6315                .policy         = nft_set_elem_list_policy,
6316        },
6317        [NFT_MSG_DELSETELEM] = {
6318                .call_batch     = nf_tables_delsetelem,
6319                .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6320                .policy         = nft_set_elem_list_policy,
6321        },
6322        [NFT_MSG_GETGEN] = {
6323                .call_rcu       = nf_tables_getgen,
6324        },
6325        [NFT_MSG_NEWOBJ] = {
6326                .call_batch     = nf_tables_newobj,
6327                .attr_count     = NFTA_OBJ_MAX,
6328                .policy         = nft_obj_policy,
6329        },
6330        [NFT_MSG_GETOBJ] = {
6331                .call_rcu       = nf_tables_getobj,
6332                .attr_count     = NFTA_OBJ_MAX,
6333                .policy         = nft_obj_policy,
6334        },
6335        [NFT_MSG_DELOBJ] = {
6336                .call_batch     = nf_tables_delobj,
6337                .attr_count     = NFTA_OBJ_MAX,
6338                .policy         = nft_obj_policy,
6339        },
6340        [NFT_MSG_GETOBJ_RESET] = {
6341                .call_rcu       = nf_tables_getobj,
6342                .attr_count     = NFTA_OBJ_MAX,
6343                .policy         = nft_obj_policy,
6344        },
6345        [NFT_MSG_NEWFLOWTABLE] = {
6346                .call_batch     = nf_tables_newflowtable,
6347                .attr_count     = NFTA_FLOWTABLE_MAX,
6348                .policy         = nft_flowtable_policy,
6349        },
6350        [NFT_MSG_GETFLOWTABLE] = {
6351                .call_rcu       = nf_tables_getflowtable,
6352                .attr_count     = NFTA_FLOWTABLE_MAX,
6353                .policy         = nft_flowtable_policy,
6354        },
6355        [NFT_MSG_DELFLOWTABLE] = {
6356                .call_batch     = nf_tables_delflowtable,
6357                .attr_count     = NFTA_FLOWTABLE_MAX,
6358                .policy         = nft_flowtable_policy,
6359        },
6360};
6361
6362static int nf_tables_validate(struct net *net)
6363{
6364        struct nft_table *table;
6365
6366        switch (net->nft.validate_state) {
6367        case NFT_VALIDATE_SKIP:
6368                break;
6369        case NFT_VALIDATE_NEED:
6370                nft_validate_state_update(net, NFT_VALIDATE_DO);
6371                /* fall through */
6372        case NFT_VALIDATE_DO:
6373                list_for_each_entry(table, &net->nft.tables, list) {
6374                        if (nft_table_validate(net, table) < 0)
6375                                return -EAGAIN;
6376                }
6377                break;
6378        }
6379
6380        return 0;
6381}
6382
6383/* a drop policy has to be deferred until all rules have been activated,
6384 * otherwise a large ruleset that contains a drop-policy base chain will
6385 * cause all packets to get dropped until the full transaction has been
6386 * processed.
6387 *
6388 * We defer the drop policy until the transaction has been finalized.
6389 */
6390static void nft_chain_commit_drop_policy(struct nft_trans *trans)
6391{
6392        struct nft_base_chain *basechain;
6393
6394        if (nft_trans_chain_policy(trans) != NF_DROP)
6395                return;
6396
6397        if (!nft_is_base_chain(trans->ctx.chain))
6398                return;
6399
6400        basechain = nft_base_chain(trans->ctx.chain);
6401        basechain->policy = NF_DROP;
6402}
6403
6404static void nft_chain_commit_update(struct nft_trans *trans)
6405{
6406        struct nft_base_chain *basechain;
6407
6408        if (nft_trans_chain_name(trans)) {
6409                rhltable_remove(&trans->ctx.table->chains_ht,
6410                                &trans->ctx.chain->rhlhead,
6411                                nft_chain_ht_params);
6412                swap(trans->ctx.chain->name, nft_trans_chain_name(trans));
6413                rhltable_insert_key(&trans->ctx.table->chains_ht,
6414                                    trans->ctx.chain->name,
6415                                    &trans->ctx.chain->rhlhead,
6416                                    nft_chain_ht_params);
6417        }
6418
6419        if (!nft_is_base_chain(trans->ctx.chain))
6420                return;
6421
6422        nft_chain_stats_replace(trans);
6423
6424        basechain = nft_base_chain(trans->ctx.chain);
6425
6426        switch (nft_trans_chain_policy(trans)) {
6427        case NF_DROP:
6428        case NF_ACCEPT:
6429                basechain->policy = nft_trans_chain_policy(trans);
6430                break;
6431        }
6432}
6433
6434static void nft_commit_release(struct nft_trans *trans)
6435{
6436        switch (trans->msg_type) {
6437        case NFT_MSG_DELTABLE:
6438                nf_tables_table_destroy(&trans->ctx);
6439                break;
6440        case NFT_MSG_NEWCHAIN:
6441                free_percpu(nft_trans_chain_stats(trans));
6442                kfree(nft_trans_chain_name(trans));
6443                break;
6444        case NFT_MSG_DELCHAIN:
6445                nf_tables_chain_destroy(&trans->ctx);
6446                break;
6447        case NFT_MSG_DELRULE:
6448                nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6449                break;
6450        case NFT_MSG_DELSET:
6451                nft_set_destroy(nft_trans_set(trans));
6452                break;
6453        case NFT_MSG_DELSETELEM:
6454                nf_tables_set_elem_destroy(&trans->ctx,
6455                                           nft_trans_elem_set(trans),
6456                                           nft_trans_elem(trans).priv);
6457                break;
6458        case NFT_MSG_DELOBJ:
6459                nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6460                break;
6461        case NFT_MSG_DELFLOWTABLE:
6462                nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6463                break;
6464        }
6465
6466        if (trans->put_net)
6467                put_net(trans->ctx.net);
6468
6469        kfree(trans);
6470}
6471
6472static void nf_tables_trans_destroy_work(struct work_struct *w)
6473{
6474        struct nft_trans *trans, *next;
6475        LIST_HEAD(head);
6476
6477        spin_lock(&nf_tables_destroy_list_lock);
6478        list_splice_init(&nf_tables_destroy_list, &head);
6479        spin_unlock(&nf_tables_destroy_list_lock);
6480
6481        if (list_empty(&head))
6482                return;
6483
6484        synchronize_rcu();
6485
6486        list_for_each_entry_safe(trans, next, &head, list) {
6487                list_del(&trans->list);
6488                nft_commit_release(trans);
6489        }
6490}
6491
6492static int nf_tables_commit_chain_prepare(struct net *net, struct nft_chain *chain)
6493{
6494        struct nft_rule *rule;
6495        unsigned int alloc = 0;
6496        int i;
6497
6498        /* already handled or inactive chain? */
6499        if (chain->rules_next || !nft_is_active_next(net, chain))
6500                return 0;
6501
6502        rule = list_entry(&chain->rules, struct nft_rule, list);
6503        i = 0;
6504
6505        list_for_each_entry_continue(rule, &chain->rules, list) {
6506                if (nft_is_active_next(net, rule))
6507                        alloc++;
6508        }
6509
6510        chain->rules_next = nf_tables_chain_alloc_rules(chain, alloc);
6511        if (!chain->rules_next)
6512                return -ENOMEM;
6513
6514        list_for_each_entry_continue(rule, &chain->rules, list) {
6515                if (nft_is_active_next(net, rule))
6516                        chain->rules_next[i++] = rule;
6517        }
6518
6519        chain->rules_next[i] = NULL;
6520        return 0;
6521}
6522
6523static void nf_tables_commit_chain_prepare_cancel(struct net *net)
6524{
6525        struct nft_trans *trans, *next;
6526
6527        list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6528                struct nft_chain *chain = trans->ctx.chain;
6529
6530                if (trans->msg_type == NFT_MSG_NEWRULE ||
6531                    trans->msg_type == NFT_MSG_DELRULE) {
6532                        kvfree(chain->rules_next);
6533                        chain->rules_next = NULL;
6534                }
6535        }
6536}
6537
6538static void __nf_tables_commit_chain_free_rules_old(struct rcu_head *h)
6539{
6540        struct nft_rules_old *o = container_of(h, struct nft_rules_old, h);
6541
6542        kvfree(o->start);
6543}
6544
6545static void nf_tables_commit_chain_free_rules_old(struct nft_rule **rules)
6546{
6547        struct nft_rule **r = rules;
6548        struct nft_rules_old *old;
6549
6550        while (*r)
6551                r++;
6552
6553        r++;    /* rcu_head is after end marker */
6554        old = (void *) r;
6555        old->start = rules;
6556
6557        call_rcu(&old->h, __nf_tables_commit_chain_free_rules_old);
6558}
6559
6560static void nf_tables_commit_chain(struct net *net, struct nft_chain *chain)
6561{
6562        struct nft_rule **g0, **g1;
6563        bool next_genbit;
6564
6565        next_genbit = nft_gencursor_next(net);
6566
6567        g0 = rcu_dereference_protected(chain->rules_gen_0,
6568                                       lockdep_commit_lock_is_held(net));
6569        g1 = rcu_dereference_protected(chain->rules_gen_1,
6570                                       lockdep_commit_lock_is_held(net));
6571
6572        /* No changes to this chain? */
6573        if (chain->rules_next == NULL) {
6574                /* chain had no change in last or next generation */
6575                if (g0 == g1)
6576                        return;
6577                /*
6578                 * chain had no change in this generation; make sure next
6579                 * one uses same rules as current generation.
6580                 */
6581                if (next_genbit) {
6582                        rcu_assign_pointer(chain->rules_gen_1, g0);
6583                        nf_tables_commit_chain_free_rules_old(g1);
6584                } else {
6585                        rcu_assign_pointer(chain->rules_gen_0, g1);
6586                        nf_tables_commit_chain_free_rules_old(g0);
6587                }
6588
6589                return;
6590        }
6591
6592        if (next_genbit)
6593                rcu_assign_pointer(chain->rules_gen_1, chain->rules_next);
6594        else
6595                rcu_assign_pointer(chain->rules_gen_0, chain->rules_next);
6596
6597        chain->rules_next = NULL;
6598
6599        if (g0 == g1)
6600                return;
6601
6602        if (next_genbit)
6603                nf_tables_commit_chain_free_rules_old(g1);
6604        else
6605                nf_tables_commit_chain_free_rules_old(g0);
6606}
6607
6608static void nft_obj_del(struct nft_object *obj)
6609{
6610        rhltable_remove(&nft_objname_ht, &obj->rhlhead, nft_objname_ht_params);
6611        list_del_rcu(&obj->list);
6612}
6613
6614static void nft_chain_del(struct nft_chain *chain)
6615{
6616        struct nft_table *table = chain->table;
6617
6618        WARN_ON_ONCE(rhltable_remove(&table->chains_ht, &chain->rhlhead,
6619                                     nft_chain_ht_params));
6620        list_del_rcu(&chain->list);
6621}
6622
6623static void nf_tables_commit_release(struct net *net)
6624{
6625        struct nft_trans *trans;
6626
6627        /* all side effects have to be made visible.
6628         * For example, if a chain named 'foo' has been deleted, a
6629         * new transaction must not find it anymore.
6630         *
6631         * Memory reclaim happens asynchronously from work queue
6632         * to prevent expensive synchronize_rcu() in commit phase.
6633         */
6634        if (list_empty(&net->nft.commit_list)) {
6635                mutex_unlock(&net->nft.commit_mutex);
6636                return;
6637        }
6638
6639        trans = list_last_entry(&net->nft.commit_list,
6640                                struct nft_trans, list);
6641        get_net(trans->ctx.net);
6642        WARN_ON_ONCE(trans->put_net);
6643
6644        trans->put_net = true;
6645        spin_lock(&nf_tables_destroy_list_lock);
6646        list_splice_tail_init(&net->nft.commit_list, &nf_tables_destroy_list);
6647        spin_unlock(&nf_tables_destroy_list_lock);
6648
6649        mutex_unlock(&net->nft.commit_mutex);
6650
6651        schedule_work(&trans_destroy_work);
6652}
6653
6654static int nf_tables_commit(struct net *net, struct sk_buff *skb)
6655{
6656        struct nft_trans *trans, *next;
6657        struct nft_trans_elem *te;
6658        struct nft_chain *chain;
6659        struct nft_table *table;
6660        int err;
6661
6662        if (list_empty(&net->nft.commit_list)) {
6663                mutex_unlock(&net->nft.commit_mutex);
6664                return 0;
6665        }
6666
6667        /* 0. Validate ruleset, otherwise roll back for error reporting. */
6668        if (nf_tables_validate(net) < 0)
6669                return -EAGAIN;
6670
6671        err = nft_flow_rule_offload_commit(net);
6672        if (err < 0)
6673                return err;
6674
6675        /* 1.  Allocate space for next generation rules_gen_X[] */
6676        list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6677                int ret;
6678
6679                if (trans->msg_type == NFT_MSG_NEWRULE ||
6680                    trans->msg_type == NFT_MSG_DELRULE) {
6681                        chain = trans->ctx.chain;
6682
6683                        ret = nf_tables_commit_chain_prepare(net, chain);
6684                        if (ret < 0) {
6685                                nf_tables_commit_chain_prepare_cancel(net);
6686                                return ret;
6687                        }
6688                }
6689        }
6690
6691        /* step 2.  Make rules_gen_X visible to packet path */
6692        list_for_each_entry(table, &net->nft.tables, list) {
6693                list_for_each_entry(chain, &table->chains, list)
6694                        nf_tables_commit_chain(net, chain);
6695        }
6696
6697        /*
6698         * Bump generation counter, invalidate any dump in progress.
6699         * Cannot fail after this point.
6700         */
6701        while (++net->nft.base_seq == 0);
6702
6703        /* step 3. Start new generation, rules_gen_X now in use. */
6704        net->nft.gencursor = nft_gencursor_next(net);
6705
6706        list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6707                switch (trans->msg_type) {
6708                case NFT_MSG_NEWTABLE:
6709                        if (nft_trans_table_update(trans)) {
6710                                if (!nft_trans_table_enable(trans)) {
6711                                        nf_tables_table_disable(net,
6712                                                                trans->ctx.table);
6713                                        trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6714                                }
6715                        } else {
6716                                nft_clear(net, trans->ctx.table);
6717                        }
6718                        nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
6719                        nft_trans_destroy(trans);
6720                        break;
6721                case NFT_MSG_DELTABLE:
6722                        list_del_rcu(&trans->ctx.table->list);
6723                        nf_tables_table_notify(&trans->ctx, NFT_MSG_DELTABLE);
6724                        break;
6725                case NFT_MSG_NEWCHAIN:
6726                        if (nft_trans_chain_update(trans)) {
6727                                nft_chain_commit_update(trans);
6728                                nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6729                                /* trans destroyed after rcu grace period */
6730                        } else {
6731                                nft_chain_commit_drop_policy(trans);
6732                                nft_clear(net, trans->ctx.chain);
6733                                nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6734                                nft_trans_destroy(trans);
6735                        }
6736                        break;
6737                case NFT_MSG_DELCHAIN:
6738                        nft_chain_del(trans->ctx.chain);
6739                        nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN);
6740                        nf_tables_unregister_hook(trans->ctx.net,
6741                                                  trans->ctx.table,
6742                                                  trans->ctx.chain);
6743                        break;
6744                case NFT_MSG_NEWRULE:
6745                        nft_clear(trans->ctx.net, nft_trans_rule(trans));
6746                        nf_tables_rule_notify(&trans->ctx,
6747                                              nft_trans_rule(trans),
6748                                              NFT_MSG_NEWRULE);
6749                        nft_trans_destroy(trans);
6750                        break;
6751                case NFT_MSG_DELRULE:
6752                        list_del_rcu(&nft_trans_rule(trans)->list);
6753                        nf_tables_rule_notify(&trans->ctx,
6754                                              nft_trans_rule(trans),
6755                                              NFT_MSG_DELRULE);
6756                        nft_rule_expr_deactivate(&trans->ctx,
6757                                                 nft_trans_rule(trans),
6758                                                 NFT_TRANS_COMMIT);
6759                        break;
6760                case NFT_MSG_NEWSET:
6761                        nft_clear(net, nft_trans_set(trans));
6762                        /* This avoids hitting -EBUSY when deleting the table
6763                         * from the transaction.
6764                         */
6765                        if (nft_set_is_anonymous(nft_trans_set(trans)) &&
6766                            !list_empty(&nft_trans_set(trans)->bindings))
6767                                trans->ctx.table->use--;
6768
6769                        nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6770                                             NFT_MSG_NEWSET, GFP_KERNEL);
6771                        nft_trans_destroy(trans);
6772                        break;
6773                case NFT_MSG_DELSET:
6774                        list_del_rcu(&nft_trans_set(trans)->list);
6775                        nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6776                                             NFT_MSG_DELSET, GFP_KERNEL);
6777                        break;
6778                case NFT_MSG_NEWSETELEM:
6779                        te = (struct nft_trans_elem *)trans->data;
6780
6781                        te->set->ops->activate(net, te->set, &te->elem);
6782                        nf_tables_setelem_notify(&trans->ctx, te->set,
6783                                                 &te->elem,
6784                                                 NFT_MSG_NEWSETELEM, 0);
6785                        nft_trans_destroy(trans);
6786                        break;
6787                case NFT_MSG_DELSETELEM:
6788                        te = (struct nft_trans_elem *)trans->data;
6789
6790                        nf_tables_setelem_notify(&trans->ctx, te->set,
6791                                                 &te->elem,
6792                                                 NFT_MSG_DELSETELEM, 0);
6793                        te->set->ops->remove(net, te->set, &te->elem);
6794                        atomic_dec(&te->set->nelems);
6795                        te->set->ndeact--;
6796                        break;
6797                case NFT_MSG_NEWOBJ:
6798                        nft_clear(net, nft_trans_obj(trans));
6799                        nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6800                                             NFT_MSG_NEWOBJ);
6801                        nft_trans_destroy(trans);
6802                        break;
6803                case NFT_MSG_DELOBJ:
6804                        nft_obj_del(nft_trans_obj(trans));
6805                        nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6806                                             NFT_MSG_DELOBJ);
6807                        break;
6808                case NFT_MSG_NEWFLOWTABLE:
6809                        nft_clear(net, nft_trans_flowtable(trans));
6810                        nf_tables_flowtable_notify(&trans->ctx,
6811                                                   nft_trans_flowtable(trans),
6812                                                   NFT_MSG_NEWFLOWTABLE);
6813                        nft_trans_destroy(trans);
6814                        break;
6815                case NFT_MSG_DELFLOWTABLE:
6816                        list_del_rcu(&nft_trans_flowtable(trans)->list);
6817                        nf_tables_flowtable_notify(&trans->ctx,
6818                                                   nft_trans_flowtable(trans),
6819                                                   NFT_MSG_DELFLOWTABLE);
6820                        nft_unregister_flowtable_net_hooks(net,
6821                                        nft_trans_flowtable(trans));
6822                        break;
6823                }
6824        }
6825
6826        nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
6827        nf_tables_commit_release(net);
6828
6829        return 0;
6830}
6831
6832static void nf_tables_abort_release(struct nft_trans *trans)
6833{
6834        switch (trans->msg_type) {
6835        case NFT_MSG_NEWTABLE:
6836                nf_tables_table_destroy(&trans->ctx);
6837                break;
6838        case NFT_MSG_NEWCHAIN:
6839                nf_tables_chain_destroy(&trans->ctx);
6840                break;
6841        case NFT_MSG_NEWRULE:
6842                nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6843                break;
6844        case NFT_MSG_NEWSET:
6845                nft_set_destroy(nft_trans_set(trans));
6846                break;
6847        case NFT_MSG_NEWSETELEM:
6848                nft_set_elem_destroy(nft_trans_elem_set(trans),
6849                                     nft_trans_elem(trans).priv, true);
6850                break;
6851        case NFT_MSG_NEWOBJ:
6852                nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6853                break;
6854        case NFT_MSG_NEWFLOWTABLE:
6855                nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6856                break;
6857        }
6858        kfree(trans);
6859}
6860
6861static int __nf_tables_abort(struct net *net)
6862{
6863        struct nft_trans *trans, *next;
6864        struct nft_trans_elem *te;
6865
6866        list_for_each_entry_safe_reverse(trans, next, &net->nft.commit_list,
6867                                         list) {
6868                switch (trans->msg_type) {
6869                case NFT_MSG_NEWTABLE:
6870                        if (nft_trans_table_update(trans)) {
6871                                if (nft_trans_table_enable(trans)) {
6872                                        nf_tables_table_disable(net,
6873                                                                trans->ctx.table);
6874                                        trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6875                                }
6876                                nft_trans_destroy(trans);
6877                        } else {
6878                                list_del_rcu(&trans->ctx.table->list);
6879                        }
6880                        break;
6881                case NFT_MSG_DELTABLE:
6882                        nft_clear(trans->ctx.net, trans->ctx.table);
6883                        nft_trans_destroy(trans);
6884                        break;
6885                case NFT_MSG_NEWCHAIN:
6886                        if (nft_trans_chain_update(trans)) {
6887                                free_percpu(nft_trans_chain_stats(trans));
6888                                kfree(nft_trans_chain_name(trans));
6889                                nft_trans_destroy(trans);
6890                        } else {
6891                                trans->ctx.table->use--;
6892                                nft_chain_del(trans->ctx.chain);
6893                                nf_tables_unregister_hook(trans->ctx.net,
6894                                                          trans->ctx.table,
6895                                                          trans->ctx.chain);
6896                        }
6897                        break;
6898                case NFT_MSG_DELCHAIN:
6899                        trans->ctx.table->use++;
6900                        nft_clear(trans->ctx.net, trans->ctx.chain);
6901                        nft_trans_destroy(trans);
6902                        break;
6903                case NFT_MSG_NEWRULE:
6904                        trans->ctx.chain->use--;
6905                        list_del_rcu(&nft_trans_rule(trans)->list);
6906                        nft_rule_expr_deactivate(&trans->ctx,
6907                                                 nft_trans_rule(trans),
6908                                                 NFT_TRANS_ABORT);
6909                        break;
6910                case NFT_MSG_DELRULE:
6911                        trans->ctx.chain->use++;
6912                        nft_clear(trans->ctx.net, nft_trans_rule(trans));
6913                        nft_rule_expr_activate(&trans->ctx, nft_trans_rule(trans));
6914                        nft_trans_destroy(trans);
6915                        break;
6916                case NFT_MSG_NEWSET:
6917                        trans->ctx.table->use--;
6918                        if (nft_trans_set_bound(trans)) {
6919                                nft_trans_destroy(trans);
6920                                break;
6921                        }
6922                        list_del_rcu(&nft_trans_set(trans)->list);
6923                        break;
6924                case NFT_MSG_DELSET:
6925                        trans->ctx.table->use++;
6926                        nft_clear(trans->ctx.net, nft_trans_set(trans));
6927                        nft_trans_destroy(trans);
6928                        break;
6929                case NFT_MSG_NEWSETELEM:
6930                        if (nft_trans_elem_set_bound(trans)) {
6931                                nft_trans_destroy(trans);
6932                                break;
6933                        }
6934                        te = (struct nft_trans_elem *)trans->data;
6935                        te->set->ops->remove(net, te->set, &te->elem);
6936                        atomic_dec(&te->set->nelems);
6937                        break;
6938                case NFT_MSG_DELSETELEM:
6939                        te = (struct nft_trans_elem *)trans->data;
6940
6941                        nft_set_elem_activate(net, te->set, &te->elem);
6942                        te->set->ops->activate(net, te->set, &te->elem);
6943                        te->set->ndeact--;
6944
6945                        nft_trans_destroy(trans);
6946                        break;
6947                case NFT_MSG_NEWOBJ:
6948                        trans->ctx.table->use--;
6949                        nft_obj_del(nft_trans_obj(trans));
6950                        break;
6951                case NFT_MSG_DELOBJ:
6952                        trans->ctx.table->use++;
6953                        nft_clear(trans->ctx.net, nft_trans_obj(trans));
6954                        nft_trans_destroy(trans);
6955                        break;
6956                case NFT_MSG_NEWFLOWTABLE:
6957                        trans->ctx.table->use--;
6958                        list_del_rcu(&nft_trans_flowtable(trans)->list);
6959                        nft_unregister_flowtable_net_hooks(net,
6960                                        nft_trans_flowtable(trans));
6961                        break;
6962                case NFT_MSG_DELFLOWTABLE:
6963                        trans->ctx.table->use++;
6964                        nft_clear(trans->ctx.net, nft_trans_flowtable(trans));
6965                        nft_trans_destroy(trans);
6966                        break;
6967                }
6968        }
6969
6970        synchronize_rcu();
6971
6972        list_for_each_entry_safe_reverse(trans, next,
6973                                         &net->nft.commit_list, list) {
6974                list_del(&trans->list);
6975                nf_tables_abort_release(trans);
6976        }
6977
6978        return 0;
6979}
6980
6981static void nf_tables_cleanup(struct net *net)
6982{
6983        nft_validate_state_update(net, NFT_VALIDATE_SKIP);
6984}
6985
6986static int nf_tables_abort(struct net *net, struct sk_buff *skb)
6987{
6988        int ret = __nf_tables_abort(net);
6989
6990        mutex_unlock(&net->nft.commit_mutex);
6991
6992        return ret;
6993}
6994
6995static bool nf_tables_valid_genid(struct net *net, u32 genid)
6996{
6997        bool genid_ok;
6998
6999        mutex_lock(&net->nft.commit_mutex);
7000
7001        genid_ok = genid == 0 || net->nft.base_seq == genid;
7002        if (!genid_ok)
7003                mutex_unlock(&net->nft.commit_mutex);
7004
7005        /* else, commit mutex has to be released by commit or abort function */
7006        return genid_ok;
7007}
7008
7009static const struct nfnetlink_subsystem nf_tables_subsys = {
7010        .name           = "nf_tables",
7011        .subsys_id      = NFNL_SUBSYS_NFTABLES,
7012        .cb_count       = NFT_MSG_MAX,
7013        .cb             = nf_tables_cb,
7014        .commit         = nf_tables_commit,
7015        .abort          = nf_tables_abort,
7016        .cleanup        = nf_tables_cleanup,
7017        .valid_genid    = nf_tables_valid_genid,
7018        .owner          = THIS_MODULE,
7019};
7020
7021int nft_chain_validate_dependency(const struct nft_chain *chain,
7022                                  enum nft_chain_types type)
7023{
7024        const struct nft_base_chain *basechain;
7025
7026        if (nft_is_base_chain(chain)) {
7027                basechain = nft_base_chain(chain);
7028                if (basechain->type->type != type)
7029                        return -EOPNOTSUPP;
7030        }
7031        return 0;
7032}
7033EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
7034
7035int nft_chain_validate_hooks(const struct nft_chain *chain,
7036                             unsigned int hook_flags)
7037{
7038        struct nft_base_chain *basechain;
7039
7040        if (nft_is_base_chain(chain)) {
7041                basechain = nft_base_chain(chain);
7042
7043                if ((1 << basechain->ops.hooknum) & hook_flags)
7044                        return 0;
7045
7046                return -EOPNOTSUPP;
7047        }
7048
7049        return 0;
7050}
7051EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
7052
7053/*
7054 * Loop detection - walk through the ruleset beginning at the destination chain
7055 * of a new jump until either the source chain is reached (loop) or all
7056 * reachable chains have been traversed.
7057 *
7058 * The loop check is performed whenever a new jump verdict is added to an
7059 * expression or verdict map or a verdict map is bound to a new chain.
7060 */
7061
7062static int nf_tables_check_loops(const struct nft_ctx *ctx,
7063                                 const struct nft_chain *chain);
7064
7065static int nf_tables_loop_check_setelem(const struct nft_ctx *ctx,
7066                                        struct nft_set *set,
7067                                        const struct nft_set_iter *iter,
7068                                        struct nft_set_elem *elem)
7069{
7070        const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7071        const struct nft_data *data;
7072
7073        if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
7074            *nft_set_ext_flags(ext) & NFT_SET_ELEM_INTERVAL_END)
7075                return 0;
7076
7077        data = nft_set_ext_data(ext);
7078        switch (data->verdict.code) {
7079        case NFT_JUMP:
7080        case NFT_GOTO:
7081                return nf_tables_check_loops(ctx, data->verdict.chain);
7082        default:
7083                return 0;
7084        }
7085}
7086
7087static int nf_tables_check_loops(const struct nft_ctx *ctx,
7088                                 const struct nft_chain *chain)
7089{
7090        const struct nft_rule *rule;
7091        const struct nft_expr *expr, *last;
7092        struct nft_set *set;
7093        struct nft_set_binding *binding;
7094        struct nft_set_iter iter;
7095
7096        if (ctx->chain == chain)
7097                return -ELOOP;
7098
7099        list_for_each_entry(rule, &chain->rules, list) {
7100                nft_rule_for_each_expr(expr, last, rule) {
7101                        struct nft_immediate_expr *priv;
7102                        const struct nft_data *data;
7103                        int err;
7104
7105                        if (strcmp(expr->ops->type->name, "immediate"))
7106                                continue;
7107
7108                        priv = nft_expr_priv(expr);
7109                        if (priv->dreg != NFT_REG_VERDICT)
7110                                continue;
7111
7112                        data = &priv->data;
7113                        switch (data->verdict.code) {
7114                        case NFT_JUMP:
7115                        case NFT_GOTO:
7116                                err = nf_tables_check_loops(ctx,
7117                                                        data->verdict.chain);
7118                                if (err < 0)
7119                                        return err;
7120                        default:
7121                                break;
7122                        }
7123                }
7124        }
7125
7126        list_for_each_entry(set, &ctx->table->sets, list) {
7127                if (!nft_is_active_next(ctx->net, set))
7128                        continue;
7129                if (!(set->flags & NFT_SET_MAP) ||
7130                    set->dtype != NFT_DATA_VERDICT)
7131                        continue;
7132
7133                list_for_each_entry(binding, &set->bindings, list) {
7134                        if (!(binding->flags & NFT_SET_MAP) ||
7135                            binding->chain != chain)
7136                                continue;
7137
7138                        iter.genmask    = nft_genmask_next(ctx->net);
7139                        iter.skip       = 0;
7140                        iter.count      = 0;
7141                        iter.err        = 0;
7142                        iter.fn         = nf_tables_loop_check_setelem;
7143
7144                        set->ops->walk(ctx, set, &iter);
7145                        if (iter.err < 0)
7146                                return iter.err;
7147                }
7148        }
7149
7150        return 0;
7151}
7152
7153/**
7154 *      nft_parse_u32_check - fetch u32 attribute and check for maximum value
7155 *
7156 *      @attr: netlink attribute to fetch value from
7157 *      @max: maximum value to be stored in dest
7158 *      @dest: pointer to the variable
7159 *
7160 *      Parse, check and store a given u32 netlink attribute into variable.
7161 *      This function returns -ERANGE if the value goes over maximum value.
7162 *      Otherwise a 0 is returned and the attribute value is stored in the
7163 *      destination variable.
7164 */
7165int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest)
7166{
7167        u32 val;
7168
7169        val = ntohl(nla_get_be32(attr));
7170        if (val > max)
7171                return -ERANGE;
7172
7173        *dest = val;
7174        return 0;
7175}
7176EXPORT_SYMBOL_GPL(nft_parse_u32_check);
7177
7178/**
7179 *      nft_parse_register - parse a register value from a netlink attribute
7180 *
7181 *      @attr: netlink attribute
7182 *
7183 *      Parse and translate a register value from a netlink attribute.
7184 *      Registers used to be 128 bit wide, these register numbers will be
7185 *      mapped to the corresponding 32 bit register numbers.
7186 */
7187unsigned int nft_parse_register(const struct nlattr *attr)
7188{
7189        unsigned int reg;
7190
7191        reg = ntohl(nla_get_be32(attr));
7192        switch (reg) {
7193        case NFT_REG_VERDICT...NFT_REG_4:
7194                return reg * NFT_REG_SIZE / NFT_REG32_SIZE;
7195        default:
7196                return reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
7197        }
7198}
7199EXPORT_SYMBOL_GPL(nft_parse_register);
7200
7201/**
7202 *      nft_dump_register - dump a register value to a netlink attribute
7203 *
7204 *      @skb: socket buffer
7205 *      @attr: attribute number
7206 *      @reg: register number
7207 *
7208 *      Construct a netlink attribute containing the register number. For
7209 *      compatibility reasons, register numbers being a multiple of 4 are
7210 *      translated to the corresponding 128 bit register numbers.
7211 */
7212int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg)
7213{
7214        if (reg % (NFT_REG_SIZE / NFT_REG32_SIZE) == 0)
7215                reg = reg / (NFT_REG_SIZE / NFT_REG32_SIZE);
7216        else
7217                reg = reg - NFT_REG_SIZE / NFT_REG32_SIZE + NFT_REG32_00;
7218
7219        return nla_put_be32(skb, attr, htonl(reg));
7220}
7221EXPORT_SYMBOL_GPL(nft_dump_register);
7222
7223/**
7224 *      nft_validate_register_load - validate a load from a register
7225 *
7226 *      @reg: the register number
7227 *      @len: the length of the data
7228 *
7229 *      Validate that the input register is one of the general purpose
7230 *      registers and that the length of the load is within the bounds.
7231 */
7232int nft_validate_register_load(enum nft_registers reg, unsigned int len)
7233{
7234        if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7235                return -EINVAL;
7236        if (len == 0)
7237                return -EINVAL;
7238        if (reg * NFT_REG32_SIZE + len > FIELD_SIZEOF(struct nft_regs, data))
7239                return -ERANGE;
7240
7241        return 0;
7242}
7243EXPORT_SYMBOL_GPL(nft_validate_register_load);
7244
7245/**
7246 *      nft_validate_register_store - validate an expressions' register store
7247 *
7248 *      @ctx: context of the expression performing the load
7249 *      @reg: the destination register number
7250 *      @data: the data to load
7251 *      @type: the data type
7252 *      @len: the length of the data
7253 *
7254 *      Validate that a data load uses the appropriate data type for
7255 *      the destination register and the length is within the bounds.
7256 *      A value of NULL for the data means that its runtime gathered
7257 *      data.
7258 */
7259int nft_validate_register_store(const struct nft_ctx *ctx,
7260                                enum nft_registers reg,
7261                                const struct nft_data *data,
7262                                enum nft_data_types type, unsigned int len)
7263{
7264        int err;
7265
7266        switch (reg) {
7267        case NFT_REG_VERDICT:
7268                if (type != NFT_DATA_VERDICT)
7269                        return -EINVAL;
7270
7271                if (data != NULL &&
7272                    (data->verdict.code == NFT_GOTO ||
7273                     data->verdict.code == NFT_JUMP)) {
7274                        err = nf_tables_check_loops(ctx, data->verdict.chain);
7275                        if (err < 0)
7276                                return err;
7277                }
7278
7279                return 0;
7280        default:
7281                if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7282                        return -EINVAL;
7283                if (len == 0)
7284                        return -EINVAL;
7285                if (reg * NFT_REG32_SIZE + len >
7286                    FIELD_SIZEOF(struct nft_regs, data))
7287                        return -ERANGE;
7288
7289                if (data != NULL && type != NFT_DATA_VALUE)
7290                        return -EINVAL;
7291                return 0;
7292        }
7293}
7294EXPORT_SYMBOL_GPL(nft_validate_register_store);
7295
7296static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
7297        [NFTA_VERDICT_CODE]     = { .type = NLA_U32 },
7298        [NFTA_VERDICT_CHAIN]    = { .type = NLA_STRING,
7299                                    .len = NFT_CHAIN_MAXNAMELEN - 1 },
7300};
7301
7302static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
7303                            struct nft_data_desc *desc, const struct nlattr *nla)
7304{
7305        u8 genmask = nft_genmask_next(ctx->net);
7306        struct nlattr *tb[NFTA_VERDICT_MAX + 1];
7307        struct nft_chain *chain;
7308        int err;
7309
7310        err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
7311                                          nft_verdict_policy, NULL);
7312        if (err < 0)
7313                return err;
7314
7315        if (!tb[NFTA_VERDICT_CODE])
7316                return -EINVAL;
7317        data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
7318
7319        switch (data->verdict.code) {
7320        default:
7321                switch (data->verdict.code & NF_VERDICT_MASK) {
7322                case NF_ACCEPT:
7323                case NF_DROP:
7324                case NF_QUEUE:
7325                        break;
7326                default:
7327                        return -EINVAL;
7328                }
7329                /* fall through */
7330        case NFT_CONTINUE:
7331        case NFT_BREAK:
7332        case NFT_RETURN:
7333                break;
7334        case NFT_JUMP:
7335        case NFT_GOTO:
7336                if (!tb[NFTA_VERDICT_CHAIN])
7337                        return -EINVAL;
7338                chain = nft_chain_lookup(ctx->net, ctx->table,
7339                                         tb[NFTA_VERDICT_CHAIN], genmask);
7340                if (IS_ERR(chain))
7341                        return PTR_ERR(chain);
7342                if (nft_is_base_chain(chain))
7343                        return -EOPNOTSUPP;
7344
7345                chain->use++;
7346                data->verdict.chain = chain;
7347                break;
7348        }
7349
7350        desc->len = sizeof(data->verdict);
7351        desc->type = NFT_DATA_VERDICT;
7352        return 0;
7353}
7354
7355static void nft_verdict_uninit(const struct nft_data *data)
7356{
7357        switch (data->verdict.code) {
7358        case NFT_JUMP:
7359        case NFT_GOTO:
7360                data->verdict.chain->use--;
7361                break;
7362        }
7363}
7364
7365int nft_verdict_dump(struct sk_buff *skb, int type, const struct nft_verdict *v)
7366{
7367        struct nlattr *nest;
7368
7369        nest = nla_nest_start_noflag(skb, type);
7370        if (!nest)
7371                goto nla_put_failure;
7372
7373        if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(v->code)))
7374                goto nla_put_failure;
7375
7376        switch (v->code) {
7377        case NFT_JUMP:
7378        case NFT_GOTO:
7379                if (nla_put_string(skb, NFTA_VERDICT_CHAIN,
7380                                   v->chain->name))
7381                        goto nla_put_failure;
7382        }
7383        nla_nest_end(skb, nest);
7384        return 0;
7385
7386nla_put_failure:
7387        return -1;
7388}
7389
7390static int nft_value_init(const struct nft_ctx *ctx,
7391                          struct nft_data *data, unsigned int size,
7392                          struct nft_data_desc *desc, const struct nlattr *nla)
7393{
7394        unsigned int len;
7395
7396        len = nla_len(nla);
7397        if (len == 0)
7398                return -EINVAL;
7399        if (len > size)
7400                return -EOVERFLOW;
7401
7402        nla_memcpy(data->data, nla, len);
7403        desc->type = NFT_DATA_VALUE;
7404        desc->len  = len;
7405        return 0;
7406}
7407
7408static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
7409                          unsigned int len)
7410{
7411        return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
7412}
7413
7414static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
7415        [NFTA_DATA_VALUE]       = { .type = NLA_BINARY },
7416        [NFTA_DATA_VERDICT]     = { .type = NLA_NESTED },
7417};
7418
7419/**
7420 *      nft_data_init - parse nf_tables data netlink attributes
7421 *
7422 *      @ctx: context of the expression using the data
7423 *      @data: destination struct nft_data
7424 *      @size: maximum data length
7425 *      @desc: data description
7426 *      @nla: netlink attribute containing data
7427 *
7428 *      Parse the netlink data attributes and initialize a struct nft_data.
7429 *      The type and length of data are returned in the data description.
7430 *
7431 *      The caller can indicate that it only wants to accept data of type
7432 *      NFT_DATA_VALUE by passing NULL for the ctx argument.
7433 */
7434int nft_data_init(const struct nft_ctx *ctx,
7435                  struct nft_data *data, unsigned int size,
7436                  struct nft_data_desc *desc, const struct nlattr *nla)
7437{
7438        struct nlattr *tb[NFTA_DATA_MAX + 1];
7439        int err;
7440
7441        err = nla_parse_nested_deprecated(tb, NFTA_DATA_MAX, nla,
7442                                          nft_data_policy, NULL);
7443        if (err < 0)
7444                return err;
7445
7446        if (tb[NFTA_DATA_VALUE])
7447                return nft_value_init(ctx, data, size, desc,
7448                                      tb[NFTA_DATA_VALUE]);
7449        if (tb[NFTA_DATA_VERDICT] && ctx != NULL)
7450                return nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
7451        return -EINVAL;
7452}
7453EXPORT_SYMBOL_GPL(nft_data_init);
7454
7455/**
7456 *      nft_data_release - release a nft_data item
7457 *
7458 *      @data: struct nft_data to release
7459 *      @type: type of data
7460 *
7461 *      Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
7462 *      all others need to be released by calling this function.
7463 */
7464void nft_data_release(const struct nft_data *data, enum nft_data_types type)
7465{
7466        if (type < NFT_DATA_VERDICT)
7467                return;
7468        switch (type) {
7469        case NFT_DATA_VERDICT:
7470                return nft_verdict_uninit(data);
7471        default:
7472                WARN_ON(1);
7473        }
7474}
7475EXPORT_SYMBOL_GPL(nft_data_release);
7476
7477int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
7478                  enum nft_data_types type, unsigned int len)
7479{
7480        struct nlattr *nest;
7481        int err;
7482
7483        nest = nla_nest_start_noflag(skb, attr);
7484        if (nest == NULL)
7485                return -1;
7486
7487        switch (type) {
7488        case NFT_DATA_VALUE:
7489                err = nft_value_dump(skb, data, len);
7490                break;
7491        case NFT_DATA_VERDICT:
7492                err = nft_verdict_dump(skb, NFTA_DATA_VERDICT, &data->verdict);
7493                break;
7494        default:
7495                err = -EINVAL;
7496                WARN_ON(1);
7497        }
7498
7499        nla_nest_end(skb, nest);
7500        return err;
7501}
7502EXPORT_SYMBOL_GPL(nft_data_dump);
7503
7504int __nft_release_basechain(struct nft_ctx *ctx)
7505{
7506        struct nft_rule *rule, *nr;
7507
7508        if (WARN_ON(!nft_is_base_chain(ctx->chain)))
7509                return 0;
7510
7511        nf_tables_unregister_hook(ctx->net, ctx->chain->table, ctx->chain);
7512        list_for_each_entry_safe(rule, nr, &ctx->chain->rules, list) {
7513                list_del(&rule->list);
7514                ctx->chain->use--;
7515                nf_tables_rule_release(ctx, rule);
7516        }
7517        nft_chain_del(ctx->chain);
7518        ctx->table->use--;
7519        nf_tables_chain_destroy(ctx);
7520
7521        return 0;
7522}
7523EXPORT_SYMBOL_GPL(__nft_release_basechain);
7524
7525static void __nft_release_tables(struct net *net)
7526{
7527        struct nft_flowtable *flowtable, *nf;
7528        struct nft_table *table, *nt;
7529        struct nft_chain *chain, *nc;
7530        struct nft_object *obj, *ne;
7531        struct nft_rule *rule, *nr;
7532        struct nft_set *set, *ns;
7533        struct nft_ctx ctx = {
7534                .net    = net,
7535                .family = NFPROTO_NETDEV,
7536        };
7537
7538        list_for_each_entry_safe(table, nt, &net->nft.tables, list) {
7539                ctx.family = table->family;
7540
7541                list_for_each_entry(chain, &table->chains, list)
7542                        nf_tables_unregister_hook(net, table, chain);
7543                /* No packets are walking on these chains anymore. */
7544                ctx.table = table;
7545                list_for_each_entry(chain, &table->chains, list) {
7546                        ctx.chain = chain;
7547                        list_for_each_entry_safe(rule, nr, &chain->rules, list) {
7548                                list_del(&rule->list);
7549                                chain->use--;
7550                                nf_tables_rule_release(&ctx, rule);
7551                        }
7552                }
7553                list_for_each_entry_safe(flowtable, nf, &table->flowtables, list) {
7554                        list_del(&flowtable->list);
7555                        table->use--;
7556                        nf_tables_flowtable_destroy(flowtable);
7557                }
7558                list_for_each_entry_safe(set, ns, &table->sets, list) {
7559                        list_del(&set->list);
7560                        table->use--;
7561                        nft_set_destroy(set);
7562                }
7563                list_for_each_entry_safe(obj, ne, &table->objects, list) {
7564                        nft_obj_del(obj);
7565                        table->use--;
7566                        nft_obj_destroy(&ctx, obj);
7567                }
7568                list_for_each_entry_safe(chain, nc, &table->chains, list) {
7569                        ctx.chain = chain;
7570                        nft_chain_del(chain);
7571                        table->use--;
7572                        nf_tables_chain_destroy(&ctx);
7573                }
7574                list_del(&table->list);
7575                nf_tables_table_destroy(&ctx);
7576        }
7577}
7578
7579static int __net_init nf_tables_init_net(struct net *net)
7580{
7581        INIT_LIST_HEAD(&net->nft.tables);
7582        INIT_LIST_HEAD(&net->nft.commit_list);
7583        mutex_init(&net->nft.commit_mutex);
7584        net->nft.base_seq = 1;
7585        net->nft.validate_state = NFT_VALIDATE_SKIP;
7586
7587        return 0;
7588}
7589
7590static void __net_exit nf_tables_exit_net(struct net *net)
7591{
7592        mutex_lock(&net->nft.commit_mutex);
7593        if (!list_empty(&net->nft.commit_list))
7594                __nf_tables_abort(net);
7595        __nft_release_tables(net);
7596        mutex_unlock(&net->nft.commit_mutex);
7597        WARN_ON_ONCE(!list_empty(&net->nft.tables));
7598}
7599
7600static struct pernet_operations nf_tables_net_ops = {
7601        .init   = nf_tables_init_net,
7602        .exit   = nf_tables_exit_net,
7603};
7604
7605static int __init nf_tables_module_init(void)
7606{
7607        int err;
7608
7609        spin_lock_init(&nf_tables_destroy_list_lock);
7610        err = register_pernet_subsys(&nf_tables_net_ops);
7611        if (err < 0)
7612                return err;
7613
7614        err = nft_chain_filter_init();
7615        if (err < 0)
7616                goto err1;
7617
7618        err = nf_tables_core_module_init();
7619        if (err < 0)
7620                goto err2;
7621
7622        err = register_netdevice_notifier(&nf_tables_flowtable_notifier);
7623        if (err < 0)
7624                goto err3;
7625
7626        err = rhltable_init(&nft_objname_ht, &nft_objname_ht_params);
7627        if (err < 0)
7628                goto err4;
7629
7630        /* must be last */
7631        err = nfnetlink_subsys_register(&nf_tables_subsys);
7632        if (err < 0)
7633                goto err5;
7634
7635        nft_chain_route_init();
7636        return err;
7637err5:
7638        rhltable_destroy(&nft_objname_ht);
7639err4:
7640        unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7641err3:
7642        nf_tables_core_module_exit();
7643err2:
7644        nft_chain_filter_fini();
7645err1:
7646        unregister_pernet_subsys(&nf_tables_net_ops);
7647        return err;
7648}
7649
7650static void __exit nf_tables_module_exit(void)
7651{
7652        nfnetlink_subsys_unregister(&nf_tables_subsys);
7653        unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7654        nft_chain_filter_fini();
7655        nft_chain_route_fini();
7656        unregister_pernet_subsys(&nf_tables_net_ops);
7657        cancel_work_sync(&trans_destroy_work);
7658        rcu_barrier();
7659        rhltable_destroy(&nft_objname_ht);
7660        nf_tables_core_module_exit();
7661}
7662
7663module_init(nf_tables_module_init);
7664module_exit(nf_tables_module_exit);
7665
7666MODULE_LICENSE("GPL");
7667MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
7668MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);
7669