How to Restrict SSH Login to a Specific IP or Host
Restricting SSH login to a specific IP or host ensures that only trusted IP addresses or networks can access your server via SSH. This is an important security measure to prevent unauthorized access to your server, reducing the attack surface for brute-force or other remote attacks.
We use TCP Wrappers, a simple tool that controls which devices can connect to your server based on their IP addresses or hostnames. Although it may seem a bit complicated at first, TCP Wrappers work with just two files: /etc/hosts.allow and /etc/hosts.deny. These files let you specify which IP addresses are allowed to access SSH and which are blocked.
Restrict SSH Login to a Specific IP or Host on Ubuntu/Debian,
Install TCP Wrappers (if needed) TCP Wrappers are typically installed by default. If not, install them with:
apt-get install tcpd -y
To deny all incoming SSH connections, Edit /etc/hosts.deny
file to deny SSH access,
nano /etc/hosts.deny
Add the following line to block all SSH connections:
sshd: ALL
Save and close the file. This blocks all SSH access by default.
Allow Specific IP Addresses for SSH Access
To allow SSH access only from specific IPs, Edit /etc/hosts.allow
file to allow connections from your IP:
nano /etc/hosts.allow
Add a line to allow SSH from a specific IP address (e.g., 172.168.0.21):
sshd: 172.168.0.21
Save and close the file.
Allow Multiple IPs or Subnets
You can allow multiple IPs or subnets in the /etc/hosts.allow
file.
Example:
sshd: 172.168.0.21, 10.83.33.77, 10.63.152.9
Or allow a whole subnet like this:
sshd: 172.168.0.
After editing the files, restart the SSH service to apply changes:
Systemctl restart sshd
Restrict SSH Login to a Specific IP or Host on CentOS,
Install TCP Wrappers (if needed) For CentOS, TCP Wrappers should be installed by default. If not, install them with:
yum install tcp_wrappers -y
To deny all incoming SSH connections, Edit /etc/hosts.deny
file to deny all SSH access:
nano /etc/hosts.deny
Add the following line to block all SSH connections:
sshd: ALL
Save and close the file.
Allow Specific IP Addresses for SSH Access
Edit /etc/hosts.allow
file to allow SSH access from your desired IP:
nano /etc/hosts.allow
Add a line to allow access from a specific IP address (e.g., 172.168.0.21):
sshd: 172.168.0.21
Save and close the file.
Allow Multiple IPs or Subnets
To allow multiple IPs or subnets
sshd: 172.168.0.21, 10.83.33.77, 10.63.152.9
To allow an entire subnet (e.g., 172.168.0.0/24):
sshd: 172.168.0.
You can also allow specific hosts or localhost:
sshd: localhost
sshd: 192.168.0.
After making the changes, restart the SSH service to apply:
systemctl restart sshd
Done.
CrownCloud - Get a SSD powered KVM VPS at $4.5/month!
Use the code WELCOME
for 10% off!
1 GB RAM / 25 GB SSD / 1 CPU Core / 1 TB Bandwidth per month
Available Locations: LAX | MIA | ATL | FRA | AMS