1 // SPDX-License-Identifier: GPL-2.0-only
3 * (C) 1999-2001 Paul `Rusty' Russell
4 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
5 * Copyright (c) 2011 Patrick McHardy <kaber@trash.net>
7 * Based on Rusty Russell's IPv4 REDIRECT target. Development of IPv6
8 * NAT funded by Astaro.
12 #include <linux/inetdevice.h>
15 #include <linux/kernel.h>
16 #include <linux/netdevice.h>
17 #include <linux/netfilter.h>
18 #include <linux/types.h>
19 #include <linux/netfilter_ipv4.h>
20 #include <linux/netfilter_ipv6.h>
21 #include <linux/netfilter/x_tables.h>
22 #include <net/addrconf.h>
23 #include <net/checksum.h>
24 #include <net/protocol.h>
25 #include <net/netfilter/nf_nat.h>
26 #include <net/netfilter/nf_nat_redirect.h>
29 nf_nat_redirect(struct sk_buff *skb, const struct nf_nat_range2 *range,
30 const union nf_inet_addr *newdst)
32 struct nf_nat_range2 newrange;
33 enum ip_conntrack_info ctinfo;
36 ct = nf_ct_get(skb, &ctinfo);
38 memset(&newrange, 0, sizeof(newrange));
40 newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS;
41 newrange.min_addr = *newdst;
42 newrange.max_addr = *newdst;
43 newrange.min_proto = range->min_proto;
44 newrange.max_proto = range->max_proto;
46 return nf_nat_setup_info(ct, &newrange, NF_NAT_MANIP_DST);
50 nf_nat_redirect_ipv4(struct sk_buff *skb, const struct nf_nat_range2 *range,
53 union nf_inet_addr newdst = {};
55 WARN_ON(hooknum != NF_INET_PRE_ROUTING &&
56 hooknum != NF_INET_LOCAL_OUT);
58 /* Local packets: make them go to loopback */
59 if (hooknum == NF_INET_LOCAL_OUT) {
60 newdst.ip = htonl(INADDR_LOOPBACK);
62 const struct in_device *indev;
64 indev = __in_dev_get_rcu(skb->dev);
66 const struct in_ifaddr *ifa;
68 ifa = rcu_dereference(indev->ifa_list);
70 newdst.ip = ifa->ifa_local;
77 return nf_nat_redirect(skb, range, &newdst);
79 EXPORT_SYMBOL_GPL(nf_nat_redirect_ipv4);
81 static const struct in6_addr loopback_addr = IN6ADDR_LOOPBACK_INIT;
83 static bool nf_nat_redirect_ipv6_usable(const struct inet6_ifaddr *ifa, unsigned int scope)
85 unsigned int ifa_addr_type = ipv6_addr_type(&ifa->addr);
87 if (ifa_addr_type & IPV6_ADDR_MAPPED)
90 if ((ifa->flags & IFA_F_TENTATIVE) && (!(ifa->flags & IFA_F_OPTIMISTIC)))
94 unsigned int ifa_scope = ifa_addr_type & IPV6_ADDR_SCOPE_MASK;
96 if (!(scope & ifa_scope))
104 nf_nat_redirect_ipv6(struct sk_buff *skb, const struct nf_nat_range2 *range,
105 unsigned int hooknum)
107 union nf_inet_addr newdst = {};
109 if (hooknum == NF_INET_LOCAL_OUT) {
110 newdst.in6 = loopback_addr;
112 unsigned int scope = ipv6_addr_scope(&ipv6_hdr(skb)->daddr);
113 struct inet6_dev *idev;
116 idev = __in6_dev_get(skb->dev);
118 const struct inet6_ifaddr *ifa;
120 read_lock_bh(&idev->lock);
121 list_for_each_entry(ifa, &idev->addr_list, if_list) {
122 if (!nf_nat_redirect_ipv6_usable(ifa, scope))
125 newdst.in6 = ifa->addr;
129 read_unlock_bh(&idev->lock);
136 return nf_nat_redirect(skb, range, &newdst);
138 EXPORT_SYMBOL_GPL(nf_nat_redirect_ipv6);