Secure SSH on Ubuntu: Key-Only Authentication, Fail2ban, and Access Controls
Introduction
Secure Shell (SSH) is a protocol that enables secure communication between clients and servers over an unsecured network. It is widely used for remote server administration, file transfers, and secure command-line access. Given its importance, ensuring the security of SSH access is paramount to safeguard systems from unauthorized access and potential attacks.
This tutorial will cover key-only authentication, the use of Fail2ban to block malicious login attempts, and access controls through the sshd_config file. We'll focus on disabling password authentication, enabling public key authentication, and implementing user restrictions to further enhance SSH security. By following these practices, you'll significantly reduce the risk of unauthorized access to your Ubuntu servers.
Prerequisites
- Ubuntu Version: This tutorial is applicable for Ubuntu 20.04 LTS and later.
- Required Packages: The
openssh-serverpackage should be installed, which is typically included in Ubuntu installations. - Permissions: Root or sudo access is required to modify SSH configurations and restart services.
- Risks: Misconfiguration may lock you out of your server, so it's crucial to test changes before closing active sessions.
Core Concepts
- SSH (Secure Shell): A protocol for securely accessing network services over an unsecured network.
- Public Key Authentication: A method of authenticating users without passwords, using cryptographic keys instead.
- Fail2ban: A security tool that monitors log files and bans IPs that show malicious signs, such as too many password failures.
sshd_config: The main configuration file for the SSH daemon (server), where various settings related to SSH can be defined.- AllowUsers: A directive in the
sshd_configfile that restricts SSH access to specified users.
When to Use
These security measures are crucial when deploying any server accessible over the internet, especially for servers hosting sensitive data or services.
Limits
Note that while these measures significantly enhance security, they do not eliminate all risks. Continuous monitoring and regular updates are essential.
Syntax/Commands
| Command | Description |
|---|---|
sudo nano /etc/ssh/sshd_config |
Edit SSH daemon configuration file |
sudo systemctl restart ssh |
Restart SSH service |
ssh-keygen |
Generate a new SSH key pair |
fail2ban-client |
Manage Fail2ban |
sudo ufw allow ssh |
Allow SSH through the firewall |
Practical Examples
1. Install OpenSSH Server
sudo apt update
sudo apt install openssh-server # Install SSH server
2. Generate SSH Key Pair
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # Generate a new SSH key pair
# Follow the prompts to save the key in the default location
3. Copy Public Key to Server
ssh-copy-id username@your_server_ip # Copy public key to the remote server
4. Edit sshd_config
sudo nano /etc/ssh/sshd_config # Open SSH configuration file
Within the file, make the following changes:
PasswordAuthentication no # Disable password authentication
PubkeyAuthentication yes # Enable public key authentication
AllowUsers your_username # Restrict SSH access to specific users
5. Restart SSH Service
sudo systemctl restart ssh # Restart the SSH service to apply changes
6. Install Fail2ban
sudo apt install fail2ban # Install Fail2ban for added security
7. Configure Fail2ban
Create a jail configuration for SSH:
sudo nano /etc/fail2ban/jail.local # Create or edit jail configuration file
Add the following configuration:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 600 # Ban for 10 minutes
8. Start and Enable Fail2ban
sudo systemctl start fail2ban # Start Fail2ban service
sudo systemctl enable fail2ban # Enable Fail2ban on boot
Real-World Scenarios
Scenario 1: Securing a Web Server
You run a web server that is publicly accessible. By implementing key-only authentication and Fail2ban, you reduce the risk of brute-force attacks. This ensures that only users with the correct private key can access the server, while Fail2ban temporarily bans IP addresses that trigger multiple failed login attempts.
Scenario 2: Managing Multiple Users
In a development environment with multiple team members, using the AllowUsers directive ensures that only specified users can SSH into the server. This is particularly useful for restricting access to sensitive production systems.
Scenario 3: Remote Administration
For remote administration, you set up SSH with key-only authentication and Fail2ban on a cloud VM. This mitigates the risk of unauthorized access, ensuring that only admins with valid keys can manage the server.
Best Practices
- Use Strong Keys: Always generate SSH keys with at least 2048-bit encryption.
- Regularly Update Software: Keep your Ubuntu system and installed packages up-to-date to protect against vulnerabilities.
- Limit User Access: Use the
AllowUsersdirective to restrict SSH access to only those who need it. - Monitor Logs: Regularly check
/var/log/auth.logfor unusual login attempts. - Backup Configuration: Before making changes to
sshd_configor Fail2ban, back up your configuration files.
Common Errors
Error:
sshd: no hostkeys available -- exiting.- Cause: SSH host keys are missing.
- Fix: Generate host keys using
ssh-keygen -A.
Error:
Permission denied (publickey).- Cause: The public key is not in the
~/.ssh/authorized_keysfile on the server. - Fix: Ensure the public key is correctly copied to the server.
- Cause: The public key is not in the
Error:
Could not resolve hostname: Name or service not known.- Cause: The hostname is incorrect or the server is unreachable.
- Fix: Check the IP address/hostname and network connectivity.
Error:
Connection refused.- Cause: SSH daemon is not running or firewall settings are incorrect.
- Fix: Check if the SSH service is active with
sudo systemctl status sshand adjust firewall settings.
Related Commands
| Command | Description |
|---|---|
ssh |
Connect to a remote server using SSH |
scp |
Securely copy files between hosts |
sftp |
Securely transfer files using SSH |
ssh-keygen |
Generate SSH key pairs |
Automation Script
#!/bin/bash
# Secure SSH Configuration Script
# Update and install OpenSSH server
sudo apt update
sudo apt install -y openssh-server
# Generate SSH key pair if it doesn't exist
if [ ! -f ~/.ssh/id_rsa ]; then
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -N "" -f ~/.ssh/id_rsa
fi
# Configure SSH daemon
cat <<EOT | sudo tee /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers your_username
EOT
# Restart SSH service
sudo systemctl restart ssh
# Install and configure Fail2ban
sudo apt install -y fail2ban
cat <<EOT | sudo tee /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 600
EOT
# Start and enable Fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
echo "SSH hardening complete!"
Conclusion
Securing SSH on your Ubuntu system is a crucial step in protecting against unauthorized access and potential security breaches. By implementing key-only authentication, configuring Fail2ban, and restricting access through the sshd_config file, you can significantly enhance your server's security posture.
Next steps should involve regularly monitoring SSH logs, conducting security audits, and staying informed about best practices in server security.
