I observed that netfilter changes the source port when a connection is established in the conntrack module. I need to prevent this behavior.
Here is what I have done to reproduce my problem:
- I create a netfilter rule that will perform DNAT from port 2002 to 2003
sudo iptables -w -t nat -A OUTPUT -s 192.168.30.3 -d 192.168.30.1 -p udp --sport 2001 --dport 2002 -j DNAT --to-destination :2003
- I then create a conntrack entry to simulate a connection from 192.168.30.1:2001 (My computer) to 192.168.30.1:2003
sudo /sbin/conntrack -I -s 192.168.30.1 -d 192.168.30.3 -p udp --sport 2003 --dport 2001 --timeout 100000
- Eventually, I perform a connection to 192.168.30.1:2002 from my computer with source port 2001:
sudo nc -u -p 2001 192.168.30.1 2002
Due to the netfilter DNAT rule, I expected an output packet with destination port 2003 and source port 2001. However, on wireshark I observed the source port changed to a random number. I guess this is because my computer considers that there is an existing connection on port 2001 (due to the conntrack entry) and then prevents the source port to be 2001 (right?). But I don't want this behavior? How can I force the use of the port number 2001?