大网数据广告活动
服务器运维问答

Why SSH still works after applying SNAT and DNAT rules to forward ip (on the SSH server)?

· 52CE 我爱测

I have the following situation: I have a Ubuntu Server VM with a bridged network adapter (let's say its ip is 192.168.100.3) that exposes an ssh server on port 22, the VM is hosted on a Ubuntu Desktop, when I connect over ssh wit…

问题原文

原帖链接 · johny.bravo · CC BY-SA 4.0

I have the following situation:

  • I have a Ubuntu Server VM with a bridged network adapter (let's say its ip is 192.168.100.3) that exposes an ssh server on port 22,
  • the VM is hosted on a Ubuntu Desktop,
  • when I connect over ssh with my VM (from the host) and append some rules in the NAT table of the VM like below:
sudo iptables \
--table nat \
--append PREROUTING \
--protocol ALL \
--destination 192.168.100.3 \
--jump DNAT \
--to-destination 192.168.100.4 # some other machine in my local network

sudo iptables \
--table nat \
--append POSTROUTING \
--protocol ALL \
--destination 192.168.100.4 \
--jump SNAT \
--to-source 192.168.100.3

The ongoing ssh connection remains and I don't get disconnected. However if I open a new terminal on the host and try going ssh [email omitted] I actually connect with the other machine in my network, to which I forwarded using iptables (192.168.100.4). Why does my first connection remain and not get disconnected? From my understanding the rules I specified should forward ALL packets to the ip 192.168.100.4 and yet it is not the case.

已采纳解答

原帖链接 · Nikita Kipriyanov · CC BY-SA 4.0

The nat table is traversed only by the first packet of the connection. It defines all the translations and these are recorded in the connection tracking table. Subsequent packets don't traverse the nat table at all, instead the connection tracker just takes the recorded translation parameters from its table and applies them.

Therefore, nat rules that appeared after the connection was established never apply to the already running connections. The previous connection in your case knows there were no translation rules defined, so it does no translation. If you now connect to another computer and remove nat rules, the connection will be kept, but new connections will be created again without translation.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-06-12)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。