1. 程式人生 > 其它 >ssh埠反向代理與內網穿透

ssh埠反向代理與內網穿透

背景

出於安全考慮公網IP僅暴露了內網跳板機的22埠,想借用ssh埠轉發實現簡易內網穿透。

思考

之前的文章通過ssh隧道實現tcp埠轉發介紹了ssh正向轉發(local port forward)
比較適合在外網訪問內網資源,如內網http服務
假設跳板機的22埠通過埠對映暴露在公網123.45.67.89:2222

ssh -L 8080:192.168.1.4:80 [email protected] -p 2222

可通過ssh將內網的192.168.1.4:80轉發至本機的8080
對於明文傳輸http也起到了加密作用,適用於不安全的網路環境
而這次的目的是將本地埠轉發至內網,實現內網對本地的遠端訪問

方法

使用ssh自帶的反向轉發(remote port forward)

ssh -R 80:localhost:8080 [email protected] -p 2222

上述命令通過ssh將本地的80埠轉發至跳板機的8080埠
但預設情況下轉發埠僅允許本地訪問,不對區域網開放,需要修改GatewayPorts引數位於/etc/ssh/sshd_config

GatewayPorts - "Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect."

取消註釋GatewayPorts並修改預設值no為yes後重啟sshd服務即可生效。該設定允許轉發後的埠繫結在0.0.0.0上,確保從每個網絡卡的ip上都能訪問到8080服務。
有關0.0.0.0和127.0.0.1的區別參考文末連結

進階

即使通過ssh -Nf引數後臺執行,上述方法缺點依然明顯,session斷開後端口轉發隨之消失。
想要實現類似商用內網穿透的開機自動連線可以使用autossh進行自動連線併發送心跳包

參考

security - How to create a restricted SSH user for port forwarding? - Ask Ubuntu
SSH Tunneling (Port Forwarding) 詳解 · John Engineering Stuff


127.0.0.1和0.0.0.0地址的區別 | 程式前沿