出于安全考虑公网IP仅暴露了内网跳板机的22端口,想借用ssh端口转发实现简易内网穿透。html
以前的文章经过ssh隧道实现tcp端口转发介绍了ssh正向转发(local port forward)
比较适合在外网访问内网资源,如内网http服务
假设跳板机的22端口经过端口映射暴露在公网123.45.67.89:2222ubuntu
ssh -L 8080:192.168.1.4:80 jump@123.45.67.89 -p 2222
可经过ssh将内网的192.168.1.4:80转发至本机的8080
对于明文传输http也起到了加密做用,适用于不安全的网络环境
而此次的目的是将本地端口转发至内网,实现内网对本地的远程访问后端
使用ssh自带的反向转发(remote port forward)安全
ssh -R 80:localhost:8080 jump@123.45.67.89 -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."session
取消注释GatewayPorts
并修改默认值no为yes后重启sshd服务便可生效。该设置容许转发后的端口绑定在0.0.0.0上,确保从每一个网卡的ip上都能访问到8080服务。有关0.0.0.0和127.0.0.1的区别参考文末连接并发
即便经过ssh -Nf
参数后台执行,上述方法缺点依然明显,session断开后端口转发随之消失。
想要实现相似商用内网穿透的开机自动链接能够使用autossh进行自动链接并发送心跳包ssh
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地址的區別 | 程式前沿tcp