GNU Linux-libre 5.4.257-gnu1
[releases.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 <net/netlink.h>
19 #include <net/pkt_sched.h>
20 #include <net/pkt_cls.h>
21 #include <net/act_api.h>
22 #include <net/ip.h>
23 #include <net/ipv6_frag.h>
24 #include <uapi/linux/tc_act/tc_ct.h>
25 #include <net/tc_act/tc_ct.h>
26
27 #include <net/netfilter/nf_conntrack.h>
28 #include <net/netfilter/nf_conntrack_core.h>
29 #include <net/netfilter/nf_conntrack_zones.h>
30 #include <net/netfilter/nf_conntrack_helper.h>
31 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
32 #include <uapi/linux/netfilter/nf_nat.h>
33
34 static struct tc_action_ops act_ct_ops;
35 static unsigned int ct_net_id;
36
37 struct tc_ct_action_net {
38         struct tc_action_net tn; /* Must be first */
39         bool labels;
40 };
41
42 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
43 static bool tcf_ct_skb_nfct_cached(struct net *net, struct sk_buff *skb,
44                                    u16 zone_id, bool force)
45 {
46         enum ip_conntrack_info ctinfo;
47         struct nf_conn *ct;
48
49         ct = nf_ct_get(skb, &ctinfo);
50         if (!ct)
51                 return false;
52         if (!net_eq(net, read_pnet(&ct->ct_net)))
53                 return false;
54         if (nf_ct_zone(ct)->id != zone_id)
55                 return false;
56
57         /* Force conntrack entry direction. */
58         if (force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
59                 if (nf_ct_is_confirmed(ct))
60                         nf_ct_kill(ct);
61
62                 nf_conntrack_put(&ct->ct_general);
63                 nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
64
65                 return false;
66         }
67
68         return true;
69 }
70
71 /* Trim the skb to the length specified by the IP/IPv6 header,
72  * removing any trailing lower-layer padding. This prepares the skb
73  * for higher-layer processing that assumes skb->len excludes padding
74  * (such as nf_ip_checksum). The caller needs to pull the skb to the
75  * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
76  */
77 static int tcf_ct_skb_network_trim(struct sk_buff *skb, int family)
78 {
79         unsigned int len;
80         int err;
81
82         switch (family) {
83         case NFPROTO_IPV4:
84                 len = ntohs(ip_hdr(skb)->tot_len);
85                 break;
86         case NFPROTO_IPV6:
87                 len = sizeof(struct ipv6hdr)
88                         + ntohs(ipv6_hdr(skb)->payload_len);
89                 break;
90         default:
91                 len = skb->len;
92         }
93
94         err = pskb_trim_rcsum(skb, len);
95
96         return err;
97 }
98
99 static u8 tcf_ct_skb_nf_family(struct sk_buff *skb)
100 {
101         u8 family = NFPROTO_UNSPEC;
102
103         switch (skb_protocol(skb, true)) {
104         case htons(ETH_P_IP):
105                 family = NFPROTO_IPV4;
106                 break;
107         case htons(ETH_P_IPV6):
108                 family = NFPROTO_IPV6;
109                 break;
110         default:
111                 break;
112         }
113
114         return family;
115 }
116
117 static int tcf_ct_ipv4_is_fragment(struct sk_buff *skb, bool *frag)
118 {
119         unsigned int len;
120
121         len =  skb_network_offset(skb) + sizeof(struct iphdr);
122         if (unlikely(skb->len < len))
123                 return -EINVAL;
124         if (unlikely(!pskb_may_pull(skb, len)))
125                 return -ENOMEM;
126
127         *frag = ip_is_fragment(ip_hdr(skb));
128         return 0;
129 }
130
131 static int tcf_ct_ipv6_is_fragment(struct sk_buff *skb, bool *frag)
132 {
133         unsigned int flags = 0, len, payload_ofs = 0;
134         unsigned short frag_off;
135         int nexthdr;
136
137         len =  skb_network_offset(skb) + sizeof(struct ipv6hdr);
138         if (unlikely(skb->len < len))
139                 return -EINVAL;
140         if (unlikely(!pskb_may_pull(skb, len)))
141                 return -ENOMEM;
142
143         nexthdr = ipv6_find_hdr(skb, &payload_ofs, -1, &frag_off, &flags);
144         if (unlikely(nexthdr < 0))
145                 return -EPROTO;
146
147         *frag = flags & IP6_FH_F_FRAG;
148         return 0;
149 }
150
151 static int tcf_ct_handle_fragments(struct net *net, struct sk_buff *skb,
152                                    u8 family, u16 zone)
153 {
154         enum ip_conntrack_info ctinfo;
155         struct nf_conn *ct;
156         int err = 0;
157         bool frag;
158
159         /* Previously seen (loopback)? Ignore. */
160         ct = nf_ct_get(skb, &ctinfo);
161         if ((ct && !nf_ct_is_template(ct)) || ctinfo == IP_CT_UNTRACKED)
162                 return 0;
163
164         if (family == NFPROTO_IPV4)
165                 err = tcf_ct_ipv4_is_fragment(skb, &frag);
166         else
167                 err = tcf_ct_ipv6_is_fragment(skb, &frag);
168         if (err || !frag)
169                 return err;
170
171         skb_get(skb);
172
173         if (family == NFPROTO_IPV4) {
174                 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
175
176                 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
177                 local_bh_disable();
178                 err = ip_defrag(net, skb, user);
179                 local_bh_enable();
180                 if (err && err != -EINPROGRESS)
181                         goto out_free;
182         } else { /* NFPROTO_IPV6 */
183 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
184                 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
185
186                 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
187                 err = nf_ct_frag6_gather(net, skb, user);
188                 if (err && err != -EINPROGRESS)
189                         return err;
190 #else
191                 err = -EOPNOTSUPP;
192                 goto out_free;
193 #endif
194         }
195
196         skb_clear_hash(skb);
197         skb->ignore_df = 1;
198         return err;
199
200 out_free:
201         kfree_skb(skb);
202         return err;
203 }
204
205 static void tcf_ct_params_free(struct rcu_head *head)
206 {
207         struct tcf_ct_params *params = container_of(head,
208                                                     struct tcf_ct_params, rcu);
209
210         if (params->tmpl)
211                 nf_conntrack_put(&params->tmpl->ct_general);
212         kfree(params);
213 }
214
215 #if IS_ENABLED(CONFIG_NF_NAT)
216 /* Modelled after nf_nat_ipv[46]_fn().
217  * range is only used for new, uninitialized NAT state.
218  * Returns either NF_ACCEPT or NF_DROP.
219  */
220 static int ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
221                           enum ip_conntrack_info ctinfo,
222                           const struct nf_nat_range2 *range,
223                           enum nf_nat_manip_type maniptype)
224 {
225         __be16 proto = skb_protocol(skb, true);
226         int hooknum, err = NF_ACCEPT;
227
228         /* See HOOK2MANIP(). */
229         if (maniptype == NF_NAT_MANIP_SRC)
230                 hooknum = NF_INET_LOCAL_IN; /* Source NAT */
231         else
232                 hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
233
234         switch (ctinfo) {
235         case IP_CT_RELATED:
236         case IP_CT_RELATED_REPLY:
237                 if (proto == htons(ETH_P_IP) &&
238                     ip_hdr(skb)->protocol == IPPROTO_ICMP) {
239                         if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
240                                                            hooknum))
241                                 err = NF_DROP;
242                         goto out;
243                 } else if (IS_ENABLED(CONFIG_IPV6) && proto == htons(ETH_P_IPV6)) {
244                         __be16 frag_off;
245                         u8 nexthdr = ipv6_hdr(skb)->nexthdr;
246                         int hdrlen = ipv6_skip_exthdr(skb,
247                                                       sizeof(struct ipv6hdr),
248                                                       &nexthdr, &frag_off);
249
250                         if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
251                                 if (!nf_nat_icmpv6_reply_translation(skb, ct,
252                                                                      ctinfo,
253                                                                      hooknum,
254                                                                      hdrlen))
255                                         err = NF_DROP;
256                                 goto out;
257                         }
258                 }
259                 /* Non-ICMP, fall thru to initialize if needed. */
260                 /* fall through */
261         case IP_CT_NEW:
262                 /* Seen it before?  This can happen for loopback, retrans,
263                  * or local packets.
264                  */
265                 if (!nf_nat_initialized(ct, maniptype)) {
266                         /* Initialize according to the NAT action. */
267                         err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
268                                 /* Action is set up to establish a new
269                                  * mapping.
270                                  */
271                                 ? nf_nat_setup_info(ct, range, maniptype)
272                                 : nf_nat_alloc_null_binding(ct, hooknum);
273                         if (err != NF_ACCEPT)
274                                 goto out;
275                 }
276                 break;
277
278         case IP_CT_ESTABLISHED:
279         case IP_CT_ESTABLISHED_REPLY:
280                 break;
281
282         default:
283                 err = NF_DROP;
284                 goto out;
285         }
286
287         err = nf_nat_packet(ct, ctinfo, hooknum, skb);
288 out:
289         return err;
290 }
291 #endif /* CONFIG_NF_NAT */
292
293 static void tcf_ct_act_set_mark(struct nf_conn *ct, u32 mark, u32 mask)
294 {
295 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
296         u32 new_mark;
297
298         if (!mask)
299                 return;
300
301         new_mark = mark | (ct->mark & ~(mask));
302         if (ct->mark != new_mark) {
303                 ct->mark = new_mark;
304                 if (nf_ct_is_confirmed(ct))
305                         nf_conntrack_event_cache(IPCT_MARK, ct);
306         }
307 #endif
308 }
309
310 static void tcf_ct_act_set_labels(struct nf_conn *ct,
311                                   u32 *labels,
312                                   u32 *labels_m)
313 {
314 #if IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)
315         size_t labels_sz = FIELD_SIZEOF(struct tcf_ct_params, labels);
316
317         if (!memchr_inv(labels_m, 0, labels_sz))
318                 return;
319
320         nf_connlabels_replace(ct, labels, labels_m, 4);
321 #endif
322 }
323
324 static int tcf_ct_act_nat(struct sk_buff *skb,
325                           struct nf_conn *ct,
326                           enum ip_conntrack_info ctinfo,
327                           int ct_action,
328                           struct nf_nat_range2 *range,
329                           bool commit)
330 {
331 #if IS_ENABLED(CONFIG_NF_NAT)
332         int err;
333         enum nf_nat_manip_type maniptype;
334
335         if (!(ct_action & TCA_CT_ACT_NAT))
336                 return NF_ACCEPT;
337
338         /* Add NAT extension if not confirmed yet. */
339         if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
340                 return NF_DROP;   /* Can't NAT. */
341
342         if (ctinfo != IP_CT_NEW && (ct->status & IPS_NAT_MASK) &&
343             (ctinfo != IP_CT_RELATED || commit)) {
344                 /* NAT an established or related connection like before. */
345                 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
346                         /* This is the REPLY direction for a connection
347                          * for which NAT was applied in the forward
348                          * direction.  Do the reverse NAT.
349                          */
350                         maniptype = ct->status & IPS_SRC_NAT
351                                 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
352                 else
353                         maniptype = ct->status & IPS_SRC_NAT
354                                 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
355         } else if (ct_action & TCA_CT_ACT_NAT_SRC) {
356                 maniptype = NF_NAT_MANIP_SRC;
357         } else if (ct_action & TCA_CT_ACT_NAT_DST) {
358                 maniptype = NF_NAT_MANIP_DST;
359         } else {
360                 return NF_ACCEPT;
361         }
362
363         err = ct_nat_execute(skb, ct, ctinfo, range, maniptype);
364         if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
365                 if (ct->status & IPS_SRC_NAT) {
366                         if (maniptype == NF_NAT_MANIP_SRC)
367                                 maniptype = NF_NAT_MANIP_DST;
368                         else
369                                 maniptype = NF_NAT_MANIP_SRC;
370
371                         err = ct_nat_execute(skb, ct, ctinfo, range,
372                                              maniptype);
373                 } else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
374                         err = ct_nat_execute(skb, ct, ctinfo, NULL,
375                                              NF_NAT_MANIP_SRC);
376                 }
377         }
378         return err;
379 #else
380         return NF_ACCEPT;
381 #endif
382 }
383
384 static int tcf_ct_act(struct sk_buff *skb, const struct tc_action *a,
385                       struct tcf_result *res)
386 {
387         struct net *net = dev_net(skb->dev);
388         bool cached, commit, clear, force;
389         enum ip_conntrack_info ctinfo;
390         struct tcf_ct *c = to_ct(a);
391         struct nf_conn *tmpl = NULL;
392         struct nf_hook_state state;
393         int nh_ofs, err, retval;
394         struct tcf_ct_params *p;
395         struct nf_conn *ct;
396         u8 family;
397
398         p = rcu_dereference_bh(c->params);
399
400         retval = READ_ONCE(c->tcf_action);
401         commit = p->ct_action & TCA_CT_ACT_COMMIT;
402         clear = p->ct_action & TCA_CT_ACT_CLEAR;
403         force = p->ct_action & TCA_CT_ACT_FORCE;
404         tmpl = p->tmpl;
405
406         if (clear) {
407                 ct = nf_ct_get(skb, &ctinfo);
408                 if (ct) {
409                         nf_conntrack_put(&ct->ct_general);
410                         nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
411                 }
412
413                 goto out;
414         }
415
416         family = tcf_ct_skb_nf_family(skb);
417         if (family == NFPROTO_UNSPEC)
418                 goto drop;
419
420         /* The conntrack module expects to be working at L3.
421          * We also try to pull the IPv4/6 header to linear area
422          */
423         nh_ofs = skb_network_offset(skb);
424         skb_pull_rcsum(skb, nh_ofs);
425         err = tcf_ct_handle_fragments(net, skb, family, p->zone);
426         if (err == -EINPROGRESS) {
427                 retval = TC_ACT_STOLEN;
428                 goto out;
429         }
430         if (err)
431                 goto drop;
432
433         err = tcf_ct_skb_network_trim(skb, family);
434         if (err)
435                 goto drop;
436
437         /* If we are recirculating packets to match on ct fields and
438          * committing with a separate ct action, then we don't need to
439          * actually run the packet through conntrack twice unless it's for a
440          * different zone.
441          */
442         cached = tcf_ct_skb_nfct_cached(net, skb, p->zone, force);
443         if (!cached) {
444                 /* Associate skb with specified zone. */
445                 if (tmpl) {
446                         ct = nf_ct_get(skb, &ctinfo);
447                         if (skb_nfct(skb))
448                                 nf_conntrack_put(skb_nfct(skb));
449                         nf_conntrack_get(&tmpl->ct_general);
450                         nf_ct_set(skb, tmpl, IP_CT_NEW);
451                 }
452
453                 state.hook = NF_INET_PRE_ROUTING;
454                 state.net = net;
455                 state.pf = family;
456                 err = nf_conntrack_in(skb, &state);
457                 if (err != NF_ACCEPT)
458                         goto out_push;
459         }
460
461         ct = nf_ct_get(skb, &ctinfo);
462         if (!ct)
463                 goto out_push;
464         nf_ct_deliver_cached_events(ct);
465
466         err = tcf_ct_act_nat(skb, ct, ctinfo, p->ct_action, &p->range, commit);
467         if (err != NF_ACCEPT)
468                 goto drop;
469
470         if (commit) {
471                 tcf_ct_act_set_mark(ct, p->mark, p->mark_mask);
472                 tcf_ct_act_set_labels(ct, p->labels, p->labels_mask);
473
474                 /* This will take care of sending queued events
475                  * even if the connection is already confirmed.
476                  */
477                 if (nf_conntrack_confirm(skb) != NF_ACCEPT)
478                         goto drop;
479         }
480
481 out_push:
482         skb_push_rcsum(skb, nh_ofs);
483
484 out:
485         bstats_cpu_update(this_cpu_ptr(a->cpu_bstats), skb);
486         return retval;
487
488 drop:
489         qstats_drop_inc(this_cpu_ptr(a->cpu_qstats));
490         return TC_ACT_SHOT;
491 }
492
493 static const struct nla_policy ct_policy[TCA_CT_MAX + 1] = {
494         [TCA_CT_UNSPEC] = { .strict_start_type = TCA_CT_UNSPEC + 1 },
495         [TCA_CT_ACTION] = { .type = NLA_U16 },
496         [TCA_CT_PARMS] = { .type = NLA_EXACT_LEN, .len = sizeof(struct tc_ct) },
497         [TCA_CT_ZONE] = { .type = NLA_U16 },
498         [TCA_CT_MARK] = { .type = NLA_U32 },
499         [TCA_CT_MARK_MASK] = { .type = NLA_U32 },
500         [TCA_CT_LABELS] = { .type = NLA_BINARY,
501                             .len = 128 / BITS_PER_BYTE },
502         [TCA_CT_LABELS_MASK] = { .type = NLA_BINARY,
503                                  .len = 128 / BITS_PER_BYTE },
504         [TCA_CT_NAT_IPV4_MIN] = { .type = NLA_U32 },
505         [TCA_CT_NAT_IPV4_MAX] = { .type = NLA_U32 },
506         [TCA_CT_NAT_IPV6_MIN] = { .type = NLA_EXACT_LEN,
507                                   .len = sizeof(struct in6_addr) },
508         [TCA_CT_NAT_IPV6_MAX] = { .type = NLA_EXACT_LEN,
509                                    .len = sizeof(struct in6_addr) },
510         [TCA_CT_NAT_PORT_MIN] = { .type = NLA_U16 },
511         [TCA_CT_NAT_PORT_MAX] = { .type = NLA_U16 },
512 };
513
514 static int tcf_ct_fill_params_nat(struct tcf_ct_params *p,
515                                   struct tc_ct *parm,
516                                   struct nlattr **tb,
517                                   struct netlink_ext_ack *extack)
518 {
519         struct nf_nat_range2 *range;
520
521         if (!(p->ct_action & TCA_CT_ACT_NAT))
522                 return 0;
523
524         if (!IS_ENABLED(CONFIG_NF_NAT)) {
525                 NL_SET_ERR_MSG_MOD(extack, "Netfilter nat isn't enabled in kernel");
526                 return -EOPNOTSUPP;
527         }
528
529         if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
530                 return 0;
531
532         if ((p->ct_action & TCA_CT_ACT_NAT_SRC) &&
533             (p->ct_action & TCA_CT_ACT_NAT_DST)) {
534                 NL_SET_ERR_MSG_MOD(extack, "dnat and snat can't be enabled at the same time");
535                 return -EOPNOTSUPP;
536         }
537
538         range = &p->range;
539         if (tb[TCA_CT_NAT_IPV4_MIN]) {
540                 struct nlattr *max_attr = tb[TCA_CT_NAT_IPV4_MAX];
541
542                 p->ipv4_range = true;
543                 range->flags |= NF_NAT_RANGE_MAP_IPS;
544                 range->min_addr.ip =
545                         nla_get_in_addr(tb[TCA_CT_NAT_IPV4_MIN]);
546
547                 range->max_addr.ip = max_attr ?
548                                      nla_get_in_addr(max_attr) :
549                                      range->min_addr.ip;
550         } else if (tb[TCA_CT_NAT_IPV6_MIN]) {
551                 struct nlattr *max_attr = tb[TCA_CT_NAT_IPV6_MAX];
552
553                 p->ipv4_range = false;
554                 range->flags |= NF_NAT_RANGE_MAP_IPS;
555                 range->min_addr.in6 =
556                         nla_get_in6_addr(tb[TCA_CT_NAT_IPV6_MIN]);
557
558                 range->max_addr.in6 = max_attr ?
559                                       nla_get_in6_addr(max_attr) :
560                                       range->min_addr.in6;
561         }
562
563         if (tb[TCA_CT_NAT_PORT_MIN]) {
564                 range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
565                 range->min_proto.all = nla_get_be16(tb[TCA_CT_NAT_PORT_MIN]);
566
567                 range->max_proto.all = tb[TCA_CT_NAT_PORT_MAX] ?
568                                        nla_get_be16(tb[TCA_CT_NAT_PORT_MAX]) :
569                                        range->min_proto.all;
570         }
571
572         return 0;
573 }
574
575 static void tcf_ct_set_key_val(struct nlattr **tb,
576                                void *val, int val_type,
577                                void *mask, int mask_type,
578                                int len)
579 {
580         if (!tb[val_type])
581                 return;
582         nla_memcpy(val, tb[val_type], len);
583
584         if (!mask)
585                 return;
586
587         if (mask_type == TCA_CT_UNSPEC || !tb[mask_type])
588                 memset(mask, 0xff, len);
589         else
590                 nla_memcpy(mask, tb[mask_type], len);
591 }
592
593 static int tcf_ct_fill_params(struct net *net,
594                               struct tcf_ct_params *p,
595                               struct tc_ct *parm,
596                               struct nlattr **tb,
597                               struct netlink_ext_ack *extack)
598 {
599         struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
600         struct nf_conntrack_zone zone;
601         struct nf_conn *tmpl;
602         int err;
603
604         p->zone = NF_CT_DEFAULT_ZONE_ID;
605
606         tcf_ct_set_key_val(tb,
607                            &p->ct_action, TCA_CT_ACTION,
608                            NULL, TCA_CT_UNSPEC,
609                            sizeof(p->ct_action));
610
611         if (p->ct_action & TCA_CT_ACT_CLEAR)
612                 return 0;
613
614         err = tcf_ct_fill_params_nat(p, parm, tb, extack);
615         if (err)
616                 return err;
617
618         if (tb[TCA_CT_MARK]) {
619                 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)) {
620                         NL_SET_ERR_MSG_MOD(extack, "Conntrack mark isn't enabled.");
621                         return -EOPNOTSUPP;
622                 }
623                 tcf_ct_set_key_val(tb,
624                                    &p->mark, TCA_CT_MARK,
625                                    &p->mark_mask, TCA_CT_MARK_MASK,
626                                    sizeof(p->mark));
627         }
628
629         if (tb[TCA_CT_LABELS]) {
630                 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS)) {
631                         NL_SET_ERR_MSG_MOD(extack, "Conntrack labels isn't enabled.");
632                         return -EOPNOTSUPP;
633                 }
634
635                 if (!tn->labels) {
636                         NL_SET_ERR_MSG_MOD(extack, "Failed to set connlabel length");
637                         return -EOPNOTSUPP;
638                 }
639                 tcf_ct_set_key_val(tb,
640                                    p->labels, TCA_CT_LABELS,
641                                    p->labels_mask, TCA_CT_LABELS_MASK,
642                                    sizeof(p->labels));
643         }
644
645         if (tb[TCA_CT_ZONE]) {
646                 if (!IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES)) {
647                         NL_SET_ERR_MSG_MOD(extack, "Conntrack zones isn't enabled.");
648                         return -EOPNOTSUPP;
649                 }
650
651                 tcf_ct_set_key_val(tb,
652                                    &p->zone, TCA_CT_ZONE,
653                                    NULL, TCA_CT_UNSPEC,
654                                    sizeof(p->zone));
655         }
656
657         nf_ct_zone_init(&zone, p->zone, NF_CT_DEFAULT_ZONE_DIR, 0);
658         tmpl = nf_ct_tmpl_alloc(net, &zone, GFP_KERNEL);
659         if (!tmpl) {
660                 NL_SET_ERR_MSG_MOD(extack, "Failed to allocate conntrack template");
661                 return -ENOMEM;
662         }
663         __set_bit(IPS_CONFIRMED_BIT, &tmpl->status);
664         nf_conntrack_get(&tmpl->ct_general);
665         p->tmpl = tmpl;
666
667         return 0;
668 }
669
670 static int tcf_ct_init(struct net *net, struct nlattr *nla,
671                        struct nlattr *est, struct tc_action **a,
672                        int replace, int bind, bool rtnl_held,
673                        struct tcf_proto *tp,
674                        struct netlink_ext_ack *extack)
675 {
676         struct tc_action_net *tn = net_generic(net, ct_net_id);
677         struct tcf_ct_params *params = NULL;
678         struct nlattr *tb[TCA_CT_MAX + 1];
679         struct tcf_chain *goto_ch = NULL;
680         struct tc_ct *parm;
681         struct tcf_ct *c;
682         int err, res = 0;
683         u32 index;
684
685         if (!nla) {
686                 NL_SET_ERR_MSG_MOD(extack, "Ct requires attributes to be passed");
687                 return -EINVAL;
688         }
689
690         err = nla_parse_nested(tb, TCA_CT_MAX, nla, ct_policy, extack);
691         if (err < 0)
692                 return err;
693
694         if (!tb[TCA_CT_PARMS]) {
695                 NL_SET_ERR_MSG_MOD(extack, "Missing required ct parameters");
696                 return -EINVAL;
697         }
698         parm = nla_data(tb[TCA_CT_PARMS]);
699         index = parm->index;
700         err = tcf_idr_check_alloc(tn, &index, a, bind);
701         if (err < 0)
702                 return err;
703
704         if (!err) {
705                 err = tcf_idr_create(tn, index, est, a,
706                                      &act_ct_ops, bind, true);
707                 if (err) {
708                         tcf_idr_cleanup(tn, index);
709                         return err;
710                 }
711                 res = ACT_P_CREATED;
712         } else {
713                 if (bind)
714                         return 0;
715
716                 if (!replace) {
717                         tcf_idr_release(*a, bind);
718                         return -EEXIST;
719                 }
720         }
721         err = tcf_action_check_ctrlact(parm->action, tp, &goto_ch, extack);
722         if (err < 0)
723                 goto cleanup;
724
725         c = to_ct(*a);
726
727         params = kzalloc(sizeof(*params), GFP_KERNEL);
728         if (unlikely(!params)) {
729                 err = -ENOMEM;
730                 goto cleanup;
731         }
732
733         err = tcf_ct_fill_params(net, params, parm, tb, extack);
734         if (err)
735                 goto cleanup;
736
737         spin_lock_bh(&c->tcf_lock);
738         goto_ch = tcf_action_set_ctrlact(*a, parm->action, goto_ch);
739         rcu_swap_protected(c->params, params, lockdep_is_held(&c->tcf_lock));
740         spin_unlock_bh(&c->tcf_lock);
741
742         if (goto_ch)
743                 tcf_chain_put_by_act(goto_ch);
744         if (params)
745                 call_rcu(&params->rcu, tcf_ct_params_free);
746
747         return res;
748
749 cleanup:
750         if (goto_ch)
751                 tcf_chain_put_by_act(goto_ch);
752         kfree(params);
753         tcf_idr_release(*a, bind);
754         return err;
755 }
756
757 static void tcf_ct_cleanup(struct tc_action *a)
758 {
759         struct tcf_ct_params *params;
760         struct tcf_ct *c = to_ct(a);
761
762         params = rcu_dereference_protected(c->params, 1);
763         if (params)
764                 call_rcu(&params->rcu, tcf_ct_params_free);
765 }
766
767 static int tcf_ct_dump_key_val(struct sk_buff *skb,
768                                void *val, int val_type,
769                                void *mask, int mask_type,
770                                int len)
771 {
772         int err;
773
774         if (mask && !memchr_inv(mask, 0, len))
775                 return 0;
776
777         err = nla_put(skb, val_type, len, val);
778         if (err)
779                 return err;
780
781         if (mask_type != TCA_CT_UNSPEC) {
782                 err = nla_put(skb, mask_type, len, mask);
783                 if (err)
784                         return err;
785         }
786
787         return 0;
788 }
789
790 static int tcf_ct_dump_nat(struct sk_buff *skb, struct tcf_ct_params *p)
791 {
792         struct nf_nat_range2 *range = &p->range;
793
794         if (!(p->ct_action & TCA_CT_ACT_NAT))
795                 return 0;
796
797         if (!(p->ct_action & (TCA_CT_ACT_NAT_SRC | TCA_CT_ACT_NAT_DST)))
798                 return 0;
799
800         if (range->flags & NF_NAT_RANGE_MAP_IPS) {
801                 if (p->ipv4_range) {
802                         if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MIN,
803                                             range->min_addr.ip))
804                                 return -1;
805                         if (nla_put_in_addr(skb, TCA_CT_NAT_IPV4_MAX,
806                                             range->max_addr.ip))
807                                 return -1;
808                 } else {
809                         if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MIN,
810                                              &range->min_addr.in6))
811                                 return -1;
812                         if (nla_put_in6_addr(skb, TCA_CT_NAT_IPV6_MAX,
813                                              &range->max_addr.in6))
814                                 return -1;
815                 }
816         }
817
818         if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
819                 if (nla_put_be16(skb, TCA_CT_NAT_PORT_MIN,
820                                  range->min_proto.all))
821                         return -1;
822                 if (nla_put_be16(skb, TCA_CT_NAT_PORT_MAX,
823                                  range->max_proto.all))
824                         return -1;
825         }
826
827         return 0;
828 }
829
830 static inline int tcf_ct_dump(struct sk_buff *skb, struct tc_action *a,
831                               int bind, int ref)
832 {
833         unsigned char *b = skb_tail_pointer(skb);
834         struct tcf_ct *c = to_ct(a);
835         struct tcf_ct_params *p;
836
837         struct tc_ct opt = {
838                 .index   = c->tcf_index,
839                 .refcnt  = refcount_read(&c->tcf_refcnt) - ref,
840                 .bindcnt = atomic_read(&c->tcf_bindcnt) - bind,
841         };
842         struct tcf_t t;
843
844         spin_lock_bh(&c->tcf_lock);
845         p = rcu_dereference_protected(c->params,
846                                       lockdep_is_held(&c->tcf_lock));
847         opt.action = c->tcf_action;
848
849         if (tcf_ct_dump_key_val(skb,
850                                 &p->ct_action, TCA_CT_ACTION,
851                                 NULL, TCA_CT_UNSPEC,
852                                 sizeof(p->ct_action)))
853                 goto nla_put_failure;
854
855         if (p->ct_action & TCA_CT_ACT_CLEAR)
856                 goto skip_dump;
857
858         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
859             tcf_ct_dump_key_val(skb,
860                                 &p->mark, TCA_CT_MARK,
861                                 &p->mark_mask, TCA_CT_MARK_MASK,
862                                 sizeof(p->mark)))
863                 goto nla_put_failure;
864
865         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
866             tcf_ct_dump_key_val(skb,
867                                 p->labels, TCA_CT_LABELS,
868                                 p->labels_mask, TCA_CT_LABELS_MASK,
869                                 sizeof(p->labels)))
870                 goto nla_put_failure;
871
872         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
873             tcf_ct_dump_key_val(skb,
874                                 &p->zone, TCA_CT_ZONE,
875                                 NULL, TCA_CT_UNSPEC,
876                                 sizeof(p->zone)))
877                 goto nla_put_failure;
878
879         if (tcf_ct_dump_nat(skb, p))
880                 goto nla_put_failure;
881
882 skip_dump:
883         if (nla_put(skb, TCA_CT_PARMS, sizeof(opt), &opt))
884                 goto nla_put_failure;
885
886         tcf_tm_dump(&t, &c->tcf_tm);
887         if (nla_put_64bit(skb, TCA_CT_TM, sizeof(t), &t, TCA_CT_PAD))
888                 goto nla_put_failure;
889         spin_unlock_bh(&c->tcf_lock);
890
891         return skb->len;
892 nla_put_failure:
893         spin_unlock_bh(&c->tcf_lock);
894         nlmsg_trim(skb, b);
895         return -1;
896 }
897
898 static int tcf_ct_walker(struct net *net, struct sk_buff *skb,
899                          struct netlink_callback *cb, int type,
900                          const struct tc_action_ops *ops,
901                          struct netlink_ext_ack *extack)
902 {
903         struct tc_action_net *tn = net_generic(net, ct_net_id);
904
905         return tcf_generic_walker(tn, skb, cb, type, ops, extack);
906 }
907
908 static int tcf_ct_search(struct net *net, struct tc_action **a, u32 index)
909 {
910         struct tc_action_net *tn = net_generic(net, ct_net_id);
911
912         return tcf_idr_search(tn, a, index);
913 }
914
915 static void tcf_stats_update(struct tc_action *a, u64 bytes, u32 packets,
916                              u64 lastuse, bool hw)
917 {
918         struct tcf_ct *c = to_ct(a);
919
920         _bstats_cpu_update(this_cpu_ptr(a->cpu_bstats), bytes, packets);
921
922         if (hw)
923                 _bstats_cpu_update(this_cpu_ptr(a->cpu_bstats_hw),
924                                    bytes, packets);
925         c->tcf_tm.lastuse = max_t(u64, c->tcf_tm.lastuse, lastuse);
926 }
927
928 static struct tc_action_ops act_ct_ops = {
929         .kind           =       "ct",
930         .id             =       TCA_ID_CT,
931         .owner          =       THIS_MODULE,
932         .act            =       tcf_ct_act,
933         .dump           =       tcf_ct_dump,
934         .init           =       tcf_ct_init,
935         .cleanup        =       tcf_ct_cleanup,
936         .walk           =       tcf_ct_walker,
937         .lookup         =       tcf_ct_search,
938         .stats_update   =       tcf_stats_update,
939         .size           =       sizeof(struct tcf_ct),
940 };
941
942 static __net_init int ct_init_net(struct net *net)
943 {
944         unsigned int n_bits = FIELD_SIZEOF(struct tcf_ct_params, labels) * 8;
945         struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
946
947         if (nf_connlabels_get(net, n_bits - 1)) {
948                 tn->labels = false;
949                 pr_err("act_ct: Failed to set connlabels length");
950         } else {
951                 tn->labels = true;
952         }
953
954         return tc_action_net_init(net, &tn->tn, &act_ct_ops);
955 }
956
957 static void __net_exit ct_exit_net(struct list_head *net_list)
958 {
959         struct net *net;
960
961         rtnl_lock();
962         list_for_each_entry(net, net_list, exit_list) {
963                 struct tc_ct_action_net *tn = net_generic(net, ct_net_id);
964
965                 if (tn->labels)
966                         nf_connlabels_put(net);
967         }
968         rtnl_unlock();
969
970         tc_action_net_exit(net_list, ct_net_id);
971 }
972
973 static struct pernet_operations ct_net_ops = {
974         .init = ct_init_net,
975         .exit_batch = ct_exit_net,
976         .id   = &ct_net_id,
977         .size = sizeof(struct tc_ct_action_net),
978 };
979
980 static int __init ct_init_module(void)
981 {
982         return tcf_register_action(&act_ct_ops, &ct_net_ops);
983 }
984
985 static void __exit ct_cleanup_module(void)
986 {
987         tcf_unregister_action(&act_ct_ops, &ct_net_ops);
988 }
989
990 module_init(ct_init_module);
991 module_exit(ct_cleanup_module);
992 MODULE_AUTHOR("Paul Blakey <paulb@mellanox.com>");
993 MODULE_AUTHOR("Yossi Kuperman <yossiku@mellanox.com>");
994 MODULE_AUTHOR("Marcelo Ricardo Leitner <marcelo.leitner@gmail.com>");
995 MODULE_DESCRIPTION("Connection tracking action");
996 MODULE_LICENSE("GPL v2");