0

I want to forward my local port 2221 to a remote machine (192.168.2.100), where ssh listens on port 2222.

Connecting to the remote machine works:

ssh  -p 2222 192.168.2.100
[email protected]'s password:

The setup of my iptables is very simple with only one rule:

sudo iptables -t nat -A PREROUTING -p tcp --dport 2221 -j DNAT --to-destination 192.168.2.100:2222

>sudo iptables -t raw -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination    

>sudo iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         
DNAT       tcp  --  anywhere             anywhere             tcp     dpt:2221 to:192.168.2.100:2222

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination       

>sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination       

When I now try to connect to ssh on the (presumably) forwarded port, it fails:

>ssh  -p 2221 127.0.0.1
ssh: connect to host 127.0.0.1 port 2221: Connection refused

There is probably something fundamental I have missed. How do I go about debugging this?

Update: according to https://www.debuntu.org/how-to-redirecting-network-traffic-to-a-new-ip-using-iptables/ you need to add masquerading:

sudo iptables -t nat -A POSTROUTING -j MASQUERADE

And make sure port forwarding is enabled:

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

However, it still does not work for me.

If someone can explain how to get further debug information, that would be great.

1 Answer 1

1

I found a solution based on socat in this post:

https://superuser.com/a/536295/621970

so, this does the trick:

sudo socat TCP-LISTEN:2221,su=nobody,fork,reuseaddr TCP-CONNECT:192.168.2.100:2222

It connects Port 2221 on the local host to port 2222 on the remote machine 192.168.2.100

sudo needed to su to nobody.

The fork option means that it will renegotiate the incoming port, so that it doesn't block.

You must log in to answer this question.

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