Let's say I have two machines mA
(Private ip: 192.168.0.3) and mB
(Private ip: 192.168.0.4) within the same LAN whos public IP address is 2.2.2.2
. These machines both have users with common username root
. Additionally, mA
has user uA
and mB
has user uB
.
I understand how ssh
communication from mA
or mB
to another public IP 3.3.3.3
works. SSH from mA port 22
creates a NAT table in the router which corresponds to 2.2.2.2 port 22
as source address. So any incoming reply from ssh requests from 3.3.3.3
to 2.2.2.2 port 22
can be reverse translated to mA port 22
. This is possible because of the existence of NAT table entry for mA
.
Now, if any other server outside the LAN tries to ssh
to mB
using ssh root@2.2.2.2
. How does the router know which machine in the LAN to send this SSH request? (Since there is nothing to identify mB
in NAT table now. And both mA
and mB
have root).
Is it different from what happens when you try to ssh uB@2.2.2.2
where user uB
only exists in mB
?
Outgoing connections
on mA: ssh 3.3.3.3
This creates a NAT table entry on the router with the following connection information
Source-IP IP of mA
Source-Port >1024
Dest-IP 3.3.3.3
Dest-Port 22
The Source-IP is NATed to 2.2.2.2
and every time a packet with the above connection information (Source-IP is the NATed Source-IP) arrives at the router, the NATed Source-IP is translated back to the IP of mA
and the packet is then forwarded to mA
.
Incoming connections
For incoming connections, there is no connection information available at the router, this means, the router doesn't know what to do with a packet that has
Dest-IP 2.2.2.2
Dest-Port 22
in the TCP/IP header, assuming that the router itself is not reachable via SSH. Routers therefore have the ability to define so called port forwarding rules. A port forwarding rule has the form of
[Dest-IP:]Dest-Port --> Real-Dest-IP:Real-Dest-Port
If the router accepts more IP addresses the port forwarding rule can also distinguish between different Dest-IPs.
So in your case you have to create two port forwarding rules, one for mA
and one for mB
.
22 --> mA:22
2222 --> mB:22
Unfortunately you have to connect to different ports from outside to get access to your servers.
With this rules the ssh commands for accessing your servers are the following:
mA: ssh 2.2.2.2
mB: ssh -p 2222 2.2.2.2
BTW: For security reasons, it is not advisable to access your servers directly as root
.