Ssh – iptables with DNAT and multiple gateways: How to route replies to correct gateway

dnatgatewayiptablesroutingssh

I have a problem setting up iptables rules and routes on a Linux client for a scenario with DNAT and multiple gateways:

We have two gateways to the Internet. The first has a fixed IP, the second offers a better bandwidth. Both gateways do SNAT for outgoing traffic from our private network.

On the first gateway with the fixed IP I've set up port forwarding for port 22 so that all SSH traffic will be forwarded to my Linux client.

That works fine.

But only if I use this first gateway as default route on the Linux client.

When I switch the Linux client to the second gateway as default route, incoming SSH connections no longer work.

How can I setup the Linux client to send reply packets related to incoming SSH connections to the first gateway, but all other traffic to the second gateway?

Best Answer

I found a solution in the accepted answer to the question "Route return traffic to correct gateway depending on service".

I've implemented these rules on my Linux client:

# Default route is second gateway:
ip route add default via 10.0.0.2

# Create a routing table "FIXED" using our fixed IP gateway
echo "200 FIXED" >>/etc/iproute2/rt_tables
ip route add default table FIXED via 10.0.0.1

# Create a rule to route any packets marked "42" through FIXED:
ip rule add fwmark 42 table FIXED

# Finally, the iptables rule:
# Any outgoing traffic from source port 22 of my Linux client
# that has a destination inside our private network (10.0.0.0/24)
# is marked "42" (and therefore goes to FIXED):
iptables -t mangle -A OUTPUT ! -d 10.0.0.0/24 \
                             -p tcp -m tcp --sport 22 \
                             -j MARK --set-mark 42