Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright (c) 2015 Nicira, Inc.
0004  */
0005 
0006 #include <linux/module.h>
0007 #include <linux/openvswitch.h>
0008 #include <linux/tcp.h>
0009 #include <linux/udp.h>
0010 #include <linux/sctp.h>
0011 #include <linux/static_key.h>
0012 #include <net/ip.h>
0013 #include <net/genetlink.h>
0014 #include <net/netfilter/nf_conntrack_core.h>
0015 #include <net/netfilter/nf_conntrack_count.h>
0016 #include <net/netfilter/nf_conntrack_helper.h>
0017 #include <net/netfilter/nf_conntrack_labels.h>
0018 #include <net/netfilter/nf_conntrack_seqadj.h>
0019 #include <net/netfilter/nf_conntrack_timeout.h>
0020 #include <net/netfilter/nf_conntrack_zones.h>
0021 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
0022 #include <net/ipv6_frag.h>
0023 
0024 #if IS_ENABLED(CONFIG_NF_NAT)
0025 #include <net/netfilter/nf_nat.h>
0026 #endif
0027 
0028 #include <net/netfilter/nf_conntrack_act_ct.h>
0029 
0030 #include "datapath.h"
0031 #include "conntrack.h"
0032 #include "flow.h"
0033 #include "flow_netlink.h"
0034 
0035 struct ovs_ct_len_tbl {
0036     int maxlen;
0037     int minlen;
0038 };
0039 
0040 /* Metadata mark for masked write to conntrack mark */
0041 struct md_mark {
0042     u32 value;
0043     u32 mask;
0044 };
0045 
0046 /* Metadata label for masked write to conntrack label. */
0047 struct md_labels {
0048     struct ovs_key_ct_labels value;
0049     struct ovs_key_ct_labels mask;
0050 };
0051 
0052 enum ovs_ct_nat {
0053     OVS_CT_NAT = 1 << 0,     /* NAT for committed connections only. */
0054     OVS_CT_SRC_NAT = 1 << 1, /* Source NAT for NEW connections. */
0055     OVS_CT_DST_NAT = 1 << 2, /* Destination NAT for NEW connections. */
0056 };
0057 
0058 /* Conntrack action context for execution. */
0059 struct ovs_conntrack_info {
0060     struct nf_conntrack_helper *helper;
0061     struct nf_conntrack_zone zone;
0062     struct nf_conn *ct;
0063     u8 commit : 1;
0064     u8 nat : 3;                 /* enum ovs_ct_nat */
0065     u8 force : 1;
0066     u8 have_eventmask : 1;
0067     u16 family;
0068     u32 eventmask;              /* Mask of 1 << IPCT_*. */
0069     struct md_mark mark;
0070     struct md_labels labels;
0071     char timeout[CTNL_TIMEOUT_NAME_MAX];
0072     struct nf_ct_timeout *nf_ct_timeout;
0073 #if IS_ENABLED(CONFIG_NF_NAT)
0074     struct nf_nat_range2 range;  /* Only present for SRC NAT and DST NAT. */
0075 #endif
0076 };
0077 
0078 #if IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
0079 #define OVS_CT_LIMIT_UNLIMITED  0
0080 #define OVS_CT_LIMIT_DEFAULT OVS_CT_LIMIT_UNLIMITED
0081 #define CT_LIMIT_HASH_BUCKETS 512
0082 static DEFINE_STATIC_KEY_FALSE(ovs_ct_limit_enabled);
0083 
0084 struct ovs_ct_limit {
0085     /* Elements in ovs_ct_limit_info->limits hash table */
0086     struct hlist_node hlist_node;
0087     struct rcu_head rcu;
0088     u16 zone;
0089     u32 limit;
0090 };
0091 
0092 struct ovs_ct_limit_info {
0093     u32 default_limit;
0094     struct hlist_head *limits;
0095     struct nf_conncount_data *data;
0096 };
0097 
0098 static const struct nla_policy ct_limit_policy[OVS_CT_LIMIT_ATTR_MAX + 1] = {
0099     [OVS_CT_LIMIT_ATTR_ZONE_LIMIT] = { .type = NLA_NESTED, },
0100 };
0101 #endif
0102 
0103 static bool labels_nonzero(const struct ovs_key_ct_labels *labels);
0104 
0105 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
0106 
0107 static u16 key_to_nfproto(const struct sw_flow_key *key)
0108 {
0109     switch (ntohs(key->eth.type)) {
0110     case ETH_P_IP:
0111         return NFPROTO_IPV4;
0112     case ETH_P_IPV6:
0113         return NFPROTO_IPV6;
0114     default:
0115         return NFPROTO_UNSPEC;
0116     }
0117 }
0118 
0119 /* Map SKB connection state into the values used by flow definition. */
0120 static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
0121 {
0122     u8 ct_state = OVS_CS_F_TRACKED;
0123 
0124     switch (ctinfo) {
0125     case IP_CT_ESTABLISHED_REPLY:
0126     case IP_CT_RELATED_REPLY:
0127         ct_state |= OVS_CS_F_REPLY_DIR;
0128         break;
0129     default:
0130         break;
0131     }
0132 
0133     switch (ctinfo) {
0134     case IP_CT_ESTABLISHED:
0135     case IP_CT_ESTABLISHED_REPLY:
0136         ct_state |= OVS_CS_F_ESTABLISHED;
0137         break;
0138     case IP_CT_RELATED:
0139     case IP_CT_RELATED_REPLY:
0140         ct_state |= OVS_CS_F_RELATED;
0141         break;
0142     case IP_CT_NEW:
0143         ct_state |= OVS_CS_F_NEW;
0144         break;
0145     default:
0146         break;
0147     }
0148 
0149     return ct_state;
0150 }
0151 
0152 static u32 ovs_ct_get_mark(const struct nf_conn *ct)
0153 {
0154 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
0155     return ct ? ct->mark : 0;
0156 #else
0157     return 0;
0158 #endif
0159 }
0160 
0161 /* Guard against conntrack labels max size shrinking below 128 bits. */
0162 #if NF_CT_LABELS_MAX_SIZE < 16
0163 #error NF_CT_LABELS_MAX_SIZE must be at least 16 bytes
0164 #endif
0165 
0166 static void ovs_ct_get_labels(const struct nf_conn *ct,
0167                   struct ovs_key_ct_labels *labels)
0168 {
0169     struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
0170 
0171     if (cl)
0172         memcpy(labels, cl->bits, OVS_CT_LABELS_LEN);
0173     else
0174         memset(labels, 0, OVS_CT_LABELS_LEN);
0175 }
0176 
0177 static void __ovs_ct_update_key_orig_tp(struct sw_flow_key *key,
0178                     const struct nf_conntrack_tuple *orig,
0179                     u8 icmp_proto)
0180 {
0181     key->ct_orig_proto = orig->dst.protonum;
0182     if (orig->dst.protonum == icmp_proto) {
0183         key->ct.orig_tp.src = htons(orig->dst.u.icmp.type);
0184         key->ct.orig_tp.dst = htons(orig->dst.u.icmp.code);
0185     } else {
0186         key->ct.orig_tp.src = orig->src.u.all;
0187         key->ct.orig_tp.dst = orig->dst.u.all;
0188     }
0189 }
0190 
0191 static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
0192                 const struct nf_conntrack_zone *zone,
0193                 const struct nf_conn *ct)
0194 {
0195     key->ct_state = state;
0196     key->ct_zone = zone->id;
0197     key->ct.mark = ovs_ct_get_mark(ct);
0198     ovs_ct_get_labels(ct, &key->ct.labels);
0199 
0200     if (ct) {
0201         const struct nf_conntrack_tuple *orig;
0202 
0203         /* Use the master if we have one. */
0204         if (ct->master)
0205             ct = ct->master;
0206         orig = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
0207 
0208         /* IP version must match with the master connection. */
0209         if (key->eth.type == htons(ETH_P_IP) &&
0210             nf_ct_l3num(ct) == NFPROTO_IPV4) {
0211             key->ipv4.ct_orig.src = orig->src.u3.ip;
0212             key->ipv4.ct_orig.dst = orig->dst.u3.ip;
0213             __ovs_ct_update_key_orig_tp(key, orig, IPPROTO_ICMP);
0214             return;
0215         } else if (key->eth.type == htons(ETH_P_IPV6) &&
0216                !sw_flow_key_is_nd(key) &&
0217                nf_ct_l3num(ct) == NFPROTO_IPV6) {
0218             key->ipv6.ct_orig.src = orig->src.u3.in6;
0219             key->ipv6.ct_orig.dst = orig->dst.u3.in6;
0220             __ovs_ct_update_key_orig_tp(key, orig, NEXTHDR_ICMP);
0221             return;
0222         }
0223     }
0224     /* Clear 'ct_orig_proto' to mark the non-existence of conntrack
0225      * original direction key fields.
0226      */
0227     key->ct_orig_proto = 0;
0228 }
0229 
0230 /* Update 'key' based on skb->_nfct.  If 'post_ct' is true, then OVS has
0231  * previously sent the packet to conntrack via the ct action.  If
0232  * 'keep_nat_flags' is true, the existing NAT flags retained, else they are
0233  * initialized from the connection status.
0234  */
0235 static void ovs_ct_update_key(const struct sk_buff *skb,
0236                   const struct ovs_conntrack_info *info,
0237                   struct sw_flow_key *key, bool post_ct,
0238                   bool keep_nat_flags)
0239 {
0240     const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
0241     enum ip_conntrack_info ctinfo;
0242     struct nf_conn *ct;
0243     u8 state = 0;
0244 
0245     ct = nf_ct_get(skb, &ctinfo);
0246     if (ct) {
0247         state = ovs_ct_get_state(ctinfo);
0248         /* All unconfirmed entries are NEW connections. */
0249         if (!nf_ct_is_confirmed(ct))
0250             state |= OVS_CS_F_NEW;
0251         /* OVS persists the related flag for the duration of the
0252          * connection.
0253          */
0254         if (ct->master)
0255             state |= OVS_CS_F_RELATED;
0256         if (keep_nat_flags) {
0257             state |= key->ct_state & OVS_CS_F_NAT_MASK;
0258         } else {
0259             if (ct->status & IPS_SRC_NAT)
0260                 state |= OVS_CS_F_SRC_NAT;
0261             if (ct->status & IPS_DST_NAT)
0262                 state |= OVS_CS_F_DST_NAT;
0263         }
0264         zone = nf_ct_zone(ct);
0265     } else if (post_ct) {
0266         state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
0267         if (info)
0268             zone = &info->zone;
0269     }
0270     __ovs_ct_update_key(key, state, zone, ct);
0271 }
0272 
0273 /* This is called to initialize CT key fields possibly coming in from the local
0274  * stack.
0275  */
0276 void ovs_ct_fill_key(const struct sk_buff *skb,
0277              struct sw_flow_key *key,
0278              bool post_ct)
0279 {
0280     ovs_ct_update_key(skb, NULL, key, post_ct, false);
0281 }
0282 
0283 int ovs_ct_put_key(const struct sw_flow_key *swkey,
0284            const struct sw_flow_key *output, struct sk_buff *skb)
0285 {
0286     if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, output->ct_state))
0287         return -EMSGSIZE;
0288 
0289     if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
0290         nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, output->ct_zone))
0291         return -EMSGSIZE;
0292 
0293     if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
0294         nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, output->ct.mark))
0295         return -EMSGSIZE;
0296 
0297     if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
0298         nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(output->ct.labels),
0299             &output->ct.labels))
0300         return -EMSGSIZE;
0301 
0302     if (swkey->ct_orig_proto) {
0303         if (swkey->eth.type == htons(ETH_P_IP)) {
0304             struct ovs_key_ct_tuple_ipv4 orig;
0305 
0306             memset(&orig, 0, sizeof(orig));
0307             orig.ipv4_src = output->ipv4.ct_orig.src;
0308             orig.ipv4_dst = output->ipv4.ct_orig.dst;
0309             orig.src_port = output->ct.orig_tp.src;
0310             orig.dst_port = output->ct.orig_tp.dst;
0311             orig.ipv4_proto = output->ct_orig_proto;
0312 
0313             if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4,
0314                     sizeof(orig), &orig))
0315                 return -EMSGSIZE;
0316         } else if (swkey->eth.type == htons(ETH_P_IPV6)) {
0317             struct ovs_key_ct_tuple_ipv6 orig;
0318 
0319             memset(&orig, 0, sizeof(orig));
0320             memcpy(orig.ipv6_src, output->ipv6.ct_orig.src.s6_addr32,
0321                    sizeof(orig.ipv6_src));
0322             memcpy(orig.ipv6_dst, output->ipv6.ct_orig.dst.s6_addr32,
0323                    sizeof(orig.ipv6_dst));
0324             orig.src_port = output->ct.orig_tp.src;
0325             orig.dst_port = output->ct.orig_tp.dst;
0326             orig.ipv6_proto = output->ct_orig_proto;
0327 
0328             if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6,
0329                     sizeof(orig), &orig))
0330                 return -EMSGSIZE;
0331         }
0332     }
0333 
0334     return 0;
0335 }
0336 
0337 static int ovs_ct_set_mark(struct nf_conn *ct, struct sw_flow_key *key,
0338                u32 ct_mark, u32 mask)
0339 {
0340 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
0341     u32 new_mark;
0342 
0343     new_mark = ct_mark | (ct->mark & ~(mask));
0344     if (ct->mark != new_mark) {
0345         ct->mark = new_mark;
0346         if (nf_ct_is_confirmed(ct))
0347             nf_conntrack_event_cache(IPCT_MARK, ct);
0348         key->ct.mark = new_mark;
0349     }
0350 
0351     return 0;
0352 #else
0353     return -ENOTSUPP;
0354 #endif
0355 }
0356 
0357 static struct nf_conn_labels *ovs_ct_get_conn_labels(struct nf_conn *ct)
0358 {
0359     struct nf_conn_labels *cl;
0360 
0361     cl = nf_ct_labels_find(ct);
0362     if (!cl) {
0363         nf_ct_labels_ext_add(ct);
0364         cl = nf_ct_labels_find(ct);
0365     }
0366 
0367     return cl;
0368 }
0369 
0370 /* Initialize labels for a new, yet to be committed conntrack entry.  Note that
0371  * since the new connection is not yet confirmed, and thus no-one else has
0372  * access to it's labels, we simply write them over.
0373  */
0374 static int ovs_ct_init_labels(struct nf_conn *ct, struct sw_flow_key *key,
0375                   const struct ovs_key_ct_labels *labels,
0376                   const struct ovs_key_ct_labels *mask)
0377 {
0378     struct nf_conn_labels *cl, *master_cl;
0379     bool have_mask = labels_nonzero(mask);
0380 
0381     /* Inherit master's labels to the related connection? */
0382     master_cl = ct->master ? nf_ct_labels_find(ct->master) : NULL;
0383 
0384     if (!master_cl && !have_mask)
0385         return 0;   /* Nothing to do. */
0386 
0387     cl = ovs_ct_get_conn_labels(ct);
0388     if (!cl)
0389         return -ENOSPC;
0390 
0391     /* Inherit the master's labels, if any. */
0392     if (master_cl)
0393         *cl = *master_cl;
0394 
0395     if (have_mask) {
0396         u32 *dst = (u32 *)cl->bits;
0397         int i;
0398 
0399         for (i = 0; i < OVS_CT_LABELS_LEN_32; i++)
0400             dst[i] = (dst[i] & ~mask->ct_labels_32[i]) |
0401                 (labels->ct_labels_32[i]
0402                  & mask->ct_labels_32[i]);
0403     }
0404 
0405     /* Labels are included in the IPCTNL_MSG_CT_NEW event only if the
0406      * IPCT_LABEL bit is set in the event cache.
0407      */
0408     nf_conntrack_event_cache(IPCT_LABEL, ct);
0409 
0410     memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
0411 
0412     return 0;
0413 }
0414 
0415 static int ovs_ct_set_labels(struct nf_conn *ct, struct sw_flow_key *key,
0416                  const struct ovs_key_ct_labels *labels,
0417                  const struct ovs_key_ct_labels *mask)
0418 {
0419     struct nf_conn_labels *cl;
0420     int err;
0421 
0422     cl = ovs_ct_get_conn_labels(ct);
0423     if (!cl)
0424         return -ENOSPC;
0425 
0426     err = nf_connlabels_replace(ct, labels->ct_labels_32,
0427                     mask->ct_labels_32,
0428                     OVS_CT_LABELS_LEN_32);
0429     if (err)
0430         return err;
0431 
0432     memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
0433 
0434     return 0;
0435 }
0436 
0437 /* 'skb' should already be pulled to nh_ofs. */
0438 static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
0439 {
0440     const struct nf_conntrack_helper *helper;
0441     const struct nf_conn_help *help;
0442     enum ip_conntrack_info ctinfo;
0443     unsigned int protoff;
0444     struct nf_conn *ct;
0445     int err;
0446 
0447     ct = nf_ct_get(skb, &ctinfo);
0448     if (!ct || ctinfo == IP_CT_RELATED_REPLY)
0449         return NF_ACCEPT;
0450 
0451     help = nfct_help(ct);
0452     if (!help)
0453         return NF_ACCEPT;
0454 
0455     helper = rcu_dereference(help->helper);
0456     if (!helper)
0457         return NF_ACCEPT;
0458 
0459     switch (proto) {
0460     case NFPROTO_IPV4:
0461         protoff = ip_hdrlen(skb);
0462         break;
0463     case NFPROTO_IPV6: {
0464         u8 nexthdr = ipv6_hdr(skb)->nexthdr;
0465         __be16 frag_off;
0466         int ofs;
0467 
0468         ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
0469                        &frag_off);
0470         if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
0471             pr_debug("proto header not found\n");
0472             return NF_ACCEPT;
0473         }
0474         protoff = ofs;
0475         break;
0476     }
0477     default:
0478         WARN_ONCE(1, "helper invoked on non-IP family!");
0479         return NF_DROP;
0480     }
0481 
0482     err = helper->help(skb, protoff, ct, ctinfo);
0483     if (err != NF_ACCEPT)
0484         return err;
0485 
0486     /* Adjust seqs after helper.  This is needed due to some helpers (e.g.,
0487      * FTP with NAT) adusting the TCP payload size when mangling IP
0488      * addresses and/or port numbers in the text-based control connection.
0489      */
0490     if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
0491         !nf_ct_seq_adjust(skb, ct, ctinfo, protoff))
0492         return NF_DROP;
0493     return NF_ACCEPT;
0494 }
0495 
0496 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
0497  * value if 'skb' is freed.
0498  */
0499 static int handle_fragments(struct net *net, struct sw_flow_key *key,
0500                 u16 zone, struct sk_buff *skb)
0501 {
0502     struct ovs_skb_cb ovs_cb = *OVS_CB(skb);
0503     int err;
0504 
0505     if (key->eth.type == htons(ETH_P_IP)) {
0506         enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
0507 
0508         memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
0509         err = ip_defrag(net, skb, user);
0510         if (err)
0511             return err;
0512 
0513         ovs_cb.mru = IPCB(skb)->frag_max_size;
0514 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
0515     } else if (key->eth.type == htons(ETH_P_IPV6)) {
0516         enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
0517 
0518         memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
0519         err = nf_ct_frag6_gather(net, skb, user);
0520         if (err) {
0521             if (err != -EINPROGRESS)
0522                 kfree_skb(skb);
0523             return err;
0524         }
0525 
0526         key->ip.proto = ipv6_hdr(skb)->nexthdr;
0527         ovs_cb.mru = IP6CB(skb)->frag_max_size;
0528 #endif
0529     } else {
0530         kfree_skb(skb);
0531         return -EPFNOSUPPORT;
0532     }
0533 
0534     /* The key extracted from the fragment that completed this datagram
0535      * likely didn't have an L4 header, so regenerate it.
0536      */
0537     ovs_flow_key_update_l3l4(skb, key);
0538 
0539     key->ip.frag = OVS_FRAG_TYPE_NONE;
0540     skb_clear_hash(skb);
0541     skb->ignore_df = 1;
0542     *OVS_CB(skb) = ovs_cb;
0543 
0544     return 0;
0545 }
0546 
0547 static struct nf_conntrack_expect *
0548 ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
0549            u16 proto, const struct sk_buff *skb)
0550 {
0551     struct nf_conntrack_tuple tuple;
0552     struct nf_conntrack_expect *exp;
0553 
0554     if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
0555         return NULL;
0556 
0557     exp = __nf_ct_expect_find(net, zone, &tuple);
0558     if (exp) {
0559         struct nf_conntrack_tuple_hash *h;
0560 
0561         /* Delete existing conntrack entry, if it clashes with the
0562          * expectation.  This can happen since conntrack ALGs do not
0563          * check for clashes between (new) expectations and existing
0564          * conntrack entries.  nf_conntrack_in() will check the
0565          * expectations only if a conntrack entry can not be found,
0566          * which can lead to OVS finding the expectation (here) in the
0567          * init direction, but which will not be removed by the
0568          * nf_conntrack_in() call, if a matching conntrack entry is
0569          * found instead.  In this case all init direction packets
0570          * would be reported as new related packets, while reply
0571          * direction packets would be reported as un-related
0572          * established packets.
0573          */
0574         h = nf_conntrack_find_get(net, zone, &tuple);
0575         if (h) {
0576             struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
0577 
0578             nf_ct_delete(ct, 0, 0);
0579             nf_ct_put(ct);
0580         }
0581     }
0582 
0583     return exp;
0584 }
0585 
0586 /* This replicates logic from nf_conntrack_core.c that is not exported. */
0587 static enum ip_conntrack_info
0588 ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
0589 {
0590     const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
0591 
0592     if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
0593         return IP_CT_ESTABLISHED_REPLY;
0594     /* Once we've had two way comms, always ESTABLISHED. */
0595     if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
0596         return IP_CT_ESTABLISHED;
0597     if (test_bit(IPS_EXPECTED_BIT, &ct->status))
0598         return IP_CT_RELATED;
0599     return IP_CT_NEW;
0600 }
0601 
0602 /* Find an existing connection which this packet belongs to without
0603  * re-attributing statistics or modifying the connection state.  This allows an
0604  * skb->_nfct lost due to an upcall to be recovered during actions execution.
0605  *
0606  * Must be called with rcu_read_lock.
0607  *
0608  * On success, populates skb->_nfct and returns the connection.  Returns NULL
0609  * if there is no existing entry.
0610  */
0611 static struct nf_conn *
0612 ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
0613              u8 l3num, struct sk_buff *skb, bool natted)
0614 {
0615     struct nf_conntrack_tuple tuple;
0616     struct nf_conntrack_tuple_hash *h;
0617     struct nf_conn *ct;
0618 
0619     if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), l3num,
0620                    net, &tuple)) {
0621         pr_debug("ovs_ct_find_existing: Can't get tuple\n");
0622         return NULL;
0623     }
0624 
0625     /* Must invert the tuple if skb has been transformed by NAT. */
0626     if (natted) {
0627         struct nf_conntrack_tuple inverse;
0628 
0629         if (!nf_ct_invert_tuple(&inverse, &tuple)) {
0630             pr_debug("ovs_ct_find_existing: Inversion failed!\n");
0631             return NULL;
0632         }
0633         tuple = inverse;
0634     }
0635 
0636     /* look for tuple match */
0637     h = nf_conntrack_find_get(net, zone, &tuple);
0638     if (!h)
0639         return NULL;   /* Not found. */
0640 
0641     ct = nf_ct_tuplehash_to_ctrack(h);
0642 
0643     /* Inverted packet tuple matches the reverse direction conntrack tuple,
0644      * select the other tuplehash to get the right 'ctinfo' bits for this
0645      * packet.
0646      */
0647     if (natted)
0648         h = &ct->tuplehash[!h->tuple.dst.dir];
0649 
0650     nf_ct_set(skb, ct, ovs_ct_get_info(h));
0651     return ct;
0652 }
0653 
0654 static
0655 struct nf_conn *ovs_ct_executed(struct net *net,
0656                 const struct sw_flow_key *key,
0657                 const struct ovs_conntrack_info *info,
0658                 struct sk_buff *skb,
0659                 bool *ct_executed)
0660 {
0661     struct nf_conn *ct = NULL;
0662 
0663     /* If no ct, check if we have evidence that an existing conntrack entry
0664      * might be found for this skb.  This happens when we lose a skb->_nfct
0665      * due to an upcall, or if the direction is being forced.  If the
0666      * connection was not confirmed, it is not cached and needs to be run
0667      * through conntrack again.
0668      */
0669     *ct_executed = (key->ct_state & OVS_CS_F_TRACKED) &&
0670                !(key->ct_state & OVS_CS_F_INVALID) &&
0671                (key->ct_zone == info->zone.id);
0672 
0673     if (*ct_executed || (!key->ct_state && info->force)) {
0674         ct = ovs_ct_find_existing(net, &info->zone, info->family, skb,
0675                       !!(key->ct_state &
0676                       OVS_CS_F_NAT_MASK));
0677     }
0678 
0679     return ct;
0680 }
0681 
0682 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
0683 static bool skb_nfct_cached(struct net *net,
0684                 const struct sw_flow_key *key,
0685                 const struct ovs_conntrack_info *info,
0686                 struct sk_buff *skb)
0687 {
0688     enum ip_conntrack_info ctinfo;
0689     struct nf_conn *ct;
0690     bool ct_executed = true;
0691 
0692     ct = nf_ct_get(skb, &ctinfo);
0693     if (!ct)
0694         ct = ovs_ct_executed(net, key, info, skb, &ct_executed);
0695 
0696     if (ct)
0697         nf_ct_get(skb, &ctinfo);
0698     else
0699         return false;
0700 
0701     if (!net_eq(net, read_pnet(&ct->ct_net)))
0702         return false;
0703     if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
0704         return false;
0705     if (info->helper) {
0706         struct nf_conn_help *help;
0707 
0708         help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
0709         if (help && rcu_access_pointer(help->helper) != info->helper)
0710             return false;
0711     }
0712     if (info->nf_ct_timeout) {
0713         struct nf_conn_timeout *timeout_ext;
0714 
0715         timeout_ext = nf_ct_timeout_find(ct);
0716         if (!timeout_ext || info->nf_ct_timeout !=
0717             rcu_dereference(timeout_ext->timeout))
0718             return false;
0719     }
0720     /* Force conntrack entry direction to the current packet? */
0721     if (info->force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
0722         /* Delete the conntrack entry if confirmed, else just release
0723          * the reference.
0724          */
0725         if (nf_ct_is_confirmed(ct))
0726             nf_ct_delete(ct, 0, 0);
0727 
0728         nf_ct_put(ct);
0729         nf_ct_set(skb, NULL, 0);
0730         return false;
0731     }
0732 
0733     return ct_executed;
0734 }
0735 
0736 #if IS_ENABLED(CONFIG_NF_NAT)
0737 static void ovs_nat_update_key(struct sw_flow_key *key,
0738                    const struct sk_buff *skb,
0739                    enum nf_nat_manip_type maniptype)
0740 {
0741     if (maniptype == NF_NAT_MANIP_SRC) {
0742         __be16 src;
0743 
0744         key->ct_state |= OVS_CS_F_SRC_NAT;
0745         if (key->eth.type == htons(ETH_P_IP))
0746             key->ipv4.addr.src = ip_hdr(skb)->saddr;
0747         else if (key->eth.type == htons(ETH_P_IPV6))
0748             memcpy(&key->ipv6.addr.src, &ipv6_hdr(skb)->saddr,
0749                    sizeof(key->ipv6.addr.src));
0750         else
0751             return;
0752 
0753         if (key->ip.proto == IPPROTO_UDP)
0754             src = udp_hdr(skb)->source;
0755         else if (key->ip.proto == IPPROTO_TCP)
0756             src = tcp_hdr(skb)->source;
0757         else if (key->ip.proto == IPPROTO_SCTP)
0758             src = sctp_hdr(skb)->source;
0759         else
0760             return;
0761 
0762         key->tp.src = src;
0763     } else {
0764         __be16 dst;
0765 
0766         key->ct_state |= OVS_CS_F_DST_NAT;
0767         if (key->eth.type == htons(ETH_P_IP))
0768             key->ipv4.addr.dst = ip_hdr(skb)->daddr;
0769         else if (key->eth.type == htons(ETH_P_IPV6))
0770             memcpy(&key->ipv6.addr.dst, &ipv6_hdr(skb)->daddr,
0771                    sizeof(key->ipv6.addr.dst));
0772         else
0773             return;
0774 
0775         if (key->ip.proto == IPPROTO_UDP)
0776             dst = udp_hdr(skb)->dest;
0777         else if (key->ip.proto == IPPROTO_TCP)
0778             dst = tcp_hdr(skb)->dest;
0779         else if (key->ip.proto == IPPROTO_SCTP)
0780             dst = sctp_hdr(skb)->dest;
0781         else
0782             return;
0783 
0784         key->tp.dst = dst;
0785     }
0786 }
0787 
0788 /* Modelled after nf_nat_ipv[46]_fn().
0789  * range is only used for new, uninitialized NAT state.
0790  * Returns either NF_ACCEPT or NF_DROP.
0791  */
0792 static int ovs_ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
0793                   enum ip_conntrack_info ctinfo,
0794                   const struct nf_nat_range2 *range,
0795                   enum nf_nat_manip_type maniptype, struct sw_flow_key *key)
0796 {
0797     int hooknum, nh_off, err = NF_ACCEPT;
0798 
0799     nh_off = skb_network_offset(skb);
0800     skb_pull_rcsum(skb, nh_off);
0801 
0802     /* See HOOK2MANIP(). */
0803     if (maniptype == NF_NAT_MANIP_SRC)
0804         hooknum = NF_INET_LOCAL_IN; /* Source NAT */
0805     else
0806         hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
0807 
0808     switch (ctinfo) {
0809     case IP_CT_RELATED:
0810     case IP_CT_RELATED_REPLY:
0811         if (IS_ENABLED(CONFIG_NF_NAT) &&
0812             skb->protocol == htons(ETH_P_IP) &&
0813             ip_hdr(skb)->protocol == IPPROTO_ICMP) {
0814             if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
0815                                hooknum))
0816                 err = NF_DROP;
0817             goto push;
0818         } else if (IS_ENABLED(CONFIG_IPV6) &&
0819                skb->protocol == htons(ETH_P_IPV6)) {
0820             __be16 frag_off;
0821             u8 nexthdr = ipv6_hdr(skb)->nexthdr;
0822             int hdrlen = ipv6_skip_exthdr(skb,
0823                               sizeof(struct ipv6hdr),
0824                               &nexthdr, &frag_off);
0825 
0826             if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
0827                 if (!nf_nat_icmpv6_reply_translation(skb, ct,
0828                                      ctinfo,
0829                                      hooknum,
0830                                      hdrlen))
0831                     err = NF_DROP;
0832                 goto push;
0833             }
0834         }
0835         /* Non-ICMP, fall thru to initialize if needed. */
0836         fallthrough;
0837     case IP_CT_NEW:
0838         /* Seen it before?  This can happen for loopback, retrans,
0839          * or local packets.
0840          */
0841         if (!nf_nat_initialized(ct, maniptype)) {
0842             /* Initialize according to the NAT action. */
0843             err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
0844                 /* Action is set up to establish a new
0845                  * mapping.
0846                  */
0847                 ? nf_nat_setup_info(ct, range, maniptype)
0848                 : nf_nat_alloc_null_binding(ct, hooknum);
0849             if (err != NF_ACCEPT)
0850                 goto push;
0851         }
0852         break;
0853 
0854     case IP_CT_ESTABLISHED:
0855     case IP_CT_ESTABLISHED_REPLY:
0856         break;
0857 
0858     default:
0859         err = NF_DROP;
0860         goto push;
0861     }
0862 
0863     err = nf_nat_packet(ct, ctinfo, hooknum, skb);
0864 push:
0865     skb_push_rcsum(skb, nh_off);
0866 
0867     /* Update the flow key if NAT successful. */
0868     if (err == NF_ACCEPT)
0869         ovs_nat_update_key(key, skb, maniptype);
0870 
0871     return err;
0872 }
0873 
0874 /* Returns NF_DROP if the packet should be dropped, NF_ACCEPT otherwise. */
0875 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
0876               const struct ovs_conntrack_info *info,
0877               struct sk_buff *skb, struct nf_conn *ct,
0878               enum ip_conntrack_info ctinfo)
0879 {
0880     enum nf_nat_manip_type maniptype;
0881     int err;
0882 
0883     /* Add NAT extension if not confirmed yet. */
0884     if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
0885         return NF_ACCEPT;   /* Can't NAT. */
0886 
0887     /* Determine NAT type.
0888      * Check if the NAT type can be deduced from the tracked connection.
0889      * Make sure new expected connections (IP_CT_RELATED) are NATted only
0890      * when committing.
0891      */
0892     if (info->nat & OVS_CT_NAT && ctinfo != IP_CT_NEW &&
0893         ct->status & IPS_NAT_MASK &&
0894         (ctinfo != IP_CT_RELATED || info->commit)) {
0895         /* NAT an established or related connection like before. */
0896         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
0897             /* This is the REPLY direction for a connection
0898              * for which NAT was applied in the forward
0899              * direction.  Do the reverse NAT.
0900              */
0901             maniptype = ct->status & IPS_SRC_NAT
0902                 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
0903         else
0904             maniptype = ct->status & IPS_SRC_NAT
0905                 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
0906     } else if (info->nat & OVS_CT_SRC_NAT) {
0907         maniptype = NF_NAT_MANIP_SRC;
0908     } else if (info->nat & OVS_CT_DST_NAT) {
0909         maniptype = NF_NAT_MANIP_DST;
0910     } else {
0911         return NF_ACCEPT; /* Connection is not NATed. */
0912     }
0913     err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range, maniptype, key);
0914 
0915     if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
0916         if (ct->status & IPS_SRC_NAT) {
0917             if (maniptype == NF_NAT_MANIP_SRC)
0918                 maniptype = NF_NAT_MANIP_DST;
0919             else
0920                 maniptype = NF_NAT_MANIP_SRC;
0921 
0922             err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range,
0923                          maniptype, key);
0924         } else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
0925             err = ovs_ct_nat_execute(skb, ct, ctinfo, NULL,
0926                          NF_NAT_MANIP_SRC, key);
0927         }
0928     }
0929 
0930     return err;
0931 }
0932 #else /* !CONFIG_NF_NAT */
0933 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
0934               const struct ovs_conntrack_info *info,
0935               struct sk_buff *skb, struct nf_conn *ct,
0936               enum ip_conntrack_info ctinfo)
0937 {
0938     return NF_ACCEPT;
0939 }
0940 #endif
0941 
0942 /* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
0943  * not done already.  Update key with new CT state after passing the packet
0944  * through conntrack.
0945  * Note that if the packet is deemed invalid by conntrack, skb->_nfct will be
0946  * set to NULL and 0 will be returned.
0947  */
0948 static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
0949                const struct ovs_conntrack_info *info,
0950                struct sk_buff *skb)
0951 {
0952     /* If we are recirculating packets to match on conntrack fields and
0953      * committing with a separate conntrack action,  then we don't need to
0954      * actually run the packet through conntrack twice unless it's for a
0955      * different zone.
0956      */
0957     bool cached = skb_nfct_cached(net, key, info, skb);
0958     enum ip_conntrack_info ctinfo;
0959     struct nf_conn *ct;
0960 
0961     if (!cached) {
0962         struct nf_hook_state state = {
0963             .hook = NF_INET_PRE_ROUTING,
0964             .pf = info->family,
0965             .net = net,
0966         };
0967         struct nf_conn *tmpl = info->ct;
0968         int err;
0969 
0970         /* Associate skb with specified zone. */
0971         if (tmpl) {
0972             ct = nf_ct_get(skb, &ctinfo);
0973             nf_ct_put(ct);
0974             nf_conntrack_get(&tmpl->ct_general);
0975             nf_ct_set(skb, tmpl, IP_CT_NEW);
0976         }
0977 
0978         err = nf_conntrack_in(skb, &state);
0979         if (err != NF_ACCEPT)
0980             return -ENOENT;
0981 
0982         /* Clear CT state NAT flags to mark that we have not yet done
0983          * NAT after the nf_conntrack_in() call.  We can actually clear
0984          * the whole state, as it will be re-initialized below.
0985          */
0986         key->ct_state = 0;
0987 
0988         /* Update the key, but keep the NAT flags. */
0989         ovs_ct_update_key(skb, info, key, true, true);
0990     }
0991 
0992     ct = nf_ct_get(skb, &ctinfo);
0993     if (ct) {
0994         bool add_helper = false;
0995 
0996         /* Packets starting a new connection must be NATted before the
0997          * helper, so that the helper knows about the NAT.  We enforce
0998          * this by delaying both NAT and helper calls for unconfirmed
0999          * 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. */
1059 static 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 
1097 static 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)
1109 static 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 */
1116 static 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 */
1136 static 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 */
1153 static 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 
1167 static 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. */
1192 static 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  */
1277 static 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  */
1304 int 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 
1336 int 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 
1346     if (key)
1347         ovs_ct_fill_key(skb, key, false);
1348 
1349     return 0;
1350 }
1351 
1352 static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
1353                  const struct sw_flow_key *key, bool log)
1354 {
1355     struct nf_conntrack_helper *helper;
1356     struct nf_conn_help *help;
1357     int ret = 0;
1358 
1359     helper = nf_conntrack_helper_try_module_get(name, info->family,
1360                             key->ip.proto);
1361     if (!helper) {
1362         OVS_NLERR(log, "Unknown helper \"%s\"", name);
1363         return -EINVAL;
1364     }
1365 
1366     help = nf_ct_helper_ext_add(info->ct, GFP_KERNEL);
1367     if (!help) {
1368         nf_conntrack_helper_put(helper);
1369         return -ENOMEM;
1370     }
1371 
1372 #if IS_ENABLED(CONFIG_NF_NAT)
1373     if (info->nat) {
1374         ret = nf_nat_helper_try_module_get(name, info->family,
1375                            key->ip.proto);
1376         if (ret) {
1377             nf_conntrack_helper_put(helper);
1378             OVS_NLERR(log, "Failed to load \"%s\" NAT helper, error: %d",
1379                   name, ret);
1380             return ret;
1381         }
1382     }
1383 #endif
1384     rcu_assign_pointer(help->helper, helper);
1385     info->helper = helper;
1386     return ret;
1387 }
1388 
1389 #if IS_ENABLED(CONFIG_NF_NAT)
1390 static int parse_nat(const struct nlattr *attr,
1391              struct ovs_conntrack_info *info, bool log)
1392 {
1393     struct nlattr *a;
1394     int rem;
1395     bool have_ip_max = false;
1396     bool have_proto_max = false;
1397     bool ip_vers = (info->family == NFPROTO_IPV6);
1398 
1399     nla_for_each_nested(a, attr, rem) {
1400         static const int ovs_nat_attr_lens[OVS_NAT_ATTR_MAX + 1][2] = {
1401             [OVS_NAT_ATTR_SRC] = {0, 0},
1402             [OVS_NAT_ATTR_DST] = {0, 0},
1403             [OVS_NAT_ATTR_IP_MIN] = {sizeof(struct in_addr),
1404                          sizeof(struct in6_addr)},
1405             [OVS_NAT_ATTR_IP_MAX] = {sizeof(struct in_addr),
1406                          sizeof(struct in6_addr)},
1407             [OVS_NAT_ATTR_PROTO_MIN] = {sizeof(u16), sizeof(u16)},
1408             [OVS_NAT_ATTR_PROTO_MAX] = {sizeof(u16), sizeof(u16)},
1409             [OVS_NAT_ATTR_PERSISTENT] = {0, 0},
1410             [OVS_NAT_ATTR_PROTO_HASH] = {0, 0},
1411             [OVS_NAT_ATTR_PROTO_RANDOM] = {0, 0},
1412         };
1413         int type = nla_type(a);
1414 
1415         if (type > OVS_NAT_ATTR_MAX) {
1416             OVS_NLERR(log, "Unknown NAT attribute (type=%d, max=%d)",
1417                   type, OVS_NAT_ATTR_MAX);
1418             return -EINVAL;
1419         }
1420 
1421         if (nla_len(a) != ovs_nat_attr_lens[type][ip_vers]) {
1422             OVS_NLERR(log, "NAT attribute type %d has unexpected length (%d != %d)",
1423                   type, nla_len(a),
1424                   ovs_nat_attr_lens[type][ip_vers]);
1425             return -EINVAL;
1426         }
1427 
1428         switch (type) {
1429         case OVS_NAT_ATTR_SRC:
1430         case OVS_NAT_ATTR_DST:
1431             if (info->nat) {
1432                 OVS_NLERR(log, "Only one type of NAT may be specified");
1433                 return -ERANGE;
1434             }
1435             info->nat |= OVS_CT_NAT;
1436             info->nat |= ((type == OVS_NAT_ATTR_SRC)
1437                     ? OVS_CT_SRC_NAT : OVS_CT_DST_NAT);
1438             break;
1439 
1440         case OVS_NAT_ATTR_IP_MIN:
1441             nla_memcpy(&info->range.min_addr, a,
1442                    sizeof(info->range.min_addr));
1443             info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1444             break;
1445 
1446         case OVS_NAT_ATTR_IP_MAX:
1447             have_ip_max = true;
1448             nla_memcpy(&info->range.max_addr, a,
1449                    sizeof(info->range.max_addr));
1450             info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1451             break;
1452 
1453         case OVS_NAT_ATTR_PROTO_MIN:
1454             info->range.min_proto.all = htons(nla_get_u16(a));
1455             info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1456             break;
1457 
1458         case OVS_NAT_ATTR_PROTO_MAX:
1459             have_proto_max = true;
1460             info->range.max_proto.all = htons(nla_get_u16(a));
1461             info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1462             break;
1463 
1464         case OVS_NAT_ATTR_PERSISTENT:
1465             info->range.flags |= NF_NAT_RANGE_PERSISTENT;
1466             break;
1467 
1468         case OVS_NAT_ATTR_PROTO_HASH:
1469             info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM;
1470             break;
1471 
1472         case OVS_NAT_ATTR_PROTO_RANDOM:
1473             info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY;
1474             break;
1475 
1476         default:
1477             OVS_NLERR(log, "Unknown nat attribute (%d)", type);
1478             return -EINVAL;
1479         }
1480     }
1481 
1482     if (rem > 0) {
1483         OVS_NLERR(log, "NAT attribute has %d unknown bytes", rem);
1484         return -EINVAL;
1485     }
1486     if (!info->nat) {
1487         /* Do not allow flags if no type is given. */
1488         if (info->range.flags) {
1489             OVS_NLERR(log,
1490                   "NAT flags may be given only when NAT range (SRC or DST) is also specified."
1491                   );
1492             return -EINVAL;
1493         }
1494         info->nat = OVS_CT_NAT;   /* NAT existing connections. */
1495     } else if (!info->commit) {
1496         OVS_NLERR(log,
1497               "NAT attributes may be specified only when CT COMMIT flag is also specified."
1498               );
1499         return -EINVAL;
1500     }
1501     /* Allow missing IP_MAX. */
1502     if (info->range.flags & NF_NAT_RANGE_MAP_IPS && !have_ip_max) {
1503         memcpy(&info->range.max_addr, &info->range.min_addr,
1504                sizeof(info->range.max_addr));
1505     }
1506     /* Allow missing PROTO_MAX. */
1507     if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1508         !have_proto_max) {
1509         info->range.max_proto.all = info->range.min_proto.all;
1510     }
1511     return 0;
1512 }
1513 #endif
1514 
1515 static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
1516     [OVS_CT_ATTR_COMMIT]    = { .minlen = 0, .maxlen = 0 },
1517     [OVS_CT_ATTR_FORCE_COMMIT]  = { .minlen = 0, .maxlen = 0 },
1518     [OVS_CT_ATTR_ZONE]  = { .minlen = sizeof(u16),
1519                     .maxlen = sizeof(u16) },
1520     [OVS_CT_ATTR_MARK]  = { .minlen = sizeof(struct md_mark),
1521                     .maxlen = sizeof(struct md_mark) },
1522     [OVS_CT_ATTR_LABELS]    = { .minlen = sizeof(struct md_labels),
1523                     .maxlen = sizeof(struct md_labels) },
1524     [OVS_CT_ATTR_HELPER]    = { .minlen = 1,
1525                     .maxlen = NF_CT_HELPER_NAME_LEN },
1526 #if IS_ENABLED(CONFIG_NF_NAT)
1527     /* NAT length is checked when parsing the nested attributes. */
1528     [OVS_CT_ATTR_NAT]   = { .minlen = 0, .maxlen = INT_MAX },
1529 #endif
1530     [OVS_CT_ATTR_EVENTMASK] = { .minlen = sizeof(u32),
1531                     .maxlen = sizeof(u32) },
1532     [OVS_CT_ATTR_TIMEOUT] = { .minlen = 1,
1533                   .maxlen = CTNL_TIMEOUT_NAME_MAX },
1534 };
1535 
1536 static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
1537             const char **helper, bool log)
1538 {
1539     struct nlattr *a;
1540     int rem;
1541 
1542     nla_for_each_nested(a, attr, rem) {
1543         int type = nla_type(a);
1544         int maxlen;
1545         int minlen;
1546 
1547         if (type > OVS_CT_ATTR_MAX) {
1548             OVS_NLERR(log,
1549                   "Unknown conntrack attr (type=%d, max=%d)",
1550                   type, OVS_CT_ATTR_MAX);
1551             return -EINVAL;
1552         }
1553 
1554         maxlen = ovs_ct_attr_lens[type].maxlen;
1555         minlen = ovs_ct_attr_lens[type].minlen;
1556         if (nla_len(a) < minlen || nla_len(a) > maxlen) {
1557             OVS_NLERR(log,
1558                   "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
1559                   type, nla_len(a), maxlen);
1560             return -EINVAL;
1561         }
1562 
1563         switch (type) {
1564         case OVS_CT_ATTR_FORCE_COMMIT:
1565             info->force = true;
1566             fallthrough;
1567         case OVS_CT_ATTR_COMMIT:
1568             info->commit = true;
1569             break;
1570 #ifdef CONFIG_NF_CONNTRACK_ZONES
1571         case OVS_CT_ATTR_ZONE:
1572             info->zone.id = nla_get_u16(a);
1573             break;
1574 #endif
1575 #ifdef CONFIG_NF_CONNTRACK_MARK
1576         case OVS_CT_ATTR_MARK: {
1577             struct md_mark *mark = nla_data(a);
1578 
1579             if (!mark->mask) {
1580                 OVS_NLERR(log, "ct_mark mask cannot be 0");
1581                 return -EINVAL;
1582             }
1583             info->mark = *mark;
1584             break;
1585         }
1586 #endif
1587 #ifdef CONFIG_NF_CONNTRACK_LABELS
1588         case OVS_CT_ATTR_LABELS: {
1589             struct md_labels *labels = nla_data(a);
1590 
1591             if (!labels_nonzero(&labels->mask)) {
1592                 OVS_NLERR(log, "ct_labels mask cannot be 0");
1593                 return -EINVAL;
1594             }
1595             info->labels = *labels;
1596             break;
1597         }
1598 #endif
1599         case OVS_CT_ATTR_HELPER:
1600             *helper = nla_data(a);
1601             if (!memchr(*helper, '\0', nla_len(a))) {
1602                 OVS_NLERR(log, "Invalid conntrack helper");
1603                 return -EINVAL;
1604             }
1605             break;
1606 #if IS_ENABLED(CONFIG_NF_NAT)
1607         case OVS_CT_ATTR_NAT: {
1608             int err = parse_nat(a, info, log);
1609 
1610             if (err)
1611                 return err;
1612             break;
1613         }
1614 #endif
1615         case OVS_CT_ATTR_EVENTMASK:
1616             info->have_eventmask = true;
1617             info->eventmask = nla_get_u32(a);
1618             break;
1619 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
1620         case OVS_CT_ATTR_TIMEOUT:
1621             memcpy(info->timeout, nla_data(a), nla_len(a));
1622             if (!memchr(info->timeout, '\0', nla_len(a))) {
1623                 OVS_NLERR(log, "Invalid conntrack timeout");
1624                 return -EINVAL;
1625             }
1626             break;
1627 #endif
1628 
1629         default:
1630             OVS_NLERR(log, "Unknown conntrack attr (%d)",
1631                   type);
1632             return -EINVAL;
1633         }
1634     }
1635 
1636 #ifdef CONFIG_NF_CONNTRACK_MARK
1637     if (!info->commit && info->mark.mask) {
1638         OVS_NLERR(log,
1639               "Setting conntrack mark requires 'commit' flag.");
1640         return -EINVAL;
1641     }
1642 #endif
1643 #ifdef CONFIG_NF_CONNTRACK_LABELS
1644     if (!info->commit && labels_nonzero(&info->labels.mask)) {
1645         OVS_NLERR(log,
1646               "Setting conntrack labels requires 'commit' flag.");
1647         return -EINVAL;
1648     }
1649 #endif
1650     if (rem > 0) {
1651         OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
1652         return -EINVAL;
1653     }
1654 
1655     return 0;
1656 }
1657 
1658 bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
1659 {
1660     if (attr == OVS_KEY_ATTR_CT_STATE)
1661         return true;
1662     if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1663         attr == OVS_KEY_ATTR_CT_ZONE)
1664         return true;
1665     if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1666         attr == OVS_KEY_ATTR_CT_MARK)
1667         return true;
1668     if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1669         attr == OVS_KEY_ATTR_CT_LABELS) {
1670         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1671 
1672         return ovs_net->xt_label;
1673     }
1674 
1675     return false;
1676 }
1677 
1678 int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
1679                const struct sw_flow_key *key,
1680                struct sw_flow_actions **sfa,  bool log)
1681 {
1682     struct ovs_conntrack_info ct_info;
1683     const char *helper = NULL;
1684     u16 family;
1685     int err;
1686 
1687     family = key_to_nfproto(key);
1688     if (family == NFPROTO_UNSPEC) {
1689         OVS_NLERR(log, "ct family unspecified");
1690         return -EINVAL;
1691     }
1692 
1693     memset(&ct_info, 0, sizeof(ct_info));
1694     ct_info.family = family;
1695 
1696     nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
1697             NF_CT_DEFAULT_ZONE_DIR, 0);
1698 
1699     err = parse_ct(attr, &ct_info, &helper, log);
1700     if (err)
1701         return err;
1702 
1703     /* Set up template for tracking connections in specific zones. */
1704     ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
1705     if (!ct_info.ct) {
1706         OVS_NLERR(log, "Failed to allocate conntrack template");
1707         return -ENOMEM;
1708     }
1709 
1710     if (ct_info.timeout[0]) {
1711         if (nf_ct_set_timeout(net, ct_info.ct, family, key->ip.proto,
1712                       ct_info.timeout))
1713             pr_info_ratelimited("Failed to associated timeout "
1714                         "policy `%s'\n", ct_info.timeout);
1715         else
1716             ct_info.nf_ct_timeout = rcu_dereference(
1717                 nf_ct_timeout_find(ct_info.ct)->timeout);
1718 
1719     }
1720 
1721     if (helper) {
1722         err = ovs_ct_add_helper(&ct_info, helper, key, log);
1723         if (err)
1724             goto err_free_ct;
1725     }
1726 
1727     err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
1728                  sizeof(ct_info), log);
1729     if (err)
1730         goto err_free_ct;
1731 
1732     __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
1733     return 0;
1734 err_free_ct:
1735     __ovs_ct_free_action(&ct_info);
1736     return err;
1737 }
1738 
1739 #if IS_ENABLED(CONFIG_NF_NAT)
1740 static bool ovs_ct_nat_to_attr(const struct ovs_conntrack_info *info,
1741                    struct sk_buff *skb)
1742 {
1743     struct nlattr *start;
1744 
1745     start = nla_nest_start_noflag(skb, OVS_CT_ATTR_NAT);
1746     if (!start)
1747         return false;
1748 
1749     if (info->nat & OVS_CT_SRC_NAT) {
1750         if (nla_put_flag(skb, OVS_NAT_ATTR_SRC))
1751             return false;
1752     } else if (info->nat & OVS_CT_DST_NAT) {
1753         if (nla_put_flag(skb, OVS_NAT_ATTR_DST))
1754             return false;
1755     } else {
1756         goto out;
1757     }
1758 
1759     if (info->range.flags & NF_NAT_RANGE_MAP_IPS) {
1760         if (IS_ENABLED(CONFIG_NF_NAT) &&
1761             info->family == NFPROTO_IPV4) {
1762             if (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MIN,
1763                         info->range.min_addr.ip) ||
1764                 (info->range.max_addr.ip
1765                  != info->range.min_addr.ip &&
1766                  (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MAX,
1767                           info->range.max_addr.ip))))
1768                 return false;
1769         } else if (IS_ENABLED(CONFIG_IPV6) &&
1770                info->family == NFPROTO_IPV6) {
1771             if (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MIN,
1772                          &info->range.min_addr.in6) ||
1773                 (memcmp(&info->range.max_addr.in6,
1774                     &info->range.min_addr.in6,
1775                     sizeof(info->range.max_addr.in6)) &&
1776                  (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MAX,
1777                            &info->range.max_addr.in6))))
1778                 return false;
1779         } else {
1780             return false;
1781         }
1782     }
1783     if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1784         (nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MIN,
1785              ntohs(info->range.min_proto.all)) ||
1786          (info->range.max_proto.all != info->range.min_proto.all &&
1787           nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MAX,
1788               ntohs(info->range.max_proto.all)))))
1789         return false;
1790 
1791     if (info->range.flags & NF_NAT_RANGE_PERSISTENT &&
1792         nla_put_flag(skb, OVS_NAT_ATTR_PERSISTENT))
1793         return false;
1794     if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM &&
1795         nla_put_flag(skb, OVS_NAT_ATTR_PROTO_HASH))
1796         return false;
1797     if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY &&
1798         nla_put_flag(skb, OVS_NAT_ATTR_PROTO_RANDOM))
1799         return false;
1800 out:
1801     nla_nest_end(skb, start);
1802 
1803     return true;
1804 }
1805 #endif
1806 
1807 int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
1808               struct sk_buff *skb)
1809 {
1810     struct nlattr *start;
1811 
1812     start = nla_nest_start_noflag(skb, OVS_ACTION_ATTR_CT);
1813     if (!start)
1814         return -EMSGSIZE;
1815 
1816     if (ct_info->commit && nla_put_flag(skb, ct_info->force
1817                         ? OVS_CT_ATTR_FORCE_COMMIT
1818                         : OVS_CT_ATTR_COMMIT))
1819         return -EMSGSIZE;
1820     if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1821         nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
1822         return -EMSGSIZE;
1823     if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
1824         nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
1825             &ct_info->mark))
1826         return -EMSGSIZE;
1827     if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1828         labels_nonzero(&ct_info->labels.mask) &&
1829         nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
1830             &ct_info->labels))
1831         return -EMSGSIZE;
1832     if (ct_info->helper) {
1833         if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
1834                    ct_info->helper->name))
1835             return -EMSGSIZE;
1836     }
1837     if (ct_info->have_eventmask &&
1838         nla_put_u32(skb, OVS_CT_ATTR_EVENTMASK, ct_info->eventmask))
1839         return -EMSGSIZE;
1840     if (ct_info->timeout[0]) {
1841         if (nla_put_string(skb, OVS_CT_ATTR_TIMEOUT, ct_info->timeout))
1842             return -EMSGSIZE;
1843     }
1844 
1845 #if IS_ENABLED(CONFIG_NF_NAT)
1846     if (ct_info->nat && !ovs_ct_nat_to_attr(ct_info, skb))
1847         return -EMSGSIZE;
1848 #endif
1849     nla_nest_end(skb, start);
1850 
1851     return 0;
1852 }
1853 
1854 void ovs_ct_free_action(const struct nlattr *a)
1855 {
1856     struct ovs_conntrack_info *ct_info = nla_data(a);
1857 
1858     __ovs_ct_free_action(ct_info);
1859 }
1860 
1861 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
1862 {
1863     if (ct_info->helper) {
1864 #if IS_ENABLED(CONFIG_NF_NAT)
1865         if (ct_info->nat)
1866             nf_nat_helper_put(ct_info->helper);
1867 #endif
1868         nf_conntrack_helper_put(ct_info->helper);
1869     }
1870     if (ct_info->ct) {
1871         if (ct_info->timeout[0])
1872             nf_ct_destroy_timeout(ct_info->ct);
1873         nf_ct_tmpl_free(ct_info->ct);
1874     }
1875 }
1876 
1877 #if IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1878 static int ovs_ct_limit_init(struct net *net, struct ovs_net *ovs_net)
1879 {
1880     int i, err;
1881 
1882     ovs_net->ct_limit_info = kmalloc(sizeof(*ovs_net->ct_limit_info),
1883                      GFP_KERNEL);
1884     if (!ovs_net->ct_limit_info)
1885         return -ENOMEM;
1886 
1887     ovs_net->ct_limit_info->default_limit = OVS_CT_LIMIT_DEFAULT;
1888     ovs_net->ct_limit_info->limits =
1889         kmalloc_array(CT_LIMIT_HASH_BUCKETS, sizeof(struct hlist_head),
1890                   GFP_KERNEL);
1891     if (!ovs_net->ct_limit_info->limits) {
1892         kfree(ovs_net->ct_limit_info);
1893         return -ENOMEM;
1894     }
1895 
1896     for (i = 0; i < CT_LIMIT_HASH_BUCKETS; i++)
1897         INIT_HLIST_HEAD(&ovs_net->ct_limit_info->limits[i]);
1898 
1899     ovs_net->ct_limit_info->data =
1900         nf_conncount_init(net, NFPROTO_INET, sizeof(u32));
1901 
1902     if (IS_ERR(ovs_net->ct_limit_info->data)) {
1903         err = PTR_ERR(ovs_net->ct_limit_info->data);
1904         kfree(ovs_net->ct_limit_info->limits);
1905         kfree(ovs_net->ct_limit_info);
1906         pr_err("openvswitch: failed to init nf_conncount %d\n", err);
1907         return err;
1908     }
1909     return 0;
1910 }
1911 
1912 static void ovs_ct_limit_exit(struct net *net, struct ovs_net *ovs_net)
1913 {
1914     const struct ovs_ct_limit_info *info = ovs_net->ct_limit_info;
1915     int i;
1916 
1917     nf_conncount_destroy(net, NFPROTO_INET, info->data);
1918     for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
1919         struct hlist_head *head = &info->limits[i];
1920         struct ovs_ct_limit *ct_limit;
1921 
1922         hlist_for_each_entry_rcu(ct_limit, head, hlist_node,
1923                      lockdep_ovsl_is_held())
1924             kfree_rcu(ct_limit, rcu);
1925     }
1926     kfree(info->limits);
1927     kfree(info);
1928 }
1929 
1930 static struct sk_buff *
1931 ovs_ct_limit_cmd_reply_start(struct genl_info *info, u8 cmd,
1932                  struct ovs_header **ovs_reply_header)
1933 {
1934     struct ovs_header *ovs_header = info->userhdr;
1935     struct sk_buff *skb;
1936 
1937     skb = genlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1938     if (!skb)
1939         return ERR_PTR(-ENOMEM);
1940 
1941     *ovs_reply_header = genlmsg_put(skb, info->snd_portid,
1942                     info->snd_seq,
1943                     &dp_ct_limit_genl_family, 0, cmd);
1944 
1945     if (!*ovs_reply_header) {
1946         nlmsg_free(skb);
1947         return ERR_PTR(-EMSGSIZE);
1948     }
1949     (*ovs_reply_header)->dp_ifindex = ovs_header->dp_ifindex;
1950 
1951     return skb;
1952 }
1953 
1954 static bool check_zone_id(int zone_id, u16 *pzone)
1955 {
1956     if (zone_id >= 0 && zone_id <= 65535) {
1957         *pzone = (u16)zone_id;
1958         return true;
1959     }
1960     return false;
1961 }
1962 
1963 static int ovs_ct_limit_set_zone_limit(struct nlattr *nla_zone_limit,
1964                        struct ovs_ct_limit_info *info)
1965 {
1966     struct ovs_zone_limit *zone_limit;
1967     int rem;
1968     u16 zone;
1969 
1970     rem = NLA_ALIGN(nla_len(nla_zone_limit));
1971     zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
1972 
1973     while (rem >= sizeof(*zone_limit)) {
1974         if (unlikely(zone_limit->zone_id ==
1975                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
1976             ovs_lock();
1977             info->default_limit = zone_limit->limit;
1978             ovs_unlock();
1979         } else if (unlikely(!check_zone_id(
1980                 zone_limit->zone_id, &zone))) {
1981             OVS_NLERR(true, "zone id is out of range");
1982         } else {
1983             struct ovs_ct_limit *ct_limit;
1984 
1985             ct_limit = kmalloc(sizeof(*ct_limit), GFP_KERNEL);
1986             if (!ct_limit)
1987                 return -ENOMEM;
1988 
1989             ct_limit->zone = zone;
1990             ct_limit->limit = zone_limit->limit;
1991 
1992             ovs_lock();
1993             ct_limit_set(info, ct_limit);
1994             ovs_unlock();
1995         }
1996         rem -= NLA_ALIGN(sizeof(*zone_limit));
1997         zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
1998                 NLA_ALIGN(sizeof(*zone_limit)));
1999     }
2000 
2001     if (rem)
2002         OVS_NLERR(true, "set zone limit has %d unknown bytes", rem);
2003 
2004     return 0;
2005 }
2006 
2007 static int ovs_ct_limit_del_zone_limit(struct nlattr *nla_zone_limit,
2008                        struct ovs_ct_limit_info *info)
2009 {
2010     struct ovs_zone_limit *zone_limit;
2011     int rem;
2012     u16 zone;
2013 
2014     rem = NLA_ALIGN(nla_len(nla_zone_limit));
2015     zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
2016 
2017     while (rem >= sizeof(*zone_limit)) {
2018         if (unlikely(zone_limit->zone_id ==
2019                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
2020             ovs_lock();
2021             info->default_limit = OVS_CT_LIMIT_DEFAULT;
2022             ovs_unlock();
2023         } else if (unlikely(!check_zone_id(
2024                 zone_limit->zone_id, &zone))) {
2025             OVS_NLERR(true, "zone id is out of range");
2026         } else {
2027             ovs_lock();
2028             ct_limit_del(info, zone);
2029             ovs_unlock();
2030         }
2031         rem -= NLA_ALIGN(sizeof(*zone_limit));
2032         zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
2033                 NLA_ALIGN(sizeof(*zone_limit)));
2034     }
2035 
2036     if (rem)
2037         OVS_NLERR(true, "del zone limit has %d unknown bytes", rem);
2038 
2039     return 0;
2040 }
2041 
2042 static int ovs_ct_limit_get_default_limit(struct ovs_ct_limit_info *info,
2043                       struct sk_buff *reply)
2044 {
2045     struct ovs_zone_limit zone_limit = {
2046         .zone_id = OVS_ZONE_LIMIT_DEFAULT_ZONE,
2047         .limit   = info->default_limit,
2048     };
2049 
2050     return nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
2051 }
2052 
2053 static int __ovs_ct_limit_get_zone_limit(struct net *net,
2054                      struct nf_conncount_data *data,
2055                      u16 zone_id, u32 limit,
2056                      struct sk_buff *reply)
2057 {
2058     struct nf_conntrack_zone ct_zone;
2059     struct ovs_zone_limit zone_limit;
2060     u32 conncount_key = zone_id;
2061 
2062     zone_limit.zone_id = zone_id;
2063     zone_limit.limit = limit;
2064     nf_ct_zone_init(&ct_zone, zone_id, NF_CT_DEFAULT_ZONE_DIR, 0);
2065 
2066     zone_limit.count = nf_conncount_count(net, data, &conncount_key, NULL,
2067                           &ct_zone);
2068     return nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
2069 }
2070 
2071 static int ovs_ct_limit_get_zone_limit(struct net *net,
2072                        struct nlattr *nla_zone_limit,
2073                        struct ovs_ct_limit_info *info,
2074                        struct sk_buff *reply)
2075 {
2076     struct ovs_zone_limit *zone_limit;
2077     int rem, err;
2078     u32 limit;
2079     u16 zone;
2080 
2081     rem = NLA_ALIGN(nla_len(nla_zone_limit));
2082     zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
2083 
2084     while (rem >= sizeof(*zone_limit)) {
2085         if (unlikely(zone_limit->zone_id ==
2086                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
2087             err = ovs_ct_limit_get_default_limit(info, reply);
2088             if (err)
2089                 return err;
2090         } else if (unlikely(!check_zone_id(zone_limit->zone_id,
2091                             &zone))) {
2092             OVS_NLERR(true, "zone id is out of range");
2093         } else {
2094             rcu_read_lock();
2095             limit = ct_limit_get(info, zone);
2096             rcu_read_unlock();
2097 
2098             err = __ovs_ct_limit_get_zone_limit(
2099                 net, info->data, zone, limit, reply);
2100             if (err)
2101                 return err;
2102         }
2103         rem -= NLA_ALIGN(sizeof(*zone_limit));
2104         zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
2105                 NLA_ALIGN(sizeof(*zone_limit)));
2106     }
2107 
2108     if (rem)
2109         OVS_NLERR(true, "get zone limit has %d unknown bytes", rem);
2110 
2111     return 0;
2112 }
2113 
2114 static int ovs_ct_limit_get_all_zone_limit(struct net *net,
2115                        struct ovs_ct_limit_info *info,
2116                        struct sk_buff *reply)
2117 {
2118     struct ovs_ct_limit *ct_limit;
2119     struct hlist_head *head;
2120     int i, err = 0;
2121 
2122     err = ovs_ct_limit_get_default_limit(info, reply);
2123     if (err)
2124         return err;
2125 
2126     rcu_read_lock();
2127     for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
2128         head = &info->limits[i];
2129         hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
2130             err = __ovs_ct_limit_get_zone_limit(net, info->data,
2131                 ct_limit->zone, ct_limit->limit, reply);
2132             if (err)
2133                 goto exit_err;
2134         }
2135     }
2136 
2137 exit_err:
2138     rcu_read_unlock();
2139     return err;
2140 }
2141 
2142 static int ovs_ct_limit_cmd_set(struct sk_buff *skb, struct genl_info *info)
2143 {
2144     struct nlattr **a = info->attrs;
2145     struct sk_buff *reply;
2146     struct ovs_header *ovs_reply_header;
2147     struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2148     struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2149     int err;
2150 
2151     reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_SET,
2152                          &ovs_reply_header);
2153     if (IS_ERR(reply))
2154         return PTR_ERR(reply);
2155 
2156     if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2157         err = -EINVAL;
2158         goto exit_err;
2159     }
2160 
2161     err = ovs_ct_limit_set_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2162                       ct_limit_info);
2163     if (err)
2164         goto exit_err;
2165 
2166     static_branch_enable(&ovs_ct_limit_enabled);
2167 
2168     genlmsg_end(reply, ovs_reply_header);
2169     return genlmsg_reply(reply, info);
2170 
2171 exit_err:
2172     nlmsg_free(reply);
2173     return err;
2174 }
2175 
2176 static int ovs_ct_limit_cmd_del(struct sk_buff *skb, struct genl_info *info)
2177 {
2178     struct nlattr **a = info->attrs;
2179     struct sk_buff *reply;
2180     struct ovs_header *ovs_reply_header;
2181     struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2182     struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2183     int err;
2184 
2185     reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_DEL,
2186                          &ovs_reply_header);
2187     if (IS_ERR(reply))
2188         return PTR_ERR(reply);
2189 
2190     if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2191         err = -EINVAL;
2192         goto exit_err;
2193     }
2194 
2195     err = ovs_ct_limit_del_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2196                       ct_limit_info);
2197     if (err)
2198         goto exit_err;
2199 
2200     genlmsg_end(reply, ovs_reply_header);
2201     return genlmsg_reply(reply, info);
2202 
2203 exit_err:
2204     nlmsg_free(reply);
2205     return err;
2206 }
2207 
2208 static int ovs_ct_limit_cmd_get(struct sk_buff *skb, struct genl_info *info)
2209 {
2210     struct nlattr **a = info->attrs;
2211     struct nlattr *nla_reply;
2212     struct sk_buff *reply;
2213     struct ovs_header *ovs_reply_header;
2214     struct net *net = sock_net(skb->sk);
2215     struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2216     struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2217     int err;
2218 
2219     reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_GET,
2220                          &ovs_reply_header);
2221     if (IS_ERR(reply))
2222         return PTR_ERR(reply);
2223 
2224     nla_reply = nla_nest_start_noflag(reply, OVS_CT_LIMIT_ATTR_ZONE_LIMIT);
2225     if (!nla_reply) {
2226         err = -EMSGSIZE;
2227         goto exit_err;
2228     }
2229 
2230     if (a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2231         err = ovs_ct_limit_get_zone_limit(
2232             net, a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT], ct_limit_info,
2233             reply);
2234         if (err)
2235             goto exit_err;
2236     } else {
2237         err = ovs_ct_limit_get_all_zone_limit(net, ct_limit_info,
2238                               reply);
2239         if (err)
2240             goto exit_err;
2241     }
2242 
2243     nla_nest_end(reply, nla_reply);
2244     genlmsg_end(reply, ovs_reply_header);
2245     return genlmsg_reply(reply, info);
2246 
2247 exit_err:
2248     nlmsg_free(reply);
2249     return err;
2250 }
2251 
2252 static const struct genl_small_ops ct_limit_genl_ops[] = {
2253     { .cmd = OVS_CT_LIMIT_CMD_SET,
2254         .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2255         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2256                        * privilege. */
2257         .doit = ovs_ct_limit_cmd_set,
2258     },
2259     { .cmd = OVS_CT_LIMIT_CMD_DEL,
2260         .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2261         .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2262                        * privilege. */
2263         .doit = ovs_ct_limit_cmd_del,
2264     },
2265     { .cmd = OVS_CT_LIMIT_CMD_GET,
2266         .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2267         .flags = 0,       /* OK for unprivileged users. */
2268         .doit = ovs_ct_limit_cmd_get,
2269     },
2270 };
2271 
2272 static const struct genl_multicast_group ovs_ct_limit_multicast_group = {
2273     .name = OVS_CT_LIMIT_MCGROUP,
2274 };
2275 
2276 struct genl_family dp_ct_limit_genl_family __ro_after_init = {
2277     .hdrsize = sizeof(struct ovs_header),
2278     .name = OVS_CT_LIMIT_FAMILY,
2279     .version = OVS_CT_LIMIT_VERSION,
2280     .maxattr = OVS_CT_LIMIT_ATTR_MAX,
2281     .policy = ct_limit_policy,
2282     .netnsok = true,
2283     .parallel_ops = true,
2284     .small_ops = ct_limit_genl_ops,
2285     .n_small_ops = ARRAY_SIZE(ct_limit_genl_ops),
2286     .mcgrps = &ovs_ct_limit_multicast_group,
2287     .n_mcgrps = 1,
2288     .module = THIS_MODULE,
2289 };
2290 #endif
2291 
2292 int ovs_ct_init(struct net *net)
2293 {
2294     unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
2295     struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2296 
2297     if (nf_connlabels_get(net, n_bits - 1)) {
2298         ovs_net->xt_label = false;
2299         OVS_NLERR(true, "Failed to set connlabel length");
2300     } else {
2301         ovs_net->xt_label = true;
2302     }
2303 
2304 #if IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2305     return ovs_ct_limit_init(net, ovs_net);
2306 #else
2307     return 0;
2308 #endif
2309 }
2310 
2311 void ovs_ct_exit(struct net *net)
2312 {
2313     struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2314 
2315 #if IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2316     ovs_ct_limit_exit(net, ovs_net);
2317 #endif
2318 
2319     if (ovs_net->xt_label)
2320         nf_connlabels_put(net);
2321 }