How to connect to the server behind NAT using mosh

The problem you're having lies in the port redirection. Your NAT forward at the router is sending incoming traffic sent to <domain>:9807 on to <internal-ip>:60000. When you start mosh with the -p option, the client connects to the server over ssh and tells the server to start, listening on the port specified. The mosh-server then communicates the open port number (in this case, the one you specified) back to the client, which closes the ssh connection and tries to connect to <domain>:<port>. The client is trying to communicate to the same port the server is listening on. The problem is that your NAT router is redirecting traffic from one port on the WAN side to a different port on the NAT'd machine. This will not work.

The best thing to do would be to get a direct translation, such as requesting the router forward port 9807 on the WAN side to your mosh-server machine at port 9807.

If that is not an option, the next best thing I can think of is to mangle the traffic on the server machine using iptables.

iptables -t nat -A PREROUTING -p udp --dport 60000 -j REDIRECT --to-port 9807

The execute your client as you describe

mosh -p 9807 user@my_server

What happens is:

  1. the mosh client on your machine opens an ssh connection (presumably forwarded to your machine through the NAT router) to your server, which executes mosh-server listening on port 9807.
  2. The mosh server exits, telling the client connected over ssh that the UDP port to connect to is 9807
  3. The mosh client closes the ssh connection and attempts to connect to the server at port 9807
  4. The NAT router sees this incoming traffic on port 9807 and sends it to your server at port 60000
  5. Your machine receives packets at port 60000 over UDP, which matches the iptables rule and get redirected to their destination (the server's IP, in this case), but at port 9807
  6. The client traffic's SRC port is unchanged by your NAT router, so mosh-server sends packets back out to your client at the port the client is listening on, which are received properly.

Tags:

Udp

Nat

Mosh