5

I have a local application that needs to connect to a remote mysql server at 40.40.40.40:3306

The main firewall blocks all connections but ssh, I can set up a ssh tunnel and connect to the server without problems

ssh remoteuser@40.40.40.40 -L 3306:127.0.0.1:3306 -N  

(in another terminal)

$ mysql -udb_user -h127.0.0.1 -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
[...]

My intent is to configure iptables to forwards the connection destinated to 40.40.40.40:3306 to my tunnel at 127.0.0.1:3306

# iptables -t nat -A PREROUTING -d 40.40.40.40 -p tcp --dport 3306 -j DNAT --to-destination 127.0.0.1:3306

# iptables -L -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         
DNAT       tcp  --  anywhere             40.40.40.40       tcp dpt:mysql to:127.0.0.1:3306

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination 

#cat /proc/sys/net/ipv4/ip_forward
1

With this setup my applications still can't connect to the database, if I change the connection settings to 127.0.0.1 I have no problems, so I assume that the application works perfectly.

5
+100

You need to use the OUTPUT chain to redirect an outbound connection to a local port.
This rule will work as you need:

iptables -t nat -A OUTPUT -p tcp -d 40.40.40.40 --dport 3306 -j REDIRECT --to-port 3306
  • exactly what I needed. – rsmoorthy Jul 16 '16 at 1:57

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.