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