Restricting SSH login by IP address on Debian

I want to allow SSH logins only from 3 IP addresses: 111.111.111.111 and 222.222.222.222 and 333.333.333.333. I know, I have to edit /etc/hosts.allow and /etc/hosts.deny files.

My question is about the content of these files. I have seen different variants:

# /etc/hosts.allow

Variant 1:

sshd: 111.111.111
sshd: 222.222.222
sshd: 333.333.333

Variant 2:

sshd: 111.111.111, 222.222.222, 333.333.333

Variant 3: (without commas):

sshd: 111.111.111 222.222.222 333.333.333

Variant 4 (with sshdfwd-X11):

sshd,sshdfwd-X11: 111.111.111 222.222.222 333.333.333

/etc/hosts.deny

Variant 1:

sshd: ALL

Variant2:

sshd,sshdfwd-X11:ALL

Which is the correct one? I am afraid to lock me out. Thanks.


Solution 1:

I would do this personally in the sshd_config using AllowUsers.

AllowUsers = *@111.111.111.111, *@222.222.222.222, *@333.333.333.333

To me, that keeps all the config in the place associated with the application you're controlling. There's always more than one way to skin a cat with UNIX, but if the tool offers a specific control mechanism I tend to prefer that over anything else (it's usually more portable).

When making changes to anything in relation to remote access,

  1. always have multiple sessions on the server already
  2. make the changes from within a screen or tmux session so you can reconnect to it if you lose connection
  3. try and make the changes from a non-ssh console if possible

I find that as long as you've got a few remote sessions already, you'll be fine. Changing /etc/ssh/sshd_config and recycling SSH does not disconnect any existing sessions.

Although I appreciate that doesn't answer your specific question. I believe Jeff's answer does (in that all those variants are valid if you use /etc/hosts.deny or /etc/hosts.allow).

Solution 2:

Generally, it is my preference to implement rules like this using iptables.

As far as the correct variant, all of those should work. The relevant man page (thanks for catching this Oliver) says using blanks or commas is acceptable. It also does go on to discuss that any match of daemon: client will count and that multiple clients can be listed to a line, and multiple entries for a daemon will all be evaluated.