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