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?


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

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

# 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 (
# is marked "42" (and therefore goes to FIXED):
iptables -t mangle -A OUTPUT ! -d \
                             -p tcp -m tcp --sport 22 \
                             -j MARK --set-mark 42

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.