iptables question: forwarding port x to an ssh port of different machine on the network

I have a Ubuntu PC, with two networks cards, acting as a router. One card eth0 is connected to internet and other eth1 is connected to LAN. I want to expose ssh ports of different hosts in LAN to different port numbers to outside world. i.e. "ssh user@router -p 1234" should go to ssh port of host1 and "ssh user@router -p 3456" should ssh to host2. I added following iptable rule for host1 but it doesn't work:

iptables -A FORWARD -i $EXTIF -o $INTIF -p tcp --dport 1234 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -A PREROUTING -t nat -p tcp -d $EXTIP --dport 1234 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j DNAT --to-destination 10.9.0.2:22

EXTIF is external inteface (eth0), INTIF is internal interface (eth1), EXTIP Is IP address of eth0.

Any help? (Not sure if question is clear, please edit with right jargon if somebody understands my intent)


Solution 1:

The rule for the FORWARD chain needs to use the target port, because it is executed after the prerouting chain, i.e. after the DNAT has been done.

iptables -A FORWARD -i $EXTIF -o $INTIF -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

A good overview diagram of how the various tables and chains are linked together is here: http://www.csie.ntu.edu.tw/~b92035/cnl/hw1/Iptables.gif