I have a box B (say on which I can only ssh to from another box A. But a certain development tool on only allows me to specify the host and port of a ssh server and not anything more complicated than this, so I plan to have a port on A to automatically forward ssh traffic to B.

I've tried the following but it always gives me Connection timed out. How should I be doing this?

sudo iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination
sudo iptables -t nat -A POSTROUTING -p tcp -d --dport 22 -j SNAT --to-source
  • Do you know why it wouldn't work? Can't I make B think it's A connecting to it? – simonzack Aug 13 '15 at 23:04
  • @CIA: The second rule is changing the source address of the connection. It's just doing it wrong. – womble Aug 14 '15 at 0:07

Your SNAT rule is wrong. Assuming that:

  1. You're running these iptables commands on machine A, and
  2. That machine A is not, in fact,

Then the value of the --to-source argument should be the IP address of A, not the address of the machine you want to allow the connection from.

You may also need to add some other firewall rules to allow the port 2222 traffic to flow; NAT rules don't get around filter rules.

If things still aren't working after those changes, packet captures via tcpdump from machine A will likely reveal what's going wrong.

  • Thanks, after fixing this and enabling forwarding (the other machine was on a vpn interface) this works. – simonzack Aug 14 '15 at 5:11

Here's what I had in the end:

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

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

iptables -P FORWARD DROP
iptables -A FORWARD -i vpn0 -p tcp -s --sport 22 -j ACCEPT
iptables -A FORWARD -i ens192 -p tcp -d --dport 22 -j ACCEPT
iptables -t nat -I PREROUTING -p tcp -i ens192 --dport 2222 -j DNAT --to
iptables -t nat -A POSTROUTING -p tcp -d --dport 22 -j MASQUERADE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.