How to Restrict SSH Access by User, IP, and Firewall on Linux Servers

This guide explains how to secure Linux servers by configuring sshd to allow or deny specific users or IPs, using hosts.allow/hosts.deny for IP filtering, and setting up iptables rules to open only required ports while blocking all others.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Restrict SSH Access by User, IP, and Firewall on Linux Servers

Restricting SSH Access via sshd_config

To limit SSH login to a bastion host, edit /etc/ssh/sshd_config and use the AllowUsers directive for a whitelist. Example: AllowUsers [email protected] Only the specified user from the given IP can log in; all other users are denied.

For a blacklist, add a DenyUsers line, e.g.: DenyUsers jituan01 After changes, restart the SSH service:

CentOS 6: # service sshd restart CentOS 7 / EulerOS:

# systemctl restart sshd

IP‑Based Access Control with hosts.allow / hosts.deny

Linux can also filter SSH connections via /etc/hosts.allow and /etc/hosts.deny. To permit a single IP: sshd: 192.168.1.10 To block all other IPs, add to hosts.deny: sshd: ALL When both files contain rules, entries in hosts.allow take precedence.

Firewall Configuration with iptables

Open the required ports (e.g., SSH 22, HTTP 80, HTTPS 443) and drop everything else:

# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Allow return traffic for established or related connections:

# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Set the default policy to drop all other inbound traffic: # iptables -P INPUT DROP To block a malicious subnet, insert a DROP rule before the accept rules, for example: # iptables -I INPUT -s 85.31.46.0/24 -j DROP After configuring the rules, verify them with # iptables -L -n. The output will show ACCEPT rules for the allowed ports and a final DROP policy.

Persisting iptables Rules

Save the current firewall configuration so it survives a reboot: # service iptables save Optionally enable the iptables service at boot: # chkconfig iptables on Note: On cloud providers such as Alibaba Cloud, you must also open the same ports in the security‑group settings; otherwise the firewall changes alone will not allow access.

access controlLinuxSecurityiptablesSSHsshd_config
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.