Wednesday, October 8, 2008

2 ssh servers on the same port

A tcp port can only be used by one server process for incoming connections. If another process wants to listen on the same port it will get an "address already in use" error from the OS. If you know the background it's pretty clear why it must be so.

But imagine a case like the following:
  • You want to make a linux machine reachable via ssh
  • From the same subnet passwords are sufficient
  • From outside only public key authentication is allowed
  • Your users are already happy if they get their ssh clients working on Windows XP. You don't want to bother them (and indirectly yourself as the admin) with nonstandard port numbers.
  • Your sshd doesn't support different configurations depending on the source address.
At a first glance, this looks unsolvable. But if you have an iptables firewall (and you will have one if the machine is worldwide reachable) there is a little known trick called port redirection.

You run 2 ssh servers: The external one (with public key authentication) listens at port 22, the internal one (with passwords) listens e.g. at port 2222. Then you configure your iptables such, that incoming packets which come from the subnet to port 22 are redirected to port 2222. The corresponding lines in the firewall script look like:

# Our Subnet

# iptables command

# default policies, flush all tables etc....

# ssh from our subnet (redirect to port 2222 and let them through)
$IPTABLES -t nat -A PREROUTING -s $SUB_NET -p tcp --dport 22 \
-j REDIRECT --to-ports 2222
$IPTABLES -A INPUT -p tcp -s $SUB_NET --syn --dport 2222 -j ACCEPT

# ssh from outside
$IPTABLES -A INPUT -p tcp -s ! $SUB_NET --syn --dport 22 -j ACCEPT

I have this configuration on 2 machines for many months now with zero complaints so far.

1 comment:

Hochfart said...

Vestidosnow es una 2011 vestidos de fiesta. Tenemos experiencia de muchos a?o en las Vestidos de Coctel. Les ofrecemos variedades de vestidos formales, Vestidos de Noche. Tenemos experiencia de muchos años en las vestidos de fiesta online, vestidos para graduación, vestidos de baile, así como vestidos de fiesta cortos. Todos son de precios económicos pero de alta calidad.