Ssh – How to route all traffic from a specific port to a specific network interface

ipiptablesroutessh

I have the following setup:

A computer with two network cards connected to two different routers. The first router redirects all outside traffic coming on port 5122 to port 22. So that I can connect to the machine using ssh.

I wish to use the first router only for ssh connections. Nothing else. So I want all other traffic directed through the second router.

How can I do that?

Best Answer

Like this:

1. Mark packets

Set a mark on each packet which is heading for port 5122.

iptables -A PREROUTING -t mangle -p tcp --dport 5122 \
  -j MARK --set-mark 1

Alternatively like this if you want to limit it to packets with a destination ip of 10.10.10.10:

iptables -A PREROUTING -t mangle -p tcp -d 10.10.10.10/32 --dport 5122 \
  -j MARK --set-mark 1

2. Create routing table/rule

Create routing table with a rule for it to be used for the marked packets.

echo 201 ssh5122.out >> /etc/iproute2/rt_tables
ip rule add fwmark 1 table ssh5122.out

3. Add the route

Add the route corresponding to the routing table.

ip route add default via $ssh_router_ip dev $ssh_router_interface \
  dev table ssh5122.out

That should work.

Related Topic