Merge tag 'io_uring-5.19-2022-07-01' of git://git.kernel.dk/linux-block
[linux-2.6-microblaze.git] / net / openvswitch / conntrack.c
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
35 struct ovs_ct_len_tbl {
36         int maxlen;
37         int minlen;
38 };
39
40 /* Metadata mark for masked write to conntrack mark */
41 struct md_mark {
42         u32 value;
43         u32 mask;
44 };
45
46 /* Metadata label for masked write to conntrack label. */
47 struct md_labels {
48         struct ovs_key_ct_labels value;
49         struct ovs_key_ct_labels mask;
50 };
51
52 enum 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. */
59 struct 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
82 static DEFINE_STATIC_KEY_FALSE(ovs_ct_limit_enabled);
83
84 struct 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
92 struct ovs_ct_limit_info {
93         u32 default_limit;
94         struct hlist_head *limits;
95         struct nf_conncount_data *data;
96 };
97
98 static 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
103 static bool labels_nonzero(const struct ovs_key_ct_labels *labels);
104
105 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
106
107 static 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. */
120 static 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
152 static 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
166 static 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
177 static 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
191 static 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  */
235 static 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  */
276 void 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
283 int 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
337 static 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
357 static 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  */
374 static 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
415 static 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. */
438 static 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  */
499 static 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
547 static struct nf_conntrack_expect *
548 ovs_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. */
587 static enum ip_conntrack_info
588 ovs_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  */
611 static struct nf_conn *
612 ovs_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
654 static
655 struct 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. */
683 static 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)
737 static 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  */
792 static 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);
864 push:
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. */
875 static 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 */
933 static 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  */
948 static 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. */
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 }