How do I restrict a specified SSH user to connect only from one IP or hostname?

Solution 1:

See man sshd_config. There is possibility to add AllowUsers block where you can specify both user and host like this:

AllowUsers user@host # or IP

Of course you need to specify also other users you want to allow login from, if you have some.

Another solution (depends on bug fixes!)

As I think about it once more, there is possibility to modify your sshd_config like this:

Match Host !hostname
    DenyUsers user
Match Host hostname
    AllowUsers user

This would easily block all users except from user from hostname and from everywhere else it would block user.

BUT it doesn't work, because of few bugs reported upstream [1] [2]. But we got it promised it will get fixed in next release.

  • [1] https://bugzilla.mindrot.org/show_bug.cgi?id=1918
  • [2] https://bugzilla.mindrot.org/show_bug.cgi?id=2397

Solution 2:

You can use wildcards for the AllowUsers line on the /etc/ssh/sshd_config file. So it would be feasible to add the line:

AllowUsers *@192.168.1.100

Or:

AllowUsers *@hostname

To allow everyone from that IP address or hostname access.

Remember to:

service ssh restart

Once you've made the changes, so long as you're on a version before 15.04. 15.04 uses systemd now, so has a different mechanism for controlling services.

Solution 3:

According to man pages, this should work:

DenyUsers user@"!host,*"

I tested this on Debian and it seemed to work correctly.

Solution 4:

Since this is the top search result in google, I think people should also be aware of setting permissions in the /etc/hosts.allow file (curtesy of Cameron Oltmann's blog post on the matter):

To limit ssh access to a linux box based on originating IP address, edit /etc/hosts.allow:

sshd : localhost : allow
sshd : 192.168.0. : allow
sshd : 99.151.250.7 : allow
sshd : mydomain.net : allow
sshd : ALL : deny

The above entry will allow ssh access from localhost, the 192.168.0.x subnet, the single IP address 99.151.250.7, and mydomain.net (assuming mydomain.net has a ptr record in place to facilitate reverse lookup). All other IP addresses will be denied access to sshd.

Notes: You can allow or deny based on ip address, subnet, or hostname. List rules in order of most to least specific. The file only gets read until a matching line is found, so if you start with ssdh : ALL : deny, no ssh connections will be allowed.

And you should be able to use user@address in this file, per this lifewire.com link:

The more complex forms daemon@host and user@host are explained in the sections on server endpoint patterns and on client username lookups, respectively.