How to Secure Ssh on Ubuntu Server with Key-based Authentication and Advanced Configuration
Learning how to secure SSH on Ubuntu Server with key-based authentication and advanced configuration is essential for maintaining a robust server environment. SSH (Secure Shell) serves as the primary method for remote server access, making its security critical for protecting your infrastructure from unauthorized access and potential breaches.
This comprehensive tutorial will guide you through implementing key-based authentication, disabling password logins, configuring advanced SSH settings, and applying security best practices. You’ll learn to create SSH key pairs, modify configuration files, and implement additional security measures that significantly reduce your server’s attack surface.
By following this guide, you’ll transform your Ubuntu server’s SSH service from a basic installation into a hardened, enterprise-grade access point. The techniques covered here apply to Ubuntu 20.04 LTS, 22.04 LTS, and newer versions, ensuring your server remains secure against common attack vectors while maintaining convenient access for authorized users.
Prerequisites and Requirements for SSH Security Configuration
Before beginning this tutorial on how to secure SSH on Ubuntu Server with key-based authentication and advanced configuration, ensure you meet these requirements:
You need root or sudo access to your Ubuntu server. This tutorial assumes you’re working with Ubuntu 20.04 LTS or newer versions. You should have basic command-line knowledge and understand file permissions concepts.
Required software includes OpenSSH server (usually pre-installed), a text editor like nano or vim, and SSH client software on your local machine. For Windows users, consider using PuTTY or Windows Subsystem for Linux (WSL).
Time requirements: Allow 30-45 minutes to complete all steps, including testing and verification. Have a backup access method available, such as console access through your hosting provider’s control panel, in case SSH configuration issues occur.
Network access: Ensure you can connect to your server via SSH on the current port (typically 22). Note your current SSH port and connection method before making changes.
Step-by-Step Guide to Secure SSH on Ubuntu Server with Key-based Authentication
For more strange history, see: How to Configure Nginx Reverse Proxy with Ssl Termination for Production Applications
Step 1: Generate SSH Key Pair on Your Local Machine
First, create an SSH key pair on your local computer. Open your terminal or command prompt and run:
ssh-keygen -t ed25519 -b 4096 -C "[email protected]"
When prompted, choose a secure location for your key files. The default location `~/.ssh/id_ed25519` works well for most users. Set a strong passphrase when prompted – this adds an extra security layer to your private key.
The Ed25519 algorithm provides excellent security with smaller key sizes compared to RSA. If your system doesn’t support Ed25519, use RSA with 4096 bits:
ssh-keygen -t rsa -b 4096 -C "[email protected]"
Step 2: Copy Public Key to Ubuntu Server
Transfer your public key to the server using the `ssh-copy-id` command:
ssh-copy-id username@your-server-ip
Replace `username` with your actual username and `your-server-ip` with your server’s IP address. Enter your current password when prompted.
If `ssh-copy-id` isn’t available, manually copy the key:
cat ~/.ssh/id_ed25519.pub | ssh username@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Step 3: Test Key-based Authentication
Verify that key-based authentication works before disabling password authentication:
ssh username@your-server-ip
You should connect without entering your password (only your key passphrase if you set one). If this fails, check file permissions on the server:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Step 4: Configure SSH Server Settings
Edit the SSH configuration file to implement security improvements:
sudo nano /etc/ssh/sshd_config
Modify or add these essential security settings:
# Disable password authentication
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
# Disable root login
PermitRootLogin no
# Change default port (optional but recommended)
Port 2222
# Limit user access
AllowUsers yourusername
# Disable empty passwords
PermitEmptyPasswords no
# Set login grace time
LoginGraceTime 60
# Limit authentication attempts
MaxAuthTries 3
# Enable key-based authentication
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
Step 5: Apply Advanced Security Configurations
Add these advanced security measures to your SSH configuration:
# Protocol and encryption settings
Protocol 2
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],hmac-sha2-256,hmac-sha2-512
KexAlgorithms [email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
# Disable dangerous features
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no
# Connection settings
ClientAliveInterval 300
ClientAliveCountMax 2
MaxStartups 2
MaxSessions 2
Step 6: Restart and Test SSH Service
Restart the SSH service to apply your changes:
sudo systemctl restart ssh
Test your connection using the new port (if you changed it):
ssh -p 2222 username@your-server-ip
Keep your current SSH session open while testing to avoid being locked out.
Advanced SSH Security Configuration and Troubleshooting
Configure Fail2ban for SSH Protection
Install and configure Fail2ban to automatically block suspicious connection attempts:
sudo apt update
sudo apt install fail2ban -y
Create a custom Fail2ban configuration for SSH:
sudo nano /etc/fail2ban/jail.local
Add this configuration:
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
Start and enable Fail2ban:
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
Common Troubleshooting Issues
If you can’t connect after configuration changes, check these common issues:
Permission problems: Ensure `.ssh` directory has 700 permissions and `authorized_keys` has 600 permissions.
SELinux issues (if enabled): Run `sudo setsebool -P ssh_sysadm_login on` to allow SSH access.
Firewall blocking: Update UFW rules if you changed the SSH port:
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp
Check SSH service status and logs:
sudo systemctl status ssh
sudo journalctl -u ssh -f
Additional Security Measures
Consider implementing these extra security layers:
Configure SSH certificates for even stronger authentication. The Ubuntu OpenSSH documentation provides detailed information about certificate-based authentication.
Set up a VPN for an additional network layer. This ensures SSH traffic travels through an encrypted tunnel.
Implement network-level restrictions using iptables or cloud provider security groups to limit SSH access to specific IP addresses.
Conclusion and Next Steps
You’ve successfully implemented comprehensive SSH security measures on your Ubuntu server. Your server now uses key-based authentication, has disabled password logins, and includes advanced security configurations that significantly reduce attack vectors.
The security improvements you’ve implemented include strong encryption algorithms, connection limits, automatic intrusion detection, and proper access controls. These measures transform your server from a potential target into a hardened system that follows industry best practices.
Monitor your server logs regularly using `sudo tail -f /var/log/auth.log` to observe connection attempts and ensure your security measures work effectively. Consider setting up log monitoring tools like Logwatch for automated security reports.
For additional security, explore implementing two-factor authentication with tools like Google Authenticator, setting up intrusion detection systems like OSSEC, or implementing network segmentation. The OpenSSH manual provides comprehensive documentation for advanced configurations and security features that can further enhance your server’s protection.
