MOHAMED
MOHAMED

Reputation: 43616

iptable for port forwarding

I want to redirect all trafic coming to my Linux (192.168.1.34) on the port 22 to another address

So I used the following iptable command

sudo iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 192.168.1.239:22

the command does not return error.

But when I try to open ssh session from a PC (192.168.1.133) to my linux (192.168.1.34), the ssh session is not opened. It looks like the ssh trafic is not redirected to (192.168.1.239)

If I open the ssh session directly from the PC (192.168.1.133) to the (192.168.1.239), then the session is opened

Upvotes: 2

Views: 2408

Answers (2)

isyutaro
isyutaro

Reputation: 29

You need to add two more rules: your Linux IP (192.168.1.34) and another machine's IP (192.168.1.239):

### \# prerouting
sudo iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 192.168.1.239:22

### \# postrouting
sudo iptables -t nat -A POSTROUTING -p tcp --dport 22 -j MASQUERADE

### \# forward
sudo iptables -A FORWARD -s 192.168.1.34 -d 192.168.1.239 -j ACCEPT

sudo iptables -A FORWARD -s 192.168.1.239 -d 192.168.1.34 -j ACCEPT

Upvotes: 1

wroniasty
wroniasty

Reputation: 8072

First, make sure the NAT host has IP forwarding enabled:

echo "1" > /proc/sys/net/ipv4/ip_forward

Second, all your hosts are on the same subnet which means, the SSH traffic from 192.168.1.239 back to your client (192.168.1.133) is NOT routed via 192.168.1.34.

So you can either:

  1. use both DNAT and SNAT, or
  2. use different subnets for your hosts.

Upvotes: 2

Related Questions