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.
8ksft_skip=4
9ret=0
10
11sfx=$(mktemp -u "XXXXXXXX")
12ns1="ns1-$sfx"
13ns2="ns2-$sfx"
14
15cleanup()
16{
17	ip netns del $ns1
18	ip netns del $ns2
19}
20
21iperf3 -v > /dev/null 2>&1
22if [ $? -ne 0 ];then
23	echo "SKIP: Could not run test without iperf3"
24	exit $ksft_skip
25fi
26
27iptables --version > /dev/null 2>&1
28if [ $? -ne 0 ];then
29	echo "SKIP: Could not run test without iptables"
30	exit $ksft_skip
31fi
32
33ip -Version > /dev/null 2>&1
34if [ $? -ne 0 ];then
35	echo "SKIP: Could not run test without ip tool"
36	exit $ksft_skip
37fi
38
39ip netns add "$ns1"
40if [ $? -ne 0 ];then
41	echo "SKIP: Could not create net namespace $ns1"
42	exit $ksft_skip
43fi
44
45trap cleanup EXIT
46
47ip netns add $ns2
48
49# Connect the namespaces using a veth pair
50ip link add name veth2 type veth peer name veth1
51ip link set netns $ns1 dev veth1
52ip link set netns $ns2 dev veth2
53
54ip netns exec $ns1 ip link set up dev lo
55ip netns exec $ns1 ip link set up dev veth1
56ip netns exec $ns1 ip addr add 192.168.1.1/24 dev veth1
57
58ip netns exec $ns2 ip link set up dev lo
59ip netns exec $ns2 ip link set up dev veth2
60ip netns exec $ns2 ip addr add 192.168.1.2/24 dev veth2
61
62# Create a server in one namespace
63ip netns exec $ns1 iperf3 -s > /dev/null 2>&1 &
64iperfs=$!
65
66# Restrict source port to just one so we don't have to exhaust
67# all others.
68ip netns exec $ns2 sysctl -q net.ipv4.ip_local_port_range="10000 10000"
69
70# add a virtual IP using DNAT
71ip 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
74ip netns exec $ns2 ip route add 10.96.0.1 via 192.168.1.1
75
76sleep 1
77
78# add a persistent connection from the other namespace
79ip netns exec $ns2 socat -t 10 - TCP:192.168.1.1:5201 > /dev/null &
80
81sleep 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
86echo test | ip netns exec $ns2 socat -t 3 -u STDIN TCP:10.96.0.1:443 >/dev/null
87ret=$?
88
89kill $iperfs
90
91# Check socat can connect to 10.96.0.1:443 (aka 192.168.1.1:5201).
92if [ $ret -eq 0 ]; then
93	echo "PASS: socat can connect via NAT'd address"
94else
95	echo "FAIL: socat cannot connect via NAT'd address"
96	exit 1
97fi
98
99exit 0
100