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