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