SSH 端口转发

SSH 提供了一个非常有意思的功能,就是端口转发,它能够将其他 TCP 端口的网络数据通过 SSH 链接来转发,并且自动提供了相应的加密及解密服务。

  • 本地端口转发
1
# ssh -fgN -L 2222:localhost:22 localhost
  • 远程端口转发
1
# ssh -fgN -R 2222:host1:22 localhost
  • 动态转发
1
# ssh -fgN -D 12345 root@host1

iptables 端口转发

CentOS 7.0 以下使用的是iptables,可以通过iptables实现数据包的转发。

  • 开启数据转发功能
1
2
3
# vi /etc/sysctl.conf
net.ipv4.ip_forward=1 //增加一行
# sysctl -p //使数据转发功能生效
  • 将本地的端口转发到本机端口
1
# iptables -t nat -A PREROUTING -p tcp --dport 2222 -j REDIRECT --to-port 22
  • 将本机的端口转发到其他机器
1
2
3
# iptables -t nat -A PREROUTING -d 192.168.172.130 -p tcp --dport 8000 -j DNAT --to-destination 192.168.172.131:80
# iptables -t nat -A POSTROUTING -d 192.168.172.131 -p tcp --dport 80 -j SNAT --to 192.168.172.130
# iptables -t nat -F PREROUTING //清空nat表的所有链

firewall 端口转发

CentOS 7.0以上使用的是firewall,通过命令行配置实现端口转发。

  • 开启伪装IP
1
# firewall-cmd --permanent --add-masquerade
  • 配置端口转发,将到达本机的12345端口的访问转发到另一台服务器的22端口。
1
# firewall-cmd --permanent --add-forward-port=port=12345:proto=tcp:toaddr=192.168.172.131:toport=22
  • 重新载入,使其失效。
1
# firewall-cmd --reload

rinetd 端口转发

rinetd是一个轻量级TCP转发工具,简单配置就可以实现端口映射/转发/重定向。

  • 源码下载
1
# wget https://li.nux.ro/download/nux/misc/el7/x86_64/rinetd-0.62-9.el7.nux.x86_64.rpm
  • 安装rinetd
1
# rpm -ivh rinetd-0.62-9.el7.nux.x86_64.rpm
  • 编辑配置文件
1
2
# vi rinetd.conf
0.0.0.0 1234 127.0.0.1 22 //添加
  • 启动转发
1
# rinetd -c /etc/rinetd.conf

socat 端口转发

socat是一个多功能的网络工具,使用socat进行端口转发。

  • socat安装
1
# yum install -y socat
  • 在本地监听12345端口,并将请求转发至192.168.172.131的22端口。
1
# socat TCP4-LISTEN:12345,reuseaddr,fork TCP4:192.168.172.131:22

portmap 端口转发

Linux 版的lcx,内网端口转发工具。

  • 下载地址:

[http://www.vuln.cn/wp-content/uploads/2016/06/lcx_vuln.cn_.zip]

  • 监听本地1234端口,转发给192.168.172.131的22端口
1
# ./portmap -m 1 -p1 1234 -h2 192.168.172.131 -p2 22