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