How to install and configure OpenSSH server in Linux
How to Install and Configure OpenSSH Server in Linux
OpenSSH (Open Secure Shell) is a powerful network protocol that enables secure remote access to Linux systems over encrypted connections. As the de facto standard for remote system administration, SSH has replaced older, insecure protocols like Telnet and rlogin. This comprehensive guide will walk you through installing, configuring, and securing an OpenSSH server on various Linux distributions.
Table of Contents
- [Understanding OpenSSH Server](#understanding-openssh-server)
- [Prerequisites](#prerequisites)
- [Installing OpenSSH Server](#installing-openssh-server)
- [Basic Configuration](#basic-configuration)
- [Security Configuration](#security-configuration)
- [Advanced Configuration Options](#advanced-configuration-options)
- [Managing SSH Keys](#managing-ssh-keys)
- [Firewall Configuration](#firewall-configuration)
- [Testing Your SSH Setup](#testing-your-ssh-setup)
- [Troubleshooting Common Issues](#troubleshooting-common-issues)
- [Best Practices](#best-practices)
- [Conclusion](#conclusion)
Understanding OpenSSH Server
OpenSSH provides encrypted communication sessions over a computer network using the SSH protocol. The SSH server daemon (sshd) listens for connections from SSH clients, authenticates users, and provides secure command-line access to the system.
Key Features of OpenSSH
- Encryption: All communications are encrypted using strong cryptographic algorithms
- Authentication: Multiple authentication methods including passwords, public keys, and two-factor authentication
- Port Forwarding: Secure tunneling of network connections
- File Transfer: Secure file transfer capabilities through SCP and SFTP
- X11 Forwarding: Remote GUI application support
Prerequisites
Before installing OpenSSH server, ensure you have:
- A Linux system with administrative privileges
- Basic understanding of command-line operations
- Network connectivity
- Sufficient disk space (typically 10-50 MB)
Supported Linux Distributions
This guide covers installation on:
- Ubuntu/Debian
- CentOS/RHEL/Fedora
- openSUSE
- Arch Linux
Installing OpenSSH Server
Ubuntu and Debian-based Systems
On Ubuntu and Debian systems, use the APT package manager:
```bash
Update package repository
sudo apt update
Install OpenSSH server
sudo apt install openssh-server
Verify installation
sudo systemctl status ssh
```
CentOS, RHEL, and Fedora Systems
For Red Hat-based distributions:
CentOS/RHEL 7 and earlier:
```bash
Install OpenSSH server
sudo yum install openssh-server
Enable and start the service
sudo systemctl enable sshd
sudo systemctl start sshd
```
CentOS/RHEL 8+ and Fedora:
```bash
Install OpenSSH server
sudo dnf install openssh-server
Enable and start the service
sudo systemctl enable sshd
sudo systemctl start sshd
```
openSUSE Systems
```bash
Install OpenSSH server
sudo zypper install openssh
Enable and start the service
sudo systemctl enable sshd
sudo systemctl start sshd
```
Arch Linux
```bash
Install OpenSSH server
sudo pacman -S openssh
Enable and start the service
sudo systemctl enable sshd
sudo systemctl start sshd
```
Verifying Installation
Check if the SSH service is running:
```bash
Check service status
sudo systemctl status sshd
Verify SSH is listening on port 22
sudo netstat -tlnp | grep :22
or
sudo ss -tlnp | grep :22
```
Basic Configuration
The main SSH server configuration file is located at `/etc/ssh/sshd_config`. Before making changes, create a backup:
```bash
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
```
Essential Configuration Parameters
Edit the configuration file:
```bash
sudo nano /etc/ssh/sshd_config
```
Basic Settings
```bash
Port configuration (default is 22)
Port 22
Listen on specific IP addresses
#ListenAddress 0.0.0.0
#ListenAddress ::
Protocol version (SSH-2 only for security)
Protocol 2
Host keys
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
```
Authentication Settings
```bash
Enable public key authentication
PubkeyAuthentication yes
Authorized keys file location
AuthorizedKeysFile .ssh/authorized_keys
Password authentication (disable after setting up key-based auth)
PasswordAuthentication yes
Empty passwords (should be disabled)
PermitEmptyPasswords no
```
Login Settings
```bash
Root login configuration
PermitRootLogin no
Maximum authentication attempts
MaxAuthTries 3
Login grace time
LoginGraceTime 60
Maximum concurrent sessions
MaxSessions 10
```
Applying Configuration Changes
After modifying the configuration file, restart the SSH service:
```bash
Test configuration syntax
sudo sshd -t
If syntax is correct, restart the service
sudo systemctl restart sshd
```
Security Configuration
Securing your SSH server is crucial for protecting your system from unauthorized access.
Disable Root Login
Prevent direct root login via SSH:
```bash
PermitRootLogin no
```
Change Default Port
Change the default SSH port from 22 to a non-standard port:
```bash
Port 2222
```
Remember to update firewall rules accordingly.
Limit User Access
Restrict SSH access to specific users or groups:
```bash
Allow only specific users
AllowUsers username1 username2
Allow users from specific groups
AllowGroups sshusers
Deny specific users
DenyUsers baduser1 baduser2
```
Configure Connection Timeouts
Set appropriate timeout values:
```bash
Client alive interval (seconds)
ClientAliveInterval 300
Maximum client alive count
ClientAliveCountMax 2
Login grace time
LoginGraceTime 60
```
Disable Unused Features
Disable features you don't need:
```bash
Disable X11 forwarding if not needed
X11Forwarding no
Disable agent forwarding
AllowAgentForwarding no
Disable TCP forwarding if not needed
AllowTcpForwarding no
Disable gateway ports
GatewayPorts no
```
Configure Login Banner
Display a warning banner before login:
```bash
Create banner file
sudo nano /etc/ssh/banner.txt
```
Add your warning message:
```
*
NOTICE TO USERS
This computer system is the private property of its owner, whether
individual, corporate or government. It is for authorized use only.
Users (authorized or unauthorized) have no explicit or implicit
expectation of privacy.
*
```
Enable the banner in sshd_config:
```bash
Banner /etc/ssh/banner.txt
```
Advanced Configuration Options
SSH Protocol Optimization
Configure encryption algorithms and key exchange methods:
```bash
Key exchange algorithms
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256
Host key algorithms
HostKeyAlgorithms ssh-ed25519,ssh-rsa,ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256
Symmetric ciphers
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MAC algorithms
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha2-512
```
Configure Logging
Set up comprehensive logging:
```bash
Log level
LogLevel VERBOSE
Log facility
SyslogFacility AUTH
Log file location (varies by distribution)
Logs typically go to /var/log/auth.log or /var/log/secure
```
Chroot Configuration
Create a chrooted environment for specific users:
```bash
Create chroot directory
sudo mkdir -p /home/chroot
Configure in sshd_config
Match User chrootuser
ChrootDirectory /home/chroot
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
```
Managing SSH Keys
SSH key-based authentication is more secure than password authentication.
Generate SSH Keys (Client-side)
On the client machine:
```bash
Generate RSA key (4096 bits)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Generate ED25519 key (recommended)
ssh-keygen -t ed25519 -C "your_email@example.com"
Generate ECDSA key
ssh-keygen -t ecdsa -b 521 -C "your_email@example.com"
```
Copy Public Key to Server
```bash
Using ssh-copy-id (easiest method)
ssh-copy-id username@server_ip
Manual method
cat ~/.ssh/id_rsa.pub | ssh username@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Set correct permissions on server
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
```
Disable Password Authentication
After setting up key-based authentication:
```bash
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
```
Firewall Configuration
Configure your firewall to allow SSH connections.
UFW (Ubuntu Firewall)
```bash
Allow SSH on default port
sudo ufw allow ssh
Allow SSH on custom port
sudo ufw allow 2222/tcp
Enable firewall
sudo ufw enable
```
Firewalld (CentOS/RHEL/Fedora)
```bash
Allow SSH service
sudo firewall-cmd --permanent --add-service=ssh
Allow custom SSH port
sudo firewall-cmd --permanent --add-port=2222/tcp
Reload firewall
sudo firewall-cmd --reload
```
iptables
```bash
Allow SSH on port 22
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Save rules (method varies by distribution)
sudo iptables-save > /etc/iptables/rules.v4
```
Testing Your SSH Setup
Local Testing
Test SSH configuration syntax:
```bash
sudo sshd -t
```
Remote Testing
Test SSH connection from another machine:
```bash
Basic connection test
ssh username@server_ip
Test specific port
ssh -p 2222 username@server_ip
Verbose output for troubleshooting
ssh -v username@server_ip
```
Connection Testing Scripts
Create a simple test script:
```bash
#!/bin/bash
echo "Testing SSH connection to $1"
ssh -o ConnectTimeout=5 -o BatchMode=yes $1 exit
if [ $? -eq 0 ]; then
echo "SSH connection successful"
else
echo "SSH connection failed"
fi
```
Troubleshooting Common Issues
SSH Service Won't Start
Check service status and logs:
```bash
Check service status
sudo systemctl status sshd
Check logs
sudo journalctl -u sshd -f
Check configuration syntax
sudo sshd -t
```
Connection Refused
Common causes and solutions:
1. Service not running: Start the SSH service
2. Wrong port: Verify the port number
3. Firewall blocking: Check firewall rules
4. Network connectivity: Test basic network connection
```bash
Check if SSH is listening
sudo netstat -tlnp | grep sshd
Test network connectivity
ping server_ip
telnet server_ip 22
```
Permission Denied
Authentication issues:
```bash
Check SSH logs
sudo tail -f /var/log/auth.log
Verify user permissions
ls -la ~/.ssh/
```
Key Authentication Not Working
Common key authentication problems:
```bash
Check file permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Verify key format
ssh-keygen -l -f ~/.ssh/id_rsa.pub
Test key authentication
ssh -i ~/.ssh/id_rsa username@server_ip
```
SELinux Issues
On SELinux-enabled systems:
```bash
Check SELinux status
sestatus
Check SSH-related SELinux denials
sudo ausearch -m AVC -ts recent | grep ssh
Restore SSH SELinux contexts
sudo restorecon -R -v /home/username/.ssh
```
Best Practices
Security Best Practices
1. Use key-based authentication instead of passwords
2. Change default port to reduce automated attacks
3. Disable root login via SSH
4. Use fail2ban to prevent brute-force attacks
5. Keep OpenSSH updated to latest version
6. Use strong encryption algorithms
7. Implement connection rate limiting
8. Regular security audits of SSH configuration
Install and Configure Fail2ban
```bash
Install fail2ban
sudo apt install fail2ban # Ubuntu/Debian
sudo yum install fail2ban # CentOS/RHEL
Configure SSH jail
sudo nano /etc/fail2ban/jail.local
```
Add SSH protection:
```ini
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
```
Monitoring and Maintenance
1. Monitor SSH logs regularly
2. Review authorized_keys files periodically
3. Audit user access and remove unused accounts
4. Update SSH keys regularly
5. Monitor for suspicious activities
Performance Optimization
```bash
Optimize SSH for performance
Compression yes
UseDNS no
GSSAPIAuthentication no
```
Backup Important Files
Regularly backup SSH configuration:
```bash
Create backup directory
sudo mkdir -p /root/ssh-backup
Backup SSH configuration
sudo cp -r /etc/ssh/ /root/ssh-backup/
sudo cp -r ~/.ssh/ /root/ssh-backup/user-ssh/
```
Conclusion
Installing and configuring OpenSSH server is a fundamental skill for Linux system administrators. This comprehensive guide has covered everything from basic installation to advanced security configurations. Remember that SSH security is an ongoing process that requires regular maintenance and monitoring.
Key takeaways from this guide:
- Always backup configuration files before making changes
- Test configurations thoroughly before applying them to production systems
- Implement multiple layers of security (key authentication, firewalls, fail2ban)
- Keep OpenSSH updated to the latest version
- Monitor SSH logs regularly for suspicious activities
- Follow the principle of least privilege when configuring user access
By following the steps and best practices outlined in this guide, you'll have a secure, well-configured OpenSSH server that provides reliable remote access to your Linux systems while maintaining strong security standards.
Remember to adapt these configurations to your specific environment and security requirements. SSH configuration is highly flexible, and the optimal setup will depend on your particular use case, security policies, and network environment.