How to Harden Ssh Server Security on Ubuntu Linux
Learning how to harden SSH server security on Ubuntu Linux is essential for protecting your server from unauthorized access and potential security breaches. SSH (Secure Shell) serves as the primary gateway for remote server administration, making it a critical target for attackers. By implementing proper security measures, you can significantly reduce your server’s vulnerability to brute force attacks, unauthorized logins, and other common security threats.
This comprehensive tutorial covers essential SSH hardening techniques that every system administrator should implement. You’ll learn how to disable root login, configure key-based authentication, change default ports, and implement additional security layers. These modifications will transform your SSH server from a potential security liability into a fortified access point that maintains both security and functionality.
The techniques covered in this guide follow industry best practices and are suitable for production environments. Each step includes detailed explanations of why specific changes improve security and how they affect your server’s operation. By the end of this tutorial, you’ll have a significantly more secure SSH configuration that protects against common attack vectors while maintaining ease of use for legitimate administrators.
Prerequisites and Requirements for SSH Server Security Hardening
Before you begin implementing how to harden SSH server security on Ubuntu Linux, ensure you have the necessary access and meet the following requirements. You’ll need root or sudo privileges on your Ubuntu server to modify SSH configuration files and restart services. Additionally, maintain an active SSH connection to your server throughout this process, as some changes could potentially lock you out if not implemented correctly.
Your Ubuntu server should be running a recent version (18.04 LTS or newer) for optimal compatibility with the security features discussed in this tutorial. You’ll also need a basic understanding of Linux command-line operations and text editors like nano or vim. The entire hardening process typically takes 30-45 minutes to complete, depending on your familiarity with the commands.
Most importantly, ensure you have an alternative method to access your server (such as console access through your hosting provider’s control panel) in case SSH connectivity issues arise during the configuration process. This backup access method serves as a safety net if you accidentally misconfigure SSH settings and lose remote access to your server.
Step-by-Step Guide to Harden SSH Server Security on Ubuntu Linux
Related article: How to Optimize Wordpress Database Performance with Wp-optimize Plugin and Wp-config.php Settings
Step 1: Create a backup of the SSH configuration file
Before making any changes, create a backup of your current SSH configuration. This allows you to quickly restore the original settings if needed.
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
sudo chmod 600 /etc/ssh/sshd_config.backup
This backup ensures you can revert changes if something goes wrong during the hardening process.
Step 2: Disable root login via SSH
Root login via SSH presents a significant security risk. Disable it by editing the SSH configuration file:
sudo nano /etc/ssh/sshd_config
Find the line containing PermitRootLogin and change it to:
PermitRootLogin no
If the line doesn’t exist, add it to the configuration file. This change forces users to log in with regular accounts and use sudo for administrative tasks.
Step 3: Change the default SSH port
Changing the default SSH port (22) helps reduce automated attacks targeting the standard port. Choose a port number between 1024 and 65535:
Port 2222
Add this line to your SSH configuration file, replacing 2222 with your chosen port number. Remember to update your firewall rules and any connection scripts after implementing this change.
Step 4: Configure key-based authentication
Key-based authentication is more secure than password authentication. First, ensure public key authentication is enabled:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
Generate SSH keys on your local machine (not the server):
ssh-keygen -t rsa -b 4096 -C "[email protected]"
Copy the public key to your server:
ssh-copy-id username@your_server_ip
Step 5: Disable password authentication
After confirming key-based authentication works, disable password authentication entirely:
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
This configuration forces all connections to use SSH keys, eliminating password-based attacks.
Step 6: Limit user access and login attempts
Restrict SSH access to specific users and limit connection attempts:
AllowUsers username1 username2
MaxAuthTries 3
MaxStartups 3
Replace username1 and username2 with actual usernames that need SSH access. The MaxAuthTries setting limits authentication attempts per connection.
Step 7: Configure additional security settings
Add these security enhancements to your SSH configuration:
Protocol 2
IgnoreRhosts yes
HostbasedAuthentication no
PermitEmptyPasswords no
X11Forwarding no
MaxSessions 2
These settings disable legacy protocols and unnecessary features that could present security vulnerabilities.
Step 8: Set login timeouts and banners
Configure connection timeouts and warning banners:
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 60
Banner /etc/ssh/banner
Create a banner file to display legal warnings:
sudo nano /etc/ssh/banner
Add your warning message, such as “Unauthorized access prohibited.”
Step 9: Restart SSH service and test configuration
Apply your changes by restarting the SSH service:
sudo systemctl restart sshd
sudo systemctl status sshd
Test the configuration from another terminal session before closing your current connection. This ensures your changes work correctly and you maintain access to your server.
Troubleshooting Common SSH Security Configuration Issues
When implementing how to harden SSH server security on Ubuntu Linux, you may encounter several common issues. Connection refused errors often occur after changing the SSH port without updating firewall rules. Use sudo ufw allow 2222/tcp (replacing 2222 with your chosen port) to open the new port, then remove the old port with sudo ufw delete allow 22/tcp.
Permission denied errors typically result from incorrect SSH key permissions or misconfigured authorized_keys files. Ensure your .ssh directory has 700 permissions and the authorized_keys file has 600 permissions. Use these commands to fix permissions:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
If you accidentally lock yourself out, access your server through your hosting provider’s console or recovery mode. Restore the backup configuration file you created in Step 1, then restart the SSH service. Always test configuration changes in a separate terminal session before closing your primary connection.
For debugging SSH connection issues, enable verbose logging by temporarily adding LogLevel VERBOSE to your SSH configuration. Check the authentication logs using sudo tail -f /var/log/auth.log to identify specific connection problems. The official Ubuntu SSH documentation provides additional troubleshooting guidance for complex scenarios.
Advanced Security Measures and Best Practices
Beyond basic SSH hardening, implement additional security layers for comprehensive protection. Install and configure Fail2Ban to automatically block IP addresses that exhibit suspicious behavior:
sudo apt update
sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
Configure Fail2Ban for SSH protection by creating a custom jail configuration:
sudo nano /etc/fail2ban/jail.local
Add the following configuration:
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
Consider implementing two-factor authentication using Google Authenticator for an additional security layer. Install the necessary packages:
sudo apt install libpam-google-authenticator -y
Regular security audits help maintain your hardened SSH configuration. Use tools like ssh-audit to evaluate your SSH security posture and identify potential improvements. The SSH.com configuration guide offers detailed explanations of advanced SSH options for enterprise environments.
Monitor SSH connections regularly using who, w, and last commands to track user activity. Set up log monitoring with tools like Logwatch to receive daily reports of SSH activity and potential security events.
Successfully implementing how to harden SSH server security on Ubuntu Linux significantly improves your server’s security posture against common attack vectors. The configuration changes covered in this tutorial create multiple layers of protection, from disabling root login and implementing key-based authentication to changing default ports and limiting user access. These modifications work together to create a comprehensive security framework that maintains functionality while dramatically reducing vulnerability to unauthorized access attempts.
Regular maintenance of your SSH security configuration ensures continued protection as threats evolve. Review your SSH logs periodically, update your security policies as needed, and stay informed about new SSH vulnerabilities and patches. Consider implementing additional security measures like intrusion detection systems and network monitoring tools for enterprise environments requiring enhanced protection.
The hardened SSH configuration you’ve implemented serves as the foundation for secure server administration. Combined with regular system updates, strong firewall rules, and proper user management practices, these SSH security measures provide a solid defense against the most common server attack methods used by malicious actors today.
