Restrict ssh access to selected IP on macOS
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 [email protected] [email protected]
where you replace "username" with your actual username.
If you want you can replace parts with * to denote a wildcard, such as for example [email protected].*
or *@192.168.1.32
. You can read more about the options in the man page for sshd_config.
hosts.allow
and hosts.deny
has been deprecated and you should be using a firewall (pf
) instead.
The default rule for pf
can be found in /etc/pf.conf
. You could edit this file directory or create your own custom rule set, but be sure to copy the contents of the default file to it. Add the following two lines:
# The name of the network interface as shown in ifconfig
ext_if="en0"
tcp_services = "{ssh}"
icmp_types = "{echoreq, unreach}"
trusted = "{192.168.1.32, 192.168.1.33}"
# Exempt the loopback interface to prevent services that use if from being blocked
set skip on lo0
# This is a desktop so we have to be permissive in allowing outgoing connections
pass out quick modulate state
# Block all incoming SSH Traffic by default
block in on $ext_if inet proto tcp from any to any port $tcp_services
# Allow SSH traffic from trusted IPs
pass in on $ext_if inet proto tcp from $trusted to any port $tcp_services
Next, enable pf
with the command
$ sudo pfctl -e #if using the default /etc/pf.conf
$ sudo pfctl -e -f /path/to/custom_pf.conf #if using a custom pf.conf
This ruleset will by default, block SSH to all but the trusted IPs that are defined. All other services will not be impacted.