xref: /linux/net/sched/act_ct.c (revision 57f273adbcd44172cbe0bd10b8b7408dd255699f)
1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 /* -
3  * net/sched/act_ct.c  Connection Tracking action
4  *
5  * Authors:   Paul Blakey <paulb@mellanox.com>
6  *            Yossi Kuperman <yossiku@mellanox.com>
7  *            Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>
8  */
9 
10 #include <linux/module.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
13 #include <linux/skbuff.h>
14 #include <linux/rtnetlink.h>
15 #include <linux/pkt_cls.h>
16 #include <linux/ip.h>
17 #include <linux/ipv6.h>
18 #include <linux/rhashtable.h>
19 #include <net/netlink.h>
20 #include <net/pkt_sched.h>
21 #include <net/pkt_cls.h>
22 #include <net/act_api.h>
23 #include <net/ip.h>
24 #include <net/ipv6_frag.h>
25 #include <uapi/linux/tc_act/tc_ct.h>
26 #include <net/tc_act/tc_ct.h>
27 
28 #include <net/netfilter/nf_flow_table.h>
29 #include <net/netfilter/nf_conntrack.h>
30 #include <net/netfilter/nf_conntrack_core.h>
31 #include <net/netfilter/nf_conntrack_zones.h>
32 #include <net/netfilter/nf_conntrack_helper.h>
33 #include <net/netfilter/nf_conntrack_acct.h>
34 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
35 #include <net/netfilter/nf_conntrack_act_ct.h>
36 #include <net/netfilter/nf_conntrack_seqadj.h>
37 #include <uapi/linux/netfilter/nf_nat.h>
38 
39 static struct workqueue_struct *act_ct_wq;
40 static struct rhashtable zones_ht;
41 static DEFINE_MUTEX(zones_mutex);
42 
43 struct tcf_ct_flow_table {
44 	struct rhash_head node; /* In zones tables */
45 
46 	struct rcu_work rwork;
47 	struct nf_flowtable nf_ft;
48 	refcount_t ref;
49 	u16 zone;
50 
51 	bool dying;
52 };
53 
54 static const struct rhashtable_params zones_params = {
55 	.head_offset = offsetof(struct tcf_ct_flow_table, node),
56 	.key_offset = offsetof(struct tcf_ct_flow_table, zone),
57 	.key_len = sizeof_field(struct tcf_ct_flow_table, zone),
58 	.automatic_shrinking = true,
59 };
60 
61 static struct flow_action_entry *
62 tcf_ct_flow_table_flow_action_get_next(struct flow_action *flow_action)
63 {
64 	int i = flow_action->num_entries++;
65 
66 	return &flow_action->entries[i];
67 }
68 
69 static void tcf_ct_add_mangle_action(struct flow_action *action,
70 				     enum flow_action_mangle_base htype,
71 				     u32 offset,
72 				     u32 mask,
73 				     u32 val)
74 {
75 	struct flow_action_entry *entry;
76 
77 	entry = tcf_ct_flow_table_flow_action_get_next(action);
78 	entry->id = FLOW_ACTION_MANGLE;
79 	entry->mangle.htype = htype;
80 	entry->mangle.mask = ~mask;
81 	entry->mangle.offset = offset;
82 	entry->mangle.val = val;
83 }
84 
85 /* The following nat helper functions check if the inverted reverse tuple
86  * (target) is different then the current dir tuple - meaning nat for ports
87  * and/or ip is needed, and add the relevant mangle actions.
88  */
89 static void
90 tcf_ct_flow_table_add_action_nat_ipv4(const struct nf_conntrack_tuple *tuple,
91 				      struct nf_conntrack_tuple target,
92 				      struct flow_action *action)
93 {
94 	if (memcmp(&target.src.u3, &tuple->src.u3, sizeof(target.src.u3)))
95 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP4,
96 					 offsetof(struct iphdr, saddr),
97 					 0xFFFFFFFF,
98 					 be32_to_cpu(target.src.u3.ip));
99 	if (memcmp(&target.dst.u3, &tuple->dst.u3, sizeof(target.dst.u3)))
100 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP4,
101 					 offsetof(struct iphdr, daddr),
102 					 0xFFFFFFFF,
103 					 be32_to_cpu(target.dst.u3.ip));
104 }
105 
106 static void
107 tcf_ct_add_ipv6_addr_mangle_action(struct flow_action *action,
108 				   union nf_inet_addr *addr,
109 				   u32 offset)
110 {
111 	int i;
112 
113 	for (i = 0; i < sizeof(struct in6_addr) / sizeof(u32); i++)
114 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_IP6,
115 					 i * sizeof(u32) + offset,
116 					 0xFFFFFFFF, be32_to_cpu(addr->ip6[i]));
117 }
118 
119 static void
120 tcf_ct_flow_table_add_action_nat_ipv6(const struct nf_conntrack_tuple *tuple,
121 				      struct nf_conntrack_tuple target,
122 				      struct flow_action *action)
123 {
124 	if (memcmp(&target.src.u3, &tuple->src.u3, sizeof(target.src.u3)))
125 		tcf_ct_add_ipv6_addr_mangle_action(action, &target.src.u3,
126 						   offsetof(struct ipv6hdr,
127 							    saddr));
128 	if (memcmp(&target.dst.u3, &tuple->dst.u3, sizeof(target.dst.u3)))
129 		tcf_ct_add_ipv6_addr_mangle_action(action, &target.dst.u3,
130 						   offsetof(struct ipv6hdr,
131 							    daddr));
132 }
133 
134 static void
135 tcf_ct_flow_table_add_action_nat_tcp(const struct nf_conntrack_tuple *tuple,
136 				     struct nf_conntrack_tuple target,
137 				     struct flow_action *action)
138 {
139 	__be16 target_src = target.src.u.tcp.port;
140 	__be16 target_dst = target.dst.u.tcp.port;
141 
142 	if (target_src != tuple->src.u.tcp.port)
143 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_TCP,
144 					 offsetof(struct tcphdr, source),
145 					 0xFFFF, be16_to_cpu(target_src));
146 	if (target_dst != tuple->dst.u.tcp.port)
147 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_TCP,
148 					 offsetof(struct tcphdr, dest),
149 					 0xFFFF, be16_to_cpu(target_dst));
150 }
151 
152 static void
153 tcf_ct_flow_table_add_action_nat_udp(const struct nf_conntrack_tuple *tuple,
154 				     struct nf_conntrack_tuple target,
155 				     struct flow_action *action)
156 {
157 	__be16 target_src = target.src.u.udp.port;
158 	__be16 target_dst = target.dst.u.udp.port;
159 
160 	if (target_src != tuple->src.u.udp.port)
161 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_UDP,
162 					 offsetof(struct udphdr, source),
163 					 0xFFFF, be16_to_cpu(target_src));
164 	if (target_dst != tuple->dst.u.udp.port)
165 		tcf_ct_add_mangle_action(action, FLOW_ACT_MANGLE_HDR_TYPE_UDP,
166 					 offsetof(struct udphdr, dest),
167 					 0xFFFF, be16_to_cpu(target_dst));
168 }
169 
170 static void tcf_ct_flow_table_add_action_meta(struct nf_conn *ct,
171 					      enum ip_conntrack_dir dir,
172 					      struct flow_action *action)
173 {
174 	struct nf_conn_labels *ct_labels;
175 	struct flow_action_entry *entry;
176 	enum ip_conntrack_info ctinfo;
177 	u32 *act_ct_labels;
178 
179 	entry = tcf_ct_flow_table_flow_action_get_next(action);
180 	entry->id = FLOW_ACTION_CT_METADATA;
181 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
182 	entry->ct_metadata.mark = ct->mark;
183 #endif
184 	ctinfo = dir == IP_CT_DIR_ORIGINAL ? IP_CT_ESTABLISHED :
185 					     IP_CT_ESTABLISHED_REPLY;
186 	/* aligns with the CT reference on the SKB nf_ct_set */
187 	entry->ct_metadata.cookie = (unsigned long)ct | ctinfo;
188 	entry->ct_metadata.orig_dir = dir == IP_CT_DIR_ORIGINAL;
189 
190 	act_ct_labels = entry->ct_metadata.labels;
191 	ct_labels = nf_ct_labels_find(ct);
192 	if (ct_labels)
193 		memcpy(act_ct_labels, ct_labels->bits, NF_CT_LABELS_MAX_SIZE);
194 	else
195 		memset(act_ct_labels, 0, NF_CT_LABELS_MAX_SIZE);
196 }
197 
198 static int tcf_ct_flow_table_add_action_nat(struct net *net,
199 					    struct nf_conn *ct,
200 					    enum ip_conntrack_dir dir,
201 					    struct flow_action *action)
202 {
203 	const struct nf_conntrack_tuple *tuple = &ct->tuplehash[dir].tuple;
204 	struct nf_conntrack_tuple target;
205 
206 	if (!(ct->status & IPS_NAT_MASK))
207 		return 0;
208 
209 	nf_ct_invert_tuple(&target, &ct->tuplehash[!dir].tuple);
210 
211 	switch (tuple->src.l3num) {
212 	case NFPROTO_IPV4:
213 		tcf_ct_flow_table_add_action_nat_ipv4(tuple, target,
214 						      action);
215 		break;
216 	case NFPROTO_IPV6:
217 		tcf_ct_flow_table_add_action_nat_ipv6(tuple, target,
218 						      action);
219 		break;
220 	default:
221 		return -EOPNOTSUPP;
222 	}
223 
224 	switch (nf_ct_protonum(ct)) {
225 	case IPPROTO_TCP:
226 		tcf_ct_flow_table_add_action_nat_tcp(tuple, target, action);
227 		break;
228 	case IPPROTO_UDP:
229 		tcf_ct_flow_table_add_action_nat_udp(tuple, target, action);
230 		break;
231 	default:
232 		return -EOPNOTSUPP;
233 	}
234 
235 	return 0;
236 }
237 
238 static int tcf_ct_flow_table_fill_actions(struct net *net,
239 					  const struct flow_offload *flow,
240 					  enum flow_offload_tuple_dir tdir,
241 					  struct nf_flow_rule *flow_rule)
242 {
243 	struct flow_action *action = &flow_rule->rule->action;
244 	int num_entries = action->num_entries;
245 	struct nf_conn *ct = flow->ct;
246 	enum ip_conntrack_dir dir;
247 	int i, err;
248 
249 	switch (tdir) {
250 	case FLOW_OFFLOAD_DIR_ORIGINAL:
251 		dir = IP_CT_DIR_ORIGINAL;
252 		break;
253 	case FLOW_OFFLOAD_DIR_REPLY:
254 		dir = IP_CT_DIR_REPLY;
255 		break;
256 	default:
257 		return -EOPNOTSUPP;
258 	}
259 
260 	err = tcf_ct_flow_table_add_action_nat(net, ct, dir, action);
261 	if (err)
262 		goto err_nat;
263 
264 	tcf_ct_flow_table_add_action_meta(ct, dir, action);
265 	return 0;
266 
267 err_nat:
268 	/* Clear filled actions */
269 	for (i = num_entries; i < action->num_entries; i++)
270 		memset(&action->entries[i], 0, sizeof(action->entries[i]));
271 	action->num_entries = num_entries;
272 
273 	return err;
274 }
275 
276 static struct nf_flowtable_type flowtable_ct = {
277 	.action		= tcf_ct_flow_table_fill_actions,
278 	.owner		= THIS_MODULE,
279 };
280 
281 static int tcf_ct_flow_table_get(struct net *net, struct tcf_ct_params *params)
282 {
283 	struct tcf_ct_flow_table *ct_ft;
284 	int err = -ENOMEM;
285 
286 	mutex_lock(&zones_mutex);
287 	ct_ft = rhashtable_lookup_fast(&zones_ht, &params->zone, zones_params);
288 	if (ct_ft && refcount_inc_not_zero(&ct_ft->ref))
289 		goto out_unlock;
290 
291 	ct_ft = kzalloc(sizeof(*ct_ft), GFP_KERNEL);
292 	if (!ct_ft)
293 		goto err_alloc;
294 	refcount_set(&ct_ft->ref, 1);
295 
296 	ct_ft->zone = params->zone;
297 	err = rhashtable_insert_fast(&zones_ht, &ct_ft->node, zones_params);
298 	if (err)
299 		goto err_insert;
300 
301 	ct_ft->nf_ft.type = &flowtable_ct;
302 	ct_ft->nf_ft.flags |= NF_FLOWTABLE_HW_OFFLOAD |
303 			      NF_FLOWTABLE_COUNTER;
304 	err = nf_flow_table_init(&ct_ft->nf_ft);
305 	if (err)
306 		goto err_init;
307 	write_pnet(&ct_ft->nf_ft.net, net);
308 
309 	__module_get(THIS_MODULE);
310 out_unlock:
311 	params->ct_ft = ct_ft;
312 	params->nf_ft = &ct_ft->nf_ft;
313 	mutex_unlock(&zones_mutex);
314 
315 	return 0;
316 
317 err_init:
318 	rhashtable_remove_fast(&zones_ht, &ct_ft->node, zones_params);
319 err_insert:
320 	kfree(ct_ft);
321 err_alloc:
322 	mutex_unlock(&zones_mutex);
323 	return err;
324 }
325 
326 static void tcf_ct_flow_table_cleanup_work(struct work_struct *work)
327 {
328 	struct flow_block_cb *block_cb, *tmp_cb;
329 	struct tcf_ct_flow_table *ct_ft;
330 	struct flow_block *block;
331 
332 	ct_ft = container_of(to_rcu_work(work), struct tcf_ct_flow_table,
333 			     rwork);
334 	nf_flow_table_free(&ct_ft->nf_ft);
335 
336 	/* Remove any remaining callbacks before cleanup */
337 	block = &ct_ft->nf_ft.flow_block;
338 	down_write(&ct_ft->nf_ft.flow_block_lock);
339 	list_for_each_entry_safe(block_cb, tmp_cb, &block->cb_list, list) {
340 		list_del(&block_cb->list);
341 		flow_block_cb_free(block_cb);
342 	}
343 	up_write(&ct_ft->nf_ft.flow_block_lock);
344 	kfree(ct_ft);
345 
346 	module_put(THIS_MODULE);
347 }
348 
349 static void tcf_ct_flow_table_put(struct tcf_ct_flow_table *ct_ft)
350 {
351 	if (refcount_dec_and_test(&ct_ft->ref)) {
352 		rhashtable_remove_fast(&zones_ht, &ct_ft->node, zones_params);
353 		INIT_RCU_WORK(&ct_ft->rwork, tcf_ct_flow_table_cleanup_work);
354 		queue_rcu_work(act_ct_wq, &ct_ft->rwork);
355 	}
356 }
357 
358 static void tcf_ct_flow_tc_ifidx(struct flow_offload *entry,
359 				 struct nf_conn_act_ct_ext *act_ct_ext, u8 dir)
360 {
361 	entry->tuplehash[dir].tuple.xmit_type = FLOW_OFFLOAD_XMIT_TC;
362 	entry->tuplehash[dir].tuple.tc.iifidx = act_ct_ext->ifindex[dir];
363 }
364 
365 static void tcf_ct_flow_table_add(struct tcf_ct_flow_table *ct_ft,
366 				  struct nf_conn *ct,
367 				  bool tcp)
368 {
369 	struct nf_conn_act_ct_ext *act_ct_ext;
370 	struct flow_offload *entry;
371 	int err;
372 
373 	if (test_and_set_bit(IPS_OFFLOAD_BIT, &ct->status))
374 		return;
375 
376 	entry = flow_offload_alloc(ct);
377 	if (!entry) {
378 		WARN_ON_ONCE(1);
379 		goto err_alloc;
380 	}
381 
382 	if (tcp) {
383 		ct->proto.tcp.seen[0].flags |= IP_CT_TCP_FLAG_BE_LIBERAL;
384 		ct->proto.tcp.seen[1].flags |= IP_CT_TCP_FLAG_BE_LIBERAL;
385 	}
386 
387 	act_ct_ext = nf_conn_act_ct_ext_find(ct);
388 	if (act_ct_ext) {
389 		tcf_ct_flow_tc_ifidx(entry, act_ct_ext, FLOW_OFFLOAD_DIR_ORIGINAL);
390 		tcf_ct_flow_tc_ifidx(entry, act_ct_ext, FLOW_OFFLOAD_DIR_REPLY);
391 	}
392 
393 	err = flow_offload_add(&ct_ft->nf_ft, entry);
394 	if (err)
395 		goto err_add;
396 
397 	return;
398 
399 err_add:
400 	flow_offload_free(entry);
401 err_alloc:
402 	clear_bit(IPS_OFFLOAD_BIT, &ct->status);
403 }
404 
405 static void tcf_ct_flow_table_process_conn(struct tcf_ct_flow_table *ct_ft,
406 					   struct nf_conn *ct,
407 					   enum ip_conntrack_info ctinfo)
408 {
409 	bool tcp = false;
410 
411 	if ((ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY) ||
412 	    !test_bit(IPS_ASSURED_BIT, &ct->status))
413 		return;
414 
415 	switch (nf_ct_protonum(ct)) {
416 	case IPPROTO_TCP:
417 		tcp = true;
418 		if (ct->proto.tcp.state != TCP_CONNTRACK_ESTABLISHED)
419 			return;
420 		break;
421 	case IPPROTO_UDP:
422 		break;
423 #ifdef CONFIG_NF_CT_PROTO_GRE
424 	case IPPROTO_GRE: {
425 		struct nf_conntrack_tuple *tuple;
426 
427 		if (ct->status & IPS_NAT_MASK)
428 			return;
429 		tuple = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
430 		/* No support for GRE v1 */
431 		if (tuple->src.u.gre.key || tuple->dst.u.gre.key)
432 			return;
433 		break;
434 	}
435 #endif
436 	default:
437 		return;
438 	}
439 
440 	if (nf_ct_ext_exist(ct, NF_CT_EXT_HELPER) ||
441 	    ct->status & IPS_SEQ_ADJUST)
442 		return;
443 
444 	tcf_ct_flow_table_add(ct_ft, ct, tcp);
445 }
446 
447 static bool
448 tcf_ct_flow_table_fill_tuple_ipv4(struct sk_buff *skb,
449 				  struct flow_offload_tuple *tuple,
450 				  struct tcphdr **tcph)
451 {
452 	struct flow_ports *ports;
453 	unsigned int thoff;
454 	struct iphdr *iph;
455 	size_t hdrsize;
456 	u8 ipproto;
457 
458 	if (!pskb_network_may_pull(skb, sizeof(*iph)))
459 		return false;
460 
461 	iph = ip_hdr(skb);
462 	thoff = iph->ihl * 4;
463 
464 	if (ip_is_fragment(iph) ||
465 	    unlikely(thoff != sizeof(struct iphdr)))
466 		return false;
467 
468 	ipproto = iph->protocol;
469 	switch (ipproto) {
470 	case IPPROTO_TCP:
471 		hdrsize = sizeof(struct tcphdr);
472 		break;
473 	case IPPROTO_UDP:
474 		hdrsize = sizeof(*ports);
475 		break;
476 #ifdef CONFIG_NF_CT_PROTO_GRE
477 	case IPPROTO_GRE:
478 		hdrsize = sizeof(struct gre_base_hdr);
479 		break;
480 #endif
481 	default:
482 		return false;
483 	}
484 
485 	if (iph->ttl <= 1)
486 		return false;
487 
488 	if (!pskb_network_may_pull(skb, thoff + hdrsize))
489 		return false;
490 
491 	switch (ipproto) {
492 	case IPPROTO_TCP:
493 		*tcph = (void *)(skb_network_header(skb) + thoff);
494 		fallthrough;
495 	case IPPROTO_UDP:
496 		ports = (struct flow_ports *)(skb_network_header(skb) + thoff);
497 		tuple->src_port = ports->source;
498 		tuple->dst_port = ports->dest;
499 		break;
500 	case IPPROTO_GRE: {
501 		struct gre_base_hdr *greh;
502 
503 		greh = (struct gre_base_hdr *)(skb_network_header(skb) + thoff);
504 		if ((greh->flags & GRE_VERSION) != GRE_VERSION_0)
505 			return false;
506 		break;
507 	}
508 	}
509 
510 	iph = ip_hdr(skb);
511 
512 	tuple->src_v4.s_addr = iph->saddr;
513 	tuple->dst_v4.s_addr = iph->daddr;
514 	tuple->l3proto = AF_INET;
515 	tuple->l4proto = ipproto;
516 
517 	return true;
518 }
519 
520 static bool
521 tcf_ct_flow_table_fill_tuple_ipv6(struct sk_buff *skb,
522 				  struct flow_offload_tuple *tuple,
523 				  struct tcphdr **tcph)
524 {
525 	struct flow_ports *ports;
526 	struct ipv6hdr *ip6h;
527 	unsigned int thoff;
528 	size_t hdrsize;
529 	u8 nexthdr;
530 
531 	if (!pskb_network_may_pull(skb, sizeof(*ip6h)))
532 		return false;
533 
534 	ip6h = ipv6_hdr(skb);
535 	thoff = sizeof(*ip6h);
536 
537 	nexthdr = ip6h->nexthdr;
538 	switch (nexthdr) {
539 	case IPPROTO_TCP:
540 		hdrsize = sizeof(struct tcphdr);
541 		break;
542 	case IPPROTO_UDP:
543 		hdrsize = sizeof(*ports);
544 		break;
545 #ifdef CONFIG_NF_CT_PROTO_GRE
546 	case IPPROTO_GRE:
547 		hdrsize = sizeof(struct gre_base_hdr);
548 		break;
549 #endif
550 	default:
551 		return false;
552 	}
553 
554 	if (ip6h->hop_limit <= 1)
555 		return false;
556 
557 	if (!pskb_network_may_pull(skb, thoff + hdrsize))
558 		return false;
559 
560 	switch (nexthdr) {
561 	case IPPROTO_TCP:
562 		*tcph = (void *)(skb_network_header(skb) + thoff);
563 		fallthrough;
564 	case IPPROTO_UDP:
565 		ports = (struct flow_ports *)(skb_network_header(skb) + thoff);
566 		tuple->src_port = ports->source;
567 		tuple->dst_port = ports->dest;
568 		break;
569 	case IPPROTO_GRE: {
570 		struct gre_base_hdr *greh;
571 
572 		greh = (struct gre_base_hdr *)(skb_network_header(skb) + thoff);
573 		if ((greh->flags & GRE_VERSION) != GRE_VERSION_0)
574 			return false;
575 		break;
576 	}
577 	}
578 
579 	ip6h = ipv6_hdr(skb);
580 
581 	tuple->src_v6 = ip6h->saddr;
582 	tuple->dst_v6 = ip6h->daddr;
583 	tuple->l3proto = AF_INET6;
584 	tuple->l4proto = nexthdr;
585 
586 	return true;
587 }
588 
589 static bool tcf_ct_flow_table_lookup(struct tcf_ct_params *p,
590 				     struct sk_buff *skb,
591 				     u8 family)
592 {
593 	struct nf_flowtable *nf_ft = &p->ct_ft->nf_ft;
594 	struct flow_offload_tuple_rhash *tuplehash;
595 	struct flow_offload_tuple tuple = {};
596 	enum ip_conntrack_info ctinfo;
597 	struct tcphdr *tcph = NULL;
598 	struct flow_offload *flow;
599 	struct nf_conn *ct;
600 	u8 dir;
601 
602 	switch (family) {
603 	case NFPROTO_IPV4:
604 		if (!tcf_ct_flow_table_fill_tuple_ipv4(skb, &tuple, &tcph))
605 			return false;
606 		break;
607 	case NFPROTO_IPV6:
608 		if (!tcf_ct_flow_table_fill_tuple_ipv6(skb, &tuple, &tcph))
609 			return false;
610 		break;
611 	default:
612 		return false;
613 	}
614 
615 	tuplehash = flow_offload_lookup(nf_ft, &tuple);
616 	if (!tuplehash)
617 		return false;
618 
619 	dir = tuplehash->tuple.dir;
620 	flow = container_of(tuplehash, struct flow_offload, tuplehash[dir]);
621 	ct = flow->ct;
622 
623 	if (tcph && (unlikely(tcph->fin || tcph->rst))) {
624 		flow_offload_teardown(flow);
625 		return false;
626 	}
627 
628 	ctinfo = dir == FLOW_OFFLOAD_DIR_ORIGINAL ? IP_CT_ESTABLISHED :
629 						    IP_CT_ESTABLISHED_REPLY;
630 
631 	flow_offload_refresh(nf_ft, flow);
632 	nf_conntrack_get(&ct->ct_general);
633 	nf_ct_set(skb, ct, ctinfo);
634 	if (nf_ft->flags & NF_FLOWTABLE_COUNTER)
635 		nf_ct_acct_update(ct, dir, skb->len);
636 
637 	return true;
638 }
639 
640 static int tcf_ct_flow_tables_init(void)
641 {
642 	return rhashtable_init(&zones_ht, &zones_params);
643 }
644 
645 static void tcf_ct_flow_tables_uninit(void)
646 {
647 	rhashtable_destroy(&zones_ht);
648 }
649 
650 static struct tc_action_ops act_ct_ops;
651 
652 struct tc_ct_action_net {
653 	struct tc_action_net tn; /* Must be first */
654 	bool labels;
655 };
656 
657 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
658 static bool tcf_ct_skb_nfct_cached(struct net *net, struct sk_buff *skb,
659 				   struct tcf_ct_params *p)
660 {
661 	enum ip_conntrack_info ctinfo;
662 	struct nf_conn *ct;
663 
664 	ct = nf_ct_get(skb, &ctinfo);
665 	if (!ct)
666 		return false;
667 	if (!net_eq(net, read_pnet(&ct->ct_net)))
668 		goto drop_ct;
669 	if (nf_ct_zone(ct)->id != p->zone)
670 		goto drop_ct;
671 	if (p->helper) {
672 		struct nf_conn_help *help;
673 
674 		help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
675 		if (help && rcu_access_pointer(help->helper) != p->helper)
676 			goto drop_ct;
677 	}
678 
679 	/* Force conntrack entry direction. */
680 	if ((p->ct_action & TCA_CT_ACT_FORCE) &&
681 	    CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
682 		if (nf_ct_is_confirmed(ct))
683 			nf_ct_kill(ct);
684 
685 		goto drop_ct;
686 	}
687 
688 	return true;
689 
690 drop_ct:
691 	nf_ct_put(ct);
692 	nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
693 
694 	return false;
695 }
696 
697 /* Trim the skb to the length specified by the IP/IPv6 header,
698  * removing any trailing lower-layer padding. This prepares the skb
699  * for higher-layer processing that assumes skb->len excludes padding
700  * (such as nf_ip_checksum). The caller needs to pull the skb to the
701  * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
702  */
703 static int tcf_ct_skb_network_trim(struct sk_buff *skb, int family)
704 {
705 	unsigned int len;
706 
707 	switch (family) {
708 	case NFPROTO_IPV4:
709 		len = ntohs(ip_hdr(skb)->tot_len);
710 		break;
711 	case NFPROTO_IPV6:
712 		len = sizeof(struct ipv6hdr)
713 			+ ntohs(ipv6_hdr(skb)->payload_len);
714 		break;
715 	default:
716 		len = skb->len;
717 	}
718 
719 	return pskb_trim_rcsum(skb, len);
720 }
721 
722 static u8 tcf_ct_skb_nf_family(struct sk_buff *skb)
723 {
724 	u8 family = NFPROTO_UNSPEC;
725 
726 	switch (skb_protocol(skb, true)) {
727 	case htons(ETH_P_IP):
728 		family = NFPROTO_IPV4;
729 		break;
730 	case htons(ETH_P_IPV6):
731 		family = NFPROTO_IPV6;
732 		break;
733 	default:
734 		break;
735 	}
736 
737 	return family;
738 }
739 
740 static int tcf_ct_ipv4_is_fragment(struct sk_buff *skb, bool *frag)
741 {
742 	unsigned int len;
743 
744 	len =  skb_network_offset(skb) + sizeof(struct iphdr);
745 	if (unlikely(skb->len < len))
746 		return -EINVAL;
747 	if (unlikely(!pskb_may_pull(skb, len)))
748 		return -ENOMEM;
749 
750 	*frag = ip_is_fragment(ip_hdr(skb));
751 	return 0;
752 }
753 
754 static int tcf_ct_ipv6_is_fragment(struct sk_buff *skb, bool *frag)
755 {
756 	unsigned int flags = 0, len, payload_ofs = 0;
757 	unsigned short frag_off;
758 	int nexthdr;
759 
760 	len =  skb_network_offset(skb) + sizeof(struct ipv6hdr);
761 	if (unlikely(skb->len < len))
762 		return -EINVAL;
763 	if (unlikely(!pskb_may_pull(skb, len)))
764 		return -ENOMEM;
765 
766 	nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags);
767 	if (unlikely(nexthdr < 0))
768 		return -EPROTO;
769 
770 	*frag = flags & IP6_FH_F_FRAG;
771 	return 0;
772 }
773 
774 static int tcf_ct_handle_fragments(struct net *net, struct sk_buff *skb,
775 				   u8 family, u16 zone, bool *defrag)
776 {
777 	enum ip_conntrack_info ctinfo;
778 	struct nf_conn *ct;
779 	int err = 0;
780 	bool frag;
781 	u16 mru;
782 
783 	/* Previously seen (loopback)? Ignore. */
784 	ct = nf_ct_get(skb, &ctinfo);
785 	if ((ct && !nf_ct_is_template(ct)) || ctinfo == IP_CT_UNTRACKED)
786 		return 0;
787 
788 	if (family == NFPROTO_IPV4)
789 		err = tcf_ct_ipv4_is_fragment(skb, &frag);
790 	else
791 		err = tcf_ct_ipv6_is_fragment(skb, &frag);
792 	if (err || !frag)
793 		return err;
794 
795 	skb_get(skb);
796 	mru = tc_skb_cb(skb)->mru;
797 
798 	if (family == NFPROTO_IPV4) {
799 		enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
800 
801 		memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
802 		local_bh_disable();
803 		err = ip_defrag(net, skb, user);
804 		local_bh_enable();
805 		if (err && err != -EINPROGRESS)
806 			return err;
807 
808 		if (!err) {
809 			*defrag = true;
810 			mru = IPCB(skb)->frag_max_size;
811 		}
812 	} else { /* NFPROTO_IPV6 */
813 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
814 		enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
815 
816 		memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
817 		err = nf_ct_frag6_gather(net, skb, user);
818 		if (err && err != -EINPROGRESS)
819 			goto out_free;
820 
821 		if (!err) {
822 			*defrag = true;
823 			mru = IP6CB(skb)->frag_max_size;
824 		}
825 #else
826 		err = -EOPNOTSUPP;
827 		goto out_free;
828 #endif
829 	}
830 
831 	if (err != -EINPROGRESS)
832 		tc_skb_cb(skb)->mru = mru;
833 	skb_clear_hash(skb);
834 	skb->ignore_df = 1;
835 	return err;
836 
837 out_free:
838 	kfree_skb(skb);
839 	return err;
840 }
841 
842 static void tcf_ct_params_free(struct tcf_ct_params *params)
843 {
844 	if (params->helper) {
845 #if IS_ENABLED(CONFIG_NF_NAT)
846 		if (params->ct_action & TCA_CT_ACT_NAT)
847 			nf_nat_helper_put(params->helper);
848 #endif
849 		nf_conntrack_helper_put(params->helper);
850 	}
851 	if (params->ct_ft)
852 		tcf_ct_flow_table_put(params->ct_ft);
853 	if (params->tmpl)
854 		nf_ct_put(params->tmpl);
855 	kfree(params);
856 }
857 
858 static void tcf_ct_params_free_rcu(struct rcu_head *head)
859 {
860 	struct tcf_ct_params *params;
861 
862 	params = container_of(head, struct tcf_ct_params, rcu);
863 	tcf_ct_params_free(params);
864 }
865 
866 #if IS_ENABLED(CONFIG_NF_NAT)
867 /* Modelled after nf_nat_ipv[46]_fn().
868  * range is only used for new, uninitialized NAT state.
869  * Returns either NF_ACCEPT or NF_DROP.
870  */
871 static int ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
872 			  enum ip_conntrack_info ctinfo,
873 			  const struct nf_nat_range2 *range,
874 			  enum nf_nat_manip_type maniptype)
875 {
876 	__be16 proto = skb_protocol(skb, true);
877 	int hooknum, err = NF_ACCEPT;
878 
879 	/* See HOOK2MANIP(). */
880 	if (maniptype == NF_NAT_MANIP_SRC)
881 		hooknum = NF_INET_LOCAL_IN; /* Source NAT */
882 	else
883 		hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
884 
885 	switch (ctinfo) {
886 	case IP_CT_RELATED:
887 	case IP_CT_RELATED_REPLY:
888 		if (proto == htons(ETH_P_IP) &&
889 		    ip_hdr(skb)->protocol == IPPROTO_ICMP) {
890 			if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
891 							   hooknum))
892 				err = NF_DROP;
893 			goto out;
894 		} else if (IS_ENABLED(CONFIG_IPV6) && proto == htons(ETH_P_IPV6)) {
895 			__be16 frag_off;
896 			u8 nexthdr = ipv6_hdr(skb)->nexthdr;
897 			int hdrlen = ipv6_skip_exthdr(skb,
898 						      sizeof(struct ipv6hdr),
899 						      &nexthdr, &frag_off);
900 
901 			if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
902 				if (!nf_nat_icmpv6_reply_translation(skb, ct,
903 								     ctinfo,
904 								     hooknum,
905 								     hdrlen))
906 					err = NF_DROP;
907 				goto out;
908 			}
909 		}
910 		/* Non-ICMP, fall thru to initialize if needed. */
911 		fallthrough;
912 	case IP_CT_NEW:
913 		/* Seen it before?  This can happen for loopback, retrans,
914 		 * or local packets.
915 		 */
916 		if (!nf_nat_initialized(ct, maniptype)) {
917 			/* Initialize according to the NAT action. */
918 			err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
919 				/* Action is set up to establish a new
920 				 * mapping.
921 				 */
922 				? nf_nat_setup_info(ct, range, maniptype)
923 				: nf_nat_alloc_null_binding(ct, hooknum);
924 			if (err != NF_ACCEPT)
925 				goto out;
926 		}
927 		break;
928 
929 	case IP_CT_ESTABLISHED:
930 	case IP_CT_ESTABLISHED_REPLY:
931 		break;
932 
933 	default:
934 		err = NF_DROP;
935 		goto out;
936 	}
937 
938 	err = nf_nat_packet(ct, ctinfo, hooknum, skb);
939 	if (err == NF_ACCEPT) {
940 		if (maniptype == NF_NAT_MANIP_SRC)
941 			tc_skb_cb(skb)->post_ct_snat = 1;
942 		if (maniptype == NF_NAT_MANIP_DST)
943 			tc_skb_cb(skb)->post_ct_dnat = 1;
944 	}
945 out:
946 	return err;
947 }
948 #endif /* CONFIG_NF_NAT */
949 
950 static void tcf_ct_act_set_mark(struct nf_conn *ct, u32 mark, u32 mask)
951 {
952 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
953 	u32 new_mark;
954 
955 	if (!mask)
956 		return;
957 
958 	new_mark = mark | (ct->mark & ~(mask));
959 	if (ct->mark != new_mark) {
960 		ct->mark = new_mark;
961 		if (nf_ct_is_confirmed(ct))
962 			nf_conntrack_event_cache(IPCT_MARK, ct);
963 	}
964 #endif
965 }
966 
967 static void tcf_ct_act_set_labels(struct nf_conn *ct,
968 				  u32 *labels,
969 				  u32 *labels_m)
970 {
971 #if IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)
972 	size_t labels_sz = sizeof_field(struct tcf_ct_params, labels);
973 
974 	if (!memchr_inv(labels_m, 0, labels_sz))
975 		return;
976 
977 	nf_connlabels_replace(ct, labels, labels_m, 4);
978 #endif
979 }
980 
981 static int tcf_ct_act_nat(struct sk_buff *skb,
982 			  struct nf_conn *ct,
983 			  enum ip_conntrack_info ctinfo,
984 			  int ct_action,
985 			  struct nf_nat_range2 *range,
986 			  bool commit)
987 {
988 #if IS_ENABLED(CONFIG_NF_NAT)
989 	int err;
990 	enum nf_nat_manip_type maniptype;
991 
992 	if (!(ct_action & TCA_CT_ACT_NAT))
993 		return NF_ACCEPT;
994 
995 	/* Add NAT extension if not confirmed yet. */
996 	if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
997 		return NF_DROP;   /* Can't NAT. */
998 
999 	if (ctinfo != IP_CT_NEW && (ct->status & IPS_NAT_MASK) &&
1000 	    (ctinfo != IP_CT_RELATED || commit)) {
1001 		/* NAT an established or related connection like before. */
1002 		if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
1003 			/* This is the REPLY direction for a connection
1004 			 * for which NAT was applied in the forward
1005 			 * direction.  Do the reverse NAT.
1006 			 */
1007 			maniptype = ct->status & IPS_SRC_NAT
1008 				? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
1009 		else
1010 			maniptype = ct->status & IPS_SRC_NAT
1011 				? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
1012 	} else if (ct_action & TCA_CT_ACT_NAT_SRC) {
1013 		maniptype = NF_NAT_MANIP_SRC;
1014 	} else if (ct_action & TCA_CT_ACT_NAT_DST) {
1015 		maniptype = NF_NAT_MANIP_DST;
1016 	} else {
1017 		return NF_ACCEPT;
1018 	}
1019 
1020 	err = ct_nat_execute(skb, ct, ctinfo, range, maniptype);
1021 	if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
1022 		if (ct->status & IPS_SRC_NAT) {
1023 			if (maniptype == NF_NAT_MANIP_SRC)
1024 				maniptype = NF_NAT_MANIP_DST;
1025 			else
1026 				maniptype = NF_NAT_MANIP_SRC;
1027 
1028 			err = ct_nat_execute(skb, ct, ctinfo, range,
1029 					     maniptype);
1030 		} else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
1031 			err = ct_nat_execute(skb, ct, ctinfo, NULL,
1032 					     NF_NAT_MANIP_SRC);
1033 		}
1034 	}
1035 	return err;
1036 #else
1037 	return NF_ACCEPT;
1038 #endif
1039 }
1040 
1041 static int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,
1042 		      struct tcf_result *res)
1043 {
1044 	struct net *net = dev_net(skb->dev);
1045 	enum ip_conntrack_info ctinfo;
1046 	struct tcf_ct *c = to_ct(a);
1047 	struct nf_conn *tmpl = NULL;
1048 	struct nf_hook_state state;
1049 	bool cached, commit, clear;
1050 	int nh_ofs, err, retval;
1051 	struct tcf_ct_params *p;
1052 	bool add_helper = false;
1053 	bool skip_add = false;
1054 	bool defrag = false;
1055 	struct nf_conn *ct;
1056 	u8 family;
1057 
1058 	p = rcu_dereference_bh(c->params);
1059 
1060 	retval = READ_ONCE(c->tcf_action);
1061 	commit = p->ct_action & TCA_CT_ACT_COMMIT;
1062 	clear = p->ct_action & TCA_CT_ACT_CLEAR;
1063 	tmpl = p->tmpl;
1064 
1065 	tcf_lastuse_update(&c->tcf_tm);
1066 	tcf_action_update_bstats(&c->common, skb);
1067 
1068 	if (clear) {
1069 		tc_skb_cb(skb)->post_ct = false;
1070 		ct = nf_ct_get(skb, &ctinfo);
1071 		if (ct) {
1072 			nf_ct_put(ct);
1073 			nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
1074 		}
1075 
1076 		goto out_clear;
1077 	}
1078 
1079 	family = tcf_ct_skb_nf_family(skb);
1080 	if (family == NFPROTO_UNSPEC)
1081 		goto drop;
1082 
1083 	/* The conntrack module expects to be working at L3.
1084 	 * We also try to pull the IPv4/6 header to linear area
1085 	 */
1086 	nh_ofs = skb_network_offset(skb);
1087 	skb_pull_rcsum(skb, nh_ofs);
1088 	err = tcf_ct_handle_fragments(net, skb, family, p->zone, &defrag);
1089 	if (err == -EINPROGRESS) {
1090 		retval = TC_ACT_STOLEN;
1091 		goto out_clear;
1092 	}
1093 	if (err)
1094 		goto drop;
1095 
1096 	err = tcf_ct_skb_network_trim(skb, family);
1097 	if (err)
1098 		goto drop;
1099 
1100 	/* If we are recirculating packets to match on ct fields and
1101 	 * committing with a separate ct action, then we don't need to
1102 	 * actually run the packet through conntrack twice unless it's for a
1103 	 * different zone.
1104 	 */
1105 	cached = tcf_ct_skb_nfct_cached(net, skb, p);
1106 	if (!cached) {
1107 		if (tcf_ct_flow_table_lookup(p, skb, family)) {
1108 			skip_add = true;
1109 			goto do_nat;
1110 		}
1111 
1112 		/* Associate skb with specified zone. */
1113 		if (tmpl) {
1114 			nf_conntrack_put(skb_nfct(skb));
1115 			nf_conntrack_get(&tmpl->ct_general);
1116 			nf_ct_set(skb, tmpl, IP_CT_NEW);
1117 		}
1118 
1119 		state.hook = NF_INET_PRE_ROUTING;
1120 		state.net = net;
1121 		state.pf = family;
1122 		err = nf_conntrack_in(skb, &state);
1123 		if (err != NF_ACCEPT)
1124 			goto out_push;
1125 	}
1126 
1127 do_nat:
1128 	ct = nf_ct_get(skb, &ctinfo);
1129 	if (!ct)
1130 		goto out_push;
1131 	nf_ct_deliver_cached_events(ct);
1132 	nf_conn_act_ct_ext_fill(skb, ct, ctinfo);
1133 
1134 	err = tcf_ct_act_nat(skb, ct, ctinfo, p->ct_action, &p->range, commit);
1135 	if (err != NF_ACCEPT)
1136 		goto drop;
1137 
1138 	if (!nf_ct_is_confirmed(ct) && commit && p->helper && !nfct_help(ct)) {
1139 		err = __nf_ct_try_assign_helper(ct, p->tmpl, GFP_ATOMIC);
1140 		if (err)
1141 			goto drop;
1142 		add_helper = true;
1143 		if (p->ct_action & TCA_CT_ACT_NAT && !nfct_seqadj(ct)) {
1144 			if (!nfct_seqadj_ext_add(ct))
1145 				goto drop;
1146 		}
1147 	}
1148 
1149 	if (nf_ct_is_confirmed(ct) ? ((!cached && !skip_add) || add_helper) : commit) {
1150 		if (nf_ct_helper(skb, ct, ctinfo, family) != NF_ACCEPT)
1151 			goto drop;
1152 	}
1153 
1154 	if (commit) {
1155 		tcf_ct_act_set_mark(ct, p->mark, p->mark_mask);
1156 		tcf_ct_act_set_labels(ct, p->labels, p->labels_mask);
1157 
1158 		if (!nf_ct_is_confirmed(ct))
1159 			nf_conn_act_ct_ext_add(ct);
1160 
1161 		/* This will take care of sending queued events
1162 		 * even if the connection is already confirmed.
1163 		 */
1164 		if (nf_conntrack_confirm(skb) != NF_ACCEPT)
1165 			goto drop;
1166 	}
1167 
1168 	if (!skip_add)
1169 		tcf_ct_flow_table_process_conn(p->ct_ft, ct, ctinfo);
1170 
1171 out_push:
1172 	skb_push_rcsum(skb, nh_ofs);
1173 
1174 	tc_skb_cb(skb)->post_ct = true;
1175 	tc_skb_cb(skb)->zone = p->zone;
1176 out_clear:
1177 	if (defrag)
1178 		qdisc_skb_cb(skb)->pkt_len = skb->len;
1179 	return retval;
1180 
1181 drop:
1182 	tcf_action_inc_drop_qstats(&c->common);
1183 	return TC_ACT_SHOT;
1184 }
1185 
1186 static const struct nla_policy ct_policy[TCA_CT_MAX + 1] = {
1187 	[TCA_CT_ACTION] = { .type = NLA_U16 },
1188 	[TCA_CT_PARMS] = NLA_POLICY_EXACT_LEN(sizeof(struct tc_ct)),
1189 	[TCA_CT_ZONE] = { .type = NLA_U16 },
1190 	[TCA_CT_MARK] = { .type = NLA_U32 },
1191 	[TCA_CT_MARK_MASK] = { .type = NLA_U32 },
1192 	[TCA_CT_LABELS] = { .type = NLA_BINARY,
1193 			    .len = 128 / BITS_PER_BYTE },
1194 	[TCA_CT_LABELS_MASK] = { .type = NLA_BINARY,
1195 				 .len = 128 / BITS_PER_BYTE },
1196 	[TCA_CT_NAT_IPV4_MIN] = { .type = NLA_U32 },
1197 	[TCA_CT_NAT_IPV4_MAX] = { .type = NLA_U32 },
1198 	[TCA_CT_NAT_IPV6_MIN] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1199 	[TCA_CT_NAT_IPV6_MAX] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1200 	[TCA_CT_NAT_PORT_MIN] = { .type = NLA_U16 },
1201 	[TCA_CT_NAT_PORT_MAX] = { .type = NLA_U16 },
1202 	[TCA_CT_HELPER_NAME] = { .type = NLA_STRING, .len = NF_CT_HELPER_NAME_LEN },
1203 	[TCA_CT_HELPER_FAMILY] = { .type = NLA_U8 },
1204 	[TCA_CT_HELPER_PROTO] = { .type = NLA_U8 },
1205 };
1206 
1207 static int tcf_ct_fill_params_nat(struct tcf_ct_params *p,
1208 				  struct tc_ct *parm,
1209 				  struct nlattr **tb,
1210 				  struct netlink_ext_ack *extack)
1211 {
1212 	struct nf_nat_range2 *range;
1213 
1214 	if (!(p->ct_action & TCA_CT_ACT_NAT))
1215 		return 0;
1216 
1217 	if (!IS_ENABLED(CONFIG_NF_NAT)) {
1218 		NL_SET_ERR_MSG_MOD(extack, "Netfilter nat isn't enabled in kernel");
1219 		return -EOPNOTSUPP;
1220 	}
1221 
1222 	if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1223 		return 0;
1224 
1225 	if ((p->ct_action & TCA_CT_ACT_NAT_SRC) &&
1226 	    (p->ct_action & TCA_CT_ACT_NAT_DST)) {
1227 		NL_SET_ERR_MSG_MOD(extack, "dnat and snat can't be enabled at the same time");
1228 		return -EOPNOTSUPP;
1229 	}
1230 
1231 	range = &p->range;
1232 	if (tb[TCA_CT_NAT_IPV4_MIN]) {
1233 		struct nlattr *max_attr = tb[TCA_CT_NAT_IPV4_MAX];
1234 
1235 		p->ipv4_range = true;
1236 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1237 		range->min_addr.ip =
1238 			nla_get_in_addr(tb[TCA_CT_NAT_IPV4_MIN]);
1239 
1240 		range->max_addr.ip = max_attr ?
1241 				     nla_get_in_addr(max_attr) :
1242 				     range->min_addr.ip;
1243 	} else if (tb[TCA_CT_NAT_IPV6_MIN]) {
1244 		struct nlattr *max_attr = tb[TCA_CT_NAT_IPV6_MAX];
1245 
1246 		p->ipv4_range = false;
1247 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1248 		range->min_addr.in6 =
1249 			nla_get_in6_addr(tb[TCA_CT_NAT_IPV6_MIN]);
1250 
1251 		range->max_addr.in6 = max_attr ?
1252 				      nla_get_in6_addr(max_attr) :
1253 				      range->min_addr.in6;
1254 	}
1255 
1256 	if (tb[TCA_CT_NAT_PORT_MIN]) {
1257 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1258 		range->min_proto.all = nla_get_be16(tb[TCA_CT_NAT_PORT_MIN]);
1259 
1260 		range->max_proto.all = tb[TCA_CT_NAT_PORT_MAX] ?
1261 				       nla_get_be16(tb[TCA_CT_NAT_PORT_MAX]) :
1262 				       range->min_proto.all;
1263 	}
1264 
1265 	return 0;
1266 }
1267 
1268 static void tcf_ct_set_key_val(struct nlattr **tb,
1269 			       void *val, int val_type,
1270 			       void *mask, int mask_type,
1271 			       int len)
1272 {
1273 	if (!tb[val_type])
1274 		return;
1275 	nla_memcpy(val, tb[val_type], len);
1276 
1277 	if (!mask)
1278 		return;
1279 
1280 	if (mask_type == TCA_CT_UNSPEC || !tb[mask_type])
1281 		memset(mask, 0xff, len);
1282 	else
1283 		nla_memcpy(mask, tb[mask_type], len);
1284 }
1285 
1286 static int tcf_ct_fill_params(struct net *net,
1287 			      struct tcf_ct_params *p,
1288 			      struct tc_ct *parm,
1289 			      struct nlattr **tb,
1290 			      struct netlink_ext_ack *extack)
1291 {
1292 	struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1293 	struct nf_conntrack_zone zone;
1294 	int err, family, proto, len;
1295 	struct nf_conn *tmpl;
1296 	char *name;
1297 
1298 	p->zone = NF_CT_DEFAULT_ZONE_ID;
1299 
1300 	tcf_ct_set_key_val(tb,
1301 			   &p->ct_action, TCA_CT_ACTION,
1302 			   NULL, TCA_CT_UNSPEC,
1303 			   sizeof(p->ct_action));
1304 
1305 	if (p->ct_action & TCA_CT_ACT_CLEAR)
1306 		return 0;
1307 
1308 	err = tcf_ct_fill_params_nat(p, parm, tb, extack);
1309 	if (err)
1310 		return err;
1311 
1312 	if (tb[TCA_CT_MARK]) {
1313 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)) {
1314 			NL_SET_ERR_MSG_MOD(extack, "Conntrack mark isn't enabled.");
1315 			return -EOPNOTSUPP;
1316 		}
1317 		tcf_ct_set_key_val(tb,
1318 				   &p->mark, TCA_CT_MARK,
1319 				   &p->mark_mask, TCA_CT_MARK_MASK,
1320 				   sizeof(p->mark));
1321 	}
1322 
1323 	if (tb[TCA_CT_LABELS]) {
1324 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)) {
1325 			NL_SET_ERR_MSG_MOD(extack, "Conntrack labels isn't enabled.");
1326 			return -EOPNOTSUPP;
1327 		}
1328 
1329 		if (!tn->labels) {
1330 			NL_SET_ERR_MSG_MOD(extack, "Failed to set connlabel length");
1331 			return -EOPNOTSUPP;
1332 		}
1333 		tcf_ct_set_key_val(tb,
1334 				   p->labels, TCA_CT_LABELS,
1335 				   p->labels_mask, TCA_CT_LABELS_MASK,
1336 				   sizeof(p->labels));
1337 	}
1338 
1339 	if (tb[TCA_CT_ZONE]) {
1340 		if (!IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES)) {
1341 			NL_SET_ERR_MSG_MOD(extack, "Conntrack zones isn't enabled.");
1342 			return -EOPNOTSUPP;
1343 		}
1344 
1345 		tcf_ct_set_key_val(tb,
1346 				   &p->zone, TCA_CT_ZONE,
1347 				   NULL, TCA_CT_UNSPEC,
1348 				   sizeof(p->zone));
1349 	}
1350 
1351 	nf_ct_zone_init(&zone, p->zone, NF_CT_DEFAULT_ZONE_DIR, 0);
1352 	tmpl = nf_ct_tmpl_alloc(net, &zone, GFP_KERNEL);
1353 	if (!tmpl) {
1354 		NL_SET_ERR_MSG_MOD(extack, "Failed to allocate conntrack template");
1355 		return -ENOMEM;
1356 	}
1357 	p->tmpl = tmpl;
1358 	if (tb[TCA_CT_HELPER_NAME]) {
1359 		name = nla_data(tb[TCA_CT_HELPER_NAME]);
1360 		len = nla_len(tb[TCA_CT_HELPER_NAME]);
1361 		if (len > 16 || name[len - 1] != '\0') {
1362 			NL_SET_ERR_MSG_MOD(extack, "Failed to parse helper name.");
1363 			err = -EINVAL;
1364 			goto err;
1365 		}
1366 		family = tb[TCA_CT_HELPER_FAMILY] ? nla_get_u8(tb[TCA_CT_HELPER_FAMILY]) : AF_INET;
1367 		proto = tb[TCA_CT_HELPER_PROTO] ? nla_get_u8(tb[TCA_CT_HELPER_PROTO]) : IPPROTO_TCP;
1368 		err = nf_ct_add_helper(tmpl, name, family, proto,
1369 				       p->ct_action & TCA_CT_ACT_NAT, &p->helper);
1370 		if (err) {
1371 			NL_SET_ERR_MSG_MOD(extack, "Failed to add helper");
1372 			goto err;
1373 		}
1374 	}
1375 
1376 	__set_bit(IPS_CONFIRMED_BIT, &tmpl->status);
1377 	return 0;
1378 err:
1379 	nf_ct_put(p->tmpl);
1380 	p->tmpl = NULL;
1381 	return err;
1382 }
1383 
1384 static int tcf_ct_init(struct net *net, struct nlattr *nla,
1385 		       struct nlattr *est, struct tc_action **a,
1386 		       struct tcf_proto *tp, u32 flags,
1387 		       struct netlink_ext_ack *extack)
1388 {
1389 	struct tc_action_net *tn = net_generic(net, act_ct_ops.net_id);
1390 	bool bind = flags & TCA_ACT_FLAGS_BIND;
1391 	struct tcf_ct_params *params = NULL;
1392 	struct nlattr *tb[TCA_CT_MAX + 1];
1393 	struct tcf_chain *goto_ch = NULL;
1394 	struct tc_ct *parm;
1395 	struct tcf_ct *c;
1396 	int err, res = 0;
1397 	u32 index;
1398 
1399 	if (!nla) {
1400 		NL_SET_ERR_MSG_MOD(extack, "Ct requires attributes to be passed");
1401 		return -EINVAL;
1402 	}
1403 
1404 	err = nla_parse_nested(tb, TCA_CT_MAX, nla, ct_policy, extack);
1405 	if (err < 0)
1406 		return err;
1407 
1408 	if (!tb[TCA_CT_PARMS]) {
1409 		NL_SET_ERR_MSG_MOD(extack, "Missing required ct parameters");
1410 		return -EINVAL;
1411 	}
1412 	parm = nla_data(tb[TCA_CT_PARMS]);
1413 	index = parm->index;
1414 	err = tcf_idr_check_alloc(tn, &index, a, bind);
1415 	if (err < 0)
1416 		return err;
1417 
1418 	if (!err) {
1419 		err = tcf_idr_create_from_flags(tn, index, est, a,
1420 						&act_ct_ops, bind, flags);
1421 		if (err) {
1422 			tcf_idr_cleanup(tn, index);
1423 			return err;
1424 		}
1425 		res = ACT_P_CREATED;
1426 	} else {
1427 		if (bind)
1428 			return 0;
1429 
1430 		if (!(flags & TCA_ACT_FLAGS_REPLACE)) {
1431 			tcf_idr_release(*a, bind);
1432 			return -EEXIST;
1433 		}
1434 	}
1435 	err = tcf_action_check_ctrlact(parm->action, tp, &goto_ch, extack);
1436 	if (err < 0)
1437 		goto cleanup;
1438 
1439 	c = to_ct(*a);
1440 
1441 	params = kzalloc(sizeof(*params), GFP_KERNEL);
1442 	if (unlikely(!params)) {
1443 		err = -ENOMEM;
1444 		goto cleanup;
1445 	}
1446 
1447 	err = tcf_ct_fill_params(net, params, parm, tb, extack);
1448 	if (err)
1449 		goto cleanup;
1450 
1451 	err = tcf_ct_flow_table_get(net, params);
1452 	if (err)
1453 		goto cleanup;
1454 
1455 	spin_lock_bh(&c->tcf_lock);
1456 	goto_ch = tcf_action_set_ctrlact(*a, parm->action, goto_ch);
1457 	params = rcu_replace_pointer(c->params, params,
1458 				     lockdep_is_held(&c->tcf_lock));
1459 	spin_unlock_bh(&c->tcf_lock);
1460 
1461 	if (goto_ch)
1462 		tcf_chain_put_by_act(goto_ch);
1463 	if (params)
1464 		call_rcu(&params->rcu, tcf_ct_params_free_rcu);
1465 
1466 	return res;
1467 
1468 cleanup:
1469 	if (goto_ch)
1470 		tcf_chain_put_by_act(goto_ch);
1471 	if (params)
1472 		tcf_ct_params_free(params);
1473 	tcf_idr_release(*a, bind);
1474 	return err;
1475 }
1476 
1477 static void tcf_ct_cleanup(struct tc_action *a)
1478 {
1479 	struct tcf_ct_params *params;
1480 	struct tcf_ct *c = to_ct(a);
1481 
1482 	params = rcu_dereference_protected(c->params, 1);
1483 	if (params)
1484 		call_rcu(&params->rcu, tcf_ct_params_free_rcu);
1485 }
1486 
1487 static int tcf_ct_dump_key_val(struct sk_buff *skb,
1488 			       void *val, int val_type,
1489 			       void *mask, int mask_type,
1490 			       int len)
1491 {
1492 	int err;
1493 
1494 	if (mask && !memchr_inv(mask, 0, len))
1495 		return 0;
1496 
1497 	err = nla_put(skb, val_type, len, val);
1498 	if (err)
1499 		return err;
1500 
1501 	if (mask_type != TCA_CT_UNSPEC) {
1502 		err = nla_put(skb, mask_type, len, mask);
1503 		if (err)
1504 			return err;
1505 	}
1506 
1507 	return 0;
1508 }
1509 
1510 static int tcf_ct_dump_nat(struct sk_buff *skb, struct tcf_ct_params *p)
1511 {
1512 	struct nf_nat_range2 *range = &p->range;
1513 
1514 	if (!(p->ct_action & TCA_CT_ACT_NAT))
1515 		return 0;
1516 
1517 	if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1518 		return 0;
1519 
1520 	if (range->flags & NF_NAT_RANGE_MAP_IPS) {
1521 		if (p->ipv4_range) {
1522 			if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MIN,
1523 					    range->min_addr.ip))
1524 				return -1;
1525 			if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MAX,
1526 					    range->max_addr.ip))
1527 				return -1;
1528 		} else {
1529 			if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MIN,
1530 					     &range->min_addr.in6))
1531 				return -1;
1532 			if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MAX,
1533 					     &range->max_addr.in6))
1534 				return -1;
1535 		}
1536 	}
1537 
1538 	if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
1539 		if (nla_put_be16(skb, TCA_CT_NAT_PORT_MIN,
1540 				 range->min_proto.all))
1541 			return -1;
1542 		if (nla_put_be16(skb, TCA_CT_NAT_PORT_MAX,
1543 				 range->max_proto.all))
1544 			return -1;
1545 	}
1546 
1547 	return 0;
1548 }
1549 
1550 static int tcf_ct_dump_helper(struct sk_buff *skb, struct nf_conntrack_helper *helper)
1551 {
1552 	if (!helper)
1553 		return 0;
1554 
1555 	if (nla_put_string(skb, TCA_CT_HELPER_NAME, helper->name) ||
1556 	    nla_put_u8(skb, TCA_CT_HELPER_FAMILY, helper->tuple.src.l3num) ||
1557 	    nla_put_u8(skb, TCA_CT_HELPER_PROTO, helper->tuple.dst.protonum))
1558 		return -1;
1559 
1560 	return 0;
1561 }
1562 
1563 static inline int tcf_ct_dump(struct sk_buff *skb, struct tc_action *a,
1564 			      int bind, int ref)
1565 {
1566 	unsigned char *b = skb_tail_pointer(skb);
1567 	struct tcf_ct *c = to_ct(a);
1568 	struct tcf_ct_params *p;
1569 
1570 	struct tc_ct opt = {
1571 		.index   = c->tcf_index,
1572 		.refcnt  = refcount_read(&c->tcf_refcnt) - ref,
1573 		.bindcnt = atomic_read(&c->tcf_bindcnt) - bind,
1574 	};
1575 	struct tcf_t t;
1576 
1577 	spin_lock_bh(&c->tcf_lock);
1578 	p = rcu_dereference_protected(c->params,
1579 				      lockdep_is_held(&c->tcf_lock));
1580 	opt.action = c->tcf_action;
1581 
1582 	if (tcf_ct_dump_key_val(skb,
1583 				&p->ct_action, TCA_CT_ACTION,
1584 				NULL, TCA_CT_UNSPEC,
1585 				sizeof(p->ct_action)))
1586 		goto nla_put_failure;
1587 
1588 	if (p->ct_action & TCA_CT_ACT_CLEAR)
1589 		goto skip_dump;
1590 
1591 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1592 	    tcf_ct_dump_key_val(skb,
1593 				&p->mark, TCA_CT_MARK,
1594 				&p->mark_mask, TCA_CT_MARK_MASK,
1595 				sizeof(p->mark)))
1596 		goto nla_put_failure;
1597 
1598 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1599 	    tcf_ct_dump_key_val(skb,
1600 				p->labels, TCA_CT_LABELS,
1601 				p->labels_mask, TCA_CT_LABELS_MASK,
1602 				sizeof(p->labels)))
1603 		goto nla_put_failure;
1604 
1605 	if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1606 	    tcf_ct_dump_key_val(skb,
1607 				&p->zone, TCA_CT_ZONE,
1608 				NULL, TCA_CT_UNSPEC,
1609 				sizeof(p->zone)))
1610 		goto nla_put_failure;
1611 
1612 	if (tcf_ct_dump_nat(skb, p))
1613 		goto nla_put_failure;
1614 
1615 	if (tcf_ct_dump_helper(skb, p->helper))
1616 		goto nla_put_failure;
1617 
1618 skip_dump:
1619 	if (nla_put(skb, TCA_CT_PARMS, sizeof(opt), &opt))
1620 		goto nla_put_failure;
1621 
1622 	tcf_tm_dump(&t, &c->tcf_tm);
1623 	if (nla_put_64bit(skb, TCA_CT_TM, sizeof(t), &t, TCA_CT_PAD))
1624 		goto nla_put_failure;
1625 	spin_unlock_bh(&c->tcf_lock);
1626 
1627 	return skb->len;
1628 nla_put_failure:
1629 	spin_unlock_bh(&c->tcf_lock);
1630 	nlmsg_trim(skb, b);
1631 	return -1;
1632 }
1633 
1634 static void tcf_stats_update(struct tc_action *a, u64 bytes, u64 packets,
1635 			     u64 drops, u64 lastuse, bool hw)
1636 {
1637 	struct tcf_ct *c = to_ct(a);
1638 
1639 	tcf_action_update_stats(a, bytes, packets, drops, hw);
1640 	c->tcf_tm.lastuse = max_t(u64, c->tcf_tm.lastuse, lastuse);
1641 }
1642 
1643 static int tcf_ct_offload_act_setup(struct tc_action *act, void *entry_data,
1644 				    u32 *index_inc, bool bind,
1645 				    struct netlink_ext_ack *extack)
1646 {
1647 	if (bind) {
1648 		struct flow_action_entry *entry = entry_data;
1649 
1650 		entry->id = FLOW_ACTION_CT;
1651 		entry->ct.action = tcf_ct_action(act);
1652 		entry->ct.zone = tcf_ct_zone(act);
1653 		entry->ct.flow_table = tcf_ct_ft(act);
1654 		*index_inc = 1;
1655 	} else {
1656 		struct flow_offload_action *fl_action = entry_data;
1657 
1658 		fl_action->id = FLOW_ACTION_CT;
1659 	}
1660 
1661 	return 0;
1662 }
1663 
1664 static struct tc_action_ops act_ct_ops = {
1665 	.kind		=	"ct",
1666 	.id		=	TCA_ID_CT,
1667 	.owner		=	THIS_MODULE,
1668 	.act		=	tcf_ct_act,
1669 	.dump		=	tcf_ct_dump,
1670 	.init		=	tcf_ct_init,
1671 	.cleanup	=	tcf_ct_cleanup,
1672 	.stats_update	=	tcf_stats_update,
1673 	.offload_act_setup =	tcf_ct_offload_act_setup,
1674 	.size		=	sizeof(struct tcf_ct),
1675 };
1676 
1677 static __net_init int ct_init_net(struct net *net)
1678 {
1679 	unsigned int n_bits = sizeof_field(struct tcf_ct_params, labels) * 8;
1680 	struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1681 
1682 	if (nf_connlabels_get(net, n_bits - 1)) {
1683 		tn->labels = false;
1684 		pr_err("act_ct: Failed to set connlabels length");
1685 	} else {
1686 		tn->labels = true;
1687 	}
1688 
1689 	return tc_action_net_init(net, &tn->tn, &act_ct_ops);
1690 }
1691 
1692 static void __net_exit ct_exit_net(struct list_head *net_list)
1693 {
1694 	struct net *net;
1695 
1696 	rtnl_lock();
1697 	list_for_each_entry(net, net_list, exit_list) {
1698 		struct tc_ct_action_net *tn = net_generic(net, act_ct_ops.net_id);
1699 
1700 		if (tn->labels)
1701 			nf_connlabels_put(net);
1702 	}
1703 	rtnl_unlock();
1704 
1705 	tc_action_net_exit(net_list, act_ct_ops.net_id);
1706 }
1707 
1708 static struct pernet_operations ct_net_ops = {
1709 	.init = ct_init_net,
1710 	.exit_batch = ct_exit_net,
1711 	.id   = &act_ct_ops.net_id,
1712 	.size = sizeof(struct tc_ct_action_net),
1713 };
1714 
1715 static int __init ct_init_module(void)
1716 {
1717 	int err;
1718 
1719 	act_ct_wq = alloc_ordered_workqueue("act_ct_workqueue", 0);
1720 	if (!act_ct_wq)
1721 		return -ENOMEM;
1722 
1723 	err = tcf_ct_flow_tables_init();
1724 	if (err)
1725 		goto err_tbl_init;
1726 
1727 	err = tcf_register_action(&act_ct_ops, &ct_net_ops);
1728 	if (err)
1729 		goto err_register;
1730 
1731 	static_branch_inc(&tcf_frag_xmit_count);
1732 
1733 	return 0;
1734 
1735 err_register:
1736 	tcf_ct_flow_tables_uninit();
1737 err_tbl_init:
1738 	destroy_workqueue(act_ct_wq);
1739 	return err;
1740 }
1741 
1742 static void __exit ct_cleanup_module(void)
1743 {
1744 	static_branch_dec(&tcf_frag_xmit_count);
1745 	tcf_unregister_action(&act_ct_ops, &ct_net_ops);
1746 	tcf_ct_flow_tables_uninit();
1747 	destroy_workqueue(act_ct_wq);
1748 }
1749 
1750 module_init(ct_init_module);
1751 module_exit(ct_cleanup_module);
1752 MODULE_AUTHOR("Paul Blakey <paulb@mellanox.com>");
1753 MODULE_AUTHOR("Yossi Kuperman <yossiku@mellanox.com>");
1754 MODULE_AUTHOR("Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>");
1755 MODULE_DESCRIPTION("Connection tracking action");
1756 MODULE_LICENSE("GPL v2");
1757