iptables is re-writing the source port on my UDP packets that go out of a tun interface. I have NAT rules setup with port X forwarded (details below). When an application behind the NAT receives a forwarded UDP packet on port X, and then "replies" to it by sending another UDP packet, which should have source port X), that packet somehow gets source port 1024. The source port is already re-written before it even leaves the NATed box. Remote app rejects this packet because it is expecting source port X, not 1024.

I think the "implicit source port mapping" is taking place. I don't need that because port X is dedicated to one function and no clashing can occur: neither the NATing machine, nor any other machine will use that port. How do I force iptables to just keep the source port as it is?

On the host behind NAT where the packets with re-written source port originate, I tried the following (one a time), all with same results:

iptables -t nat -A POSTROUTING -o tun0 -p udp --sport X -j SNAT --to
iptables -t nat -A POSTROUTING -o tun0 -p udp -j SNAT --to
iptables -t nat -A POSTROUTING -o tun0 -p udp -j MASQUERADE

On the remote externally-facing box that does the NAT:

iptables -t nat -A PREROUTING -i eth0 -p udp --dport X -j DNAT --to-destination
 iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  • 2
    install the conntrack command (from conntrack-tools) and see where are the conflicting flows. According to your own link, this rewrite happens when there are multiple flows that would appear identical. Once found, remove the cause. If NAT really rewrites the port, that's because there's no other choice
    – A.B
    Commented Dec 3, 2017 at 19:06

1 Answer 1


Problem solved by binding the app to the tun0 interface, instead of to

I tried that because in conntrack -E, I saw that the connection had the source address from a different interface (not tun0). So, even though the packet reached the right destination, with the right source address re-written, the state of the packet in the connection tracker was not right.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .