将所有 mysql 流量转发到 ssh 隧道

Inf*_*rid 5 ssh iptables ssh-tunneling mysql

我有一个本地应用程序需要连接到 40.40.40.40:3306 的远程 mysql 服务器

主防火墙阻止了除 ssh 之外的所有连接,我可以设置 ssh 隧道并毫无问题地连接到服务器

ssh remoteuser@40.40.40.40 -L 3306:127.0.0.1:3306 -N  
Run Code Online (Sandbox Code Playgroud)

(在另一个终端)

$ mysql -udb_user -h127.0.0.1 -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
[...]
Run Code Online (Sandbox Code Playgroud)

我的目的是配置 iptables 将目的地为 40.40.40.40:3306 的连接转发到我的隧道 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
Run Code Online (Sandbox Code Playgroud)

通过这种设置,我的应用程序仍然无法连接到数据库,如果我将连接设置更改为 127.0.0.1 我没有问题,所以我假设应用程序运行良好。

Tim*_*Tim 5

您需要使用OUTPUT链将出站连接重定向到本地端口。
此规则将根据您的需要工作:

iptables -t nat -A 输出 -p tcp -d 40.40.40.40 --dport 3306 -j REDIRECT --to-port 3306