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