Merge branch 'for-mingo-kcsan' of git://git.kernel.org/pub/scm/linux/kernel/git/paulm...
[linux-2.6-microblaze.git] / tools / testing / selftests / netfilter / nf_nat_edemux.sh
1 #!/bin/bash
2 # SPDX-License-Identifier: GPL-2.0
3 #
4 # Test NAT source port clash resolution
5 #
6
7 # Kselftest framework requirement - SKIP code is 4.
8 ksft_skip=4
9 ret=0
10
11 sfx=$(mktemp -u "XXXXXXXX")
12 ns1="ns1-$sfx"
13 ns2="ns2-$sfx"
14
15 cleanup()
16 {
17         ip netns del $ns1
18         ip netns del $ns2
19 }
20
21 iperf3 -v > /dev/null 2>&1
22 if [ $? -ne 0 ];then
23         echo "SKIP: Could not run test without iperf3"
24         exit $ksft_skip
25 fi
26
27 iptables --version > /dev/null 2>&1
28 if [ $? -ne 0 ];then
29         echo "SKIP: Could not run test without iptables"
30         exit $ksft_skip
31 fi
32
33 ip -Version > /dev/null 2>&1
34 if [ $? -ne 0 ];then
35         echo "SKIP: Could not run test without ip tool"
36         exit $ksft_skip
37 fi
38
39 ip netns add "$ns1"
40 if [ $? -ne 0 ];then
41         echo "SKIP: Could not create net namespace $ns1"
42         exit $ksft_skip
43 fi
44
45 trap cleanup EXIT
46
47 ip netns add $ns2
48
49 # Connect the namespaces using a veth pair
50 ip link add name veth2 type veth peer name veth1
51 ip link set netns $ns1 dev veth1
52 ip link set netns $ns2 dev veth2
53
54 ip netns exec $ns1 ip link set up dev lo
55 ip netns exec $ns1 ip link set up dev veth1
56 ip netns exec $ns1 ip addr add 192.168.1.1/24 dev veth1
57
58 ip netns exec $ns2 ip link set up dev lo
59 ip netns exec $ns2 ip link set up dev veth2
60 ip netns exec $ns2 ip addr add 192.168.1.2/24 dev veth2
61
62 # Create a server in one namespace
63 ip netns exec $ns1 iperf3 -s > /dev/null 2>&1 &
64 iperfs=$!
65
66 # Restrict source port to just one so we don't have to exhaust
67 # all others.
68 ip netns exec $ns2 sysctl -q net.ipv4.ip_local_port_range="10000 10000"
69
70 # add a virtual IP using DNAT
71 ip netns exec $ns2 iptables -t nat -A OUTPUT -d 10.96.0.1/32 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.1:5201
72
73 # ... and route it to the other namespace
74 ip netns exec $ns2 ip route add 10.96.0.1 via 192.168.1.1
75
76 sleep 1
77
78 # add a persistent connection from the other namespace
79 ip netns exec $ns2 nc -q 10 -w 10 192.168.1.1 5201 > /dev/null &
80
81 sleep 1
82
83 # ip daddr:dport will be rewritten to 192.168.1.1 5201
84 # NAT must reallocate source port 10000 because
85 # 192.168.1.2:10000 -> 192.168.1.1:5201 is already in use
86 echo test | ip netns exec $ns2 nc -w 3 -q 3 10.96.0.1 443 >/dev/null
87 ret=$?
88
89 kill $iperfs
90
91 # Check nc can connect to 10.96.0.1:443 (aka 192.168.1.1:5201).
92 if [ $ret -eq 0 ]; then
93         echo "PASS: nc can connect via NAT'd address"
94 else
95         echo "FAIL: nc cannot connect via NAT'd address"
96         exit 1
97 fi
98
99 exit 0