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