linux/net/openvswitch/conntrack.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Copyright (c) 2015 Nicira, Inc.
   4 */
   5
   6#include <linux/module.h>
   7#include <linux/openvswitch.h>
   8#include <linux/tcp.h>
   9#include <linux/udp.h>
  10#include <linux/sctp.h>
  11#include <linux/static_key.h>
  12#include <net/ip.h>
  13#include <net/genetlink.h>
  14#include <net/netfilter/nf_conntrack_core.h>
  15#include <net/netfilter/nf_conntrack_count.h>
  16#include <net/netfilter/nf_conntrack_helper.h>
  17#include <net/netfilter/nf_conntrack_labels.h>
  18#include <net/netfilter/nf_conntrack_seqadj.h>
  19#include <net/netfilter/nf_conntrack_timeout.h>
  20#include <net/netfilter/nf_conntrack_zones.h>
  21#include <net/netfilter/ipv6/nf_defrag_ipv6.h>
  22#include <net/ipv6_frag.h>
  23
  24#if IS_ENABLED(CONFIG_NF_NAT)
  25#include <net/netfilter/nf_nat.h>
  26#endif
  27
  28#include <net/netfilter/nf_conntrack_act_ct.h>
  29
  30#include "datapath.h"
  31#include "conntrack.h"
  32#include "flow.h"
  33#include "flow_netlink.h"
  34
  35struct ovs_ct_len_tbl {
  36        int maxlen;
  37        int minlen;
  38};
  39
  40/* Metadata mark for masked write to conntrack mark */
  41struct md_mark {
  42        u32 value;
  43        u32 mask;
  44};
  45
  46/* Metadata label for masked write to conntrack label. */
  47struct md_labels {
  48        struct ovs_key_ct_labels value;
  49        struct ovs_key_ct_labels mask;
  50};
  51
  52enum ovs_ct_nat {
  53        OVS_CT_NAT = 1 << 0,     /* NAT for committed connections only. */
  54        OVS_CT_SRC_NAT = 1 << 1, /* Source NAT for NEW connections. */
  55        OVS_CT_DST_NAT = 1 << 2, /* Destination NAT for NEW connections. */
  56};
  57
  58/* Conntrack action context for execution. */
  59struct ovs_conntrack_info {
  60        struct nf_conntrack_helper *helper;
  61        struct nf_conntrack_zone zone;
  62        struct nf_conn *ct;
  63        u8 commit : 1;
  64        u8 nat : 3;                 /* enum ovs_ct_nat */
  65        u8 force : 1;
  66        u8 have_eventmask : 1;
  67        u16 family;
  68        u32 eventmask;              /* Mask of 1 << IPCT_*. */
  69        struct md_mark mark;
  70        struct md_labels labels;
  71        char timeout[CTNL_TIMEOUT_NAME_MAX];
  72        struct nf_ct_timeout *nf_ct_timeout;
  73#if IS_ENABLED(CONFIG_NF_NAT)
  74        struct nf_nat_range2 range;  /* Only present for SRC NAT and DST NAT. */
  75#endif
  76};
  77
  78#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
  79#define OVS_CT_LIMIT_UNLIMITED  0
  80#define OVS_CT_LIMIT_DEFAULT OVS_CT_LIMIT_UNLIMITED
  81#define CT_LIMIT_HASH_BUCKETS 512
  82static DEFINE_STATIC_KEY_FALSE(ovs_ct_limit_enabled);
  83
  84struct ovs_ct_limit {
  85        /* Elements in ovs_ct_limit_info->limits hash table */
  86        struct hlist_node hlist_node;
  87        struct rcu_head rcu;
  88        u16 zone;
  89        u32 limit;
  90};
  91
  92struct ovs_ct_limit_info {
  93        u32 default_limit;
  94        struct hlist_head *limits;
  95        struct nf_conncount_data *data;
  96};
  97
  98static const struct nla_policy ct_limit_policy[OVS_CT_LIMIT_ATTR_MAX + 1] = {
  99        [OVS_CT_LIMIT_ATTR_ZONE_LIMIT] = { .type = NLA_NESTED, },
 100};
 101#endif
 102
 103static bool labels_nonzero(const struct ovs_key_ct_labels *labels);
 104
 105static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
 106
 107static u16 key_to_nfproto(const struct sw_flow_key *key)
 108{
 109        switch (ntohs(key->eth.type)) {
 110        case ETH_P_IP:
 111                return NFPROTO_IPV4;
 112        case ETH_P_IPV6:
 113                return NFPROTO_IPV6;
 114        default:
 115                return NFPROTO_UNSPEC;
 116        }
 117}
 118
 119/* Map SKB connection state into the values used by flow definition. */
 120static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
 121{
 122        u8 ct_state = OVS_CS_F_TRACKED;
 123
 124        switch (ctinfo) {
 125        case IP_CT_ESTABLISHED_REPLY:
 126        case IP_CT_RELATED_REPLY:
 127                ct_state |= OVS_CS_F_REPLY_DIR;
 128                break;
 129        default:
 130                break;
 131        }
 132
 133        switch (ctinfo) {
 134        case IP_CT_ESTABLISHED:
 135        case IP_CT_ESTABLISHED_REPLY:
 136                ct_state |= OVS_CS_F_ESTABLISHED;
 137                break;
 138        case IP_CT_RELATED:
 139        case IP_CT_RELATED_REPLY:
 140                ct_state |= OVS_CS_F_RELATED;
 141                break;
 142        case IP_CT_NEW:
 143                ct_state |= OVS_CS_F_NEW;
 144                break;
 145        default:
 146                break;
 147        }
 148
 149        return ct_state;
 150}
 151
 152static u32 ovs_ct_get_mark(const struct nf_conn *ct)
 153{
 154#if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
 155        return ct ? ct->mark : 0;
 156#else
 157        return 0;
 158#endif
 159}
 160
 161/* Guard against conntrack labels max size shrinking below 128 bits. */
 162#if NF_CT_LABELS_MAX_SIZE < 16
 163#error NF_CT_LABELS_MAX_SIZE must be at least 16 bytes
 164#endif
 165
 166static void ovs_ct_get_labels(const struct nf_conn *ct,
 167                              struct ovs_key_ct_labels *labels)
 168{
 169        struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
 170
 171        if (cl)
 172                memcpy(labels, cl->bits, OVS_CT_LABELS_LEN);
 173        else
 174                memset(labels, 0, OVS_CT_LABELS_LEN);
 175}
 176
 177static void __ovs_ct_update_key_orig_tp(struct sw_flow_key *key,
 178                                        const struct nf_conntrack_tuple *orig,
 179                                        u8 icmp_proto)
 180{
 181        key->ct_orig_proto = orig->dst.protonum;
 182        if (orig->dst.protonum == icmp_proto) {
 183                key->ct.orig_tp.src = htons(orig->dst.u.icmp.type);
 184                key->ct.orig_tp.dst = htons(orig->dst.u.icmp.code);
 185        } else {
 186                key->ct.orig_tp.src = orig->src.u.all;
 187                key->ct.orig_tp.dst = orig->dst.u.all;
 188        }
 189}
 190
 191static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
 192                                const struct nf_conntrack_zone *zone,
 193                                const struct nf_conn *ct)
 194{
 195        key->ct_state = state;
 196        key->ct_zone = zone->id;
 197        key->ct.mark = ovs_ct_get_mark(ct);
 198        ovs_ct_get_labels(ct, &key->ct.labels);
 199
 200        if (ct) {
 201                const struct nf_conntrack_tuple *orig;
 202
 203                /* Use the master if we have one. */
 204                if (ct->master)
 205                        ct = ct->master;
 206                orig = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
 207
 208                /* IP version must match with the master connection. */
 209                if (key->eth.type == htons(ETH_P_IP) &&
 210                    nf_ct_l3num(ct) == NFPROTO_IPV4) {
 211                        key->ipv4.ct_orig.src = orig->src.u3.ip;
 212                        key->ipv4.ct_orig.dst = orig->dst.u3.ip;
 213                        __ovs_ct_update_key_orig_tp(key, orig, IPPROTO_ICMP);
 214                        return;
 215                } else if (key->eth.type == htons(ETH_P_IPV6) &&
 216                           !sw_flow_key_is_nd(key) &&
 217                           nf_ct_l3num(ct) == NFPROTO_IPV6) {
 218                        key->ipv6.ct_orig.src = orig->src.u3.in6;
 219                        key->ipv6.ct_orig.dst = orig->dst.u3.in6;
 220                        __ovs_ct_update_key_orig_tp(key, orig, NEXTHDR_ICMP);
 221                        return;
 222                }
 223        }
 224        /* Clear 'ct_orig_proto' to mark the non-existence of conntrack
 225         * original direction key fields.
 226         */
 227        key->ct_orig_proto = 0;
 228}
 229
 230/* Update 'key' based on skb->_nfct.  If 'post_ct' is true, then OVS has
 231 * previously sent the packet to conntrack via the ct action.  If
 232 * 'keep_nat_flags' is true, the existing NAT flags retained, else they are
 233 * initialized from the connection status.
 234 */
 235static void ovs_ct_update_key(const struct sk_buff *skb,
 236                              const struct ovs_conntrack_info *info,
 237                              struct sw_flow_key *key, bool post_ct,
 238                              bool keep_nat_flags)
 239{
 240        const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
 241        enum ip_conntrack_info ctinfo;
 242        struct nf_conn *ct;
 243        u8 state = 0;
 244
 245        ct = nf_ct_get(skb, &ctinfo);
 246        if (ct) {
 247                state = ovs_ct_get_state(ctinfo);
 248                /* All unconfirmed entries are NEW connections. */
 249                if (!nf_ct_is_confirmed(ct))
 250                        state |= OVS_CS_F_NEW;
 251                /* OVS persists the related flag for the duration of the
 252                 * connection.
 253                 */
 254                if (ct->master)
 255                        state |= OVS_CS_F_RELATED;
 256                if (keep_nat_flags) {
 257                        state |= key->ct_state & OVS_CS_F_NAT_MASK;
 258                } else {
 259                        if (ct->status & IPS_SRC_NAT)
 260                                state |= OVS_CS_F_SRC_NAT;
 261                        if (ct->status & IPS_DST_NAT)
 262                                state |= OVS_CS_F_DST_NAT;
 263                }
 264                zone = nf_ct_zone(ct);
 265        } else if (post_ct) {
 266                state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
 267                if (info)
 268                        zone = &info->zone;
 269        }
 270        __ovs_ct_update_key(key, state, zone, ct);
 271}
 272
 273/* This is called to initialize CT key fields possibly coming in from the local
 274 * stack.
 275 */
 276void ovs_ct_fill_key(const struct sk_buff *skb,
 277                     struct sw_flow_key *key,
 278                     bool post_ct)
 279{
 280        ovs_ct_update_key(skb, NULL, key, post_ct, false);
 281}
 282
 283int ovs_ct_put_key(const struct sw_flow_key *swkey,
 284                   const struct sw_flow_key *output, struct sk_buff *skb)
 285{
 286        if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, output->ct_state))
 287                return -EMSGSIZE;
 288
 289        if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
 290            nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, output->ct_zone))
 291                return -EMSGSIZE;
 292
 293        if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
 294            nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, output->ct.mark))
 295                return -EMSGSIZE;
 296
 297        if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
 298            nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(output->ct.labels),
 299                    &output->ct.labels))
 300                return -EMSGSIZE;
 301
 302        if (swkey->ct_orig_proto) {
 303                if (swkey->eth.type == htons(ETH_P_IP)) {
 304                        struct ovs_key_ct_tuple_ipv4 orig;
 305
 306                        memset(&orig, 0, sizeof(orig));
 307                        orig.ipv4_src = output->ipv4.ct_orig.src;
 308                        orig.ipv4_dst = output->ipv4.ct_orig.dst;
 309                        orig.src_port = output->ct.orig_tp.src;
 310                        orig.dst_port = output->ct.orig_tp.dst;
 311                        orig.ipv4_proto = output->ct_orig_proto;
 312
 313                        if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4,
 314                                    sizeof(orig), &orig))
 315                                return -EMSGSIZE;
 316                } else if (swkey->eth.type == htons(ETH_P_IPV6)) {
 317                        struct ovs_key_ct_tuple_ipv6 orig;
 318
 319                        memset(&orig, 0, sizeof(orig));
 320                        memcpy(orig.ipv6_src, output->ipv6.ct_orig.src.s6_addr32,
 321                               sizeof(orig.ipv6_src));
 322                        memcpy(orig.ipv6_dst, output->ipv6.ct_orig.dst.s6_addr32,
 323                               sizeof(orig.ipv6_dst));
 324                        orig.src_port = output->ct.orig_tp.src;
 325                        orig.dst_port = output->ct.orig_tp.dst;
 326                        orig.ipv6_proto = output->ct_orig_proto;
 327
 328                        if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6,
 329                                    sizeof(orig), &orig))
 330                                return -EMSGSIZE;
 331                }
 332        }
 333
 334        return 0;
 335}
 336
 337static int ovs_ct_set_mark(struct nf_conn *ct, struct sw_flow_key *key,
 338                           u32 ct_mark, u32 mask)
 339{
 340#if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
 341        u32 new_mark;
 342
 343        new_mark = ct_mark | (ct->mark & ~(mask));
 344        if (ct->mark != new_mark) {
 345                ct->mark = new_mark;
 346                if (nf_ct_is_confirmed(ct))
 347                        nf_conntrack_event_cache(IPCT_MARK, ct);
 348                key->ct.mark = new_mark;
 349        }
 350
 351        return 0;
 352#else
 353        return -ENOTSUPP;
 354#endif
 355}
 356
 357static struct nf_conn_labels *ovs_ct_get_conn_labels(struct nf_conn *ct)
 358{
 359        struct nf_conn_labels *cl;
 360
 361        cl = nf_ct_labels_find(ct);
 362        if (!cl) {
 363                nf_ct_labels_ext_add(ct);
 364                cl = nf_ct_labels_find(ct);
 365        }
 366
 367        return cl;
 368}
 369
 370/* Initialize labels for a new, yet to be committed conntrack entry.  Note that
 371 * since the new connection is not yet confirmed, and thus no-one else has
 372 * access to it's labels, we simply write them over.
 373 */
 374static int ovs_ct_init_labels(struct nf_conn *ct, struct sw_flow_key *key,
 375                              const struct ovs_key_ct_labels *labels,
 376                              const struct ovs_key_ct_labels *mask)
 377{
 378        struct nf_conn_labels *cl, *master_cl;
 379        bool have_mask = labels_nonzero(mask);
 380
 381        /* Inherit master's labels to the related connection? */
 382        master_cl = ct->master ? nf_ct_labels_find(ct->master) : NULL;
 383
 384        if (!master_cl && !have_mask)
 385                return 0;   /* Nothing to do. */
 386
 387        cl = ovs_ct_get_conn_labels(ct);
 388        if (!cl)
 389                return -ENOSPC;
 390
 391        /* Inherit the master's labels, if any. */
 392        if (master_cl)
 393                *cl = *master_cl;
 394
 395        if (have_mask) {
 396                u32 *dst = (u32 *)cl->bits;
 397                int i;
 398
 399                for (i = 0; i < OVS_CT_LABELS_LEN_32; i++)
 400                        dst[i] = (dst[i] & ~mask->ct_labels_32[i]) |
 401                                (labels->ct_labels_32[i]
 402                                 & mask->ct_labels_32[i]);
 403        }
 404
 405        /* Labels are included in the IPCTNL_MSG_CT_NEW event only if the
 406         * IPCT_LABEL bit is set in the event cache.
 407         */
 408        nf_conntrack_event_cache(IPCT_LABEL, ct);
 409
 410        memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
 411
 412        return 0;
 413}
 414
 415static int ovs_ct_set_labels(struct nf_conn *ct, struct sw_flow_key *key,
 416                             const struct ovs_key_ct_labels *labels,
 417                             const struct ovs_key_ct_labels *mask)
 418{
 419        struct nf_conn_labels *cl;
 420        int err;
 421
 422        cl = ovs_ct_get_conn_labels(ct);
 423        if (!cl)
 424                return -ENOSPC;
 425
 426        err = nf_connlabels_replace(ct, labels->ct_labels_32,
 427                                    mask->ct_labels_32,
 428                                    OVS_CT_LABELS_LEN_32);
 429        if (err)
 430                return err;
 431
 432        memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
 433
 434        return 0;
 435}
 436
 437/* 'skb' should already be pulled to nh_ofs. */
 438static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
 439{
 440        const struct nf_conntrack_helper *helper;
 441        const struct nf_conn_help *help;
 442        enum ip_conntrack_info ctinfo;
 443        unsigned int protoff;
 444        struct nf_conn *ct;
 445        int err;
 446
 447        ct = nf_ct_get(skb, &ctinfo);
 448        if (!ct || ctinfo == IP_CT_RELATED_REPLY)
 449                return NF_ACCEPT;
 450
 451        help = nfct_help(ct);
 452        if (!help)
 453                return NF_ACCEPT;
 454
 455        helper = rcu_dereference(help->helper);
 456        if (!helper)
 457                return NF_ACCEPT;
 458
 459        switch (proto) {
 460        case NFPROTO_IPV4:
 461                protoff = ip_hdrlen(skb);
 462                break;
 463        case NFPROTO_IPV6: {
 464                u8 nexthdr = ipv6_hdr(skb)->nexthdr;
 465                __be16 frag_off;
 466                int ofs;
 467
 468                ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
 469                                       &frag_off);
 470                if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
 471                        pr_debug("proto header not found\n");
 472                        return NF_ACCEPT;
 473                }
 474                protoff = ofs;
 475                break;
 476        }
 477        default:
 478                WARN_ONCE(1, "helper invoked on non-IP family!");
 479                return NF_DROP;
 480        }
 481
 482        err = helper->help(skb, protoff, ct, ctinfo);
 483        if (err != NF_ACCEPT)
 484                return err;
 485
 486        /* Adjust seqs after helper.  This is needed due to some helpers (e.g.,
 487         * FTP with NAT) adusting the TCP payload size when mangling IP
 488         * addresses and/or port numbers in the text-based control connection.
 489         */
 490        if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
 491            !nf_ct_seq_adjust(skb, ct, ctinfo, protoff))
 492                return NF_DROP;
 493        return NF_ACCEPT;
 494}
 495
 496/* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
 497 * value if 'skb' is freed.
 498 */
 499static int handle_fragments(struct net *net, struct sw_flow_key *key,
 500                            u16 zone, struct sk_buff *skb)
 501{
 502        struct ovs_skb_cb ovs_cb = *OVS_CB(skb);
 503        int err;
 504
 505        if (key->eth.type == htons(ETH_P_IP)) {
 506                enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
 507
 508                memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
 509                err = ip_defrag(net, skb, user);
 510                if (err)
 511                        return err;
 512
 513                ovs_cb.mru = IPCB(skb)->frag_max_size;
 514#if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
 515        } else if (key->eth.type == htons(ETH_P_IPV6)) {
 516                enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
 517
 518                memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
 519                err = nf_ct_frag6_gather(net, skb, user);
 520                if (err) {
 521                        if (err != -EINPROGRESS)
 522                                kfree_skb(skb);
 523                        return err;
 524                }
 525
 526                key->ip.proto = ipv6_hdr(skb)->nexthdr;
 527                ovs_cb.mru = IP6CB(skb)->frag_max_size;
 528#endif
 529        } else {
 530                kfree_skb(skb);
 531                return -EPFNOSUPPORT;
 532        }
 533
 534        /* The key extracted from the fragment that completed this datagram
 535         * likely didn't have an L4 header, so regenerate it.
 536         */
 537        ovs_flow_key_update_l3l4(skb, key);
 538
 539        key->ip.frag = OVS_FRAG_TYPE_NONE;
 540        skb_clear_hash(skb);
 541        skb->ignore_df = 1;
 542        *OVS_CB(skb) = ovs_cb;
 543
 544        return 0;
 545}
 546
 547static struct nf_conntrack_expect *
 548ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
 549                   u16 proto, const struct sk_buff *skb)
 550{
 551        struct nf_conntrack_tuple tuple;
 552        struct nf_conntrack_expect *exp;
 553
 554        if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
 555                return NULL;
 556
 557        exp = __nf_ct_expect_find(net, zone, &tuple);
 558        if (exp) {
 559                struct nf_conntrack_tuple_hash *h;
 560
 561                /* Delete existing conntrack entry, if it clashes with the
 562                 * expectation.  This can happen since conntrack ALGs do not
 563                 * check for clashes between (new) expectations and existing
 564                 * conntrack entries.  nf_conntrack_in() will check the
 565                 * expectations only if a conntrack entry can not be found,
 566                 * which can lead to OVS finding the expectation (here) in the
 567                 * init direction, but which will not be removed by the
 568                 * nf_conntrack_in() call, if a matching conntrack entry is
 569                 * found instead.  In this case all init direction packets
 570                 * would be reported as new related packets, while reply
 571                 * direction packets would be reported as un-related
 572                 * established packets.
 573                 */
 574                h = nf_conntrack_find_get(net, zone, &tuple);
 575                if (h) {
 576                        struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
 577
 578                        nf_ct_delete(ct, 0, 0);
 579                        nf_ct_put(ct);
 580                }
 581        }
 582
 583        return exp;
 584}
 585
 586/* This replicates logic from nf_conntrack_core.c that is not exported. */
 587static enum ip_conntrack_info
 588ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
 589{
 590        const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
 591
 592        if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
 593                return IP_CT_ESTABLISHED_REPLY;
 594        /* Once we've had two way comms, always ESTABLISHED. */
 595        if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
 596                return IP_CT_ESTABLISHED;
 597        if (test_bit(IPS_EXPECTED_BIT, &ct->status))
 598                return IP_CT_RELATED;
 599        return IP_CT_NEW;
 600}
 601
 602/* Find an existing connection which this packet belongs to without
 603 * re-attributing statistics or modifying the connection state.  This allows an
 604 * skb->_nfct lost due to an upcall to be recovered during actions execution.
 605 *
 606 * Must be called with rcu_read_lock.
 607 *
 608 * On success, populates skb->_nfct and returns the connection.  Returns NULL
 609 * if there is no existing entry.
 610 */
 611static struct nf_conn *
 612ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
 613                     u8 l3num, struct sk_buff *skb, bool natted)
 614{
 615        struct nf_conntrack_tuple tuple;
 616        struct nf_conntrack_tuple_hash *h;
 617        struct nf_conn *ct;
 618
 619        if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), l3num,
 620                               net, &tuple)) {
 621                pr_debug("ovs_ct_find_existing: Can't get tuple\n");
 622                return NULL;
 623        }
 624
 625        /* Must invert the tuple if skb has been transformed by NAT. */
 626        if (natted) {
 627                struct nf_conntrack_tuple inverse;
 628
 629                if (!nf_ct_invert_tuple(&inverse, &tuple)) {
 630                        pr_debug("ovs_ct_find_existing: Inversion failed!\n");
 631                        return NULL;
 632                }
 633                tuple = inverse;
 634        }
 635
 636        /* look for tuple match */
 637        h = nf_conntrack_find_get(net, zone, &tuple);
 638        if (!h)
 639                return NULL;   /* Not found. */
 640
 641        ct = nf_ct_tuplehash_to_ctrack(h);
 642
 643        /* Inverted packet tuple matches the reverse direction conntrack tuple,
 644         * select the other tuplehash to get the right 'ctinfo' bits for this
 645         * packet.
 646         */
 647        if (natted)
 648                h = &ct->tuplehash[!h->tuple.dst.dir];
 649
 650        nf_ct_set(skb, ct, ovs_ct_get_info(h));
 651        return ct;
 652}
 653
 654static
 655struct nf_conn *ovs_ct_executed(struct net *net,
 656                                const struct sw_flow_key *key,
 657                                const struct ovs_conntrack_info *info,
 658                                struct sk_buff *skb,
 659                                bool *ct_executed)
 660{
 661        struct nf_conn *ct = NULL;
 662
 663        /* If no ct, check if we have evidence that an existing conntrack entry
 664         * might be found for this skb.  This happens when we lose a skb->_nfct
 665         * due to an upcall, or if the direction is being forced.  If the
 666         * connection was not confirmed, it is not cached and needs to be run
 667         * through conntrack again.
 668         */
 669        *ct_executed = (key->ct_state & OVS_CS_F_TRACKED) &&
 670                       !(key->ct_state & OVS_CS_F_INVALID) &&
 671                       (key->ct_zone == info->zone.id);
 672
 673        if (*ct_executed || (!key->ct_state && info->force)) {
 674                ct = ovs_ct_find_existing(net, &info->zone, info->family, skb,
 675                                          !!(key->ct_state &
 676                                          OVS_CS_F_NAT_MASK));
 677        }
 678
 679        return ct;
 680}
 681
 682/* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
 683static bool skb_nfct_cached(struct net *net,
 684                            const struct sw_flow_key *key,
 685                            const struct ovs_conntrack_info *info,
 686                            struct sk_buff *skb)
 687{
 688        enum ip_conntrack_info ctinfo;
 689        struct nf_conn *ct;
 690        bool ct_executed = true;
 691
 692        ct = nf_ct_get(skb, &ctinfo);
 693        if (!ct)
 694                ct = ovs_ct_executed(net, key, info, skb, &ct_executed);
 695
 696        if (ct)
 697                nf_ct_get(skb, &ctinfo);
 698        else
 699                return false;
 700
 701        if (!net_eq(net, read_pnet(&ct->ct_net)))
 702                return false;
 703        if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
 704                return false;
 705        if (info->helper) {
 706                struct nf_conn_help *help;
 707
 708                help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
 709                if (help && rcu_access_pointer(help->helper) != info->helper)
 710                        return false;
 711        }
 712        if (info->nf_ct_timeout) {
 713                struct nf_conn_timeout *timeout_ext;
 714
 715                timeout_ext = nf_ct_timeout_find(ct);
 716                if (!timeout_ext || info->nf_ct_timeout !=
 717                    rcu_dereference(timeout_ext->timeout))
 718                        return false;
 719        }
 720        /* Force conntrack entry direction to the current packet? */
 721        if (info->force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
 722                /* Delete the conntrack entry if confirmed, else just release
 723                 * the reference.
 724                 */
 725                if (nf_ct_is_confirmed(ct))
 726                        nf_ct_delete(ct, 0, 0);
 727
 728                nf_ct_put(ct);
 729                nf_ct_set(skb, NULL, 0);
 730                return false;
 731        }
 732
 733        return ct_executed;
 734}
 735
 736#if IS_ENABLED(CONFIG_NF_NAT)
 737static void ovs_nat_update_key(struct sw_flow_key *key,
 738                               const struct sk_buff *skb,
 739                               enum nf_nat_manip_type maniptype)
 740{
 741        if (maniptype == NF_NAT_MANIP_SRC) {
 742                __be16 src;
 743
 744                key->ct_state |= OVS_CS_F_SRC_NAT;
 745                if (key->eth.type == htons(ETH_P_IP))
 746                        key->ipv4.addr.src = ip_hdr(skb)->saddr;
 747                else if (key->eth.type == htons(ETH_P_IPV6))
 748                        memcpy(&key->ipv6.addr.src, &ipv6_hdr(skb)->saddr,
 749                               sizeof(key->ipv6.addr.src));
 750                else
 751                        return;
 752
 753                if (key->ip.proto == IPPROTO_UDP)
 754                        src = udp_hdr(skb)->source;
 755                else if (key->ip.proto == IPPROTO_TCP)
 756                        src = tcp_hdr(skb)->source;
 757                else if (key->ip.proto == IPPROTO_SCTP)
 758                        src = sctp_hdr(skb)->source;
 759                else
 760                        return;
 761
 762                key->tp.src = src;
 763        } else {
 764                __be16 dst;
 765
 766                key->ct_state |= OVS_CS_F_DST_NAT;
 767                if (key->eth.type == htons(ETH_P_IP))
 768                        key->ipv4.addr.dst = ip_hdr(skb)->daddr;
 769                else if (key->eth.type == htons(ETH_P_IPV6))
 770                        memcpy(&key->ipv6.addr.dst, &ipv6_hdr(skb)->daddr,
 771                               sizeof(key->ipv6.addr.dst));
 772                else
 773                        return;
 774
 775                if (key->ip.proto == IPPROTO_UDP)
 776                        dst = udp_hdr(skb)->dest;
 777                else if (key->ip.proto == IPPROTO_TCP)
 778                        dst = tcp_hdr(skb)->dest;
 779                else if (key->ip.proto == IPPROTO_SCTP)
 780                        dst = sctp_hdr(skb)->dest;
 781                else
 782                        return;
 783
 784                key->tp.dst = dst;
 785        }
 786}
 787
 788/* Modelled after nf_nat_ipv[46]_fn().
 789 * range is only used for new, uninitialized NAT state.
 790 * Returns either NF_ACCEPT or NF_DROP.
 791 */
 792static int ovs_ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
 793                              enum ip_conntrack_info ctinfo,
 794                              const struct nf_nat_range2 *range,
 795                              enum nf_nat_manip_type maniptype, struct sw_flow_key *key)
 796{
 797        int hooknum, nh_off, err = NF_ACCEPT;
 798
 799        nh_off = skb_network_offset(skb);
 800        skb_pull_rcsum(skb, nh_off);
 801
 802        /* See HOOK2MANIP(). */
 803        if (maniptype == NF_NAT_MANIP_SRC)
 804                hooknum = NF_INET_LOCAL_IN; /* Source NAT */
 805        else
 806                hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
 807
 808        switch (ctinfo) {
 809        case IP_CT_RELATED:
 810        case IP_CT_RELATED_REPLY:
 811                if (IS_ENABLED(CONFIG_NF_NAT) &&
 812                    skb->protocol == htons(ETH_P_IP) &&
 813                    ip_hdr(skb)->protocol == IPPROTO_ICMP) {
 814                        if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
 815                                                           hooknum))
 816                                err = NF_DROP;
 817                        goto push;
 818                } else if (IS_ENABLED(CONFIG_IPV6) &&
 819                           skb->protocol == htons(ETH_P_IPV6)) {
 820                        __be16 frag_off;
 821                        u8 nexthdr = ipv6_hdr(skb)->nexthdr;
 822                        int hdrlen = ipv6_skip_exthdr(skb,
 823                                                      sizeof(struct ipv6hdr),
 824                                                      &nexthdr, &frag_off);
 825
 826                        if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
 827                                if (!nf_nat_icmpv6_reply_translation(skb, ct,
 828                                                                     ctinfo,
 829                                                                     hooknum,
 830                                                                     hdrlen))
 831                                        err = NF_DROP;
 832                                goto push;
 833                        }
 834                }
 835                /* Non-ICMP, fall thru to initialize if needed. */
 836                fallthrough;
 837        case IP_CT_NEW:
 838                /* Seen it before?  This can happen for loopback, retrans,
 839                 * or local packets.
 840                 */
 841                if (!nf_nat_initialized(ct, maniptype)) {
 842                        /* Initialize according to the NAT action. */
 843                        err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
 844                                /* Action is set up to establish a new
 845                                 * mapping.
 846                                 */
 847                                ? nf_nat_setup_info(ct, range, maniptype)
 848                                : nf_nat_alloc_null_binding(ct, hooknum);
 849                        if (err != NF_ACCEPT)
 850                                goto push;
 851                }
 852                break;
 853
 854        case IP_CT_ESTABLISHED:
 855        case IP_CT_ESTABLISHED_REPLY:
 856                break;
 857
 858        default:
 859                err = NF_DROP;
 860                goto push;
 861        }
 862
 863        err = nf_nat_packet(ct, ctinfo, hooknum, skb);
 864push:
 865        skb_push_rcsum(skb, nh_off);
 866
 867        /* Update the flow key if NAT successful. */
 868        if (err == NF_ACCEPT)
 869                ovs_nat_update_key(key, skb, maniptype);
 870
 871        return err;
 872}
 873
 874/* Returns NF_DROP if the packet should be dropped, NF_ACCEPT otherwise. */
 875static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
 876                      const struct ovs_conntrack_info *info,
 877                      struct sk_buff *skb, struct nf_conn *ct,
 878                      enum ip_conntrack_info ctinfo)
 879{
 880        enum nf_nat_manip_type maniptype;
 881        int err;
 882
 883        /* Add NAT extension if not confirmed yet. */
 884        if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
 885                return NF_ACCEPT;   /* Can't NAT. */
 886
 887        /* Determine NAT type.
 888         * Check if the NAT type can be deduced from the tracked connection.
 889         * Make sure new expected connections (IP_CT_RELATED) are NATted only
 890         * when committing.
 891         */
 892        if (info->nat & OVS_CT_NAT && ctinfo != IP_CT_NEW &&
 893            ct->status & IPS_NAT_MASK &&
 894            (ctinfo != IP_CT_RELATED || info->commit)) {
 895                /* NAT an established or related connection like before. */
 896                if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
 897                        /* This is the REPLY direction for a connection
 898                         * for which NAT was applied in the forward
 899                         * direction.  Do the reverse NAT.
 900                         */
 901                        maniptype = ct->status & IPS_SRC_NAT
 902                                ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
 903                else
 904                        maniptype = ct->status & IPS_SRC_NAT
 905                                ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
 906        } else if (info->nat & OVS_CT_SRC_NAT) {
 907                maniptype = NF_NAT_MANIP_SRC;
 908        } else if (info->nat & OVS_CT_DST_NAT) {
 909                maniptype = NF_NAT_MANIP_DST;
 910        } else {
 911                return NF_ACCEPT; /* Connection is not NATed. */
 912        }
 913        err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range, maniptype, key);
 914
 915        if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
 916                if (ct->status & IPS_SRC_NAT) {
 917                        if (maniptype == NF_NAT_MANIP_SRC)
 918                                maniptype = NF_NAT_MANIP_DST;
 919                        else
 920                                maniptype = NF_NAT_MANIP_SRC;
 921
 922                        err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range,
 923                                                 maniptype, key);
 924                } else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
 925                        err = ovs_ct_nat_execute(skb, ct, ctinfo, NULL,
 926                                                 NF_NAT_MANIP_SRC, key);
 927                }
 928        }
 929
 930        return err;
 931}
 932#else /* !CONFIG_NF_NAT */
 933static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
 934                      const struct ovs_conntrack_info *info,
 935                      struct sk_buff *skb, struct nf_conn *ct,
 936                      enum ip_conntrack_info ctinfo)
 937{
 938        return NF_ACCEPT;
 939}
 940#endif
 941
 942/* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
 943 * not done already.  Update key with new CT state after passing the packet
 944 * through conntrack.
 945 * Note that if the packet is deemed invalid by conntrack, skb->_nfct will be
 946 * set to NULL and 0 will be returned.
 947 */
 948static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
 949                           const struct ovs_conntrack_info *info,
 950                           struct sk_buff *skb)
 951{
 952        /* If we are recirculating packets to match on conntrack fields and
 953         * committing with a separate conntrack action,  then we don't need to
 954         * actually run the packet through conntrack twice unless it's for a
 955         * different zone.
 956         */
 957        bool cached = skb_nfct_cached(net, key, info, skb);
 958        enum ip_conntrack_info ctinfo;
 959        struct nf_conn *ct;
 960
 961        if (!cached) {
 962                struct nf_hook_state state = {
 963                        .hook = NF_INET_PRE_ROUTING,
 964                        .pf = info->family,
 965                        .net = net,
 966                };
 967                struct nf_conn *tmpl = info->ct;
 968                int err;
 969
 970                /* Associate skb with specified zone. */
 971                if (tmpl) {
 972                        ct = nf_ct_get(skb, &ctinfo);
 973                        nf_ct_put(ct);
 974                        nf_conntrack_get(&tmpl->ct_general);
 975                        nf_ct_set(skb, tmpl, IP_CT_NEW);
 976                }
 977
 978                err = nf_conntrack_in(skb, &state);
 979                if (err != NF_ACCEPT)
 980                        return -ENOENT;
 981
 982                /* Clear CT state NAT flags to mark that we have not yet done
 983                 * NAT after the nf_conntrack_in() call.  We can actually clear
 984                 * the whole state, as it will be re-initialized below.
 985                 */
 986                key->ct_state = 0;
 987
 988                /* Update the key, but keep the NAT flags. */
 989                ovs_ct_update_key(skb, info, key, true, true);
 990        }
 991
 992        ct = nf_ct_get(skb, &ctinfo);
 993        if (ct) {
 994                bool add_helper = false;
 995
 996                /* Packets starting a new connection must be NATted before the
 997                 * helper, so that the helper knows about the NAT.  We enforce
 998                 * this by delaying both NAT and helper calls for unconfirmed
 999                 * connections until the committing CT action.  For later
1000                 * packets NAT and Helper may be called in either order.
1001                 *
1002                 * NAT will be done only if the CT action has NAT, and only
1003                 * once per packet (per zone), as guarded by the NAT bits in
1004                 * the key->ct_state.
1005                 */
1006                if (info->nat && !(key->ct_state & OVS_CS_F_NAT_MASK) &&
1007                    (nf_ct_is_confirmed(ct) || info->commit) &&
1008                    ovs_ct_nat(net, key, info, skb, ct, ctinfo) != NF_ACCEPT) {
1009                        return -EINVAL;
1010                }
1011
1012                /* Userspace may decide to perform a ct lookup without a helper
1013                 * specified followed by a (recirculate and) commit with one,
1014                 * or attach a helper in a later commit.  Therefore, for
1015                 * connections which we will commit, we may need to attach
1016                 * the helper here.
1017                 */
1018                if (info->commit && info->helper && !nfct_help(ct)) {
1019                        int err = __nf_ct_try_assign_helper(ct, info->ct,
1020                                                            GFP_ATOMIC);
1021                        if (err)
1022                                return err;
1023                        add_helper = true;
1024
1025                        /* helper installed, add seqadj if NAT is required */
1026                        if (info->nat && !nfct_seqadj(ct)) {
1027                                if (!nfct_seqadj_ext_add(ct))
1028                                        return -EINVAL;
1029                        }
1030                }
1031
1032                /* Call the helper only if:
1033                 * - nf_conntrack_in() was executed above ("!cached") or a
1034                 *   helper was just attached ("add_helper") for a confirmed
1035                 *   connection, or
1036                 * - When committing an unconfirmed connection.
1037                 */
1038                if ((nf_ct_is_confirmed(ct) ? !cached || add_helper :
1039                                              info->commit) &&
1040                    ovs_ct_helper(skb, info->family) != NF_ACCEPT) {
1041                        return -EINVAL;
1042                }
1043
1044                if (nf_ct_protonum(ct) == IPPROTO_TCP &&
1045                    nf_ct_is_confirmed(ct) && nf_conntrack_tcp_established(ct)) {
1046                        /* Be liberal for tcp packets so that out-of-window
1047                         * packets are not marked invalid.
1048                         */
1049                        nf_ct_set_tcp_be_liberal(ct);
1050                }
1051
1052                nf_conn_act_ct_ext_fill(skb, ct, ctinfo);
1053        }
1054
1055        return 0;
1056}
1057
1058/* Lookup connection and read fields into key. */
1059static int ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
1060                         const struct ovs_conntrack_info *info,
1061                         struct sk_buff *skb)
1062{
1063        struct nf_conntrack_expect *exp;
1064
1065        /* If we pass an expected packet through nf_conntrack_in() the
1066         * expectation is typically removed, but the packet could still be
1067         * lost in upcall processing.  To prevent this from happening we
1068         * perform an explicit expectation lookup.  Expected connections are
1069         * always new, and will be passed through conntrack only when they are
1070         * committed, as it is OK to remove the expectation at that time.
1071         */
1072        exp = ovs_ct_expect_find(net, &info->zone, info->family, skb);
1073        if (exp) {
1074                u8 state;
1075
1076                /* NOTE: New connections are NATted and Helped only when
1077                 * committed, so we are not calling into NAT here.
1078                 */
1079                state = OVS_CS_F_TRACKED | OVS_CS_F_NEW | OVS_CS_F_RELATED;
1080                __ovs_ct_update_key(key, state, &info->zone, exp->master);
1081        } else {
1082                struct nf_conn *ct;
1083                int err;
1084
1085                err = __ovs_ct_lookup(net, key, info, skb);
1086                if (err)
1087                        return err;
1088
1089                ct = (struct nf_conn *)skb_nfct(skb);
1090                if (ct)
1091                        nf_ct_deliver_cached_events(ct);
1092        }
1093
1094        return 0;
1095}
1096
1097static bool labels_nonzero(const struct ovs_key_ct_labels *labels)
1098{
1099        size_t i;
1100
1101        for (i = 0; i < OVS_CT_LABELS_LEN_32; i++)
1102                if (labels->ct_labels_32[i])
1103                        return true;
1104
1105        return false;
1106}
1107
1108#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1109static struct hlist_head *ct_limit_hash_bucket(
1110        const struct ovs_ct_limit_info *info, u16 zone)
1111{
1112        return &info->limits[zone & (CT_LIMIT_HASH_BUCKETS - 1)];
1113}
1114
1115/* Call with ovs_mutex */
1116static void ct_limit_set(const struct ovs_ct_limit_info *info,
1117                         struct ovs_ct_limit *new_ct_limit)
1118{
1119        struct ovs_ct_limit *ct_limit;
1120        struct hlist_head *head;
1121
1122        head = ct_limit_hash_bucket(info, new_ct_limit->zone);
1123        hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
1124                if (ct_limit->zone == new_ct_limit->zone) {
1125                        hlist_replace_rcu(&ct_limit->hlist_node,
1126                                          &new_ct_limit->hlist_node);
1127                        kfree_rcu(ct_limit, rcu);
1128                        return;
1129                }
1130        }
1131
1132        hlist_add_head_rcu(&new_ct_limit->hlist_node, head);
1133}
1134
1135/* Call with ovs_mutex */
1136static void ct_limit_del(const struct ovs_ct_limit_info *info, u16 zone)
1137{
1138        struct ovs_ct_limit *ct_limit;
1139        struct hlist_head *head;
1140        struct hlist_node *n;
1141
1142        head = ct_limit_hash_bucket(info, zone);
1143        hlist_for_each_entry_safe(ct_limit, n, head, hlist_node) {
1144                if (ct_limit->zone == zone) {
1145                        hlist_del_rcu(&ct_limit->hlist_node);
1146                        kfree_rcu(ct_limit, rcu);
1147                        return;
1148                }
1149        }
1150}
1151
1152/* Call with RCU read lock */
1153static u32 ct_limit_get(const struct ovs_ct_limit_info *info, u16 zone)
1154{
1155        struct ovs_ct_limit *ct_limit;
1156        struct hlist_head *head;
1157
1158        head = ct_limit_hash_bucket(info, zone);
1159        hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
1160                if (ct_limit->zone == zone)
1161                        return ct_limit->limit;
1162        }
1163
1164        return info->default_limit;
1165}
1166
1167static int ovs_ct_check_limit(struct net *net,
1168                              const struct ovs_conntrack_info *info,
1169                              const struct nf_conntrack_tuple *tuple)
1170{
1171        struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1172        const struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
1173        u32 per_zone_limit, connections;
1174        u32 conncount_key;
1175
1176        conncount_key = info->zone.id;
1177
1178        per_zone_limit = ct_limit_get(ct_limit_info, info->zone.id);
1179        if (per_zone_limit == OVS_CT_LIMIT_UNLIMITED)
1180                return 0;
1181
1182        connections = nf_conncount_count(net, ct_limit_info->data,
1183                                         &conncount_key, tuple, &info->zone);
1184        if (connections > per_zone_limit)
1185                return -ENOMEM;
1186
1187        return 0;
1188}
1189#endif
1190
1191/* Lookup connection and confirm if unconfirmed. */
1192static int ovs_ct_commit(struct net *net, struct sw_flow_key *key,
1193                         const struct ovs_conntrack_info *info,
1194                         struct sk_buff *skb)
1195{
1196        enum ip_conntrack_info ctinfo;
1197        struct nf_conn *ct;
1198        int err;
1199
1200        err = __ovs_ct_lookup(net, key, info, skb);
1201        if (err)
1202                return err;
1203
1204        /* The connection could be invalid, in which case this is a no-op.*/
1205        ct = nf_ct_get(skb, &ctinfo);
1206        if (!ct)
1207                return 0;
1208
1209#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1210        if (static_branch_unlikely(&ovs_ct_limit_enabled)) {
1211                if (!nf_ct_is_confirmed(ct)) {
1212                        err = ovs_ct_check_limit(net, info,
1213                                &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
1214                        if (err) {
1215                                net_warn_ratelimited("openvswitch: zone: %u "
1216                                        "exceeds conntrack limit\n",
1217                                        info->zone.id);
1218                                return err;
1219                        }
1220                }
1221        }
1222#endif
1223
1224        /* Set the conntrack event mask if given.  NEW and DELETE events have
1225         * their own groups, but the NFNLGRP_CONNTRACK_UPDATE group listener
1226         * typically would receive many kinds of updates.  Setting the event
1227         * mask allows those events to be filtered.  The set event mask will
1228         * remain in effect for the lifetime of the connection unless changed
1229         * by a further CT action with both the commit flag and the eventmask
1230         * option. */
1231        if (info->have_eventmask) {
1232                struct nf_conntrack_ecache *cache = nf_ct_ecache_find(ct);
1233
1234                if (cache)
1235                        cache->ctmask = info->eventmask;
1236        }
1237
1238        /* Apply changes before confirming the connection so that the initial
1239         * conntrack NEW netlink event carries the values given in the CT
1240         * action.
1241         */
1242        if (info->mark.mask) {
1243                err = ovs_ct_set_mark(ct, key, info->mark.value,
1244                                      info->mark.mask);
1245                if (err)
1246                        return err;
1247        }
1248        if (!nf_ct_is_confirmed(ct)) {
1249                err = ovs_ct_init_labels(ct, key, &info->labels.value,
1250                                         &info->labels.mask);
1251                if (err)
1252                        return err;
1253
1254                nf_conn_act_ct_ext_add(ct);
1255        } else if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1256                   labels_nonzero(&info->labels.mask)) {
1257                err = ovs_ct_set_labels(ct, key, &info->labels.value,
1258                                        &info->labels.mask);
1259                if (err)
1260                        return err;
1261        }
1262        /* This will take care of sending queued events even if the connection
1263         * is already confirmed.
1264         */
1265        if (nf_conntrack_confirm(skb) != NF_ACCEPT)
1266                return -EINVAL;
1267
1268        return 0;
1269}
1270
1271/* Trim the skb to the length specified by the IP/IPv6 header,
1272 * removing any trailing lower-layer padding. This prepares the skb
1273 * for higher-layer processing that assumes skb->len excludes padding
1274 * (such as nf_ip_checksum). The caller needs to pull the skb to the
1275 * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
1276 */
1277static int ovs_skb_network_trim(struct sk_buff *skb)
1278{
1279        unsigned int len;
1280        int err;
1281
1282        switch (skb->protocol) {
1283        case htons(ETH_P_IP):
1284                len = ntohs(ip_hdr(skb)->tot_len);
1285                break;
1286        case htons(ETH_P_IPV6):
1287                len = sizeof(struct ipv6hdr)
1288                        + ntohs(ipv6_hdr(skb)->payload_len);
1289                break;
1290        default:
1291                len = skb->len;
1292        }
1293
1294        err = pskb_trim_rcsum(skb, len);
1295        if (err)
1296                kfree_skb(skb);
1297
1298        return err;
1299}
1300
1301/* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
1302 * value if 'skb' is freed.
1303 */
1304int ovs_ct_execute(struct net *net, struct sk_buff *skb,
1305                   struct sw_flow_key *key,
1306                   const struct ovs_conntrack_info *info)
1307{
1308        int nh_ofs;
1309        int err;
1310
1311        /* The conntrack module expects to be working at L3. */
1312        nh_ofs = skb_network_offset(skb);
1313        skb_pull_rcsum(skb, nh_ofs);
1314
1315        err = ovs_skb_network_trim(skb);
1316        if (err)
1317                return err;
1318
1319        if (key->ip.frag != OVS_FRAG_TYPE_NONE) {
1320                err = handle_fragments(net, key, info->zone.id, skb);
1321                if (err)
1322                        return err;
1323        }
1324
1325        if (info->commit)
1326                err = ovs_ct_commit(net, key, info, skb);
1327        else
1328                err = ovs_ct_lookup(net, key, info, skb);
1329
1330        skb_push_rcsum(skb, nh_ofs);
1331        if (err)
1332                kfree_skb(skb);
1333        return err;
1334}
1335
1336int ovs_ct_clear(struct sk_buff *skb, struct sw_flow_key *key)
1337{
1338        enum ip_conntrack_info ctinfo;
1339        struct nf_conn *ct;
1340
1341        ct = nf_ct_get(skb, &ctinfo);
1342
1343        nf_ct_put(ct);
1344        nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
1345        ovs_ct_fill_key(skb, key, false);
1346
1347        return 0;
1348}
1349
1350static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
1351                             const struct sw_flow_key *key, bool log)
1352{
1353        struct nf_conntrack_helper *helper;
1354        struct nf_conn_help *help;
1355        int ret = 0;
1356
1357        helper = nf_conntrack_helper_try_module_get(name, info->family,
1358                                                    key->ip.proto);
1359        if (!helper) {
1360                OVS_NLERR(log, "Unknown helper \"%s\"", name);
1361                return -EINVAL;
1362        }
1363
1364        help = nf_ct_helper_ext_add(info->ct, GFP_KERNEL);
1365        if (!help) {
1366                nf_conntrack_helper_put(helper);
1367                return -ENOMEM;
1368        }
1369
1370#if IS_ENABLED(CONFIG_NF_NAT)
1371        if (info->nat) {
1372                ret = nf_nat_helper_try_module_get(name, info->family,
1373                                                   key->ip.proto);
1374                if (ret) {
1375                        nf_conntrack_helper_put(helper);
1376                        OVS_NLERR(log, "Failed to load \"%s\" NAT helper, error: %d",
1377                                  name, ret);
1378                        return ret;
1379                }
1380        }
1381#endif
1382        rcu_assign_pointer(help->helper, helper);
1383        info->helper = helper;
1384        return ret;
1385}
1386
1387#if IS_ENABLED(CONFIG_NF_NAT)
1388static int parse_nat(const struct nlattr *attr,
1389                     struct ovs_conntrack_info *info, bool log)
1390{
1391        struct nlattr *a;
1392        int rem;
1393        bool have_ip_max = false;
1394        bool have_proto_max = false;
1395        bool ip_vers = (info->family == NFPROTO_IPV6);
1396
1397        nla_for_each_nested(a, attr, rem) {
1398                static const int ovs_nat_attr_lens[OVS_NAT_ATTR_MAX + 1][2] = {
1399                        [OVS_NAT_ATTR_SRC] = {0, 0},
1400                        [OVS_NAT_ATTR_DST] = {0, 0},
1401                        [OVS_NAT_ATTR_IP_MIN] = {sizeof(struct in_addr),
1402                                                 sizeof(struct in6_addr)},
1403                        [OVS_NAT_ATTR_IP_MAX] = {sizeof(struct in_addr),
1404                                                 sizeof(struct in6_addr)},
1405                        [OVS_NAT_ATTR_PROTO_MIN] = {sizeof(u16), sizeof(u16)},
1406                        [OVS_NAT_ATTR_PROTO_MAX] = {sizeof(u16), sizeof(u16)},
1407                        [OVS_NAT_ATTR_PERSISTENT] = {0, 0},
1408                        [OVS_NAT_ATTR_PROTO_HASH] = {0, 0},
1409                        [OVS_NAT_ATTR_PROTO_RANDOM] = {0, 0},
1410                };
1411                int type = nla_type(a);
1412
1413                if (type > OVS_NAT_ATTR_MAX) {
1414                        OVS_NLERR(log, "Unknown NAT attribute (type=%d, max=%d)",
1415                                  type, OVS_NAT_ATTR_MAX);
1416                        return -EINVAL;
1417                }
1418
1419                if (nla_len(a) != ovs_nat_attr_lens[type][ip_vers]) {
1420                        OVS_NLERR(log, "NAT attribute type %d has unexpected length (%d != %d)",
1421                                  type, nla_len(a),
1422                                  ovs_nat_attr_lens[type][ip_vers]);
1423                        return -EINVAL;
1424                }
1425
1426                switch (type) {
1427                case OVS_NAT_ATTR_SRC:
1428                case OVS_NAT_ATTR_DST:
1429                        if (info->nat) {
1430                                OVS_NLERR(log, "Only one type of NAT may be specified");
1431                                return -ERANGE;
1432                        }
1433                        info->nat |= OVS_CT_NAT;
1434                        info->nat |= ((type == OVS_NAT_ATTR_SRC)
1435                                        ? OVS_CT_SRC_NAT : OVS_CT_DST_NAT);
1436                        break;
1437
1438                case OVS_NAT_ATTR_IP_MIN:
1439                        nla_memcpy(&info->range.min_addr, a,
1440                                   sizeof(info->range.min_addr));
1441                        info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1442                        break;
1443
1444                case OVS_NAT_ATTR_IP_MAX:
1445                        have_ip_max = true;
1446                        nla_memcpy(&info->range.max_addr, a,
1447                                   sizeof(info->range.max_addr));
1448                        info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1449                        break;
1450
1451                case OVS_NAT_ATTR_PROTO_MIN:
1452                        info->range.min_proto.all = htons(nla_get_u16(a));
1453                        info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1454                        break;
1455
1456                case OVS_NAT_ATTR_PROTO_MAX:
1457                        have_proto_max = true;
1458                        info->range.max_proto.all = htons(nla_get_u16(a));
1459                        info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1460                        break;
1461
1462                case OVS_NAT_ATTR_PERSISTENT:
1463                        info->range.flags |= NF_NAT_RANGE_PERSISTENT;
1464                        break;
1465
1466                case OVS_NAT_ATTR_PROTO_HASH:
1467                        info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM;
1468                        break;
1469
1470                case OVS_NAT_ATTR_PROTO_RANDOM:
1471                        info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY;
1472                        break;
1473
1474                default:
1475                        OVS_NLERR(log, "Unknown nat attribute (%d)", type);
1476                        return -EINVAL;
1477                }
1478        }
1479
1480        if (rem > 0) {
1481                OVS_NLERR(log, "NAT attribute has %d unknown bytes", rem);
1482                return -EINVAL;
1483        }
1484        if (!info->nat) {
1485                /* Do not allow flags if no type is given. */
1486                if (info->range.flags) {
1487                        OVS_NLERR(log,
1488                                  "NAT flags may be given only when NAT range (SRC or DST) is also specified."
1489                                  );
1490                        return -EINVAL;
1491                }
1492                info->nat = OVS_CT_NAT;   /* NAT existing connections. */
1493        } else if (!info->commit) {
1494                OVS_NLERR(log,
1495                          "NAT attributes may be specified only when CT COMMIT flag is also specified."
1496                          );
1497                return -EINVAL;
1498        }
1499        /* Allow missing IP_MAX. */
1500        if (info->range.flags & NF_NAT_RANGE_MAP_IPS && !have_ip_max) {
1501                memcpy(&info->range.max_addr, &info->range.min_addr,
1502                       sizeof(info->range.max_addr));
1503        }
1504        /* Allow missing PROTO_MAX. */
1505        if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1506            !have_proto_max) {
1507                info->range.max_proto.all = info->range.min_proto.all;
1508        }
1509        return 0;
1510}
1511#endif
1512
1513static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
1514        [OVS_CT_ATTR_COMMIT]    = { .minlen = 0, .maxlen = 0 },
1515        [OVS_CT_ATTR_FORCE_COMMIT]      = { .minlen = 0, .maxlen = 0 },
1516        [OVS_CT_ATTR_ZONE]      = { .minlen = sizeof(u16),
1517                                    .maxlen = sizeof(u16) },
1518        [OVS_CT_ATTR_MARK]      = { .minlen = sizeof(struct md_mark),
1519                                    .maxlen = sizeof(struct md_mark) },
1520        [OVS_CT_ATTR_LABELS]    = { .minlen = sizeof(struct md_labels),
1521                                    .maxlen = sizeof(struct md_labels) },
1522        [OVS_CT_ATTR_HELPER]    = { .minlen = 1,
1523                                    .maxlen = NF_CT_HELPER_NAME_LEN },
1524#if IS_ENABLED(CONFIG_NF_NAT)
1525        /* NAT length is checked when parsing the nested attributes. */
1526        [OVS_CT_ATTR_NAT]       = { .minlen = 0, .maxlen = INT_MAX },
1527#endif
1528        [OVS_CT_ATTR_EVENTMASK] = { .minlen = sizeof(u32),
1529                                    .maxlen = sizeof(u32) },
1530        [OVS_CT_ATTR_TIMEOUT] = { .minlen = 1,
1531                                  .maxlen = CTNL_TIMEOUT_NAME_MAX },
1532};
1533
1534static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
1535                    const char **helper, bool log)
1536{
1537        struct nlattr *a;
1538        int rem;
1539
1540        nla_for_each_nested(a, attr, rem) {
1541                int type = nla_type(a);
1542                int maxlen;
1543                int minlen;
1544
1545                if (type > OVS_CT_ATTR_MAX) {
1546                        OVS_NLERR(log,
1547                                  "Unknown conntrack attr (type=%d, max=%d)",
1548                                  type, OVS_CT_ATTR_MAX);
1549                        return -EINVAL;
1550                }
1551
1552                maxlen = ovs_ct_attr_lens[type].maxlen;
1553                minlen = ovs_ct_attr_lens[type].minlen;
1554                if (nla_len(a) < minlen || nla_len(a) > maxlen) {
1555                        OVS_NLERR(log,
1556                                  "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
1557                                  type, nla_len(a), maxlen);
1558                        return -EINVAL;
1559                }
1560
1561                switch (type) {
1562                case OVS_CT_ATTR_FORCE_COMMIT:
1563                        info->force = true;
1564                        fallthrough;
1565                case OVS_CT_ATTR_COMMIT:
1566                        info->commit = true;
1567                        break;
1568#ifdef CONFIG_NF_CONNTRACK_ZONES
1569                case OVS_CT_ATTR_ZONE:
1570                        info->zone.id = nla_get_u16(a);
1571                        break;
1572#endif
1573#ifdef CONFIG_NF_CONNTRACK_MARK
1574                case OVS_CT_ATTR_MARK: {
1575                        struct md_mark *mark = nla_data(a);
1576
1577                        if (!mark->mask) {
1578                                OVS_NLERR(log, "ct_mark mask cannot be 0");
1579                                return -EINVAL;
1580                        }
1581                        info->mark = *mark;
1582                        break;
1583                }
1584#endif
1585#ifdef CONFIG_NF_CONNTRACK_LABELS
1586                case OVS_CT_ATTR_LABELS: {
1587                        struct md_labels *labels = nla_data(a);
1588
1589                        if (!labels_nonzero(&labels->mask)) {
1590                                OVS_NLERR(log, "ct_labels mask cannot be 0");
1591                                return -EINVAL;
1592                        }
1593                        info->labels = *labels;
1594                        break;
1595                }
1596#endif
1597                case OVS_CT_ATTR_HELPER:
1598                        *helper = nla_data(a);
1599                        if (!memchr(*helper, '\0', nla_len(a))) {
1600                                OVS_NLERR(log, "Invalid conntrack helper");
1601                                return -EINVAL;
1602                        }
1603                        break;
1604#if IS_ENABLED(CONFIG_NF_NAT)
1605                case OVS_CT_ATTR_NAT: {
1606                        int err = parse_nat(a, info, log);
1607
1608                        if (err)
1609                                return err;
1610                        break;
1611                }
1612#endif
1613                case OVS_CT_ATTR_EVENTMASK:
1614                        info->have_eventmask = true;
1615                        info->eventmask = nla_get_u32(a);
1616                        break;
1617#ifdef CONFIG_NF_CONNTRACK_TIMEOUT
1618                case OVS_CT_ATTR_TIMEOUT:
1619                        memcpy(info->timeout, nla_data(a), nla_len(a));
1620                        if (!memchr(info->timeout, '\0', nla_len(a))) {
1621                                OVS_NLERR(log, "Invalid conntrack timeout");
1622                                return -EINVAL;
1623                        }
1624                        break;
1625#endif
1626
1627                default:
1628                        OVS_NLERR(log, "Unknown conntrack attr (%d)",
1629                                  type);
1630                        return -EINVAL;
1631                }
1632        }
1633
1634#ifdef CONFIG_NF_CONNTRACK_MARK
1635        if (!info->commit && info->mark.mask) {
1636                OVS_NLERR(log,
1637                          "Setting conntrack mark requires 'commit' flag.");
1638                return -EINVAL;
1639        }
1640#endif
1641#ifdef CONFIG_NF_CONNTRACK_LABELS
1642        if (!info->commit && labels_nonzero(&info->labels.mask)) {
1643                OVS_NLERR(log,
1644                          "Setting conntrack labels requires 'commit' flag.");
1645                return -EINVAL;
1646        }
1647#endif
1648        if (rem > 0) {
1649                OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
1650                return -EINVAL;
1651        }
1652
1653        return 0;
1654}
1655
1656bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
1657{
1658        if (attr == OVS_KEY_ATTR_CT_STATE)
1659                return true;
1660        if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1661            attr == OVS_KEY_ATTR_CT_ZONE)
1662                return true;
1663        if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1664            attr == OVS_KEY_ATTR_CT_MARK)
1665                return true;
1666        if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1667            attr == OVS_KEY_ATTR_CT_LABELS) {
1668                struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1669
1670                return ovs_net->xt_label;
1671        }
1672
1673        return false;
1674}
1675
1676int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
1677                       const struct sw_flow_key *key,
1678                       struct sw_flow_actions **sfa,  bool log)
1679{
1680        struct ovs_conntrack_info ct_info;
1681        const char *helper = NULL;
1682        u16 family;
1683        int err;
1684
1685        family = key_to_nfproto(key);
1686        if (family == NFPROTO_UNSPEC) {
1687                OVS_NLERR(log, "ct family unspecified");
1688                return -EINVAL;
1689        }
1690
1691        memset(&ct_info, 0, sizeof(ct_info));
1692        ct_info.family = family;
1693
1694        nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
1695                        NF_CT_DEFAULT_ZONE_DIR, 0);
1696
1697        err = parse_ct(attr, &ct_info, &helper, log);
1698        if (err)
1699                return err;
1700
1701        /* Set up template for tracking connections in specific zones. */
1702        ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
1703        if (!ct_info.ct) {
1704                OVS_NLERR(log, "Failed to allocate conntrack template");
1705                return -ENOMEM;
1706        }
1707
1708        if (ct_info.timeout[0]) {
1709                if (nf_ct_set_timeout(net, ct_info.ct, family, key->ip.proto,
1710                                      ct_info.timeout))
1711                        pr_info_ratelimited("Failed to associated timeout "
1712                                            "policy `%s'\n", ct_info.timeout);
1713                else
1714                        ct_info.nf_ct_timeout = rcu_dereference(
1715                                nf_ct_timeout_find(ct_info.ct)->timeout);
1716
1717        }
1718
1719        if (helper) {
1720                err = ovs_ct_add_helper(&ct_info, helper, key, log);
1721                if (err)
1722                        goto err_free_ct;
1723        }
1724
1725        err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
1726                                 sizeof(ct_info), log);
1727        if (err)
1728                goto err_free_ct;
1729
1730        __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
1731        return 0;
1732err_free_ct:
1733        __ovs_ct_free_action(&ct_info);
1734        return err;
1735}
1736
1737#if IS_ENABLED(CONFIG_NF_NAT)
1738static bool ovs_ct_nat_to_attr(const struct ovs_conntrack_info *info,
1739                               struct sk_buff *skb)
1740{
1741        struct nlattr *start;
1742
1743        start = nla_nest_start_noflag(skb, OVS_CT_ATTR_NAT);
1744        if (!start)
1745                return false;
1746
1747        if (info->nat & OVS_CT_SRC_NAT) {
1748                if (nla_put_flag(skb, OVS_NAT_ATTR_SRC))
1749                        return false;
1750        } else if (info->nat & OVS_CT_DST_NAT) {
1751                if (nla_put_flag(skb, OVS_NAT_ATTR_DST))
1752                        return false;
1753        } else {
1754                goto out;
1755        }
1756
1757        if (info->range.flags & NF_NAT_RANGE_MAP_IPS) {
1758                if (IS_ENABLED(CONFIG_NF_NAT) &&
1759                    info->family == NFPROTO_IPV4) {
1760                        if (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MIN,
1761                                            info->range.min_addr.ip) ||
1762                            (info->range.max_addr.ip
1763                             != info->range.min_addr.ip &&
1764                             (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MAX,
1765                                              info->range.max_addr.ip))))
1766                                return false;
1767                } else if (IS_ENABLED(CONFIG_IPV6) &&
1768                           info->family == NFPROTO_IPV6) {
1769                        if (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MIN,
1770                                             &info->range.min_addr.in6) ||
1771                            (memcmp(&info->range.max_addr.in6,
1772                                    &info->range.min_addr.in6,
1773                                    sizeof(info->range.max_addr.in6)) &&
1774                             (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MAX,
1775                                               &info->range.max_addr.in6))))
1776                                return false;
1777                } else {
1778                        return false;
1779                }
1780        }
1781        if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1782            (nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MIN,
1783                         ntohs(info->range.min_proto.all)) ||
1784             (info->range.max_proto.all != info->range.min_proto.all &&
1785              nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MAX,
1786                          ntohs(info->range.max_proto.all)))))
1787                return false;
1788
1789        if (info->range.flags & NF_NAT_RANGE_PERSISTENT &&
1790            nla_put_flag(skb, OVS_NAT_ATTR_PERSISTENT))
1791                return false;
1792        if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM &&
1793            nla_put_flag(skb, OVS_NAT_ATTR_PROTO_HASH))
1794                return false;
1795        if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY &&
1796            nla_put_flag(skb, OVS_NAT_ATTR_PROTO_RANDOM))
1797                return false;
1798out:
1799        nla_nest_end(skb, start);
1800
1801        return true;
1802}
1803#endif
1804
1805int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
1806                          struct sk_buff *skb)
1807{
1808        struct nlattr *start;
1809
1810        start = nla_nest_start_noflag(skb, OVS_ACTION_ATTR_CT);
1811        if (!start)
1812                return -EMSGSIZE;
1813
1814        if (ct_info->commit && nla_put_flag(skb, ct_info->force
1815                                            ? OVS_CT_ATTR_FORCE_COMMIT
1816                                            : OVS_CT_ATTR_COMMIT))
1817                return -EMSGSIZE;
1818        if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1819            nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
1820                return -EMSGSIZE;
1821        if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
1822            nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
1823                    &ct_info->mark))
1824                return -EMSGSIZE;
1825        if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1826            labels_nonzero(&ct_info->labels.mask) &&
1827            nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
1828                    &ct_info->labels))
1829                return -EMSGSIZE;
1830        if (ct_info->helper) {
1831                if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
1832                                   ct_info->helper->name))
1833                        return -EMSGSIZE;
1834        }
1835        if (ct_info->have_eventmask &&
1836            nla_put_u32(skb, OVS_CT_ATTR_EVENTMASK, ct_info->eventmask))
1837                return -EMSGSIZE;
1838        if (ct_info->timeout[0]) {
1839                if (nla_put_string(skb, OVS_CT_ATTR_TIMEOUT, ct_info->timeout))
1840                        return -EMSGSIZE;
1841        }
1842
1843#if IS_ENABLED(CONFIG_NF_NAT)
1844        if (ct_info->nat && !ovs_ct_nat_to_attr(ct_info, skb))
1845                return -EMSGSIZE;
1846#endif
1847        nla_nest_end(skb, start);
1848
1849        return 0;
1850}
1851
1852void ovs_ct_free_action(const struct nlattr *a)
1853{
1854        struct ovs_conntrack_info *ct_info = nla_data(a);
1855
1856        __ovs_ct_free_action(ct_info);
1857}
1858
1859static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
1860{
1861        if (ct_info->helper) {
1862#if IS_ENABLED(CONFIG_NF_NAT)
1863                if (ct_info->nat)
1864                        nf_nat_helper_put(ct_info->helper);
1865#endif
1866                nf_conntrack_helper_put(ct_info->helper);
1867        }
1868        if (ct_info->ct) {
1869                if (ct_info->timeout[0])
1870                        nf_ct_destroy_timeout(ct_info->ct);
1871                nf_ct_tmpl_free(ct_info->ct);
1872        }
1873}
1874
1875#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1876static int ovs_ct_limit_init(struct net *net, struct ovs_net *ovs_net)
1877{
1878        int i, err;
1879
1880        ovs_net->ct_limit_info = kmalloc(sizeof(*ovs_net->ct_limit_info),
1881                                         GFP_KERNEL);
1882        if (!ovs_net->ct_limit_info)
1883                return -ENOMEM;
1884
1885        ovs_net->ct_limit_info->default_limit = OVS_CT_LIMIT_DEFAULT;
1886        ovs_net->ct_limit_info->limits =
1887                kmalloc_array(CT_LIMIT_HASH_BUCKETS, sizeof(struct hlist_head),
1888                              GFP_KERNEL);
1889        if (!ovs_net->ct_limit_info->limits) {
1890                kfree(ovs_net->ct_limit_info);
1891                return -ENOMEM;
1892        }
1893
1894        for (i = 0; i < CT_LIMIT_HASH_BUCKETS; i++)
1895                INIT_HLIST_HEAD(&ovs_net->ct_limit_info->limits[i]);
1896
1897        ovs_net->ct_limit_info->data =
1898                nf_conncount_init(net, NFPROTO_INET, sizeof(u32));
1899
1900        if (IS_ERR(ovs_net->ct_limit_info->data)) {
1901                err = PTR_ERR(ovs_net->ct_limit_info->data);
1902                kfree(ovs_net->ct_limit_info->limits);
1903                kfree(ovs_net->ct_limit_info);
1904                pr_err("openvswitch: failed to init nf_conncount %d\n", err);
1905                return err;
1906        }
1907        return 0;
1908}
1909
1910static void ovs_ct_limit_exit(struct net *net, struct ovs_net *ovs_net)
1911{
1912        const struct ovs_ct_limit_info *info = ovs_net->ct_limit_info;
1913        int i;
1914
1915        nf_conncount_destroy(net, NFPROTO_INET, info->data);
1916        for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
1917                struct hlist_head *head = &info->limits[i];
1918                struct ovs_ct_limit *ct_limit;
1919
1920                hlist_for_each_entry_rcu(ct_limit, head, hlist_node,
1921                                         lockdep_ovsl_is_held())
1922                        kfree_rcu(ct_limit, rcu);
1923        }
1924        kfree(info->limits);
1925        kfree(info);
1926}
1927
1928static struct sk_buff *
1929ovs_ct_limit_cmd_reply_start(struct genl_info *info, u8 cmd,
1930                             struct ovs_header **ovs_reply_header)
1931{
1932        struct ovs_header *ovs_header = info->userhdr;
1933        struct sk_buff *skb;
1934
1935        skb = genlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1936        if (!skb)
1937                return ERR_PTR(-ENOMEM);
1938
1939        *ovs_reply_header = genlmsg_put(skb, info->snd_portid,
1940                                        info->snd_seq,
1941                                        &dp_ct_limit_genl_family, 0, cmd);
1942
1943        if (!*ovs_reply_header) {
1944                nlmsg_free(skb);
1945                return ERR_PTR(-EMSGSIZE);
1946        }
1947        (*ovs_reply_header)->dp_ifindex = ovs_header->dp_ifindex;
1948
1949        return skb;
1950}
1951
1952static bool check_zone_id(int zone_id, u16 *pzone)
1953{
1954        if (zone_id >= 0 && zone_id <= 65535) {
1955                *pzone = (u16)zone_id;
1956                return true;
1957        }
1958        return false;
1959}
1960
1961static int ovs_ct_limit_set_zone_limit(struct nlattr *nla_zone_limit,
1962                                       struct ovs_ct_limit_info *info)
1963{
1964        struct ovs_zone_limit *zone_limit;
1965        int rem;
1966        u16 zone;
1967
1968        rem = NLA_ALIGN(nla_len(nla_zone_limit));
1969        zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
1970
1971        while (rem >= sizeof(*zone_limit)) {
1972                if (unlikely(zone_limit->zone_id ==
1973                                OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
1974                        ovs_lock();
1975                        info->default_limit = zone_limit->limit;
1976                        ovs_unlock();
1977                } else if (unlikely(!check_zone_id(
1978                                zone_limit->zone_id, &zone))) {
1979                        OVS_NLERR(true, "zone id is out of range");
1980                } else {
1981                        struct ovs_ct_limit *ct_limit;
1982
1983                        ct_limit = kmalloc(sizeof(*ct_limit), GFP_KERNEL);
1984                        if (!ct_limit)
1985                                return -ENOMEM;
1986
1987                        ct_limit->zone = zone;
1988                        ct_limit->limit = zone_limit->limit;
1989
1990                        ovs_lock();
1991                        ct_limit_set(info, ct_limit);
1992                        ovs_unlock();
1993                }
1994                rem -= NLA_ALIGN(sizeof(*zone_limit));
1995                zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
1996                                NLA_ALIGN(sizeof(*zone_limit)));
1997        }
1998
1999        if (rem)
2000                OVS_NLERR(true, "set zone limit has %d unknown bytes", rem);
2001
2002        return 0;
2003}
2004
2005static int ovs_ct_limit_del_zone_limit(struct nlattr *nla_zone_limit,
2006                                       struct ovs_ct_limit_info *info)
2007{
2008        struct ovs_zone_limit *zone_limit;
2009        int rem;
2010        u16 zone;
2011
2012        rem = NLA_ALIGN(nla_len(nla_zone_limit));
2013        zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
2014
2015        while (rem >= sizeof(*zone_limit)) {
2016                if (unlikely(zone_limit->zone_id ==
2017                                OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
2018                        ovs_lock();
2019                        info->default_limit = OVS_CT_LIMIT_DEFAULT;
2020                        ovs_unlock();
2021                } else if (unlikely(!check_zone_id(
2022                                zone_limit->zone_id, &zone))) {
2023                        OVS_NLERR(true, "zone id is out of range");
2024                } else {
2025                        ovs_lock();
2026                        ct_limit_del(info, zone);
2027                        ovs_unlock();
2028                }
2029                rem -= NLA_ALIGN(sizeof(*zone_limit));
2030                zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
2031                                NLA_ALIGN(sizeof(*zone_limit)));
2032        }
2033
2034        if (rem)
2035                OVS_NLERR(true, "del zone limit has %d unknown bytes", rem);
2036
2037        return 0;
2038}
2039
2040static int ovs_ct_limit_get_default_limit(struct ovs_ct_limit_info *info,
2041                                          struct sk_buff *reply)
2042{
2043        struct ovs_zone_limit zone_limit = {
2044                .zone_id = OVS_ZONE_LIMIT_DEFAULT_ZONE,
2045                .limit   = info->default_limit,
2046        };
2047
2048        return nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
2049}
2050
2051static int __ovs_ct_limit_get_zone_limit(struct net *net,
2052                                         struct nf_conncount_data *data,
2053                                         u16 zone_id, u32 limit,
2054                                         struct sk_buff *reply)
2055{
2056        struct nf_conntrack_zone ct_zone;
2057        struct ovs_zone_limit zone_limit;
2058        u32 conncount_key = zone_id;
2059
2060        zone_limit.zone_id = zone_id;
2061        zone_limit.limit = limit;
2062        nf_ct_zone_init(&ct_zone, zone_id, NF_CT_DEFAULT_ZONE_DIR, 0);
2063
2064        zone_limit.count = nf_conncount_count(net, data, &conncount_key, NULL,
2065                                              &ct_zone);
2066        return nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
2067}
2068
2069static int ovs_ct_limit_get_zone_limit(struct net *net,
2070                                       struct nlattr *nla_zone_limit,
2071                                       struct ovs_ct_limit_info *info,
2072                                       struct sk_buff *reply)
2073{
2074        struct ovs_zone_limit *zone_limit;
2075        int rem, err;
2076        u32 limit;
2077        u16 zone;
2078
2079        rem = NLA_ALIGN(nla_len(nla_zone_limit));
2080        zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
2081
2082        while (rem >= sizeof(*zone_limit)) {
2083                if (unlikely(zone_limit->zone_id ==
2084                                OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
2085                        err = ovs_ct_limit_get_default_limit(info, reply);
2086                        if (err)
2087                                return err;
2088                } else if (unlikely(!check_zone_id(zone_limit->zone_id,
2089                                                        &zone))) {
2090                        OVS_NLERR(true, "zone id is out of range");
2091                } else {
2092                        rcu_read_lock();
2093                        limit = ct_limit_get(info, zone);
2094                        rcu_read_unlock();
2095
2096                        err = __ovs_ct_limit_get_zone_limit(
2097                                net, info->data, zone, limit, reply);
2098                        if (err)
2099                                return err;
2100                }
2101                rem -= NLA_ALIGN(sizeof(*zone_limit));
2102                zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
2103                                NLA_ALIGN(sizeof(*zone_limit)));
2104        }
2105
2106        if (rem)
2107                OVS_NLERR(true, "get zone limit has %d unknown bytes", rem);
2108
2109        return 0;
2110}
2111
2112static int ovs_ct_limit_get_all_zone_limit(struct net *net,
2113                                           struct ovs_ct_limit_info *info,
2114                                           struct sk_buff *reply)
2115{
2116        struct ovs_ct_limit *ct_limit;
2117        struct hlist_head *head;
2118        int i, err = 0;
2119
2120        err = ovs_ct_limit_get_default_limit(info, reply);
2121        if (err)
2122                return err;
2123
2124        rcu_read_lock();
2125        for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
2126                head = &info->limits[i];
2127                hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
2128                        err = __ovs_ct_limit_get_zone_limit(net, info->data,
2129                                ct_limit->zone, ct_limit->limit, reply);
2130                        if (err)
2131                                goto exit_err;
2132                }
2133        }
2134
2135exit_err:
2136        rcu_read_unlock();
2137        return err;
2138}
2139
2140static int ovs_ct_limit_cmd_set(struct sk_buff *skb, struct genl_info *info)
2141{
2142        struct nlattr **a = info->attrs;
2143        struct sk_buff *reply;
2144        struct ovs_header *ovs_reply_header;
2145        struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2146        struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2147        int err;
2148
2149        reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_SET,
2150                                             &ovs_reply_header);
2151        if (IS_ERR(reply))
2152                return PTR_ERR(reply);
2153
2154        if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2155                err = -EINVAL;
2156                goto exit_err;
2157        }
2158
2159        err = ovs_ct_limit_set_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2160                                          ct_limit_info);
2161        if (err)
2162                goto exit_err;
2163
2164        static_branch_enable(&ovs_ct_limit_enabled);
2165
2166        genlmsg_end(reply, ovs_reply_header);
2167        return genlmsg_reply(reply, info);
2168
2169exit_err:
2170        nlmsg_free(reply);
2171        return err;
2172}
2173
2174static int ovs_ct_limit_cmd_del(struct sk_buff *skb, struct genl_info *info)
2175{
2176        struct nlattr **a = info->attrs;
2177        struct sk_buff *reply;
2178        struct ovs_header *ovs_reply_header;
2179        struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2180        struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2181        int err;
2182
2183        reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_DEL,
2184                                             &ovs_reply_header);
2185        if (IS_ERR(reply))
2186                return PTR_ERR(reply);
2187
2188        if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2189                err = -EINVAL;
2190                goto exit_err;
2191        }
2192
2193        err = ovs_ct_limit_del_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2194                                          ct_limit_info);
2195        if (err)
2196                goto exit_err;
2197
2198        genlmsg_end(reply, ovs_reply_header);
2199        return genlmsg_reply(reply, info);
2200
2201exit_err:
2202        nlmsg_free(reply);
2203        return err;
2204}
2205
2206static int ovs_ct_limit_cmd_get(struct sk_buff *skb, struct genl_info *info)
2207{
2208        struct nlattr **a = info->attrs;
2209        struct nlattr *nla_reply;
2210        struct sk_buff *reply;
2211        struct ovs_header *ovs_reply_header;
2212        struct net *net = sock_net(skb->sk);
2213        struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2214        struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2215        int err;
2216
2217        reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_GET,
2218                                             &ovs_reply_header);
2219        if (IS_ERR(reply))
2220                return PTR_ERR(reply);
2221
2222        nla_reply = nla_nest_start_noflag(reply, OVS_CT_LIMIT_ATTR_ZONE_LIMIT);
2223        if (!nla_reply) {
2224                err = -EMSGSIZE;
2225                goto exit_err;
2226        }
2227
2228        if (a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2229                err = ovs_ct_limit_get_zone_limit(
2230                        net, a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT], ct_limit_info,
2231                        reply);
2232                if (err)
2233                        goto exit_err;
2234        } else {
2235                err = ovs_ct_limit_get_all_zone_limit(net, ct_limit_info,
2236                                                      reply);
2237                if (err)
2238                        goto exit_err;
2239        }
2240
2241        nla_nest_end(reply, nla_reply);
2242        genlmsg_end(reply, ovs_reply_header);
2243        return genlmsg_reply(reply, info);
2244
2245exit_err:
2246        nlmsg_free(reply);
2247        return err;
2248}
2249
2250static const struct genl_small_ops ct_limit_genl_ops[] = {
2251        { .cmd = OVS_CT_LIMIT_CMD_SET,
2252                .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2253                .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2254                                           * privilege. */
2255                .doit = ovs_ct_limit_cmd_set,
2256        },
2257        { .cmd = OVS_CT_LIMIT_CMD_DEL,
2258                .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2259                .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2260                                           * privilege. */
2261                .doit = ovs_ct_limit_cmd_del,
2262        },
2263        { .cmd = OVS_CT_LIMIT_CMD_GET,
2264                .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2265                .flags = 0,               /* OK for unprivileged users. */
2266                .doit = ovs_ct_limit_cmd_get,
2267        },
2268};
2269
2270static const struct genl_multicast_group ovs_ct_limit_multicast_group = {
2271        .name = OVS_CT_LIMIT_MCGROUP,
2272};
2273
2274struct genl_family dp_ct_limit_genl_family __ro_after_init = {
2275        .hdrsize = sizeof(struct ovs_header),
2276        .name = OVS_CT_LIMIT_FAMILY,
2277        .version = OVS_CT_LIMIT_VERSION,
2278        .maxattr = OVS_CT_LIMIT_ATTR_MAX,
2279        .policy = ct_limit_policy,
2280        .netnsok = true,
2281        .parallel_ops = true,
2282        .small_ops = ct_limit_genl_ops,
2283        .n_small_ops = ARRAY_SIZE(ct_limit_genl_ops),
2284        .mcgrps = &ovs_ct_limit_multicast_group,
2285        .n_mcgrps = 1,
2286        .module = THIS_MODULE,
2287};
2288#endif
2289
2290int ovs_ct_init(struct net *net)
2291{
2292        unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
2293        struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2294
2295        if (nf_connlabels_get(net, n_bits - 1)) {
2296                ovs_net->xt_label = false;
2297                OVS_NLERR(true, "Failed to set connlabel length");
2298        } else {
2299                ovs_net->xt_label = true;
2300        }
2301
2302#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2303        return ovs_ct_limit_init(net, ovs_net);
2304#else
2305        return 0;
2306#endif
2307}
2308
2309void ovs_ct_exit(struct net *net)
2310{
2311        struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2312
2313#if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2314        ovs_ct_limit_exit(net, ovs_net);
2315#endif
2316
2317        if (ovs_net->xt_label)
2318                nf_connlabels_put(net);
2319}
2320