Create UDP Proxy – How to Create a UDP Proxy Using Iptables

iptablesPROXYUbuntuudp

I have a server running UDP server on port 50000. This server receives updates from clients, and pings back the clients every 5 seconds to the socket they were connected from.

Now I want to redirect all the traffic to and from this UDP server via another server. Basically I want to setup a transparent proxy in front of this server. The reason is that I want to be able to easily control which server handles the UDP traffic, without the need to change DNS settings.

At first I tried usingn socat to create this proxy:

socat UDP-LISTEN:50000,fork UDP:myserver:50000

But this seems to work well for incoming traffic, but back traffic from my server to the clients doesn't reach its destination. Also it seems that socat forks another process for each connection, so I might end up with too many processes and also dead processes when clients disconnect/switch IP.

I realized that I can use iptables NAT functionality for this, but it doesn't seem to work for me. The configuration I've tried is:

sudo iptables -t nat -A PREROUTING -p udp --dport 50000 -j DNAT --to-destination myserver:50000

But it doesn't seem to work — I don't even see the connections on my server. I'm not sure if it's due to wrong configuration or due to some other issues.

Some questions:

  1. Do I need to somehow restart iptables once I add the nat configuration?
  2. Do I need to allow traffic to the incoming port or having the NAT setting is enough?

UPDATE: The server that actually handles the traffic is on a different machine than the one that I'm trying to setup iptables on.

Best Answer

There are some points you did not mention in your description:

  1. If you are forwarding the traffic received by iptables machine to another one. You need to enable IP forwarding. See below for details.
  2. Also, you need to allow forwarded traffic to pass through. This can be done by setting the FORWARD chain default policy to ACCEPT, or by allowing the specific traffic (ip/port).

To enable IP forwarding, uncomment the following line in /etc/sysctl.conf:

net.ipv4.ip_forward=1

Then, execute: sudo sysctl -p.

Adding rules using iptables command will add them in memory only (they are lost after reboot). You need to save them to a text file using iptables-save and restore them when needed using iptables-restore.