Linux change source ip adress of incoming traffic
I have a web service running on port X. It was never intended to run outside a local network, but I would like to access it over the internet. Therefore, I need to change the source IP address of all incoming packets to a local one (192.168.2.100, for example). Otherwise the web service responds with an error.
So here is what I need:
If I send a packet from my home computer with the public IP X to the public IP address Y of my server, the source IP address (in that case X) needs to be changed to a local one (192.168.2.1, for example). After that, the packet should be passed on to the web application which is running on the same server on port 80.
Solution 1:
OK, now I think I understand what you want. This is a very special case and different from the normal port-forwarding approach which I posted earlier (see below). The following rules should do it.
SNAT on incoming packets
I assume the following:
-
<x>
: public IP of the server -
<y>
: public IP of the client -
<a>
: internal IP of the server (192.168.2.1
) -
<b>
: internal "faked" IP of the client (192.168.2.100
) -
<if>
: external interface (i.e.eth0
)
SNAT only
This rule will alter the packet's source address:
iptables -t nat -A INPUT -p tcp -d <x> --dport 80 -s <y> -j SNAT --to-source <b>
Combined DNAT and SNAT:
These rules will alter the packet's source and destination address:
iptables -t nat -A PREROUTING -i <if> -p tcp -d <x> --dport 80 -s <y> \
-j DNAT --to-destination <a>:80
iptables -t nat -A INPUT -p tcp -d <a> -s <y> --dport 80 \
-j SNAT --to-source <b>
Don't forget to ACCEPT the packets in the filter table.
Usual DNAT port forwarding rule for comparison (without SNAT):
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 \
-j DNAT --to-destination 192.168.2.1:80
This will forward port 8080
on incoming packets on the external interface (in this example eth0
) to the internal host 192.168.2.1
to port 80
. Replace interface, protocol, dport and to-destination with your settings.
This rule will accept the modified packet:
iptables -A FORWARD -i eth0 -p tcp -d 192.168.2.1 --dport 80 -j ACCEPT
Solution 2:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport *$srcPortNumber* -j REDIRECT --to-port *$dstPortNumber*
You will change -i attribut if yours NIC is not on eth0
Edit #1
You can for --dport and --to-port set ip adress whit port for exm: 192.168.0.1:80