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