1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
3 * net/sched/act_ct.c Connection Tracking action
5 * Authors: Paul Blakey <paulb@mellanox.com>
6 * Yossi Kuperman <yossiku@mellanox.com>
7 * Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>
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>
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>
24 #include <net/ipv6_frag.h>
25 #include <uapi/linux/tc_act/tc_ct.h>
26 #include <net/tc_act/tc_ct.h>
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>
37 static struct workqueue_struct *act_ct_wq;
38 static struct rhashtable zones_ht;
39 static DEFINE_MUTEX(zones_mutex);
41 struct tcf_ct_flow_table {
42 struct rhash_head node; /* In zones tables */
44 struct rcu_work rwork;
45 struct nf_flowtable nf_ft;
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,
59 static struct flow_action_entry *
60 tcf_ct_flow_table_flow_action_get_next(struct flow_action *flow_action)
62 int i = flow_action->num_entries++;
64 return &flow_action->entries[i];
67 static void tcf_ct_add_mangle_action(struct flow_action *action,
68 enum flow_action_mangle_base htype,
73 struct flow_action_entry *entry;
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;
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.
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)
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),
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),
101 be32_to_cpu(target.dst.u3.ip));
105 tcf_ct_add_ipv6_addr_mangle_action(struct flow_action *action,
106 union nf_inet_addr *addr,
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]));
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)
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,
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,
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)
137 __be16 target_src = target.src.u.tcp.port;
138 __be16 target_dst = target.dst.u.tcp.port;
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));
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)
155 __be16 target_src = target.src.u.udp.port;
156 __be16 target_dst = target.dst.u.udp.port;
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));
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)
172 struct nf_conn_labels *ct_labels;
173 struct flow_action_entry *entry;
174 enum ip_conntrack_info ctinfo;
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;
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;
188 act_ct_labels = entry->ct_metadata.labels;
189 ct_labels = nf_ct_labels_find(ct);
191 memcpy(act_ct_labels, ct_labels->bits, NF_CT_LABELS_MAX_SIZE);
193 memset(act_ct_labels, 0, NF_CT_LABELS_MAX_SIZE);
196 static int tcf_ct_flow_table_add_action_nat(struct net *net,
198 enum ip_conntrack_dir dir,
199 struct flow_action *action)
201 const struct nf_conntrack_tuple *tuple = &ct->tuplehash[dir].tuple;
202 struct nf_conntrack_tuple target;
204 if (!(ct->status & IPS_NAT_MASK))
207 nf_ct_invert_tuple(&target, &ct->tuplehash[!dir].tuple);
209 switch (tuple->src.l3num) {
211 tcf_ct_flow_table_add_action_nat_ipv4(tuple, target,
215 tcf_ct_flow_table_add_action_nat_ipv6(tuple, target,
222 switch (nf_ct_protonum(ct)) {
224 tcf_ct_flow_table_add_action_nat_tcp(tuple, target, action);
227 tcf_ct_flow_table_add_action_nat_udp(tuple, target, action);
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)
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;
248 case FLOW_OFFLOAD_DIR_ORIGINAL:
249 dir = IP_CT_DIR_ORIGINAL;
251 case FLOW_OFFLOAD_DIR_REPLY:
252 dir = IP_CT_DIR_REPLY;
258 err = tcf_ct_flow_table_add_action_nat(net, ct, dir, action);
262 tcf_ct_flow_table_add_action_meta(ct, dir, action);
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;
274 static struct nf_flowtable_type flowtable_ct = {
275 .action = tcf_ct_flow_table_fill_actions,
276 .owner = THIS_MODULE,
279 static int tcf_ct_flow_table_get(struct tcf_ct_params *params)
281 struct tcf_ct_flow_table *ct_ft;
284 mutex_lock(&zones_mutex);
285 ct_ft = rhashtable_lookup_fast(&zones_ht, ¶ms->zone, zones_params);
286 if (ct_ft && refcount_inc_not_zero(&ct_ft->ref))
289 ct_ft = kzalloc(sizeof(*ct_ft), GFP_KERNEL);
292 refcount_set(&ct_ft->ref, 1);
294 ct_ft->zone = params->zone;
295 err = rhashtable_insert_fast(&zones_ht, &ct_ft->node, zones_params);
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);
306 __module_get(THIS_MODULE);
308 params->ct_ft = ct_ft;
309 params->nf_ft = &ct_ft->nf_ft;
310 mutex_unlock(&zones_mutex);
315 rhashtable_remove_fast(&zones_ht, &ct_ft->node, zones_params);
319 mutex_unlock(&zones_mutex);
323 static void tcf_ct_flow_table_cleanup_work(struct work_struct *work)
325 struct flow_block_cb *block_cb, *tmp_cb;
326 struct tcf_ct_flow_table *ct_ft;
327 struct flow_block *block;
329 ct_ft = container_of(to_rcu_work(work), struct tcf_ct_flow_table,
331 nf_flow_table_free(&ct_ft->nf_ft);
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);
340 up_write(&ct_ft->nf_ft.flow_block_lock);
343 module_put(THIS_MODULE);
346 static void tcf_ct_flow_table_put(struct tcf_ct_params *params)
348 struct tcf_ct_flow_table *ct_ft = params->ct_ft;
350 if (refcount_dec_and_test(¶ms->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);
357 static void tcf_ct_flow_table_add(struct tcf_ct_flow_table *ct_ft,
361 struct flow_offload *entry;
364 if (test_and_set_bit(IPS_OFFLOAD_BIT, &ct->status))
367 entry = flow_offload_alloc(ct);
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;
378 err = flow_offload_add(&ct_ft->nf_ft, entry);
385 flow_offload_free(entry);
387 clear_bit(IPS_OFFLOAD_BIT, &ct->status);
390 static void tcf_ct_flow_table_process_conn(struct tcf_ct_flow_table *ct_ft,
392 enum ip_conntrack_info ctinfo)
396 if (ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY)
399 switch (nf_ct_protonum(ct)) {
402 if (ct->proto.tcp.state != TCP_CONNTRACK_ESTABLISHED)
411 if (nf_ct_ext_exist(ct, NF_CT_EXT_HELPER) ||
412 ct->status & IPS_SEQ_ADJUST)
415 tcf_ct_flow_table_add(ct_ft, ct, tcp);
419 tcf_ct_flow_table_fill_tuple_ipv4(struct sk_buff *skb,
420 struct flow_offload_tuple *tuple,
421 struct tcphdr **tcph)
423 struct flow_ports *ports;
427 if (!pskb_network_may_pull(skb, sizeof(*iph)))
431 thoff = iph->ihl * 4;
433 if (ip_is_fragment(iph) ||
434 unlikely(thoff != sizeof(struct iphdr)))
437 if (iph->protocol != IPPROTO_TCP &&
438 iph->protocol != IPPROTO_UDP)
444 if (!pskb_network_may_pull(skb, iph->protocol == IPPROTO_TCP ?
445 thoff + sizeof(struct tcphdr) :
446 thoff + sizeof(*ports)))
450 if (iph->protocol == IPPROTO_TCP)
451 *tcph = (void *)(skb_network_header(skb) + thoff);
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;
465 tcf_ct_flow_table_fill_tuple_ipv6(struct sk_buff *skb,
466 struct flow_offload_tuple *tuple,
467 struct tcphdr **tcph)
469 struct flow_ports *ports;
470 struct ipv6hdr *ip6h;
473 if (!pskb_network_may_pull(skb, sizeof(*ip6h)))
476 ip6h = ipv6_hdr(skb);
478 if (ip6h->nexthdr != IPPROTO_TCP &&
479 ip6h->nexthdr != IPPROTO_UDP)
482 if (ip6h->hop_limit <= 1)
485 thoff = sizeof(*ip6h);
486 if (!pskb_network_may_pull(skb, ip6h->nexthdr == IPPROTO_TCP ?
487 thoff + sizeof(struct tcphdr) :
488 thoff + sizeof(*ports)))
491 ip6h = ipv6_hdr(skb);
492 if (ip6h->nexthdr == IPPROTO_TCP)
493 *tcph = (void *)(skb_network_header(skb) + thoff);
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;
506 static bool tcf_ct_flow_table_lookup(struct tcf_ct_params *p,
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;
519 /* Previously seen or loopback */
520 ct = nf_ct_get(skb, &ctinfo);
521 if ((ct && !nf_ct_is_template(ct)) || ctinfo == IP_CT_UNTRACKED)
526 if (!tcf_ct_flow_table_fill_tuple_ipv4(skb, &tuple, &tcph))
530 if (!tcf_ct_flow_table_fill_tuple_ipv6(skb, &tuple, &tcph))
537 tuplehash = flow_offload_lookup(nf_ft, &tuple);
541 dir = tuplehash->tuple.dir;
542 flow = container_of(tuplehash, struct flow_offload, tuplehash[dir]);
545 if (tcph && (unlikely(tcph->fin || tcph->rst))) {
546 flow_offload_teardown(flow);
550 ctinfo = dir == FLOW_OFFLOAD_DIR_ORIGINAL ? IP_CT_ESTABLISHED :
551 IP_CT_ESTABLISHED_REPLY;
553 flow_offload_refresh(nf_ft, flow);
554 nf_conntrack_get(&ct->ct_general);
555 nf_ct_set(skb, ct, ctinfo);
556 if (nf_ft->flags & NF_FLOWTABLE_COUNTER)
557 nf_ct_acct_update(ct, dir, skb->len);
562 static int tcf_ct_flow_tables_init(void)
564 return rhashtable_init(&zones_ht, &zones_params);
567 static void tcf_ct_flow_tables_uninit(void)
569 rhashtable_destroy(&zones_ht);
572 static struct tc_action_ops act_ct_ops;
573 static unsigned int ct_net_id;
575 struct tc_ct_action_net {
576 struct tc_action_net tn; /* Must be first */
580 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
581 static bool tcf_ct_skb_nfct_cached(struct net *net, struct sk_buff *skb,
582 u16 zone_id, bool force)
584 enum ip_conntrack_info ctinfo;
587 ct = nf_ct_get(skb, &ctinfo);
590 if (!net_eq(net, read_pnet(&ct->ct_net)))
592 if (nf_ct_zone(ct)->id != zone_id)
595 /* Force conntrack entry direction. */
596 if (force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
597 if (nf_ct_is_confirmed(ct))
600 nf_conntrack_put(&ct->ct_general);
601 nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
609 /* Trim the skb to the length specified by the IP/IPv6 header,
610 * removing any trailing lower-layer padding. This prepares the skb
611 * for higher-layer processing that assumes skb->len excludes padding
612 * (such as nf_ip_checksum). The caller needs to pull the skb to the
613 * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
615 static int tcf_ct_skb_network_trim(struct sk_buff *skb, int family)
622 len = ntohs(ip_hdr(skb)->tot_len);
625 len = sizeof(struct ipv6hdr)
626 + ntohs(ipv6_hdr(skb)->payload_len);
632 err = pskb_trim_rcsum(skb, len);
637 static u8 tcf_ct_skb_nf_family(struct sk_buff *skb)
639 u8 family = NFPROTO_UNSPEC;
641 switch (skb_protocol(skb, true)) {
642 case htons(ETH_P_IP):
643 family = NFPROTO_IPV4;
645 case htons(ETH_P_IPV6):
646 family = NFPROTO_IPV6;
655 static int tcf_ct_ipv4_is_fragment(struct sk_buff *skb, bool *frag)
659 len = skb_network_offset(skb) + sizeof(struct iphdr);
660 if (unlikely(skb->len < len))
662 if (unlikely(!pskb_may_pull(skb, len)))
665 *frag = ip_is_fragment(ip_hdr(skb));
669 static int tcf_ct_ipv6_is_fragment(struct sk_buff *skb, bool *frag)
671 unsigned int flags = 0, len, payload_ofs = 0;
672 unsigned short frag_off;
675 len = skb_network_offset(skb) + sizeof(struct ipv6hdr);
676 if (unlikely(skb->len < len))
678 if (unlikely(!pskb_may_pull(skb, len)))
681 nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags);
682 if (unlikely(nexthdr < 0))
685 *frag = flags & IP6_FH_F_FRAG;
689 static int tcf_ct_handle_fragments(struct net *net, struct sk_buff *skb,
690 u8 family, u16 zone, bool *defrag)
692 enum ip_conntrack_info ctinfo;
693 struct qdisc_skb_cb cb;
698 /* Previously seen (loopback)? Ignore. */
699 ct = nf_ct_get(skb, &ctinfo);
700 if ((ct && !nf_ct_is_template(ct)) || ctinfo == IP_CT_UNTRACKED)
703 if (family == NFPROTO_IPV4)
704 err = tcf_ct_ipv4_is_fragment(skb, &frag);
706 err = tcf_ct_ipv6_is_fragment(skb, &frag);
711 cb = *qdisc_skb_cb(skb);
713 if (family == NFPROTO_IPV4) {
714 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
716 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
718 err = ip_defrag(net, skb, user);
720 if (err && err != -EINPROGRESS)
725 cb.mru = IPCB(skb)->frag_max_size;
727 } else { /* NFPROTO_IPV6 */
728 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
729 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
731 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
732 err = nf_ct_frag6_gather(net, skb, user);
733 if (err && err != -EINPROGRESS)
738 cb.mru = IP6CB(skb)->frag_max_size;
746 if (err != -EINPROGRESS)
747 *qdisc_skb_cb(skb) = cb;
757 static void tcf_ct_params_free(struct rcu_head *head)
759 struct tcf_ct_params *params = container_of(head,
760 struct tcf_ct_params, rcu);
762 tcf_ct_flow_table_put(params);
765 nf_conntrack_put(¶ms->tmpl->ct_general);
769 #if IS_ENABLED(CONFIG_NF_NAT)
770 /* Modelled after nf_nat_ipv[46]_fn().
771 * range is only used for new, uninitialized NAT state.
772 * Returns either NF_ACCEPT or NF_DROP.
774 static int ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
775 enum ip_conntrack_info ctinfo,
776 const struct nf_nat_range2 *range,
777 enum nf_nat_manip_type maniptype)
779 __be16 proto = skb_protocol(skb, true);
780 int hooknum, err = NF_ACCEPT;
782 /* See HOOK2MANIP(). */
783 if (maniptype == NF_NAT_MANIP_SRC)
784 hooknum = NF_INET_LOCAL_IN; /* Source NAT */
786 hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
790 case IP_CT_RELATED_REPLY:
791 if (proto == htons(ETH_P_IP) &&
792 ip_hdr(skb)->protocol == IPPROTO_ICMP) {
793 if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
797 } else if (IS_ENABLED(CONFIG_IPV6) && proto == htons(ETH_P_IPV6)) {
799 u8 nexthdr = ipv6_hdr(skb)->nexthdr;
800 int hdrlen = ipv6_skip_exthdr(skb,
801 sizeof(struct ipv6hdr),
802 &nexthdr, &frag_off);
804 if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
805 if (!nf_nat_icmpv6_reply_translation(skb, ct,
813 /* Non-ICMP, fall thru to initialize if needed. */
816 /* Seen it before? This can happen for loopback, retrans,
819 if (!nf_nat_initialized(ct, maniptype)) {
820 /* Initialize according to the NAT action. */
821 err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
822 /* Action is set up to establish a new
825 ? nf_nat_setup_info(ct, range, maniptype)
826 : nf_nat_alloc_null_binding(ct, hooknum);
827 if (err != NF_ACCEPT)
832 case IP_CT_ESTABLISHED:
833 case IP_CT_ESTABLISHED_REPLY:
841 err = nf_nat_packet(ct, ctinfo, hooknum, skb);
845 #endif /* CONFIG_NF_NAT */
847 static void tcf_ct_act_set_mark(struct nf_conn *ct, u32 mark, u32 mask)
849 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
855 new_mark = mark | (ct->mark & ~(mask));
856 if (ct->mark != new_mark) {
858 if (nf_ct_is_confirmed(ct))
859 nf_conntrack_event_cache(IPCT_MARK, ct);
864 static void tcf_ct_act_set_labels(struct nf_conn *ct,
868 #if IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)
869 size_t labels_sz = sizeof_field(struct tcf_ct_params, labels);
871 if (!memchr_inv(labels_m, 0, labels_sz))
874 nf_connlabels_replace(ct, labels, labels_m, 4);
878 static int tcf_ct_act_nat(struct sk_buff *skb,
880 enum ip_conntrack_info ctinfo,
882 struct nf_nat_range2 *range,
885 #if IS_ENABLED(CONFIG_NF_NAT)
887 enum nf_nat_manip_type maniptype;
889 if (!(ct_action & TCA_CT_ACT_NAT))
892 /* Add NAT extension if not confirmed yet. */
893 if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
894 return NF_DROP; /* Can't NAT. */
896 if (ctinfo != IP_CT_NEW && (ct->status & IPS_NAT_MASK) &&
897 (ctinfo != IP_CT_RELATED || commit)) {
898 /* NAT an established or related connection like before. */
899 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
900 /* This is the REPLY direction for a connection
901 * for which NAT was applied in the forward
902 * direction. Do the reverse NAT.
904 maniptype = ct->status & IPS_SRC_NAT
905 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
907 maniptype = ct->status & IPS_SRC_NAT
908 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
909 } else if (ct_action & TCA_CT_ACT_NAT_SRC) {
910 maniptype = NF_NAT_MANIP_SRC;
911 } else if (ct_action & TCA_CT_ACT_NAT_DST) {
912 maniptype = NF_NAT_MANIP_DST;
917 err = ct_nat_execute(skb, ct, ctinfo, range, maniptype);
918 if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
919 if (ct->status & IPS_SRC_NAT) {
920 if (maniptype == NF_NAT_MANIP_SRC)
921 maniptype = NF_NAT_MANIP_DST;
923 maniptype = NF_NAT_MANIP_SRC;
925 err = ct_nat_execute(skb, ct, ctinfo, range,
927 } else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
928 err = ct_nat_execute(skb, ct, ctinfo, NULL,
938 static int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,
939 struct tcf_result *res)
941 struct net *net = dev_net(skb->dev);
942 bool cached, commit, clear, force;
943 enum ip_conntrack_info ctinfo;
944 struct tcf_ct *c = to_ct(a);
945 struct nf_conn *tmpl = NULL;
946 struct nf_hook_state state;
947 int nh_ofs, err, retval;
948 struct tcf_ct_params *p;
949 bool skip_add = false;
954 p = rcu_dereference_bh(c->params);
956 retval = READ_ONCE(c->tcf_action);
957 commit = p->ct_action & TCA_CT_ACT_COMMIT;
958 clear = p->ct_action & TCA_CT_ACT_CLEAR;
959 force = p->ct_action & TCA_CT_ACT_FORCE;
962 tcf_lastuse_update(&c->tcf_tm);
963 tcf_action_update_bstats(&c->common, skb);
966 qdisc_skb_cb(skb)->post_ct = false;
967 ct = nf_ct_get(skb, &ctinfo);
969 nf_conntrack_put(&ct->ct_general);
970 nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
976 family = tcf_ct_skb_nf_family(skb);
977 if (family == NFPROTO_UNSPEC)
980 /* The conntrack module expects to be working at L3.
981 * We also try to pull the IPv4/6 header to linear area
983 nh_ofs = skb_network_offset(skb);
984 skb_pull_rcsum(skb, nh_ofs);
985 err = tcf_ct_handle_fragments(net, skb, family, p->zone, &defrag);
986 if (err == -EINPROGRESS) {
987 retval = TC_ACT_STOLEN;
993 err = tcf_ct_skb_network_trim(skb, family);
997 /* If we are recirculating packets to match on ct fields and
998 * committing with a separate ct action, then we don't need to
999 * actually run the packet through conntrack twice unless it's for a
1002 cached = tcf_ct_skb_nfct_cached(net, skb, p->zone, force);
1004 if (tcf_ct_flow_table_lookup(p, skb, family)) {
1009 /* Associate skb with specified zone. */
1011 nf_conntrack_put(skb_nfct(skb));
1012 nf_conntrack_get(&tmpl->ct_general);
1013 nf_ct_set(skb, tmpl, IP_CT_NEW);
1016 state.hook = NF_INET_PRE_ROUTING;
1019 err = nf_conntrack_in(skb, &state);
1020 if (err != NF_ACCEPT)
1025 ct = nf_ct_get(skb, &ctinfo);
1028 nf_ct_deliver_cached_events(ct);
1030 err = tcf_ct_act_nat(skb, ct, ctinfo, p->ct_action, &p->range, commit);
1031 if (err != NF_ACCEPT)
1035 tcf_ct_act_set_mark(ct, p->mark, p->mark_mask);
1036 tcf_ct_act_set_labels(ct, p->labels, p->labels_mask);
1038 /* This will take care of sending queued events
1039 * even if the connection is already confirmed.
1041 if (nf_conntrack_confirm(skb) != NF_ACCEPT)
1046 tcf_ct_flow_table_process_conn(p->ct_ft, ct, ctinfo);
1049 skb_push_rcsum(skb, nh_ofs);
1051 qdisc_skb_cb(skb)->post_ct = true;
1054 qdisc_skb_cb(skb)->pkt_len = skb->len;
1058 tcf_action_inc_drop_qstats(&c->common);
1062 static const struct nla_policy ct_policy[TCA_CT_MAX + 1] = {
1063 [TCA_CT_ACTION] = { .type = NLA_U16 },
1064 [TCA_CT_PARMS] = NLA_POLICY_EXACT_LEN(sizeof(struct tc_ct)),
1065 [TCA_CT_ZONE] = { .type = NLA_U16 },
1066 [TCA_CT_MARK] = { .type = NLA_U32 },
1067 [TCA_CT_MARK_MASK] = { .type = NLA_U32 },
1068 [TCA_CT_LABELS] = { .type = NLA_BINARY,
1069 .len = 128 / BITS_PER_BYTE },
1070 [TCA_CT_LABELS_MASK] = { .type = NLA_BINARY,
1071 .len = 128 / BITS_PER_BYTE },
1072 [TCA_CT_NAT_IPV4_MIN] = { .type = NLA_U32 },
1073 [TCA_CT_NAT_IPV4_MAX] = { .type = NLA_U32 },
1074 [TCA_CT_NAT_IPV6_MIN] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1075 [TCA_CT_NAT_IPV6_MAX] = NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
1076 [TCA_CT_NAT_PORT_MIN] = { .type = NLA_U16 },
1077 [TCA_CT_NAT_PORT_MAX] = { .type = NLA_U16 },
1080 static int tcf_ct_fill_params_nat(struct tcf_ct_params *p,
1083 struct netlink_ext_ack *extack)
1085 struct nf_nat_range2 *range;
1087 if (!(p->ct_action & TCA_CT_ACT_NAT))
1090 if (!IS_ENABLED(CONFIG_NF_NAT)) {
1091 NL_SET_ERR_MSG_MOD(extack, "Netfilter nat isn't enabled in kernel");
1095 if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1098 if ((p->ct_action & TCA_CT_ACT_NAT_SRC) &&
1099 (p->ct_action & TCA_CT_ACT_NAT_DST)) {
1100 NL_SET_ERR_MSG_MOD(extack, "dnat and snat can't be enabled at the same time");
1105 if (tb[TCA_CT_NAT_IPV4_MIN]) {
1106 struct nlattr *max_attr = tb[TCA_CT_NAT_IPV4_MAX];
1108 p->ipv4_range = true;
1109 range->flags |= NF_NAT_RANGE_MAP_IPS;
1110 range->min_addr.ip =
1111 nla_get_in_addr(tb[TCA_CT_NAT_IPV4_MIN]);
1113 range->max_addr.ip = max_attr ?
1114 nla_get_in_addr(max_attr) :
1116 } else if (tb[TCA_CT_NAT_IPV6_MIN]) {
1117 struct nlattr *max_attr = tb[TCA_CT_NAT_IPV6_MAX];
1119 p->ipv4_range = false;
1120 range->flags |= NF_NAT_RANGE_MAP_IPS;
1121 range->min_addr.in6 =
1122 nla_get_in6_addr(tb[TCA_CT_NAT_IPV6_MIN]);
1124 range->max_addr.in6 = max_attr ?
1125 nla_get_in6_addr(max_attr) :
1126 range->min_addr.in6;
1129 if (tb[TCA_CT_NAT_PORT_MIN]) {
1130 range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1131 range->min_proto.all = nla_get_be16(tb[TCA_CT_NAT_PORT_MIN]);
1133 range->max_proto.all = tb[TCA_CT_NAT_PORT_MAX] ?
1134 nla_get_be16(tb[TCA_CT_NAT_PORT_MAX]) :
1135 range->min_proto.all;
1141 static void tcf_ct_set_key_val(struct nlattr **tb,
1142 void *val, int val_type,
1143 void *mask, int mask_type,
1148 nla_memcpy(val, tb[val_type], len);
1153 if (mask_type == TCA_CT_UNSPEC || !tb[mask_type])
1154 memset(mask, 0xff, len);
1156 nla_memcpy(mask, tb[mask_type], len);
1159 static int tcf_ct_fill_params(struct net *net,
1160 struct tcf_ct_params *p,
1163 struct netlink_ext_ack *extack)
1165 struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
1166 struct nf_conntrack_zone zone;
1167 struct nf_conn *tmpl;
1170 p->zone = NF_CT_DEFAULT_ZONE_ID;
1172 tcf_ct_set_key_val(tb,
1173 &p->ct_action, TCA_CT_ACTION,
1174 NULL, TCA_CT_UNSPEC,
1175 sizeof(p->ct_action));
1177 if (p->ct_action & TCA_CT_ACT_CLEAR)
1180 err = tcf_ct_fill_params_nat(p, parm, tb, extack);
1184 if (tb[TCA_CT_MARK]) {
1185 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)) {
1186 NL_SET_ERR_MSG_MOD(extack, "Conntrack mark isn't enabled.");
1189 tcf_ct_set_key_val(tb,
1190 &p->mark, TCA_CT_MARK,
1191 &p->mark_mask, TCA_CT_MARK_MASK,
1195 if (tb[TCA_CT_LABELS]) {
1196 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)) {
1197 NL_SET_ERR_MSG_MOD(extack, "Conntrack labels isn't enabled.");
1202 NL_SET_ERR_MSG_MOD(extack, "Failed to set connlabel length");
1205 tcf_ct_set_key_val(tb,
1206 p->labels, TCA_CT_LABELS,
1207 p->labels_mask, TCA_CT_LABELS_MASK,
1211 if (tb[TCA_CT_ZONE]) {
1212 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES)) {
1213 NL_SET_ERR_MSG_MOD(extack, "Conntrack zones isn't enabled.");
1217 tcf_ct_set_key_val(tb,
1218 &p->zone, TCA_CT_ZONE,
1219 NULL, TCA_CT_UNSPEC,
1223 nf_ct_zone_init(&zone, p->zone, NF_CT_DEFAULT_ZONE_DIR, 0);
1224 tmpl = nf_ct_tmpl_alloc(net, &zone, GFP_KERNEL);
1226 NL_SET_ERR_MSG_MOD(extack, "Failed to allocate conntrack template");
1229 __set_bit(IPS_CONFIRMED_BIT, &tmpl->status);
1230 nf_conntrack_get(&tmpl->ct_general);
1236 static int tcf_ct_init(struct net *net, struct nlattr *nla,
1237 struct nlattr *est, struct tc_action **a,
1238 struct tcf_proto *tp, u32 flags,
1239 struct netlink_ext_ack *extack)
1241 struct tc_action_net *tn = net_generic(net, ct_net_id);
1242 bool bind = flags & TCA_ACT_FLAGS_BIND;
1243 struct tcf_ct_params *params = NULL;
1244 struct nlattr *tb[TCA_CT_MAX + 1];
1245 struct tcf_chain *goto_ch = NULL;
1252 NL_SET_ERR_MSG_MOD(extack, "Ct requires attributes to be passed");
1256 err = nla_parse_nested(tb, TCA_CT_MAX, nla, ct_policy, extack);
1260 if (!tb[TCA_CT_PARMS]) {
1261 NL_SET_ERR_MSG_MOD(extack, "Missing required ct parameters");
1264 parm = nla_data(tb[TCA_CT_PARMS]);
1265 index = parm->index;
1266 err = tcf_idr_check_alloc(tn, &index, a, bind);
1271 err = tcf_idr_create_from_flags(tn, index, est, a,
1272 &act_ct_ops, bind, flags);
1274 tcf_idr_cleanup(tn, index);
1277 res = ACT_P_CREATED;
1282 if (!(flags & TCA_ACT_FLAGS_REPLACE)) {
1283 tcf_idr_release(*a, bind);
1287 err = tcf_action_check_ctrlact(parm->action, tp, &goto_ch, extack);
1293 params = kzalloc(sizeof(*params), GFP_KERNEL);
1294 if (unlikely(!params)) {
1299 err = tcf_ct_fill_params(net, params, parm, tb, extack);
1303 err = tcf_ct_flow_table_get(params);
1307 spin_lock_bh(&c->tcf_lock);
1308 goto_ch = tcf_action_set_ctrlact(*a, parm->action, goto_ch);
1309 params = rcu_replace_pointer(c->params, params,
1310 lockdep_is_held(&c->tcf_lock));
1311 spin_unlock_bh(&c->tcf_lock);
1314 tcf_chain_put_by_act(goto_ch);
1316 call_rcu(¶ms->rcu, tcf_ct_params_free);
1322 tcf_chain_put_by_act(goto_ch);
1324 tcf_idr_release(*a, bind);
1328 static void tcf_ct_cleanup(struct tc_action *a)
1330 struct tcf_ct_params *params;
1331 struct tcf_ct *c = to_ct(a);
1333 params = rcu_dereference_protected(c->params, 1);
1335 call_rcu(¶ms->rcu, tcf_ct_params_free);
1338 static int tcf_ct_dump_key_val(struct sk_buff *skb,
1339 void *val, int val_type,
1340 void *mask, int mask_type,
1345 if (mask && !memchr_inv(mask, 0, len))
1348 err = nla_put(skb, val_type, len, val);
1352 if (mask_type != TCA_CT_UNSPEC) {
1353 err = nla_put(skb, mask_type, len, mask);
1361 static int tcf_ct_dump_nat(struct sk_buff *skb, struct tcf_ct_params *p)
1363 struct nf_nat_range2 *range = &p->range;
1365 if (!(p->ct_action & TCA_CT_ACT_NAT))
1368 if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
1371 if (range->flags & NF_NAT_RANGE_MAP_IPS) {
1372 if (p->ipv4_range) {
1373 if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MIN,
1374 range->min_addr.ip))
1376 if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MAX,
1377 range->max_addr.ip))
1380 if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MIN,
1381 &range->min_addr.in6))
1383 if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MAX,
1384 &range->max_addr.in6))
1389 if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
1390 if (nla_put_be16(skb, TCA_CT_NAT_PORT_MIN,
1391 range->min_proto.all))
1393 if (nla_put_be16(skb, TCA_CT_NAT_PORT_MAX,
1394 range->max_proto.all))
1401 static inline int tcf_ct_dump(struct sk_buff *skb, struct tc_action *a,
1404 unsigned char *b = skb_tail_pointer(skb);
1405 struct tcf_ct *c = to_ct(a);
1406 struct tcf_ct_params *p;
1408 struct tc_ct opt = {
1409 .index = c->tcf_index,
1410 .refcnt = refcount_read(&c->tcf_refcnt) - ref,
1411 .bindcnt = atomic_read(&c->tcf_bindcnt) - bind,
1415 spin_lock_bh(&c->tcf_lock);
1416 p = rcu_dereference_protected(c->params,
1417 lockdep_is_held(&c->tcf_lock));
1418 opt.action = c->tcf_action;
1420 if (tcf_ct_dump_key_val(skb,
1421 &p->ct_action, TCA_CT_ACTION,
1422 NULL, TCA_CT_UNSPEC,
1423 sizeof(p->ct_action)))
1424 goto nla_put_failure;
1426 if (p->ct_action & TCA_CT_ACT_CLEAR)
1429 if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1430 tcf_ct_dump_key_val(skb,
1431 &p->mark, TCA_CT_MARK,
1432 &p->mark_mask, TCA_CT_MARK_MASK,
1434 goto nla_put_failure;
1436 if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1437 tcf_ct_dump_key_val(skb,
1438 p->labels, TCA_CT_LABELS,
1439 p->labels_mask, TCA_CT_LABELS_MASK,
1441 goto nla_put_failure;
1443 if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1444 tcf_ct_dump_key_val(skb,
1445 &p->zone, TCA_CT_ZONE,
1446 NULL, TCA_CT_UNSPEC,
1448 goto nla_put_failure;
1450 if (tcf_ct_dump_nat(skb, p))
1451 goto nla_put_failure;
1454 if (nla_put(skb, TCA_CT_PARMS, sizeof(opt), &opt))
1455 goto nla_put_failure;
1457 tcf_tm_dump(&t, &c->tcf_tm);
1458 if (nla_put_64bit(skb, TCA_CT_TM, sizeof(t), &t, TCA_CT_PAD))
1459 goto nla_put_failure;
1460 spin_unlock_bh(&c->tcf_lock);
1464 spin_unlock_bh(&c->tcf_lock);
1469 static int tcf_ct_walker(struct net *net, struct sk_buff *skb,
1470 struct netlink_callback *cb, int type,
1471 const struct tc_action_ops *ops,
1472 struct netlink_ext_ack *extack)
1474 struct tc_action_net *tn = net_generic(net, ct_net_id);
1476 return tcf_generic_walker(tn, skb, cb, type, ops, extack);
1479 static int tcf_ct_search(struct net *net, struct tc_action **a, u32 index)
1481 struct tc_action_net *tn = net_generic(net, ct_net_id);
1483 return tcf_idr_search(tn, a, index);
1486 static void tcf_stats_update(struct tc_action *a, u64 bytes, u64 packets,
1487 u64 drops, u64 lastuse, bool hw)
1489 struct tcf_ct *c = to_ct(a);
1491 tcf_action_update_stats(a, bytes, packets, drops, hw);
1492 c->tcf_tm.lastuse = max_t(u64, c->tcf_tm.lastuse, lastuse);
1495 static struct tc_action_ops act_ct_ops = {
1498 .owner = THIS_MODULE,
1500 .dump = tcf_ct_dump,
1501 .init = tcf_ct_init,
1502 .cleanup = tcf_ct_cleanup,
1503 .walk = tcf_ct_walker,
1504 .lookup = tcf_ct_search,
1505 .stats_update = tcf_stats_update,
1506 .size = sizeof(struct tcf_ct),
1509 static __net_init int ct_init_net(struct net *net)
1511 unsigned int n_bits = sizeof_field(struct tcf_ct_params, labels) * 8;
1512 struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
1514 if (nf_connlabels_get(net, n_bits - 1)) {
1516 pr_err("act_ct: Failed to set connlabels length");
1521 return tc_action_net_init(net, &tn->tn, &act_ct_ops);
1524 static void __net_exit ct_exit_net(struct list_head *net_list)
1529 list_for_each_entry(net, net_list, exit_list) {
1530 struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
1533 nf_connlabels_put(net);
1537 tc_action_net_exit(net_list, ct_net_id);
1540 static struct pernet_operations ct_net_ops = {
1541 .init = ct_init_net,
1542 .exit_batch = ct_exit_net,
1544 .size = sizeof(struct tc_ct_action_net),
1547 static int __init ct_init_module(void)
1551 act_ct_wq = alloc_ordered_workqueue("act_ct_workqueue", 0);
1555 err = tcf_ct_flow_tables_init();
1559 err = tcf_register_action(&act_ct_ops, &ct_net_ops);
1563 static_branch_inc(&tcf_frag_xmit_count);
1568 tcf_ct_flow_tables_uninit();
1570 destroy_workqueue(act_ct_wq);
1574 static void __exit ct_cleanup_module(void)
1576 static_branch_dec(&tcf_frag_xmit_count);
1577 tcf_unregister_action(&act_ct_ops, &ct_net_ops);
1578 tcf_ct_flow_tables_uninit();
1579 destroy_workqueue(act_ct_wq);
1582 module_init(ct_init_module);
1583 module_exit(ct_cleanup_module);
1584 MODULE_AUTHOR("Paul Blakey <paulb@mellanox.com>");
1585 MODULE_AUTHOR("Yossi Kuperman <yossiku@mellanox.com>");
1586 MODULE_AUTHOR("Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>");
1587 MODULE_DESCRIPTION("Connection tracking action");
1588 MODULE_LICENSE("GPL v2");