Securing an SSH connection on Linux involves several steps to enhance the security of your server and protect against unauthorized access. Here are some best practices:
Change the Default SSH Port
By default, SSH runs on port 22. Changing it to a non-standard port can help reduce automated attacks.
Edit the SSH configuration file:
Find the line:
Uncomment it and change `22` to a different port number, e.g. `2222`:
Restart the SSH service:
Use Strong Password Authentication
Ensure that users have strong passwords to protect against brute-force attacks.
Set password policies:
Set password policies:
minlen = 12
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
Disable Root Login
Disable root login to prevent attackers from gaining root access directly.
Edit the SSH configuration file:
Find the line:
Find the line:
Find the line:
Use SSH Key-Based Authentication
Key-based authentication is more secure than password-based authentication.
Generate a key pair on the client machine:
Generate a key pair on the client machine:
Ensure the `~/.ssh/authorized_keys` file on the server has the correct permissions:
chmod 700 ~/.ssh
Disable Password Authentication
After setting up key-based authentication, disable password authentication.
Edit the SSH configuration file:
Find the lines:
Limit User Logins
Restrict SSH access to specific users or groups.
Edit the SSH configuration file:
Edit the SSH configuration file:
Or for groups:
Or for groups:
Use a Firewall
Set up a firewall to allow only specific IP addresses to connect to your SSH port.
Set up a firewall to allow only specific IP addresses to connect to your SSH port.
sudo ufw enable
For `iptables`:
Install and Configure Fail2Ban
Fail2Ban helps protect against brute-force attacks by banning IPs with multiple failed login attempts.
Fail2Ban helps protect against brute-force attacks by banning IPs with multiple failed login attempts.
Fail2Ban helps protect against brute-force attacks by banning IPs with multiple failed login attempts.
Fail2Ban helps protect against brute-force attacks by banning IPs with multiple failed login attempts.
Find the `[sshd]` section and ensure it's enabled:
[sshd]
enabled = true
port = 2222
Find the `[sshd]` section and ensure it's enabled:
Enable Two-Factor Authentication (2FA)
For an added layer of security, enable 2FA for SSH logins.
Install Google Authenticator:
Install Google Authenticator:
Install Google Authenticator:
Install Google Authenticator:
Install Google Authenticator:
Install Google Authenticator:
Restart the SSH service:
Monitor SSH Logs
Restart the SSH service:
Restart the SSH service:
Restart the SSH service: