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