SSH Sicherheit
26.10: OpenSSH-Pakete im Status rc nicht in großen Mengen bereinigen. Ersatzpakete verwenden möglicherweise immer noch die alte Konfiguration und durch das Bereinigen kann SSH beschädigt werden. Überprüfen Sie 26.10 bekannte Probleme und behalten Sie den Wiederherstellungszugriff vor der Fernwartung bei.
SSH ist das Kerntool für die Remote-Linux-Serververwaltung und eines der häufigsten Ziele für Angreifer. In diesem Artikel wird erläutert, wie Sie die Sicherheit von SSH unter Ubuntu 26.04 umfassend härten.
Schlüsselauthentifizierung
Generieren eines SSH-Schlüsselpaars
Generieren Sie ein Schlüsselpaar auf dem Client (Ihrem lokalen Computer):
# Generate an Ed25519 key (recommended, more secure and faster)
ssh-keygen -t ed25519 -C "your_email@example.com"
# If you need compatibility with older systems, use RSA 4096-bit
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# You will be prompted:
# Enter file in which to save the key (/home/user/.ssh/id_ed25519):
# Enter passphrase (empty for no passphrase):
# It is strongly recommended to set a passphraseBereitstellen des öffentlichen Schlüssels auf dem Server
# Method 1: Using ssh-copy-id (recommended)
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
# Method 2: Manual copy
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
# Method 3: Manual operation
# On the server:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
# Paste the public key content
chmod 600 ~/.ssh/authorized_keysTesten der Schlüsselanmeldung
# Log in using the key
ssh -i ~/.ssh/id_ed25519 user@server
# If configured as the default key, log in directly
ssh user@serverSSH Agentenschlüsselverwaltung
# Start SSH Agent
eval "$(ssh-agent -s)"
# Add a key to the Agent (enter the passphrase once to cache it)
ssh-add ~/.ssh/id_ed25519
# List loaded keys
ssh-add -l
# Remove all cached keys
ssh-add -DStellen Sie vor dem Ändern der SSH-Konfiguration sicher, dass die Schlüsselauthentifizierung erfolgreich getestet wurde, und lassen Sie Ihre aktuelle SSH-Sitzung geöffnet. Schließen Sie die alte Verbindung erst, nachdem Sie überprüft haben, dass Sie sich normal von einem neuen Terminal aus anmelden können. Andernfalls könnte eine Fehlkonfiguration dazu führen, dass Sie dauerhaft vom Server ausgeschlossen werden.
Härtung der SSH-Serverkonfiguration
Bearbeiten Sie die Serverkonfigurationsdatei SSH:
sudo nano /etc/ssh/sshd_configPasswort-Login deaktivieren
Deaktivieren Sie die Passwortanmeldung erst, nachdem Sie bestätigt haben, dass die Schlüsselanmeldung funktioniert:
# Disable password authentication
PasswordAuthentication no
# Disable empty passwords
PermitEmptyPasswords no
# Disable keyboard-interactive authentication
KbdInteractiveAuthentication noDeaktivieren der Root-Anmeldung
# Completely prohibit root from logging in via SSH
PermitRootLogin no
# Or only allow root to log in with keys (not recommended)
# PermitRootLogin prohibit-passwordÄndern des Standardports
# Use a non-standard port (reduces automated scanning)
Port 2222Aktualisieren Sie nach dem Ändern des Ports Ihre Firewall-Regeln:
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcpEinschränken der Anmeldebenutzer
# Only allow specific users to log in
AllowUsers admin deployer
# Only allow specific groups to log in
AllowGroups sshusers
# Deny specific users
DenyUsers guest testAndere Sicherheitseinstellungen
# Limit authentication attempts
MaxAuthTries 3
# Limit concurrent unauthenticated connections
MaxStartups 3:50:10
# Session timeout (disconnect after 300 seconds of inactivity)
ClientAliveInterval 300
ClientAliveCountMax 2
# Disable X11 forwarding (servers usually don't need it)
X11Forwarding no
# Disable Agent forwarding (unless actually needed)
AllowAgentForwarding no
# Disable TCP forwarding (unless actually needed)
AllowTcpForwarding no
# Use strong encryption algorithms
# Note: OpenSSH 10.2 (26.04) already prefers the post-quantum KEX mlkem768x25519-sha256 by default.
# Avoid overriding KexAlgorithms — hardcoding a list freezes the algorithm set
# and may end up dropping newly added post-quantum defaults in the future. Keep the secure defaults.
#
# Only override for troubleshooting or temporary interop with old clients, and always put the post-quantum algorithm first:
# KexAlgorithms mlkem768x25519-sha256,sntrup761x25519-sha512@openssh.com,curve25519-sha256@libssh.org,curve25519-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
# Display a login banner
Banner /etc/ssh/banner.txt
# Login grace time
LoginGraceTime 30Anwenden der Konfiguration
# Check configuration syntax
sudo sshd -t
# Restart SSH service (on Ubuntu the unit is ssh.service; sshd is just an alias)
sudo systemctl restart ssh
# Note: on 26.04 ssh listens via socket activation by default,
# so after changing the port you must reload the socket unit:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
# Important: Test the connection in a new terminal window -- do not close the current one!
ssh -p 2222 user@serverfail2ban-Schutz
fail2ban überwacht Protokolldateien und sperrt automatisch IP-Adressen mit mehreren fehlgeschlagenen Anmeldeversuchen.
Installation und Konfiguration
# Install
sudo apt install fail2ban
# Start and enable at boot
sudo systemctl enable --now fail2banErstellen einer lokalen Konfiguration
Bearbeiten Sie /etc/fail2ban/jail.conf nicht direkt. Erstellen Sie stattdessen eine lokale Konfiguration:
sudo nano /etc/fail2ban/jail.local[DEFAULT]
# Ban duration (seconds)
bantime = 3600
# Detection time window (seconds)
findtime = 600
# Maximum failed attempts
maxretry = 3
# Ban action
banaction = ufw
# Ignored IPs (whitelist)
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24
# Email notifications
# destemail = admin@example.com
# sendername = Fail2Ban
# mta = sendmail
# action = %(action_mwl)s
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600Fail2ban verwalten
# View status
sudo fail2ban-client status
# View SSH jail status
sudo fail2ban-client status sshd
# View banned IPs
sudo fail2ban-client status sshd | grep "Banned IP"
# Manually ban an IP
sudo fail2ban-client set sshd banip 203.0.113.50
# Manually unban an IP
sudo fail2ban-client set sshd unbanip 203.0.113.50
# View fail2ban logs
sudo tail -f /var/log/fail2ban.log
# Reload configuration
sudo fail2ban-client reloadErweiterte fail2ban-Konfiguration
Andere Dienste schützen:
# Nginx authentication protection
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 3
# Nginx malicious requests
[nginx-botsearch]
enabled = true
filter = nginx-botsearch
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 2SSH Client-Konfiguration
Erstellen Sie auf dem Client eine SSH-Konfigurationsdatei, um Verbindungen zu vereinfachen:
nano ~/.ssh/config# Global settings
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
AddKeysToAgent yes
# Production server
Host prod
HostName 203.0.113.10
User admin
Port 2222
IdentityFile ~/.ssh/id_ed25519_prod
# Jump host
Host bastion
HostName 203.0.113.20
User jump
Port 2222
IdentityFile ~/.ssh/id_ed25519
# Connect to an internal server via jump host
Host internal
HostName 10.0.1.50
User admin
ProxyJump bastion
IdentityFile ~/.ssh/id_ed25519Vereinfachte Verbindungen nach der Konfiguration:
ssh prod
ssh internalZwei-Faktor-Authentifizierung
Fügen Sie die Zwei-Faktor-Authentifizierung von Google Authenticator zu SSH hinzu:
# Install
sudo apt install libpam-google-authenticator
# Each user runs the initialization
google-authenticator
# Follow the prompts to complete setup and scan the QR code
# Configure PAM
sudo nano /etc/pam.d/sshd
# Add:
# auth required pam_google_authenticator.so
# Configure SSH
sudo nano /etc/ssh/sshd_config
# Set:
# AuthenticationMethods publickey,keyboard-interactive
# KbdInteractiveAuthentication yes
sudo systemctl restart sshOpenSSH Post-Quantum-Schlüsselaustausch
Ubuntu 26.04 liefert OpenSSH 10.2, dessen Standardschlüsselaustausch das Post-Quantum-Hybridschema mlkem768x25519-sha256 (ML-KEM-768 kombiniert mit X25519) bevorzugt und so vor „Harvest-now-decrypt-später“-Angriffen schützt.
# Confirm the KEX algorithms supported by your OpenSSH (should include mlkem768x25519-sha256)
ssh -Q kex
# Inspect the KEX algorithm actually negotiated for a connection
ssh -v user@server 2>&1 | grep "kex:"Post-Quantum-KEX wird nur verwendet, wenn beide Seiten es unterstützen. Bei der Zusammenarbeit mit älteren Clients/Servern (OpenSSH unter 9.0) wird automatisch auf den klassischen curve25519-sha256-Algorithmus zurückgegriffen, ohne dass eine manuelle Konfiguration erforderlich ist. Sofern Sie kein echtes Kompatibilitätsproblem haben, überschreiben Sie nicht die Standardeinstellung KexAlgorithms, um zu vermeiden, dass der Post-Quantum-Schutz versehentlich entfernt wird.
Überwachung und Auditierung
# View successful login records
last -n 20
# View failed login records
lastb -n 20
# View SSH authentication logs
journalctl -u ssh.service --since today | grep -E "Accepted|Failed"
# Count failed login IPs
journalctl -u ssh.service | grep "Failed" | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20
# View current SSH connections
who
w
ss -tnp | grep :22Sicherheitscheckliste
Bevor Sie Änderungen übernehmen, bestätigen Sie Folgendes:
- Die Schlüsselauthentifizierung wurde konfiguriert und getestet
- Sie haben eine Backup-Zugriffsmethode (Konsolenzugriff, ein anderer Benutzer usw.)
- Die Firewall wurde mit den entsprechenden Portregeln aktualisiert
- Die fail2ban-Whitelist enthält Ihre häufig verwendeten IPs
- Sie haben die Verbindung von einem neuen Terminal aus getestet, bevor Sie das alte geschlossen haben
- Die Konfigurationssyntax von SSH wurde mit
sshd -tvalidiert