datapath: conntrack NAT helper compat code for Linux 4.5 and earlier.
[cascardo/ovs.git] / datapath / 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/kconfig.h>
15 #include <linux/version.h>
16
17 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
18
19 #include <linux/module.h>
20 #include <linux/openvswitch.h>
21 #include <linux/tcp.h>
22 #include <linux/udp.h>
23 #include <linux/sctp.h>
24 #include <net/ip.h>
25 #include <net/netfilter/nf_conntrack_core.h>
26 #include <net/netfilter/nf_conntrack_helper.h>
27 #include <net/netfilter/nf_conntrack_labels.h>
28 #include <net/netfilter/nf_conntrack_seqadj.h>
29 #include <net/netfilter/nf_conntrack_zones.h>
30 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
31
32 #ifdef CONFIG_NF_NAT_NEEDED
33 #include <linux/netfilter/nf_nat.h>
34 #include <net/netfilter/nf_nat_core.h>
35 #include <net/netfilter/nf_nat_l3proto.h>
36 #endif
37
38 #include "datapath.h"
39 #include "conntrack.h"
40 #include "flow.h"
41 #include "flow_netlink.h"
42 #include "gso.h"
43
44 struct ovs_ct_len_tbl {
45         int maxlen;
46         int minlen;
47 };
48
49 /* Metadata mark for masked write to conntrack mark */
50 struct md_mark {
51         u32 value;
52         u32 mask;
53 };
54
55 /* Metadata label for masked write to conntrack label. */
56 struct md_labels {
57         struct ovs_key_ct_labels value;
58         struct ovs_key_ct_labels mask;
59 };
60
61 enum ovs_ct_nat {
62         OVS_CT_NAT = 1 << 0,     /* NAT for committed connections only. */
63         OVS_CT_SRC_NAT = 1 << 1, /* Source NAT for NEW connections. */
64         OVS_CT_DST_NAT = 1 << 2, /* Destination NAT for NEW connections. */
65 };
66
67 /* Conntrack action context for execution. */
68 struct ovs_conntrack_info {
69         struct nf_conntrack_helper *helper;
70         struct nf_conntrack_zone zone;
71         struct nf_conn *ct;
72         u8 commit : 1;
73         u8 nat : 3;                 /* enum ovs_ct_nat */
74         u16 family;
75         struct md_mark mark;
76         struct md_labels labels;
77 #ifdef CONFIG_NF_NAT_NEEDED
78         struct nf_nat_range range;  /* Only present for SRC NAT and DST NAT. */
79 #endif
80 };
81
82 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
83
84 static u16 key_to_nfproto(const struct sw_flow_key *key)
85 {
86         switch (ntohs(key->eth.type)) {
87         case ETH_P_IP:
88                 return NFPROTO_IPV4;
89         case ETH_P_IPV6:
90                 return NFPROTO_IPV6;
91         default:
92                 return NFPROTO_UNSPEC;
93         }
94 }
95
96 /* Map SKB connection state into the values used by flow definition. */
97 static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
98 {
99         u8 ct_state = OVS_CS_F_TRACKED;
100
101         switch (ctinfo) {
102         case IP_CT_ESTABLISHED_REPLY:
103         case IP_CT_RELATED_REPLY:
104                 ct_state |= OVS_CS_F_REPLY_DIR;
105                 break;
106         default:
107                 break;
108         }
109
110         switch (ctinfo) {
111         case IP_CT_ESTABLISHED:
112         case IP_CT_ESTABLISHED_REPLY:
113                 ct_state |= OVS_CS_F_ESTABLISHED;
114                 break;
115         case IP_CT_RELATED:
116         case IP_CT_RELATED_REPLY:
117                 ct_state |= OVS_CS_F_RELATED;
118                 break;
119         case IP_CT_NEW:
120                 ct_state |= OVS_CS_F_NEW;
121                 break;
122         default:
123                 break;
124         }
125
126         return ct_state;
127 }
128
129 static u32 ovs_ct_get_mark(const struct nf_conn *ct)
130 {
131 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
132         return ct ? ct->mark : 0;
133 #else
134         return 0;
135 #endif
136 }
137
138 static void ovs_ct_get_labels(const struct nf_conn *ct,
139                               struct ovs_key_ct_labels *labels)
140 {
141         struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
142
143         if (cl) {
144                 size_t len = cl->words * sizeof(long);
145
146                 if (len > OVS_CT_LABELS_LEN)
147                         len = OVS_CT_LABELS_LEN;
148                 else if (len < OVS_CT_LABELS_LEN)
149                         memset(labels, 0, OVS_CT_LABELS_LEN);
150                 memcpy(labels, cl->bits, len);
151         } else {
152                 memset(labels, 0, OVS_CT_LABELS_LEN);
153         }
154 }
155
156 static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
157                                 const struct nf_conntrack_zone *zone,
158                                 const struct nf_conn *ct)
159 {
160         key->ct.state = state;
161         key->ct.zone = zone->id;
162         key->ct.mark = ovs_ct_get_mark(ct);
163         ovs_ct_get_labels(ct, &key->ct.labels);
164 }
165
166 /* Update 'key' based on skb->nfct.  If 'post_ct' is true, then OVS has
167  * previously sent the packet to conntrack via the ct action.  If
168  * 'keep_nat_flags' is true, the existing NAT flags retained, else they are
169  * initialized from the connection status.
170  */
171 static void ovs_ct_update_key(const struct sk_buff *skb,
172                               const struct ovs_conntrack_info *info,
173                               struct sw_flow_key *key, bool post_ct,
174                               bool keep_nat_flags)
175 {
176         const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
177         enum ip_conntrack_info ctinfo;
178         struct nf_conn *ct;
179         u8 state = 0;
180
181         ct = nf_ct_get(skb, &ctinfo);
182         if (ct) {
183                 state = ovs_ct_get_state(ctinfo);
184                 /* All unconfirmed entries are NEW connections. */
185                 if (!nf_ct_is_confirmed(ct))
186                         state |= OVS_CS_F_NEW;
187                 /* OVS persists the related flag for the duration of the
188                  * connection.
189                  */
190                 if (ct->master)
191                         state |= OVS_CS_F_RELATED;
192                 if (keep_nat_flags) {
193                         state |= key->ct.state & OVS_CS_F_NAT_MASK;
194                 } else {
195                         if (ct->status & IPS_SRC_NAT)
196                                 state |= OVS_CS_F_SRC_NAT;
197                         if (ct->status & IPS_DST_NAT)
198                                 state |= OVS_CS_F_DST_NAT;
199                 }
200                 zone = nf_ct_zone(ct);
201         } else if (post_ct) {
202                 state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
203                 if (info)
204                         zone = &info->zone;
205         }
206         __ovs_ct_update_key(key, state, zone, ct);
207 }
208
209 /* This is called to initialize CT key fields possibly coming in from the local
210  * stack.
211  */
212 void ovs_ct_fill_key(const struct sk_buff *skb, struct sw_flow_key *key)
213 {
214         ovs_ct_update_key(skb, NULL, key, false, false);
215 }
216
217 int ovs_ct_put_key(const struct sw_flow_key *key, struct sk_buff *skb)
218 {
219         if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, key->ct.state))
220                 return -EMSGSIZE;
221
222         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
223             nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, key->ct.zone))
224                 return -EMSGSIZE;
225
226         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
227             nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, key->ct.mark))
228                 return -EMSGSIZE;
229
230         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
231             nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(key->ct.labels),
232                     &key->ct.labels))
233                 return -EMSGSIZE;
234
235         return 0;
236 }
237
238 static int ovs_ct_set_mark(struct sk_buff *skb, struct sw_flow_key *key,
239                            u32 ct_mark, u32 mask)
240 {
241 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
242         enum ip_conntrack_info ctinfo;
243         struct nf_conn *ct;
244         u32 new_mark;
245
246         /* The connection could be invalid, in which case set_mark is no-op. */
247         ct = nf_ct_get(skb, &ctinfo);
248         if (!ct)
249                 return 0;
250
251         new_mark = ct_mark | (ct->mark & ~(mask));
252         if (ct->mark != new_mark) {
253                 ct->mark = new_mark;
254                 nf_conntrack_event_cache(IPCT_MARK, ct);
255                 key->ct.mark = new_mark;
256         }
257
258         return 0;
259 #else
260         return -ENOTSUPP;
261 #endif
262 }
263
264 static int ovs_ct_set_labels(struct sk_buff *skb, struct sw_flow_key *key,
265                              const struct ovs_key_ct_labels *labels,
266                              const struct ovs_key_ct_labels *mask)
267 {
268         enum ip_conntrack_info ctinfo;
269         struct nf_conn_labels *cl;
270         struct nf_conn *ct;
271         int err;
272
273         /* The connection could be invalid, in which case set_label is no-op.*/
274         ct = nf_ct_get(skb, &ctinfo);
275         if (!ct)
276                 return 0;
277
278         cl = nf_ct_labels_find(ct);
279         if (!cl) {
280                 nf_ct_labels_ext_add(ct);
281                 cl = nf_ct_labels_find(ct);
282         }
283         if (!cl || cl->words * sizeof(long) < OVS_CT_LABELS_LEN)
284                 return -ENOSPC;
285
286         err = nf_connlabels_replace(ct, (u32 *)labels, (u32 *)mask,
287                                     OVS_CT_LABELS_LEN / sizeof(u32));
288         if (err)
289                 return err;
290
291         ovs_ct_get_labels(ct, &key->ct.labels);
292         return 0;
293 }
294
295 /* 'skb' should already be pulled to nh_ofs. */
296 static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
297 {
298         const struct nf_conntrack_helper *helper;
299         const struct nf_conn_help *help;
300         enum ip_conntrack_info ctinfo;
301         unsigned int protoff;
302         struct nf_conn *ct;
303         u8 nexthdr;
304         int err;
305
306         ct = nf_ct_get(skb, &ctinfo);
307         if (!ct || ctinfo == IP_CT_RELATED_REPLY)
308                 return NF_ACCEPT;
309
310         help = nfct_help(ct);
311         if (!help)
312                 return NF_ACCEPT;
313
314         helper = rcu_dereference(help->helper);
315         if (!helper)
316                 return NF_ACCEPT;
317
318         switch (proto) {
319         case NFPROTO_IPV4:
320                 protoff = ip_hdrlen(skb);
321                 break;
322         case NFPROTO_IPV6: {
323                 __be16 frag_off;
324                 int ofs;
325
326                 nexthdr = ipv6_hdr(skb)->nexthdr;
327                 ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
328                                        &frag_off);
329                 if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
330                         pr_debug("proto header not found\n");
331                         return NF_ACCEPT;
332                 }
333                 protoff = ofs;
334                 break;
335         }
336         default:
337                 WARN_ONCE(1, "helper invoked on non-IP family!");
338                 return NF_DROP;
339         }
340
341 #if LINUX_VERSION_CODE < KERNEL_VERSION(4,6,0)
342         /* Linux 4.5 and older depend on skb_dst being set when recalculating
343          * checksums after NAT helper has mangled TCP or UDP packet payload.
344          * This dependency is avoided when skb is CHECKSUM_PARTIAL or when UDP
345          * has no checksum.
346          *
347          * The dependency is not triggered when the main NAT code updates
348          * checksums after translating the IP header (address, port), so this
349          * fix only needs to be executed on packets that are both being NATted
350          * and that have a helper assigned.
351          */
352         if (ct->status & IPS_NAT_MASK && skb->ip_summed != CHECKSUM_PARTIAL) {
353                 u8 ipproto = (proto == NFPROTO_IPV4)
354                         ? ip_hdr(skb)->protocol : nexthdr;
355                 u16 offset = 0;
356
357                 switch (ipproto) {
358                 case IPPROTO_TCP:
359                         offset = offsetof(struct tcphdr, check);
360                         break;
361                 case IPPROTO_UDP:
362                         /* Skip if no csum. */
363                         if (udp_hdr(skb)->check)
364                                 offset = offsetof(struct udphdr, check);
365                         break;
366                 }
367                 if (offset) {
368                         if (unlikely(!pskb_may_pull(skb, protoff + offset + 2)))
369                                 return NF_DROP;
370
371                         skb->csum_start = skb_headroom(skb) + protoff;
372                         skb->csum_offset = offset;
373                         skb->ip_summed = CHECKSUM_PARTIAL;
374                 }
375         }
376 #endif
377         err = helper->help(skb, protoff, ct, ctinfo);
378         if (err != NF_ACCEPT)
379                 return err;
380
381         /* Adjust seqs after helper.  This is needed due to some helpers (e.g.,
382          * FTP with NAT) adusting the TCP payload size when mangling IP
383          * addresses and/or port numbers in the text-based control connection.
384          */
385         if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
386             !nf_ct_seq_adjust(skb, ct, ctinfo, protoff))
387                 return NF_DROP;
388         return NF_ACCEPT;
389 }
390
391 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
392  * value if 'skb' is freed.
393  */
394 static int handle_fragments(struct net *net, struct sw_flow_key *key,
395                             u16 zone, struct sk_buff *skb)
396 {
397         struct ovs_gso_cb ovs_cb = *OVS_GSO_CB(skb);
398         int err;
399
400         if (!skb->dev) {
401                 OVS_NLERR(true, "%s: skb has no dev; dropping", __func__);
402                 return -EINVAL;
403         }
404
405         if (key->eth.type == htons(ETH_P_IP)) {
406                 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
407
408                 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
409                 err = ip_defrag(net, skb, user);
410                 if (err)
411                         return err;
412
413                 ovs_cb.dp_cb.mru = IPCB(skb)->frag_max_size;
414 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
415         } else if (key->eth.type == htons(ETH_P_IPV6)) {
416                 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
417
418                 skb_orphan(skb);
419                 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
420                 err = nf_ct_frag6_gather(net, skb, user);
421                 if (err)
422                         return err;
423
424                 key->ip.proto = ipv6_hdr(skb)->nexthdr;
425                 ovs_cb.dp_cb.mru = IP6CB(skb)->frag_max_size;
426 #endif /* IP frag support */
427         } else {
428                 kfree_skb(skb);
429                 return -EPFNOSUPPORT;
430         }
431
432         key->ip.frag = OVS_FRAG_TYPE_NONE;
433         skb_clear_hash(skb);
434         skb->ignore_df = 1;
435         *OVS_GSO_CB(skb) = ovs_cb;
436
437         return 0;
438 }
439
440 static struct nf_conntrack_expect *
441 ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
442                    u16 proto, const struct sk_buff *skb)
443 {
444         struct nf_conntrack_tuple tuple;
445
446         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
447                 return NULL;
448         return __nf_ct_expect_find(net, zone, &tuple);
449 }
450
451 /* This replicates logic from nf_conntrack_core.c that is not exported. */
452 static enum ip_conntrack_info
453 ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
454 {
455         const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
456
457         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
458                 return IP_CT_ESTABLISHED_REPLY;
459         /* Once we've had two way comms, always ESTABLISHED. */
460         if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
461                 return IP_CT_ESTABLISHED;
462         if (test_bit(IPS_EXPECTED_BIT, &ct->status))
463                 return IP_CT_RELATED;
464         return IP_CT_NEW;
465 }
466
467 /* Find an existing connection which this packet belongs to without
468  * re-attributing statistics or modifying the connection state.  This allows an
469  * skb->nfct lost due to an upcall to be recovered during actions execution.
470  *
471  * Must be called with rcu_read_lock.
472  *
473  * On success, populates skb->nfct and skb->nfctinfo, and returns the
474  * connection.  Returns NULL if there is no existing entry.
475  */
476 static struct nf_conn *
477 ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
478                      u8 l3num, struct sk_buff *skb)
479 {
480         struct nf_conntrack_l3proto *l3proto;
481         struct nf_conntrack_l4proto *l4proto;
482         struct nf_conntrack_tuple tuple;
483         struct nf_conntrack_tuple_hash *h;
484         enum ip_conntrack_info ctinfo;
485         struct nf_conn *ct;
486         unsigned int dataoff;
487         u8 protonum;
488
489         l3proto = __nf_ct_l3proto_find(l3num);
490         if (!l3proto) {
491                 pr_debug("ovs_ct_find_existing: Can't get l3proto\n");
492                 return NULL;
493         }
494         if (l3proto->get_l4proto(skb, skb_network_offset(skb), &dataoff,
495                                  &protonum) <= 0) {
496                 pr_debug("ovs_ct_find_existing: Can't get protonum\n");
497                 return NULL;
498         }
499         l4proto = __nf_ct_l4proto_find(l3num, protonum);
500         if (!l4proto) {
501                 pr_debug("ovs_ct_find_existing: Can't get l4proto\n");
502                 return NULL;
503         }
504         if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
505                              protonum, net, &tuple, l3proto, l4proto)) {
506                 pr_debug("ovs_ct_find_existing: Can't get tuple\n");
507                 return NULL;
508         }
509
510         /* look for tuple match */
511         h = nf_conntrack_find_get(net, zone, &tuple);
512         if (!h)
513                 return NULL;   /* Not found. */
514
515         ct = nf_ct_tuplehash_to_ctrack(h);
516
517         ctinfo = ovs_ct_get_info(h);
518         if (ctinfo == IP_CT_NEW) {
519                 /* This should not happen. */
520                 WARN_ONCE(1, "ovs_ct_find_existing: new packet for %p\n", ct);
521         }
522         skb->nfct = &ct->ct_general;
523         skb->nfctinfo = ctinfo;
524         return ct;
525 }
526
527 /* Determine whether skb->nfct is equal to the result of conntrack lookup. */
528 static bool skb_nfct_cached(struct net *net,
529                             const struct sw_flow_key *key,
530                             const struct ovs_conntrack_info *info,
531                             struct sk_buff *skb)
532 {
533         enum ip_conntrack_info ctinfo;
534         struct nf_conn *ct;
535
536         ct = nf_ct_get(skb, &ctinfo);
537         /* If no ct, check if we have evidence that an existing conntrack entry
538          * might be found for this skb.  This happens when we lose a skb->nfct
539          * due to an upcall.  If the connection was not confirmed, it is not
540          * cached and needs to be run through conntrack again.
541          */
542         if (!ct && key->ct.state & OVS_CS_F_TRACKED &&
543             !(key->ct.state & OVS_CS_F_INVALID) &&
544             key->ct.zone == info->zone.id)
545                 ct = ovs_ct_find_existing(net, &info->zone, info->family, skb);
546         if (!ct)
547                 return false;
548         if (!net_eq(net, read_pnet(&ct->ct_net)))
549                 return false;
550         if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
551                 return false;
552         if (info->helper) {
553                 struct nf_conn_help *help;
554
555                 help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
556                 if (help && rcu_access_pointer(help->helper) != info->helper)
557                         return false;
558         }
559
560         return true;
561 }
562
563 #ifdef CONFIG_NF_NAT_NEEDED
564 /* Modelled after nf_nat_ipv[46]_fn().
565  * range is only used for new, uninitialized NAT state.
566  * Returns either NF_ACCEPT or NF_DROP.
567  */
568 static int ovs_ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
569                               enum ip_conntrack_info ctinfo,
570                               const struct nf_nat_range *range,
571                               enum nf_nat_manip_type maniptype)
572 {
573         int hooknum, nh_off, err = NF_ACCEPT;
574
575         nh_off = skb_network_offset(skb);
576         skb_pull(skb, nh_off);
577
578         /* See HOOK2MANIP(). */
579         if (maniptype == NF_NAT_MANIP_SRC)
580                 hooknum = NF_INET_LOCAL_IN; /* Source NAT */
581         else
582                 hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
583
584         switch (ctinfo) {
585         case IP_CT_RELATED:
586         case IP_CT_RELATED_REPLY:
587                 if (skb->protocol == htons(ETH_P_IP) &&
588                     ip_hdr(skb)->protocol == IPPROTO_ICMP) {
589                         if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
590                                                            hooknum))
591                                 err = NF_DROP;
592                         goto push;
593 #if IS_ENABLED(CONFIG_NF_NAT_IPV6)
594                 } else if (skb->protocol == htons(ETH_P_IPV6)) {
595                         __be16 frag_off;
596                         u8 nexthdr = ipv6_hdr(skb)->nexthdr;
597                         int hdrlen = ipv6_skip_exthdr(skb,
598                                                       sizeof(struct ipv6hdr),
599                                                       &nexthdr, &frag_off);
600
601                         if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
602                                 if (!nf_nat_icmpv6_reply_translation(skb, ct,
603                                                                      ctinfo,
604                                                                      hooknum,
605                                                                      hdrlen))
606                                         err = NF_DROP;
607                                 goto push;
608                         }
609 #endif
610                 }
611                 /* Non-ICMP, fall thru to initialize if needed. */
612         case IP_CT_NEW:
613                 /* Seen it before?  This can happen for loopback, retrans,
614                  * or local packets.
615                  */
616                 if (!nf_nat_initialized(ct, maniptype)) {
617                         /* Initialize according to the NAT action. */
618                         err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
619                                 /* Action is set up to establish a new
620                                  * mapping.
621                                  */
622                                 ? nf_nat_setup_info(ct, range, maniptype)
623                                 : nf_nat_alloc_null_binding(ct, hooknum);
624                         if (err != NF_ACCEPT)
625                                 goto push;
626                 }
627                 break;
628
629         case IP_CT_ESTABLISHED:
630         case IP_CT_ESTABLISHED_REPLY:
631                 break;
632
633         default:
634                 err = NF_DROP;
635                 goto push;
636         }
637
638         err = nf_nat_packet(ct, ctinfo, hooknum, skb);
639 push:
640         skb_push(skb, nh_off);
641
642         return err;
643 }
644
645 static void ovs_nat_update_key(struct sw_flow_key *key,
646                                const struct sk_buff *skb,
647                                enum nf_nat_manip_type maniptype)
648 {
649         if (maniptype == NF_NAT_MANIP_SRC) {
650                 __be16 src;
651
652                 key->ct.state |= OVS_CS_F_SRC_NAT;
653                 if (key->eth.type == htons(ETH_P_IP))
654                         key->ipv4.addr.src = ip_hdr(skb)->saddr;
655                 else if (key->eth.type == htons(ETH_P_IPV6))
656                         memcpy(&key->ipv6.addr.src, &ipv6_hdr(skb)->saddr,
657                                sizeof(key->ipv6.addr.src));
658                 else
659                         return;
660
661                 if (key->ip.proto == IPPROTO_UDP)
662                         src = udp_hdr(skb)->source;
663                 else if (key->ip.proto == IPPROTO_TCP)
664                         src = tcp_hdr(skb)->source;
665                 else if (key->ip.proto == IPPROTO_SCTP)
666                         src = sctp_hdr(skb)->source;
667                 else
668                         return;
669
670                 key->tp.src = src;
671         } else {
672                 __be16 dst;
673
674                 key->ct.state |= OVS_CS_F_DST_NAT;
675                 if (key->eth.type == htons(ETH_P_IP))
676                         key->ipv4.addr.dst = ip_hdr(skb)->daddr;
677                 else if (key->eth.type == htons(ETH_P_IPV6))
678                         memcpy(&key->ipv6.addr.dst, &ipv6_hdr(skb)->daddr,
679                                sizeof(key->ipv6.addr.dst));
680                 else
681                         return;
682
683                 if (key->ip.proto == IPPROTO_UDP)
684                         dst = udp_hdr(skb)->dest;
685                 else if (key->ip.proto == IPPROTO_TCP)
686                         dst = tcp_hdr(skb)->dest;
687                 else if (key->ip.proto == IPPROTO_SCTP)
688                         dst = sctp_hdr(skb)->dest;
689                 else
690                         return;
691
692                 key->tp.dst = dst;
693         }
694 }
695
696 /* Returns NF_DROP if the packet should be dropped, NF_ACCEPT otherwise. */
697 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
698                       const struct ovs_conntrack_info *info,
699                       struct sk_buff *skb, struct nf_conn *ct,
700                       enum ip_conntrack_info ctinfo)
701 {
702         enum nf_nat_manip_type maniptype;
703         int err;
704
705         if (nf_ct_is_untracked(ct)) {
706                 /* A NAT action may only be performed on tracked packets. */
707                 return NF_ACCEPT;
708         }
709
710         /* Add NAT extension if not confirmed yet. */
711         if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
712                 return NF_ACCEPT;   /* Can't NAT. */
713
714         /* Determine NAT type.
715          * Check if the NAT type can be deduced from the tracked connection.
716          * Make sure expected traffic is NATted only when committing.
717          */
718         if (info->nat & OVS_CT_NAT && ctinfo != IP_CT_NEW &&
719             ct->status & IPS_NAT_MASK &&
720             (!(ct->status & IPS_EXPECTED_BIT) || info->commit)) {
721                 /* NAT an established or related connection like before. */
722                 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
723                         /* This is the REPLY direction for a connection
724                          * for which NAT was applied in the forward
725                          * direction.  Do the reverse NAT.
726                          */
727                         maniptype = ct->status & IPS_SRC_NAT
728                                 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
729                 else
730                         maniptype = ct->status & IPS_SRC_NAT
731                                 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
732         } else if (info->nat & OVS_CT_SRC_NAT) {
733                 maniptype = NF_NAT_MANIP_SRC;
734         } else if (info->nat & OVS_CT_DST_NAT) {
735                 maniptype = NF_NAT_MANIP_DST;
736         } else {
737                 return NF_ACCEPT; /* Connection is not NATed. */
738         }
739         err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range, maniptype);
740
741         /* Mark NAT done if successful and update the flow key. */
742         if (err == NF_ACCEPT)
743                 ovs_nat_update_key(key, skb, maniptype);
744
745         return err;
746 }
747 #else /* !CONFIG_NF_NAT_NEEDED */
748 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
749                       const struct ovs_conntrack_info *info,
750                       struct sk_buff *skb, struct nf_conn *ct,
751                       enum ip_conntrack_info ctinfo)
752 {
753         return NF_ACCEPT;
754 }
755 #endif
756
757 /* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
758  * not done already.  Update key with new CT state after passing the packet
759  * through conntrack.
760  * Note that if the packet is deemed invalid by conntrack, skb->nfct will be
761  * set to NULL and 0 will be returned.
762  */
763 static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
764                            const struct ovs_conntrack_info *info,
765                            struct sk_buff *skb)
766 {
767         /* If we are recirculating packets to match on conntrack fields and
768          * committing with a separate conntrack action,  then we don't need to
769          * actually run the packet through conntrack twice unless it's for a
770          * different zone.
771          */
772         bool cached = skb_nfct_cached(net, key, info, skb);
773         enum ip_conntrack_info ctinfo;
774         struct nf_conn *ct;
775
776         if (!cached) {
777                 struct nf_conn *tmpl = info->ct;
778                 int err;
779
780                 /* Associate skb with specified zone. */
781                 if (tmpl) {
782                         if (skb->nfct)
783                                 nf_conntrack_put(skb->nfct);
784                         nf_conntrack_get(&tmpl->ct_general);
785                         skb->nfct = &tmpl->ct_general;
786                         skb->nfctinfo = IP_CT_NEW;
787                 }
788
789                 /* Repeat if requested, see nf_iterate(). */
790                 do {
791                         err = nf_conntrack_in(net, info->family,
792                                               NF_INET_FORWARD, skb);
793                 } while (err == NF_REPEAT);
794
795                 if (err != NF_ACCEPT)
796                         return -ENOENT;
797
798                 /* Clear CT state NAT flags to mark that we have not yet done
799                  * NAT after the nf_conntrack_in() call.  We can actually clear
800                  * the whole state, as it will be re-initialized below.
801                  */
802                 key->ct.state = 0;
803
804                 /* Update the key, but keep the NAT flags. */
805                 ovs_ct_update_key(skb, info, key, true, true);
806         }
807
808         ct = nf_ct_get(skb, &ctinfo);
809         if (ct) {
810                 /* Packets starting a new connection must be NATted before the
811                  * helper, so that the helper knows about the NAT.  We enforce
812                  * this by delaying both NAT and helper calls for unconfirmed
813                  * connections until the committing CT action.  For later
814                  * packets NAT and Helper may be called in either order.
815                  *
816                  * NAT will be done only if the CT action has NAT, and only
817                  * once per packet (per zone), as guarded by the NAT bits in
818                  * the key->ct.state.
819                  */
820                 if (info->nat && !(key->ct.state & OVS_CS_F_NAT_MASK) &&
821                     (nf_ct_is_confirmed(ct) || info->commit) &&
822                     ovs_ct_nat(net, key, info, skb, ct, ctinfo) != NF_ACCEPT) {
823                         return -EINVAL;
824                 }
825
826                 /* Call the helper only if:
827                  * - nf_conntrack_in() was executed above ("!cached") for a
828                  *   confirmed connection, or
829                  * - When committing an unconfirmed connection.
830                  */
831                 if ((nf_ct_is_confirmed(ct) ? !cached : info->commit) &&
832                     ovs_ct_helper(skb, info->family) != NF_ACCEPT) {
833                         return -EINVAL;
834                 }
835         }
836
837         return 0;
838 }
839
840 /* Lookup connection and read fields into key. */
841 static int ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
842                          const struct ovs_conntrack_info *info,
843                          struct sk_buff *skb)
844 {
845         struct nf_conntrack_expect *exp;
846
847         /* If we pass an expected packet through nf_conntrack_in() the
848          * expectation is typically removed, but the packet could still be
849          * lost in upcall processing.  To prevent this from happening we
850          * perform an explicit expectation lookup.  Expected connections are
851          * always new, and will be passed through conntrack only when they are
852          * committed, as it is OK to remove the expectation at that time.
853          */
854         exp = ovs_ct_expect_find(net, &info->zone, info->family, skb);
855         if (exp) {
856                 u8 state;
857
858                 /* NOTE: New connections are NATted and Helped only when
859                  * committed, so we are not calling into NAT here.
860                  */
861                 state = OVS_CS_F_TRACKED | OVS_CS_F_NEW | OVS_CS_F_RELATED;
862                 __ovs_ct_update_key(key, state, &info->zone, exp->master);
863         } else
864                 return __ovs_ct_lookup(net, key, info, skb);
865
866         return 0;
867 }
868
869 /* Lookup connection and confirm if unconfirmed. */
870 static int ovs_ct_commit(struct net *net, struct sw_flow_key *key,
871                          const struct ovs_conntrack_info *info,
872                          struct sk_buff *skb)
873 {
874         int err;
875
876         err = __ovs_ct_lookup(net, key, info, skb);
877         if (err)
878                 return err;
879         /* This is a no-op if the connection has already been confirmed. */
880         if (nf_conntrack_confirm(skb) != NF_ACCEPT)
881                 return -EINVAL;
882
883         return 0;
884 }
885
886 static bool labels_nonzero(const struct ovs_key_ct_labels *labels)
887 {
888         size_t i;
889
890         for (i = 0; i < sizeof(*labels); i++)
891                 if (labels->ct_labels[i])
892                         return true;
893
894         return false;
895 }
896
897 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
898  * value if 'skb' is freed.
899  */
900 int ovs_ct_execute(struct net *net, struct sk_buff *skb,
901                    struct sw_flow_key *key,
902                    const struct ovs_conntrack_info *info)
903 {
904         int nh_ofs;
905         int err;
906
907         /* The conntrack module expects to be working at L3. */
908         nh_ofs = skb_network_offset(skb);
909         skb_pull(skb, nh_ofs);
910
911         if (key->ip.frag != OVS_FRAG_TYPE_NONE) {
912                 err = handle_fragments(net, key, info->zone.id, skb);
913                 if (err)
914                         return err;
915         }
916
917         if (info->commit)
918                 err = ovs_ct_commit(net, key, info, skb);
919         else
920                 err = ovs_ct_lookup(net, key, info, skb);
921         if (err)
922                 goto err;
923
924         if (info->mark.mask) {
925                 err = ovs_ct_set_mark(skb, key, info->mark.value,
926                                       info->mark.mask);
927                 if (err)
928                         goto err;
929         }
930         if (labels_nonzero(&info->labels.mask))
931                 err = ovs_ct_set_labels(skb, key, &info->labels.value,
932                                         &info->labels.mask);
933 err:
934         skb_push(skb, nh_ofs);
935         if (err)
936                 kfree_skb(skb);
937         return err;
938 }
939
940 static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
941                              const struct sw_flow_key *key, bool log)
942 {
943         struct nf_conntrack_helper *helper;
944         struct nf_conn_help *help;
945
946         helper = nf_conntrack_helper_try_module_get(name, info->family,
947                                                     key->ip.proto);
948         if (!helper) {
949                 OVS_NLERR(log, "Unknown helper \"%s\"", name);
950                 return -EINVAL;
951         }
952
953         help = nf_ct_helper_ext_add(info->ct, helper, GFP_KERNEL);
954         if (!help) {
955                 module_put(helper->me);
956                 return -ENOMEM;
957         }
958
959         rcu_assign_pointer(help->helper, helper);
960         info->helper = helper;
961         return 0;
962 }
963
964 #ifdef CONFIG_NF_NAT_NEEDED
965 static int parse_nat(const struct nlattr *attr,
966                      struct ovs_conntrack_info *info, bool log)
967 {
968         struct nlattr *a;
969         int rem;
970         bool have_ip_max = false;
971         bool have_proto_max = false;
972         bool ip_vers = (info->family == NFPROTO_IPV6);
973
974         nla_for_each_nested(a, attr, rem) {
975                 static const int ovs_nat_attr_lens[OVS_NAT_ATTR_MAX + 1][2] = {
976                         [OVS_NAT_ATTR_SRC] = {0, 0},
977                         [OVS_NAT_ATTR_DST] = {0, 0},
978                         [OVS_NAT_ATTR_IP_MIN] = {sizeof(struct in_addr),
979                                                  sizeof(struct in6_addr)},
980                         [OVS_NAT_ATTR_IP_MAX] = {sizeof(struct in_addr),
981                                                  sizeof(struct in6_addr)},
982                         [OVS_NAT_ATTR_PROTO_MIN] = {sizeof(u16), sizeof(u16)},
983                         [OVS_NAT_ATTR_PROTO_MAX] = {sizeof(u16), sizeof(u16)},
984                         [OVS_NAT_ATTR_PERSISTENT] = {0, 0},
985                         [OVS_NAT_ATTR_PROTO_HASH] = {0, 0},
986                         [OVS_NAT_ATTR_PROTO_RANDOM] = {0, 0},
987                 };
988                 int type = nla_type(a);
989
990                 if (type > OVS_NAT_ATTR_MAX) {
991                         OVS_NLERR(log,
992                                   "Unknown NAT attribute (type=%d, max=%d).\n",
993                                   type, OVS_NAT_ATTR_MAX);
994                         return -EINVAL;
995                 }
996
997                 if (nla_len(a) != ovs_nat_attr_lens[type][ip_vers]) {
998                         OVS_NLERR(log,
999                                   "NAT attribute type %d has unexpected length (%d != %d).\n",
1000                                   type, nla_len(a),
1001                                   ovs_nat_attr_lens[type][ip_vers]);
1002                         return -EINVAL;
1003                 }
1004
1005                 switch (type) {
1006                 case OVS_NAT_ATTR_SRC:
1007                 case OVS_NAT_ATTR_DST:
1008                         if (info->nat) {
1009                                 OVS_NLERR(log,
1010                                           "Only one type of NAT may be specified.\n"
1011                                           );
1012                                 return -ERANGE;
1013                         }
1014                         info->nat |= OVS_CT_NAT;
1015                         info->nat |= ((type == OVS_NAT_ATTR_SRC)
1016                                         ? OVS_CT_SRC_NAT : OVS_CT_DST_NAT);
1017                         break;
1018
1019                 case OVS_NAT_ATTR_IP_MIN:
1020                         nla_memcpy(&info->range.min_addr, a, nla_len(a));
1021                         info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1022                         break;
1023
1024                 case OVS_NAT_ATTR_IP_MAX:
1025                         have_ip_max = true;
1026                         nla_memcpy(&info->range.max_addr, a,
1027                                    sizeof(info->range.max_addr));
1028                         info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1029                         break;
1030
1031                 case OVS_NAT_ATTR_PROTO_MIN:
1032                         info->range.min_proto.all = htons(nla_get_u16(a));
1033                         info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1034                         break;
1035
1036                 case OVS_NAT_ATTR_PROTO_MAX:
1037                         have_proto_max = true;
1038                         info->range.max_proto.all = htons(nla_get_u16(a));
1039                         info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1040                         break;
1041
1042                 case OVS_NAT_ATTR_PERSISTENT:
1043                         info->range.flags |= NF_NAT_RANGE_PERSISTENT;
1044                         break;
1045
1046                 case OVS_NAT_ATTR_PROTO_HASH:
1047                         info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM;
1048                         break;
1049
1050                 case OVS_NAT_ATTR_PROTO_RANDOM:
1051                         info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY;
1052                         break;
1053
1054                 default:
1055                         OVS_NLERR(log, "Unknown nat attribute (%d).\n", type);
1056                         return -EINVAL;
1057                 }
1058         }
1059
1060         if (rem > 0) {
1061                 OVS_NLERR(log, "NAT attribute has %d unknown bytes.\n", rem);
1062                 return -EINVAL;
1063         }
1064         if (!info->nat) {
1065                 /* Do not allow flags if no type is given. */
1066                 if (info->range.flags) {
1067                         OVS_NLERR(log,
1068                                   "NAT flags may be given only when NAT range (SRC or DST) is also specified.\n"
1069                                   );
1070                         return -EINVAL;
1071                 }
1072                 info->nat = OVS_CT_NAT;   /* NAT existing connections. */
1073         } else if (!info->commit) {
1074                 OVS_NLERR(log,
1075                           "NAT attributes may be specified only when CT COMMIT flag is also specified.\n"
1076                           );
1077                 return -EINVAL;
1078         }
1079         /* Allow missing IP_MAX. */
1080         if (info->range.flags & NF_NAT_RANGE_MAP_IPS && !have_ip_max) {
1081                 memcpy(&info->range.max_addr, &info->range.min_addr,
1082                        sizeof(info->range.max_addr));
1083         }
1084         /* Allow missing PROTO_MAX. */
1085         if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1086             !have_proto_max) {
1087                 info->range.max_proto.all = info->range.min_proto.all;
1088         }
1089         return 0;
1090 }
1091 #endif
1092
1093 static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
1094         [OVS_CT_ATTR_COMMIT]    = { .minlen = 0, .maxlen = 0 },
1095         [OVS_CT_ATTR_ZONE]      = { .minlen = sizeof(u16),
1096                                     .maxlen = sizeof(u16) },
1097         [OVS_CT_ATTR_MARK]      = { .minlen = sizeof(struct md_mark),
1098                                     .maxlen = sizeof(struct md_mark) },
1099         [OVS_CT_ATTR_LABELS]    = { .minlen = sizeof(struct md_labels),
1100                                     .maxlen = sizeof(struct md_labels) },
1101         [OVS_CT_ATTR_HELPER]    = { .minlen = 1,
1102                                     .maxlen = NF_CT_HELPER_NAME_LEN },
1103 #ifdef CONFIG_NF_NAT_NEEDED
1104         /* NAT length is checked when parsing the nested attributes. */
1105         [OVS_CT_ATTR_NAT]       = { .minlen = 0, .maxlen = INT_MAX },
1106 #endif
1107 };
1108
1109 static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
1110                     const char **helper, bool log)
1111 {
1112         struct nlattr *a;
1113         int rem;
1114
1115         nla_for_each_nested(a, attr, rem) {
1116                 int type = nla_type(a);
1117                 int maxlen = ovs_ct_attr_lens[type].maxlen;
1118                 int minlen = ovs_ct_attr_lens[type].minlen;
1119
1120                 if (type > OVS_CT_ATTR_MAX) {
1121                         OVS_NLERR(log,
1122                                   "Unknown conntrack attr (type=%d, max=%d)",
1123                                   type, OVS_CT_ATTR_MAX);
1124                         return -EINVAL;
1125                 }
1126                 if (nla_len(a) < minlen || nla_len(a) > maxlen) {
1127                         OVS_NLERR(log,
1128                                   "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
1129                                   type, nla_len(a), maxlen);
1130                         return -EINVAL;
1131                 }
1132
1133                 switch (type) {
1134                 case OVS_CT_ATTR_COMMIT:
1135                         info->commit = true;
1136                         break;
1137 #ifdef CONFIG_NF_CONNTRACK_ZONES
1138                 case OVS_CT_ATTR_ZONE:
1139                         info->zone.id = nla_get_u16(a);
1140                         break;
1141 #endif
1142 #ifdef CONFIG_NF_CONNTRACK_MARK
1143                 case OVS_CT_ATTR_MARK: {
1144                         struct md_mark *mark = nla_data(a);
1145
1146                         if (!mark->mask) {
1147                                 OVS_NLERR(log, "ct_mark mask cannot be 0");
1148                                 return -EINVAL;
1149                         }
1150                         info->mark = *mark;
1151                         break;
1152                 }
1153 #endif
1154 #ifdef CONFIG_NF_CONNTRACK_LABELS
1155                 case OVS_CT_ATTR_LABELS: {
1156                         struct md_labels *labels = nla_data(a);
1157
1158                         if (!labels_nonzero(&labels->mask)) {
1159                                 OVS_NLERR(log, "ct_labels mask cannot be 0");
1160                                 return -EINVAL;
1161                         }
1162                         info->labels = *labels;
1163                         break;
1164                 }
1165 #endif
1166                 case OVS_CT_ATTR_HELPER:
1167                         *helper = nla_data(a);
1168                         if (!memchr(*helper, '\0', nla_len(a))) {
1169                                 OVS_NLERR(log, "Invalid conntrack helper");
1170                                 return -EINVAL;
1171                         }
1172                         break;
1173 #ifdef CONFIG_NF_NAT_NEEDED
1174                 case OVS_CT_ATTR_NAT: {
1175                         int err = parse_nat(a, info, log);
1176
1177                         if (err)
1178                                 return err;
1179                         break;
1180                 }
1181 #endif
1182                 default:
1183                         OVS_NLERR(log, "Unknown conntrack attr (%d)",
1184                                   type);
1185                         return -EINVAL;
1186                 }
1187         }
1188
1189         if (rem > 0) {
1190                 OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
1191                 return -EINVAL;
1192         }
1193
1194         return 0;
1195 }
1196
1197 bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
1198 {
1199         if (attr == OVS_KEY_ATTR_CT_STATE)
1200                 return true;
1201         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1202             attr == OVS_KEY_ATTR_CT_ZONE)
1203                 return true;
1204         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1205             attr == OVS_KEY_ATTR_CT_MARK)
1206                 return true;
1207         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1208             attr == OVS_KEY_ATTR_CT_LABELS) {
1209                 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1210
1211                 return ovs_net->xt_label;
1212         }
1213
1214         return false;
1215 }
1216
1217 int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
1218                        const struct sw_flow_key *key,
1219                        struct sw_flow_actions **sfa,  bool log)
1220 {
1221         struct ovs_conntrack_info ct_info;
1222         const char *helper = NULL;
1223         u16 family;
1224         int err;
1225
1226         family = key_to_nfproto(key);
1227         if (family == NFPROTO_UNSPEC) {
1228                 OVS_NLERR(log, "ct family unspecified");
1229                 return -EINVAL;
1230         }
1231
1232         memset(&ct_info, 0, sizeof(ct_info));
1233         ct_info.family = family;
1234
1235         nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
1236                         NF_CT_DEFAULT_ZONE_DIR, 0);
1237
1238         err = parse_ct(attr, &ct_info, &helper, log);
1239         if (err)
1240                 return err;
1241
1242         /* Set up template for tracking connections in specific zones. */
1243         ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
1244         if (!ct_info.ct) {
1245                 OVS_NLERR(log, "Failed to allocate conntrack template");
1246                 return -ENOMEM;
1247         }
1248
1249         __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
1250         nf_conntrack_get(&ct_info.ct->ct_general);
1251
1252         if (helper) {
1253                 err = ovs_ct_add_helper(&ct_info, helper, key, log);
1254                 if (err)
1255                         goto err_free_ct;
1256         }
1257
1258         err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
1259                                  sizeof(ct_info), log);
1260         if (err)
1261                 goto err_free_ct;
1262
1263         return 0;
1264 err_free_ct:
1265         __ovs_ct_free_action(&ct_info);
1266         return err;
1267 }
1268
1269 #ifdef CONFIG_NF_NAT_NEEDED
1270 static bool ovs_ct_nat_to_attr(const struct ovs_conntrack_info *info,
1271                                struct sk_buff *skb)
1272 {
1273         struct nlattr *start;
1274
1275         start = nla_nest_start(skb, OVS_CT_ATTR_NAT);
1276         if (!start)
1277                 return false;
1278
1279         if (info->nat & OVS_CT_SRC_NAT) {
1280                 if (nla_put_flag(skb, OVS_NAT_ATTR_SRC))
1281                         return false;
1282         } else if (info->nat & OVS_CT_DST_NAT) {
1283                 if (nla_put_flag(skb, OVS_NAT_ATTR_DST))
1284                         return false;
1285         } else {
1286                 goto out;
1287         }
1288
1289         if (info->range.flags & NF_NAT_RANGE_MAP_IPS) {
1290                 if (info->family == NFPROTO_IPV4) {
1291                         if (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MIN,
1292                                             info->range.min_addr.ip) ||
1293                             (info->range.max_addr.ip
1294                              != info->range.min_addr.ip &&
1295                              (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MAX,
1296                                               info->range.max_addr.ip))))
1297                                 return false;
1298 #if IS_ENABLED(CONFIG_NF_NAT_IPV6)
1299                 } else if (info->family == NFPROTO_IPV6) {
1300                         if (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MIN,
1301                                              &info->range.min_addr.in6) ||
1302                             (memcmp(&info->range.max_addr.in6,
1303                                     &info->range.min_addr.in6,
1304                                     sizeof(info->range.max_addr.in6)) &&
1305                              (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MAX,
1306                                                &info->range.max_addr.in6))))
1307                                 return false;
1308 #endif
1309                 } else {
1310                         return false;
1311                 }
1312         }
1313         if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1314             (nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MIN,
1315                          ntohs(info->range.min_proto.all)) ||
1316              (info->range.max_proto.all != info->range.min_proto.all &&
1317               nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MAX,
1318                           ntohs(info->range.max_proto.all)))))
1319                 return false;
1320
1321         if (info->range.flags & NF_NAT_RANGE_PERSISTENT &&
1322             nla_put_flag(skb, OVS_NAT_ATTR_PERSISTENT))
1323                 return false;
1324         if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM &&
1325             nla_put_flag(skb, OVS_NAT_ATTR_PROTO_HASH))
1326                 return false;
1327         if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY &&
1328             nla_put_flag(skb, OVS_NAT_ATTR_PROTO_RANDOM))
1329                 return false;
1330 out:
1331         nla_nest_end(skb, start);
1332
1333         return true;
1334 }
1335 #endif
1336
1337 int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
1338                           struct sk_buff *skb)
1339 {
1340         struct nlattr *start;
1341
1342         start = nla_nest_start(skb, OVS_ACTION_ATTR_CT);
1343         if (!start)
1344                 return -EMSGSIZE;
1345
1346         if (ct_info->commit && nla_put_flag(skb, OVS_CT_ATTR_COMMIT))
1347                 return -EMSGSIZE;
1348         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1349             nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
1350                 return -EMSGSIZE;
1351         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
1352             nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
1353                     &ct_info->mark))
1354                 return -EMSGSIZE;
1355         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1356             labels_nonzero(&ct_info->labels.mask) &&
1357             nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
1358                     &ct_info->labels))
1359                 return -EMSGSIZE;
1360         if (ct_info->helper) {
1361                 if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
1362                                    ct_info->helper->name))
1363                         return -EMSGSIZE;
1364         }
1365 #ifdef CONFIG_NF_NAT_NEEDED
1366         if (ct_info->nat && !ovs_ct_nat_to_attr(ct_info, skb))
1367                 return -EMSGSIZE;
1368 #endif
1369         nla_nest_end(skb, start);
1370
1371         return 0;
1372 }
1373
1374 void ovs_ct_free_action(const struct nlattr *a)
1375 {
1376         struct ovs_conntrack_info *ct_info = nla_data(a);
1377
1378         __ovs_ct_free_action(ct_info);
1379 }
1380
1381 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
1382 {
1383         if (ct_info->helper)
1384                 module_put(ct_info->helper->me);
1385         if (ct_info->ct)
1386                 nf_ct_tmpl_free(ct_info->ct);
1387 }
1388
1389 void ovs_ct_init(struct net *net)
1390 {
1391         unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
1392         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1393
1394         if (nf_connlabels_get(net, n_bits)) {
1395                 ovs_net->xt_label = false;
1396                 OVS_NLERR(true, "Failed to set connlabel length");
1397         } else {
1398                 ovs_net->xt_label = true;
1399         }
1400 }
1401
1402 void ovs_ct_exit(struct net *net)
1403 {
1404         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1405
1406         if (ovs_net->xt_label)
1407                 nf_connlabels_put(net);
1408 }
1409
1410 #endif /* CONFIG_NF_CONNTRACK */