透明 ssh 隧道

透明 ssh 隧道

我在 中定义了一个 SSH 隧道/etc/ssh/ssh_config。它包含:

LocalForward 0.0.0.0:8000 some-service:80
LocalForward 0.0.0.0:8001 some-other-service:80

我仍然希望能够通过其原始 DNS 名称访问隧道(例如curl some-service应该仍然有效,而不必使用curl 0.0.0.0:8000

为了做到这一点,我在/etc/hosts文件中添加了以下内容:

127.0.0.2 some-service
127.0.0.3 some-other-service

现在,我认为我需要一些iptables可以执行以下操作的命令:

When I see a request to 127.0.0.2:80 I should proxy it to 127.0.0.1:8000
When I see a request to 127.0.0.3:80 I should proxy it to 127.0.0.0:8001

这样,curl some-service就会解析为127.0.0.2(via /etc/hosts,进而代理到127.0.0.1:8000(via iptables) ,进而命中some-service:80(via the ssh tunnel)


问题:我觉得应该有更简单的方法来实现这一点?如果没有,命令应该是什么样iptables的?

答案1

iptables在这种情况下要使用的命令是:

iptables -t nat -A OUTPUT -p tcp -d 127.0.0.2 --dport 80 -j DNAT --to-destination 127.0.0.1:8000

请注意,使用上述规则时,您不需要绑定到 SSH 配置中的任何地址。您只需使用:

LocalForward 8000 some-service:80

iptables处理到默认环回地址 127.0.0.1 的重定向。


我使用这个测试了ipify.org。他们提供了一个简单的 API,用于返回发送请求的 IP 地址(我已从输出中删除)。

这些命令全部在 SSH 客户端计算机上运行,​​并使用以下命令启动与 SSH 服务器的活动连接:

$ ssh -L 8000:api.ipify.org:80 <remote host>

规则如下iptables

$ sudo iptables -n -t nat -L OUTPUT
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  0.0.0.0/0            127.0.0.2            tcp dpt:80 to:127.0.0.1:8000

有了这些hosts条目,就可以使用 SSH 隧道了:

$ cat /etc/hosts | grep ipify
127.0.0.2       api.ipify.org
$ echo $(curl -s api.ipify.org)
<remote host IP address>

注释掉该hosts条目后,SSH 隧道将不再使用:

$ cat /etc/hosts | grep ipify
#127.0.0.2      api.ipify.org
$ echo $(curl -s api.ipify.org)
<client machine IP address>

相关内容