乐闻世界logo
搜索文章和话题

How to perform SSH security hardening? What are the best practices and security configuration recommendations?

3月6日 23:38

SSH security hardening is an important measure to protect servers from unauthorized access. Through proper configuration and best practices, you can significantly improve the security of SSH servers.

Basic Security Configuration

1. Change Default Port

bash
# /etc/ssh/sshd_config Port 2222

Changing the default port reduces automated scanning and brute force attacks.

2. Disable Password Authentication

bash
# /etc/ssh/sshd_config PasswordAuthentication no PubkeyAuthentication yes

Only allow key authentication, greatly improving security.

3. Disable Root Login

bash
# /etc/ssh/sshd_config PermitRootLogin no

Disable direct root login, requiring login as regular user first then privilege escalation.

4. Restrict Login Users

bash
# /etc/ssh/sshd_config AllowUsers admin deploy DenyUsers test guest AllowGroups ssh-users

Only allow specific users or groups to login.

Advanced Security Configuration

1. Limit Authentication Attempts

bash
# /etc/ssh/sshd_config MaxAuthTries 3 MaxStartups 10:30:100 LoginGraceTime 60

Limit authentication attempts to prevent brute force attacks.

2. Configure Login Timeout

bash
# /etc/ssh/sshd_config ClientAliveInterval 300 ClientAliveCountMax 2

Automatically disconnect idle connections after timeout.

3. Disable Insecure Features

bash
# /etc/ssh/sshd_config X11Forwarding no AllowTcpForwarding yes GatewayPorts no PermitTunnel no

Disable unnecessary features to reduce attack surface.

4. Use Strong Encryption Algorithms

bash
# /etc/ssh/sshd_config # Key exchange algorithms KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256 # Encryption algorithms Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com # MAC algorithms MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

Use modern, secure encryption algorithms.

Network Layer Security

1. Use Firewall to Restrict Access

bash
# iptables example iptables -A INPUT -p tcp --dport 2222 -s 192.168.1.0/24 -j ACCEPT iptables -A INPUT -p tcp --dport 2222 -j DROP # ufw example ufw allow from 192.168.1.0/24 to any port 2222 ufw enable

Only allow specific IPs to access SSH port.

2. Use TCP Wrappers

bash
# /etc/hosts.allow sshd: 192.168.1.0/24 : ALLOW # /etc/hosts.deny sshd: ALL : DENY

Additional access control layer.

3. Use fail2ban to Prevent Brute Force

bash
# /etc/fail2ban/jail.local [sshd] enabled = true port = 2222 maxretry = 3 bantime = 3600 findtime = 600

Automatically ban IPs that attempt brute force attacks.

Key Management Best Practices

1. Use Strong Key Types

bash
# Generate ED25519 key (recommended) ssh-keygen -t ed25519 -b 4096 # Generate RSA 4096-bit key ssh-keygen -t rsa -b 4096

2. Set Passphrase for Private Keys

bash
ssh-keygen -t ed25519 -C "user@example.com" # Enter strong passphrase when prompted

3. Regularly Rotate Keys

bash
# Generate new key ssh-keygen -t ed25519 -f ~/.ssh/new_key # Add new public key to server ssh-copy-id -i ~/.ssh/new_key.pub user@server # Remove old key rm ~/.ssh/old_key

4. Restrict Key Usage

bash
# ~/.ssh/authorized_keys # Restrict to specific command only command="/usr/local/bin/backup-script" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... # Restrict source IP from="192.168.1.0/24" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... # Disable port forwarding no-port-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI...

Monitoring and Auditing

1. Enable Verbose Logging

bash
# /etc/ssh/sshd_config LogLevel VERBOSE SyslogFacility AUTHPRIV

Record detailed login information.

2. Monitor Login Activity

bash
# View recent logins last -n 20 # View failed login attempts lastb -n 20 # Monitor SSH logs in real-time tail -f /var/log/auth.log | grep sshd

3. Set Up Login Notifications

bash
# ~/.bashrc or /etc/profile echo "SSH login: $(date) $(whoami) from $(echo $SSH_CLIENT | awk '{print $1}')" | mail -s "SSH Login Alert" admin@example.com

Receive email notifications for logins.

Multi-Factor Authentication

1. Use Google Authenticator

bash
# Install apt-get install libpam-google-authenticator # Configure google-authenticator # /etc/pam.d/sshd auth required pam_google_authenticator.so # /etc/ssh/sshd_config ChallengeResponseAuthentication yes

2. Use SSH Certificates

bash
# Generate CA key ssh-keygen -t ed25519 -f ~/.ssh/ca_key # Issue user certificate ssh-keygen -s ~/.ssh/ca_key -I user_id -n username -V +52w ~/.ssh/user_key.pub # Server configuration # /etc/ssh/sshd_config TrustedUserCAKeys /etc/ssh/ca_key.pub

Regular Maintenance

1. Update SSH Software

bash
# Regularly check for updates apt-get update apt-get upgrade openssh-server # Or use automatic updates apt-get install unattended-upgrades

2. Review Configuration

bash
# Check configuration syntax sshd -t # View effective configuration sshd -T | grep -i password

3. Clean Up Old Keys

bash
# Remove unused keys rm ~/.ssh/old_key* # Clean up authorized_keys vim ~/.ssh/authorized_keys

Security Checklist

  • Change default port
  • Disable password authentication
  • Disable root login
  • Restrict login users
  • Configure firewall rules
  • Enable fail2ban
  • Use strong encryption algorithms
  • Regularly update SSH software
  • Enable verbose logging
  • Implement multi-factor authentication
  • Regularly audit access logs
  • Backup configuration files

Incident Response

1. Detect Intrusion Signs

bash
# Check abnormal logins last -n 100 | grep -v "reboot" # Check processes ps aux | grep ssh # Check network connections netstat -tuln | grep :2222

2. Immediate Response

bash
# Stop SSH service systemctl stop sshd # Modify configuration to strengthen security vim /etc/ssh/sshd_config # Restart service systemctl start sshd

3. Post-Incident Analysis

  • Analyze log files
  • Identify attack sources
  • Fix security vulnerabilities
  • Update security policies
标签:SSH