Blog / Linux/ Secure Your Linux Server: Disable Root Password Login and Enforce SSH Key Authentication

Secure Your Linux Server: Disable Root Password Login and Enforce SSH Key Authentication

linux服务器禁用root账户密码登录,只能采用密匙登录,加强系统安全

Change the SSH Port

Changing the default SSH port (22) is a basic security measure to reduce automated attacks.

  1. Open the SSH configuration file: vi /etc/ssh/sshd_config
  2. Find the line #Port 22, remove the # comment, and change 22 to a high-numbered port (e.g., above 10000).
  3. Save and exit.

Important: Ensure the new port is open in your firewall/security group before restarting SSH.

Configure SSH Key Authentication and Disable Password Login

Using key-based authentication and disabling password login for the root account is an effective defense against brute-force attacks.

1. Generate an SSH Key Pair

On your local machine, run:

ssh-keygen -t rsa -b 4096

Follow the prompts to save the key (default location is fine) and set a strong passphrase for extra security.

This creates two files in ~/.ssh/:

  • id_rsa: Private key. Keep this secret and secure.
  • id_rsa.pub: Public key. This will be uploaded to the server.

2. Upload the Public Key to the Server

For the root user, ensure the .ssh directory exists and has correct permissions, then append the public key:

mkdir -p /root/.ssh
chmod 700 /root/.ssh
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

3. Configure the SSH Server

Edit /etc/ssh/sshd_config and ensure these settings are present:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
# Optionally, restrict root login to key-based only:
PermitRootLogin prohibit-password

If you changed the port in the first step, verify the Port directive is set correctly.

4. Restart SSH and Test

Before disconnecting, open a new terminal and test key-based login. Then restart the SSH service:

  • For systemd systems: systemctl restart sshd
  • For SysV init systems: service sshd restart

Security Best Practices:

  1. Back up your private key; losing it means losing server access.
  2. Never leave the private key on the server; only the public key (authorized_keys) should remain.
  3. Use a strong passphrase for your private key.
  4. Consider using different key pairs for different servers to limit risk.

After completing these steps, your server will only accept SSH key authentication, significantly improving security.

Post a Comment

Your email will not be published. Required fields are marked with *.