How to Restrict SSH Access to Selected IP on macOS

Networksshterminal

I want to restrict ssh access on macOS 10.12 to selected IPs on my local network. I tried writing the following files:

# /etc/hosts.allow
sshd: 192.168.1.32
sshd: 192.168.1.33

# /etc/hosts.deny
sshd: ALL

Then restarting with:

sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist
sudo launchctl load /System/Library/LaunchDaemons/ssh.plist

Unloading ssh.plist successfully disabled ssh, but after reloading I can still connect from any IP.

How can I configure an IP whitelist?

Best Answer

hosts.allow and hosts.deny are only used when you run the service (sshd) through TCP wrappers. The default macOS install does not do that, so they will not have any effect.

As recommended by other answers, you could use a firewall to restrict access to SSH. This could be a hardware (i.e. "external") firewall or a software firewall such as the built-in pf firewall.

However, I wouldn't recommend using a firewall only. The best is to limit the sshd service itself - and if you want, you can add the firewall protection to that. The reasoning behind that is that if for some reason your firewall gets disabled, outside users would suddenly be allowed access to communicate with sshd - you really do not want that.

In order to configure sshd to limit access, you will need to edit the file /etc/ssh/sshd_config, and add the following:

AllowUsers username@192.168.1.32 username@192.168.1.33

where you replace "username" with your actual username.

If you want you can replace parts with * to denote a wildcard, such as for example username@192.168.1.* or *@192.168.1.32. You can read more about the options in the man page for sshd_config.