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