2 * Copyright (c) 2015 Nicira, Inc.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
14 #include <linux/module.h>
15 #include <linux/openvswitch.h>
16 #include <linux/tcp.h>
17 #include <linux/udp.h>
18 #include <linux/sctp.h>
20 #include <net/netfilter/nf_conntrack_core.h>
21 #include <net/netfilter/nf_conntrack_helper.h>
22 #include <net/netfilter/nf_conntrack_labels.h>
23 #include <net/netfilter/nf_conntrack_seqadj.h>
24 #include <net/netfilter/nf_conntrack_zones.h>
25 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
26 #include <net/ipv6_frag.h>
28 #ifdef CONFIG_NF_NAT_NEEDED
29 #include <linux/netfilter/nf_nat.h>
30 #include <net/netfilter/nf_nat_core.h>
31 #include <net/netfilter/nf_nat_l3proto.h>
35 #include "conntrack.h"
37 #include "flow_netlink.h"
39 struct ovs_ct_len_tbl {
44 /* Metadata mark for masked write to conntrack mark */
50 /* Metadata label for masked write to conntrack label. */
52 struct ovs_key_ct_labels value;
53 struct ovs_key_ct_labels mask;
57 OVS_CT_NAT = 1 << 0, /* NAT for committed connections only. */
58 OVS_CT_SRC_NAT = 1 << 1, /* Source NAT for NEW connections. */
59 OVS_CT_DST_NAT = 1 << 2, /* Destination NAT for NEW connections. */
62 /* Conntrack action context for execution. */
63 struct ovs_conntrack_info {
64 struct nf_conntrack_helper *helper;
65 struct nf_conntrack_zone zone;
68 u8 nat : 3; /* enum ovs_ct_nat */
71 struct md_labels labels;
72 #ifdef CONFIG_NF_NAT_NEEDED
73 struct nf_nat_range range; /* Only present for SRC NAT and DST NAT. */
77 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
79 static u16 key_to_nfproto(const struct sw_flow_key *key)
81 switch (ntohs(key->eth.type)) {
87 return NFPROTO_UNSPEC;
91 /* Map SKB connection state into the values used by flow definition. */
92 static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
94 u8 ct_state = OVS_CS_F_TRACKED;
97 case IP_CT_ESTABLISHED_REPLY:
98 case IP_CT_RELATED_REPLY:
99 ct_state |= OVS_CS_F_REPLY_DIR;
106 case IP_CT_ESTABLISHED:
107 case IP_CT_ESTABLISHED_REPLY:
108 ct_state |= OVS_CS_F_ESTABLISHED;
111 case IP_CT_RELATED_REPLY:
112 ct_state |= OVS_CS_F_RELATED;
115 ct_state |= OVS_CS_F_NEW;
124 static u32 ovs_ct_get_mark(const struct nf_conn *ct)
126 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
127 return ct ? ct->mark : 0;
133 static void ovs_ct_get_labels(const struct nf_conn *ct,
134 struct ovs_key_ct_labels *labels)
136 struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
139 size_t len = sizeof(cl->bits);
141 if (len > OVS_CT_LABELS_LEN)
142 len = OVS_CT_LABELS_LEN;
143 else if (len < OVS_CT_LABELS_LEN)
144 memset(labels, 0, OVS_CT_LABELS_LEN);
145 memcpy(labels, cl->bits, len);
147 memset(labels, 0, OVS_CT_LABELS_LEN);
151 static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
152 const struct nf_conntrack_zone *zone,
153 const struct nf_conn *ct)
155 key->ct.state = state;
156 key->ct.zone = zone->id;
157 key->ct.mark = ovs_ct_get_mark(ct);
158 ovs_ct_get_labels(ct, &key->ct.labels);
161 /* Update 'key' based on skb->nfct. If 'post_ct' is true, then OVS has
162 * previously sent the packet to conntrack via the ct action. If
163 * 'keep_nat_flags' is true, the existing NAT flags retained, else they are
164 * initialized from the connection status.
166 static void ovs_ct_update_key(const struct sk_buff *skb,
167 const struct ovs_conntrack_info *info,
168 struct sw_flow_key *key, bool post_ct,
171 const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
172 enum ip_conntrack_info ctinfo;
176 ct = nf_ct_get(skb, &ctinfo);
178 state = ovs_ct_get_state(ctinfo);
179 /* All unconfirmed entries are NEW connections. */
180 if (!nf_ct_is_confirmed(ct))
181 state |= OVS_CS_F_NEW;
182 /* OVS persists the related flag for the duration of the
186 state |= OVS_CS_F_RELATED;
187 if (keep_nat_flags) {
188 state |= key->ct.state & OVS_CS_F_NAT_MASK;
190 if (ct->status & IPS_SRC_NAT)
191 state |= OVS_CS_F_SRC_NAT;
192 if (ct->status & IPS_DST_NAT)
193 state |= OVS_CS_F_DST_NAT;
195 zone = nf_ct_zone(ct);
196 } else if (post_ct) {
197 state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
201 __ovs_ct_update_key(key, state, zone, ct);
204 /* This is called to initialize CT key fields possibly coming in from the local
207 void ovs_ct_fill_key(const struct sk_buff *skb, struct sw_flow_key *key)
209 ovs_ct_update_key(skb, NULL, key, false, false);
212 int ovs_ct_put_key(const struct sw_flow_key *key, struct sk_buff *skb)
214 if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, key->ct.state))
217 if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
218 nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, key->ct.zone))
221 if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
222 nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, key->ct.mark))
225 if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
226 nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(key->ct.labels),
233 static int ovs_ct_set_mark(struct sk_buff *skb, struct sw_flow_key *key,
234 u32 ct_mark, u32 mask)
236 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
237 enum ip_conntrack_info ctinfo;
241 /* The connection could be invalid, in which case set_mark is no-op. */
242 ct = nf_ct_get(skb, &ctinfo);
246 new_mark = ct_mark | (ct->mark & ~(mask));
247 if (ct->mark != new_mark) {
249 nf_conntrack_event_cache(IPCT_MARK, ct);
250 key->ct.mark = new_mark;
259 static int ovs_ct_set_labels(struct sk_buff *skb, struct sw_flow_key *key,
260 const struct ovs_key_ct_labels *labels,
261 const struct ovs_key_ct_labels *mask)
263 enum ip_conntrack_info ctinfo;
264 struct nf_conn_labels *cl;
268 /* The connection could be invalid, in which case set_label is no-op.*/
269 ct = nf_ct_get(skb, &ctinfo);
273 cl = nf_ct_labels_find(ct);
275 nf_ct_labels_ext_add(ct);
276 cl = nf_ct_labels_find(ct);
278 if (!cl || sizeof(cl->bits) < OVS_CT_LABELS_LEN)
281 err = nf_connlabels_replace(ct, (u32 *)labels, (u32 *)mask,
282 OVS_CT_LABELS_LEN / sizeof(u32));
286 ovs_ct_get_labels(ct, &key->ct.labels);
290 /* 'skb' should already be pulled to nh_ofs. */
291 static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
293 const struct nf_conntrack_helper *helper;
294 const struct nf_conn_help *help;
295 enum ip_conntrack_info ctinfo;
296 unsigned int protoff;
300 ct = nf_ct_get(skb, &ctinfo);
301 if (!ct || ctinfo == IP_CT_RELATED_REPLY)
304 help = nfct_help(ct);
308 helper = rcu_dereference(help->helper);
314 protoff = ip_hdrlen(skb);
317 u8 nexthdr = ipv6_hdr(skb)->nexthdr;
321 ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
323 if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
324 pr_debug("proto header not found\n");
331 WARN_ONCE(1, "helper invoked on non-IP family!");
335 err = helper->help(skb, protoff, ct, ctinfo);
336 if (err != NF_ACCEPT)
339 /* Adjust seqs after helper. This is needed due to some helpers (e.g.,
340 * FTP with NAT) adusting the TCP payload size when mangling IP
341 * addresses and/or port numbers in the text-based control connection.
343 if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
344 !nf_ct_seq_adjust(skb, ct, ctinfo, protoff))
349 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
350 * value if 'skb' is freed.
352 static int handle_fragments(struct net *net, struct sw_flow_key *key,
353 u16 zone, struct sk_buff *skb)
355 struct ovs_skb_cb ovs_cb = *OVS_CB(skb);
358 if (key->eth.type == htons(ETH_P_IP)) {
359 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
361 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
362 err = ip_defrag(net, skb, user);
366 ovs_cb.mru = IPCB(skb)->frag_max_size;
367 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
368 } else if (key->eth.type == htons(ETH_P_IPV6)) {
369 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
371 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
372 err = nf_ct_frag6_gather(net, skb, user);
374 if (err != -EINPROGRESS)
379 key->ip.proto = ipv6_hdr(skb)->nexthdr;
380 ovs_cb.mru = IP6CB(skb)->frag_max_size;
384 return -EPFNOSUPPORT;
387 key->ip.frag = OVS_FRAG_TYPE_NONE;
390 *OVS_CB(skb) = ovs_cb;
395 static struct nf_conntrack_expect *
396 ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
397 u16 proto, const struct sk_buff *skb)
399 struct nf_conntrack_tuple tuple;
400 struct nf_conntrack_expect *exp;
402 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
405 exp = __nf_ct_expect_find(net, zone, &tuple);
407 struct nf_conntrack_tuple_hash *h;
409 /* Delete existing conntrack entry, if it clashes with the
410 * expectation. This can happen since conntrack ALGs do not
411 * check for clashes between (new) expectations and existing
412 * conntrack entries. nf_conntrack_in() will check the
413 * expectations only if a conntrack entry can not be found,
414 * which can lead to OVS finding the expectation (here) in the
415 * init direction, but which will not be removed by the
416 * nf_conntrack_in() call, if a matching conntrack entry is
417 * found instead. In this case all init direction packets
418 * would be reported as new related packets, while reply
419 * direction packets would be reported as un-related
420 * established packets.
422 h = nf_conntrack_find_get(net, zone, &tuple);
424 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
426 nf_ct_delete(ct, 0, 0);
427 nf_conntrack_put(&ct->ct_general);
434 /* This replicates logic from nf_conntrack_core.c that is not exported. */
435 static enum ip_conntrack_info
436 ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
438 const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
440 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
441 return IP_CT_ESTABLISHED_REPLY;
442 /* Once we've had two way comms, always ESTABLISHED. */
443 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
444 return IP_CT_ESTABLISHED;
445 if (test_bit(IPS_EXPECTED_BIT, &ct->status))
446 return IP_CT_RELATED;
450 /* Find an existing connection which this packet belongs to without
451 * re-attributing statistics or modifying the connection state. This allows an
452 * skb->nfct lost due to an upcall to be recovered during actions execution.
454 * Must be called with rcu_read_lock.
456 * On success, populates skb->nfct and skb->nfctinfo, and returns the
457 * connection. Returns NULL if there is no existing entry.
459 static struct nf_conn *
460 ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
461 u8 l3num, struct sk_buff *skb)
463 struct nf_conntrack_l3proto *l3proto;
464 struct nf_conntrack_l4proto *l4proto;
465 struct nf_conntrack_tuple tuple;
466 struct nf_conntrack_tuple_hash *h;
468 unsigned int dataoff;
471 l3proto = __nf_ct_l3proto_find(l3num);
472 if (l3proto->get_l4proto(skb, skb_network_offset(skb), &dataoff,
474 pr_debug("ovs_ct_find_existing: Can't get protonum\n");
477 l4proto = __nf_ct_l4proto_find(l3num, protonum);
478 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
479 protonum, net, &tuple, l3proto, l4proto)) {
480 pr_debug("ovs_ct_find_existing: Can't get tuple\n");
484 /* look for tuple match */
485 h = nf_conntrack_find_get(net, zone, &tuple);
487 return NULL; /* Not found. */
489 ct = nf_ct_tuplehash_to_ctrack(h);
491 skb->nfct = &ct->ct_general;
492 skb->nfctinfo = ovs_ct_get_info(h);
496 /* Determine whether skb->nfct is equal to the result of conntrack lookup. */
497 static bool skb_nfct_cached(struct net *net,
498 const struct sw_flow_key *key,
499 const struct ovs_conntrack_info *info,
502 enum ip_conntrack_info ctinfo;
505 ct = nf_ct_get(skb, &ctinfo);
506 /* If no ct, check if we have evidence that an existing conntrack entry
507 * might be found for this skb. This happens when we lose a skb->nfct
508 * due to an upcall. If the connection was not confirmed, it is not
509 * cached and needs to be run through conntrack again.
511 if (!ct && key->ct.state & OVS_CS_F_TRACKED &&
512 !(key->ct.state & OVS_CS_F_INVALID) &&
513 key->ct.zone == info->zone.id)
514 ct = ovs_ct_find_existing(net, &info->zone, info->family, skb);
517 if (!net_eq(net, read_pnet(&ct->ct_net)))
519 if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
522 struct nf_conn_help *help;
524 help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
525 if (help && rcu_access_pointer(help->helper) != info->helper)
532 #ifdef CONFIG_NF_NAT_NEEDED
533 /* Modelled after nf_nat_ipv[46]_fn().
534 * range is only used for new, uninitialized NAT state.
535 * Returns either NF_ACCEPT or NF_DROP.
537 static int ovs_ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
538 enum ip_conntrack_info ctinfo,
539 const struct nf_nat_range *range,
540 enum nf_nat_manip_type maniptype)
542 int hooknum, nh_off, err = NF_ACCEPT;
544 nh_off = skb_network_offset(skb);
545 skb_pull_rcsum(skb, nh_off);
547 /* See HOOK2MANIP(). */
548 if (maniptype == NF_NAT_MANIP_SRC)
549 hooknum = NF_INET_LOCAL_IN; /* Source NAT */
551 hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
555 case IP_CT_RELATED_REPLY:
556 if (IS_ENABLED(CONFIG_NF_NAT_IPV4) &&
557 skb->protocol == htons(ETH_P_IP) &&
558 ip_hdr(skb)->protocol == IPPROTO_ICMP) {
559 if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
563 } else if (IS_ENABLED(CONFIG_NF_NAT_IPV6) &&
564 skb->protocol == htons(ETH_P_IPV6)) {
566 u8 nexthdr = ipv6_hdr(skb)->nexthdr;
567 int hdrlen = ipv6_skip_exthdr(skb,
568 sizeof(struct ipv6hdr),
569 &nexthdr, &frag_off);
571 if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
572 if (!nf_nat_icmpv6_reply_translation(skb, ct,
580 /* Non-ICMP, fall thru to initialize if needed. */
582 /* Seen it before? This can happen for loopback, retrans,
585 if (!nf_nat_initialized(ct, maniptype)) {
586 /* Initialize according to the NAT action. */
587 err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
588 /* Action is set up to establish a new
591 ? nf_nat_setup_info(ct, range, maniptype)
592 : nf_nat_alloc_null_binding(ct, hooknum);
593 if (err != NF_ACCEPT)
598 case IP_CT_ESTABLISHED:
599 case IP_CT_ESTABLISHED_REPLY:
607 err = nf_nat_packet(ct, ctinfo, hooknum, skb);
609 skb_push(skb, nh_off);
610 skb_postpush_rcsum(skb, skb->data, nh_off);
615 static void ovs_nat_update_key(struct sw_flow_key *key,
616 const struct sk_buff *skb,
617 enum nf_nat_manip_type maniptype)
619 if (maniptype == NF_NAT_MANIP_SRC) {
622 key->ct.state |= OVS_CS_F_SRC_NAT;
623 if (key->eth.type == htons(ETH_P_IP))
624 key->ipv4.addr.src = ip_hdr(skb)->saddr;
625 else if (key->eth.type == htons(ETH_P_IPV6))
626 memcpy(&key->ipv6.addr.src, &ipv6_hdr(skb)->saddr,
627 sizeof(key->ipv6.addr.src));
631 if (key->ip.proto == IPPROTO_UDP)
632 src = udp_hdr(skb)->source;
633 else if (key->ip.proto == IPPROTO_TCP)
634 src = tcp_hdr(skb)->source;
635 else if (key->ip.proto == IPPROTO_SCTP)
636 src = sctp_hdr(skb)->source;
644 key->ct.state |= OVS_CS_F_DST_NAT;
645 if (key->eth.type == htons(ETH_P_IP))
646 key->ipv4.addr.dst = ip_hdr(skb)->daddr;
647 else if (key->eth.type == htons(ETH_P_IPV6))
648 memcpy(&key->ipv6.addr.dst, &ipv6_hdr(skb)->daddr,
649 sizeof(key->ipv6.addr.dst));
653 if (key->ip.proto == IPPROTO_UDP)
654 dst = udp_hdr(skb)->dest;
655 else if (key->ip.proto == IPPROTO_TCP)
656 dst = tcp_hdr(skb)->dest;
657 else if (key->ip.proto == IPPROTO_SCTP)
658 dst = sctp_hdr(skb)->dest;
666 /* Returns NF_DROP if the packet should be dropped, NF_ACCEPT otherwise. */
667 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
668 const struct ovs_conntrack_info *info,
669 struct sk_buff *skb, struct nf_conn *ct,
670 enum ip_conntrack_info ctinfo)
672 enum nf_nat_manip_type maniptype;
675 if (nf_ct_is_untracked(ct)) {
676 /* A NAT action may only be performed on tracked packets. */
680 /* Add NAT extension if not confirmed yet. */
681 if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
682 return NF_ACCEPT; /* Can't NAT. */
684 /* Determine NAT type.
685 * Check if the NAT type can be deduced from the tracked connection.
686 * Make sure new expected connections (IP_CT_RELATED) are NATted only
689 if (info->nat & OVS_CT_NAT && ctinfo != IP_CT_NEW &&
690 ct->status & IPS_NAT_MASK &&
691 (ctinfo != IP_CT_RELATED || info->commit)) {
692 /* NAT an established or related connection like before. */
693 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
694 /* This is the REPLY direction for a connection
695 * for which NAT was applied in the forward
696 * direction. Do the reverse NAT.
698 maniptype = ct->status & IPS_SRC_NAT
699 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
701 maniptype = ct->status & IPS_SRC_NAT
702 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
703 } else if (info->nat & OVS_CT_SRC_NAT) {
704 maniptype = NF_NAT_MANIP_SRC;
705 } else if (info->nat & OVS_CT_DST_NAT) {
706 maniptype = NF_NAT_MANIP_DST;
708 return NF_ACCEPT; /* Connection is not NATed. */
710 err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range, maniptype);
712 if (err == NF_ACCEPT && ct->status & IPS_DST_NAT) {
713 if (ct->status & IPS_SRC_NAT) {
714 if (maniptype == NF_NAT_MANIP_SRC)
715 maniptype = NF_NAT_MANIP_DST;
717 maniptype = NF_NAT_MANIP_SRC;
719 err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range,
721 } else if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL) {
722 err = ovs_ct_nat_execute(skb, ct, ctinfo, NULL,
727 /* Mark NAT done if successful and update the flow key. */
728 if (err == NF_ACCEPT)
729 ovs_nat_update_key(key, skb, maniptype);
733 #else /* !CONFIG_NF_NAT_NEEDED */
734 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
735 const struct ovs_conntrack_info *info,
736 struct sk_buff *skb, struct nf_conn *ct,
737 enum ip_conntrack_info ctinfo)
743 /* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
744 * not done already. Update key with new CT state after passing the packet
746 * Note that if the packet is deemed invalid by conntrack, skb->nfct will be
747 * set to NULL and 0 will be returned.
749 static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
750 const struct ovs_conntrack_info *info,
753 /* If we are recirculating packets to match on conntrack fields and
754 * committing with a separate conntrack action, then we don't need to
755 * actually run the packet through conntrack twice unless it's for a
758 bool cached = skb_nfct_cached(net, key, info, skb);
759 enum ip_conntrack_info ctinfo;
763 struct nf_conn *tmpl = info->ct;
766 /* Associate skb with specified zone. */
769 nf_conntrack_put(skb->nfct);
770 nf_conntrack_get(&tmpl->ct_general);
771 skb->nfct = &tmpl->ct_general;
772 skb->nfctinfo = IP_CT_NEW;
775 /* Repeat if requested, see nf_iterate(). */
777 err = nf_conntrack_in(net, info->family,
778 NF_INET_PRE_ROUTING, skb);
779 } while (err == NF_REPEAT);
781 if (err != NF_ACCEPT)
784 /* Clear CT state NAT flags to mark that we have not yet done
785 * NAT after the nf_conntrack_in() call. We can actually clear
786 * the whole state, as it will be re-initialized below.
790 /* Update the key, but keep the NAT flags. */
791 ovs_ct_update_key(skb, info, key, true, true);
794 ct = nf_ct_get(skb, &ctinfo);
796 /* Packets starting a new connection must be NATted before the
797 * helper, so that the helper knows about the NAT. We enforce
798 * this by delaying both NAT and helper calls for unconfirmed
799 * connections until the committing CT action. For later
800 * packets NAT and Helper may be called in either order.
802 * NAT will be done only if the CT action has NAT, and only
803 * once per packet (per zone), as guarded by the NAT bits in
806 if (info->nat && !(key->ct.state & OVS_CS_F_NAT_MASK) &&
807 (nf_ct_is_confirmed(ct) || info->commit) &&
808 ovs_ct_nat(net, key, info, skb, ct, ctinfo) != NF_ACCEPT) {
812 /* Userspace may decide to perform a ct lookup without a helper
813 * specified followed by a (recirculate and) commit with one.
814 * Therefore, for unconfirmed connections which we will commit,
815 * we need to attach the helper here.
817 if (!nf_ct_is_confirmed(ct) && info->commit &&
818 info->helper && !nfct_help(ct)) {
819 int err = __nf_ct_try_assign_helper(ct, info->ct,
825 /* Call the helper only if:
826 * - nf_conntrack_in() was executed above ("!cached") for a
827 * confirmed connection, or
828 * - When committing an unconfirmed connection.
830 if ((nf_ct_is_confirmed(ct) ? !cached : info->commit) &&
831 ovs_ct_helper(skb, info->family) != NF_ACCEPT) {
839 /* Lookup connection and read fields into key. */
840 static int ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
841 const struct ovs_conntrack_info *info,
844 struct nf_conntrack_expect *exp;
846 /* If we pass an expected packet through nf_conntrack_in() the
847 * expectation is typically removed, but the packet could still be
848 * lost in upcall processing. To prevent this from happening we
849 * perform an explicit expectation lookup. Expected connections are
850 * always new, and will be passed through conntrack only when they are
851 * committed, as it is OK to remove the expectation at that time.
853 exp = ovs_ct_expect_find(net, &info->zone, info->family, skb);
857 /* NOTE: New connections are NATted and Helped only when
858 * committed, so we are not calling into NAT here.
860 state = OVS_CS_F_TRACKED | OVS_CS_F_NEW | OVS_CS_F_RELATED;
861 __ovs_ct_update_key(key, state, &info->zone, exp->master);
866 err = __ovs_ct_lookup(net, key, info, skb);
870 ct = (struct nf_conn *)skb->nfct;
872 nf_ct_deliver_cached_events(ct);
878 static bool labels_nonzero(const struct ovs_key_ct_labels *labels)
882 for (i = 0; i < sizeof(*labels); i++)
883 if (labels->ct_labels[i])
889 /* Lookup connection and confirm if unconfirmed. */
890 static int ovs_ct_commit(struct net *net, struct sw_flow_key *key,
891 const struct ovs_conntrack_info *info,
896 err = __ovs_ct_lookup(net, key, info, skb);
900 /* Apply changes before confirming the connection so that the initial
901 * conntrack NEW netlink event carries the values given in the CT
904 if (info->mark.mask) {
905 err = ovs_ct_set_mark(skb, key, info->mark.value,
910 if (labels_nonzero(&info->labels.mask)) {
911 err = ovs_ct_set_labels(skb, key, &info->labels.value,
916 /* This will take care of sending queued events even if the connection
917 * is already confirmed.
919 if (nf_conntrack_confirm(skb) != NF_ACCEPT)
925 /* Trim the skb to the length specified by the IP/IPv6 header,
926 * removing any trailing lower-layer padding. This prepares the skb
927 * for higher-layer processing that assumes skb->len excludes padding
928 * (such as nf_ip_checksum). The caller needs to pull the skb to the
929 * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
931 static int ovs_skb_network_trim(struct sk_buff *skb)
936 switch (skb->protocol) {
937 case htons(ETH_P_IP):
938 len = ntohs(ip_hdr(skb)->tot_len);
940 case htons(ETH_P_IPV6):
941 len = sizeof(struct ipv6hdr)
942 + ntohs(ipv6_hdr(skb)->payload_len);
948 err = pskb_trim_rcsum(skb, len);
955 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
956 * value if 'skb' is freed.
958 int ovs_ct_execute(struct net *net, struct sk_buff *skb,
959 struct sw_flow_key *key,
960 const struct ovs_conntrack_info *info)
965 /* The conntrack module expects to be working at L3. */
966 nh_ofs = skb_network_offset(skb);
967 skb_pull_rcsum(skb, nh_ofs);
969 err = ovs_skb_network_trim(skb);
973 if (key->ip.frag != OVS_FRAG_TYPE_NONE) {
974 err = handle_fragments(net, key, info->zone.id, skb);
980 err = ovs_ct_commit(net, key, info, skb);
982 err = ovs_ct_lookup(net, key, info, skb);
984 skb_push(skb, nh_ofs);
985 skb_postpush_rcsum(skb, skb->data, nh_ofs);
991 static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
992 const struct sw_flow_key *key, bool log)
994 struct nf_conntrack_helper *helper;
995 struct nf_conn_help *help;
997 helper = nf_conntrack_helper_try_module_get(name, info->family,
1000 OVS_NLERR(log, "Unknown helper \"%s\"", name);
1004 help = nf_ct_helper_ext_add(info->ct, helper, GFP_KERNEL);
1006 module_put(helper->me);
1010 rcu_assign_pointer(help->helper, helper);
1011 info->helper = helper;
1015 #ifdef CONFIG_NF_NAT_NEEDED
1016 static int parse_nat(const struct nlattr *attr,
1017 struct ovs_conntrack_info *info, bool log)
1021 bool have_ip_max = false;
1022 bool have_proto_max = false;
1023 bool ip_vers = (info->family == NFPROTO_IPV6);
1025 nla_for_each_nested(a, attr, rem) {
1026 static const int ovs_nat_attr_lens[OVS_NAT_ATTR_MAX + 1][2] = {
1027 [OVS_NAT_ATTR_SRC] = {0, 0},
1028 [OVS_NAT_ATTR_DST] = {0, 0},
1029 [OVS_NAT_ATTR_IP_MIN] = {sizeof(struct in_addr),
1030 sizeof(struct in6_addr)},
1031 [OVS_NAT_ATTR_IP_MAX] = {sizeof(struct in_addr),
1032 sizeof(struct in6_addr)},
1033 [OVS_NAT_ATTR_PROTO_MIN] = {sizeof(u16), sizeof(u16)},
1034 [OVS_NAT_ATTR_PROTO_MAX] = {sizeof(u16), sizeof(u16)},
1035 [OVS_NAT_ATTR_PERSISTENT] = {0, 0},
1036 [OVS_NAT_ATTR_PROTO_HASH] = {0, 0},
1037 [OVS_NAT_ATTR_PROTO_RANDOM] = {0, 0},
1039 int type = nla_type(a);
1041 if (type > OVS_NAT_ATTR_MAX) {
1043 "Unknown NAT attribute (type=%d, max=%d).\n",
1044 type, OVS_NAT_ATTR_MAX);
1048 if (nla_len(a) != ovs_nat_attr_lens[type][ip_vers]) {
1050 "NAT attribute type %d has unexpected length (%d != %d).\n",
1052 ovs_nat_attr_lens[type][ip_vers]);
1057 case OVS_NAT_ATTR_SRC:
1058 case OVS_NAT_ATTR_DST:
1061 "Only one type of NAT may be specified.\n"
1065 info->nat |= OVS_CT_NAT;
1066 info->nat |= ((type == OVS_NAT_ATTR_SRC)
1067 ? OVS_CT_SRC_NAT : OVS_CT_DST_NAT);
1070 case OVS_NAT_ATTR_IP_MIN:
1071 nla_memcpy(&info->range.min_addr, a,
1072 sizeof(info->range.min_addr));
1073 info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1076 case OVS_NAT_ATTR_IP_MAX:
1078 nla_memcpy(&info->range.max_addr, a,
1079 sizeof(info->range.max_addr));
1080 info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1083 case OVS_NAT_ATTR_PROTO_MIN:
1084 info->range.min_proto.all = htons(nla_get_u16(a));
1085 info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1088 case OVS_NAT_ATTR_PROTO_MAX:
1089 have_proto_max = true;
1090 info->range.max_proto.all = htons(nla_get_u16(a));
1091 info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1094 case OVS_NAT_ATTR_PERSISTENT:
1095 info->range.flags |= NF_NAT_RANGE_PERSISTENT;
1098 case OVS_NAT_ATTR_PROTO_HASH:
1099 info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM;
1102 case OVS_NAT_ATTR_PROTO_RANDOM:
1103 info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY;
1107 OVS_NLERR(log, "Unknown nat attribute (%d).\n", type);
1113 OVS_NLERR(log, "NAT attribute has %d unknown bytes.\n", rem);
1117 /* Do not allow flags if no type is given. */
1118 if (info->range.flags) {
1120 "NAT flags may be given only when NAT range (SRC or DST) is also specified.\n"
1124 info->nat = OVS_CT_NAT; /* NAT existing connections. */
1125 } else if (!info->commit) {
1127 "NAT attributes may be specified only when CT COMMIT flag is also specified.\n"
1131 /* Allow missing IP_MAX. */
1132 if (info->range.flags & NF_NAT_RANGE_MAP_IPS && !have_ip_max) {
1133 memcpy(&info->range.max_addr, &info->range.min_addr,
1134 sizeof(info->range.max_addr));
1136 /* Allow missing PROTO_MAX. */
1137 if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1139 info->range.max_proto.all = info->range.min_proto.all;
1145 static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
1146 [OVS_CT_ATTR_COMMIT] = { .minlen = 0, .maxlen = 0 },
1147 [OVS_CT_ATTR_ZONE] = { .minlen = sizeof(u16),
1148 .maxlen = sizeof(u16) },
1149 [OVS_CT_ATTR_MARK] = { .minlen = sizeof(struct md_mark),
1150 .maxlen = sizeof(struct md_mark) },
1151 [OVS_CT_ATTR_LABELS] = { .minlen = sizeof(struct md_labels),
1152 .maxlen = sizeof(struct md_labels) },
1153 [OVS_CT_ATTR_HELPER] = { .minlen = 1,
1154 .maxlen = NF_CT_HELPER_NAME_LEN },
1155 #ifdef CONFIG_NF_NAT_NEEDED
1156 /* NAT length is checked when parsing the nested attributes. */
1157 [OVS_CT_ATTR_NAT] = { .minlen = 0, .maxlen = INT_MAX },
1161 static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
1162 const char **helper, bool log)
1167 nla_for_each_nested(a, attr, rem) {
1168 int type = nla_type(a);
1172 if (type > OVS_CT_ATTR_MAX) {
1174 "Unknown conntrack attr (type=%d, max=%d)",
1175 type, OVS_CT_ATTR_MAX);
1179 maxlen = ovs_ct_attr_lens[type].maxlen;
1180 minlen = ovs_ct_attr_lens[type].minlen;
1181 if (nla_len(a) < minlen || nla_len(a) > maxlen) {
1183 "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
1184 type, nla_len(a), maxlen);
1189 case OVS_CT_ATTR_COMMIT:
1190 info->commit = true;
1192 #ifdef CONFIG_NF_CONNTRACK_ZONES
1193 case OVS_CT_ATTR_ZONE:
1194 info->zone.id = nla_get_u16(a);
1197 #ifdef CONFIG_NF_CONNTRACK_MARK
1198 case OVS_CT_ATTR_MARK: {
1199 struct md_mark *mark = nla_data(a);
1202 OVS_NLERR(log, "ct_mark mask cannot be 0");
1209 #ifdef CONFIG_NF_CONNTRACK_LABELS
1210 case OVS_CT_ATTR_LABELS: {
1211 struct md_labels *labels = nla_data(a);
1213 if (!labels_nonzero(&labels->mask)) {
1214 OVS_NLERR(log, "ct_labels mask cannot be 0");
1217 info->labels = *labels;
1221 case OVS_CT_ATTR_HELPER:
1222 *helper = nla_data(a);
1223 if (!memchr(*helper, '\0', nla_len(a))) {
1224 OVS_NLERR(log, "Invalid conntrack helper");
1228 #ifdef CONFIG_NF_NAT_NEEDED
1229 case OVS_CT_ATTR_NAT: {
1230 int err = parse_nat(a, info, log);
1238 OVS_NLERR(log, "Unknown conntrack attr (%d)",
1244 #ifdef CONFIG_NF_CONNTRACK_MARK
1245 if (!info->commit && info->mark.mask) {
1247 "Setting conntrack mark requires 'commit' flag.");
1251 #ifdef CONFIG_NF_CONNTRACK_LABELS
1252 if (!info->commit && labels_nonzero(&info->labels.mask)) {
1254 "Setting conntrack labels requires 'commit' flag.");
1259 OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
1266 bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
1268 if (attr == OVS_KEY_ATTR_CT_STATE)
1270 if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1271 attr == OVS_KEY_ATTR_CT_ZONE)
1273 if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1274 attr == OVS_KEY_ATTR_CT_MARK)
1276 if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1277 attr == OVS_KEY_ATTR_CT_LABELS) {
1278 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1280 return ovs_net->xt_label;
1286 int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
1287 const struct sw_flow_key *key,
1288 struct sw_flow_actions **sfa, bool log)
1290 struct ovs_conntrack_info ct_info;
1291 const char *helper = NULL;
1295 family = key_to_nfproto(key);
1296 if (family == NFPROTO_UNSPEC) {
1297 OVS_NLERR(log, "ct family unspecified");
1301 memset(&ct_info, 0, sizeof(ct_info));
1302 ct_info.family = family;
1304 nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
1305 NF_CT_DEFAULT_ZONE_DIR, 0);
1307 err = parse_ct(attr, &ct_info, &helper, log);
1311 /* Set up template for tracking connections in specific zones. */
1312 ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
1314 OVS_NLERR(log, "Failed to allocate conntrack template");
1318 __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
1319 nf_conntrack_get(&ct_info.ct->ct_general);
1322 err = ovs_ct_add_helper(&ct_info, helper, key, log);
1327 err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
1328 sizeof(ct_info), log);
1334 __ovs_ct_free_action(&ct_info);
1338 #ifdef CONFIG_NF_NAT_NEEDED
1339 static bool ovs_ct_nat_to_attr(const struct ovs_conntrack_info *info,
1340 struct sk_buff *skb)
1342 struct nlattr *start;
1344 start = nla_nest_start(skb, OVS_CT_ATTR_NAT);
1348 if (info->nat & OVS_CT_SRC_NAT) {
1349 if (nla_put_flag(skb, OVS_NAT_ATTR_SRC))
1351 } else if (info->nat & OVS_CT_DST_NAT) {
1352 if (nla_put_flag(skb, OVS_NAT_ATTR_DST))
1358 if (info->range.flags & NF_NAT_RANGE_MAP_IPS) {
1359 if (IS_ENABLED(CONFIG_NF_NAT_IPV4) &&
1360 info->family == NFPROTO_IPV4) {
1361 if (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MIN,
1362 info->range.min_addr.ip) ||
1363 (info->range.max_addr.ip
1364 != info->range.min_addr.ip &&
1365 (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MAX,
1366 info->range.max_addr.ip))))
1368 } else if (IS_ENABLED(CONFIG_NF_NAT_IPV6) &&
1369 info->family == NFPROTO_IPV6) {
1370 if (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MIN,
1371 &info->range.min_addr.in6) ||
1372 (memcmp(&info->range.max_addr.in6,
1373 &info->range.min_addr.in6,
1374 sizeof(info->range.max_addr.in6)) &&
1375 (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MAX,
1376 &info->range.max_addr.in6))))
1382 if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1383 (nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MIN,
1384 ntohs(info->range.min_proto.all)) ||
1385 (info->range.max_proto.all != info->range.min_proto.all &&
1386 nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MAX,
1387 ntohs(info->range.max_proto.all)))))
1390 if (info->range.flags & NF_NAT_RANGE_PERSISTENT &&
1391 nla_put_flag(skb, OVS_NAT_ATTR_PERSISTENT))
1393 if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM &&
1394 nla_put_flag(skb, OVS_NAT_ATTR_PROTO_HASH))
1396 if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY &&
1397 nla_put_flag(skb, OVS_NAT_ATTR_PROTO_RANDOM))
1400 nla_nest_end(skb, start);
1406 int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
1407 struct sk_buff *skb)
1409 struct nlattr *start;
1411 start = nla_nest_start(skb, OVS_ACTION_ATTR_CT);
1415 if (ct_info->commit && nla_put_flag(skb, OVS_CT_ATTR_COMMIT))
1417 if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1418 nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
1420 if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
1421 nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
1424 if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1425 labels_nonzero(&ct_info->labels.mask) &&
1426 nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
1429 if (ct_info->helper) {
1430 if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
1431 ct_info->helper->name))
1434 #ifdef CONFIG_NF_NAT_NEEDED
1435 if (ct_info->nat && !ovs_ct_nat_to_attr(ct_info, skb))
1438 nla_nest_end(skb, start);
1443 void ovs_ct_free_action(const struct nlattr *a)
1445 struct ovs_conntrack_info *ct_info = nla_data(a);
1447 __ovs_ct_free_action(ct_info);
1450 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
1452 if (ct_info->helper)
1453 module_put(ct_info->helper->me);
1455 nf_ct_tmpl_free(ct_info->ct);
1458 void ovs_ct_init(struct net *net)
1460 unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
1461 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1463 if (nf_connlabels_get(net, n_bits - 1)) {
1464 ovs_net->xt_label = false;
1465 OVS_NLERR(true, "Failed to set connlabel length");
1467 ovs_net->xt_label = true;
1471 void ovs_ct_exit(struct net *net)
1473 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1475 if (ovs_net->xt_label)
1476 nf_connlabels_put(net);