SSH 보안
26.10: rc 상태의 OpenSSH 패키지를 대량 제거하지 마세요. 교체 패키지는 여전히 이전 구성을 사용할 수 있으며 제거하면 SSH가 손상될 수 있습니다. 26.10 알려진 문제을 확인하고 원격 유지 관리 전에 복구 액세스를 유지하세요.
SSH은 원격 Linux 서버 관리를 위한 핵심 도구이자 공격자의 가장 일반적인 대상 중 하나입니다. 이 문서에서는 Ubuntu 26.04에서 SSH 보안을 포괄적으로 강화하는 방법을 설명합니다.
키 인증
SSH 키 쌍 생성
클라이언트(로컬 컴퓨터)에서 키 쌍을 생성합니다.
# 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 passphrase서버에 공개 키 배포
# 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_keys키 로그인 테스트
# Log in using the key
ssh -i ~/.ssh/id_ed25519 user@server
# If configured as the default key, log in directly
ssh user@serverSSH 에이전트 키 관리
# 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 -DSSH 구성을 수정하기 전에 키 인증이 성공적으로 테스트되었는지 확인하고 현재 SSH 세션을 열어두세요. 새 터미널에서 정상적으로 로그인할 수 있는지 확인한 후에만 이전 연결을 닫으십시오. 그렇지 않으면 구성이 잘못되어 서버에서 영구적으로 잠길 수 있습니다.
SSH 서버 구성 강화
SSH 서버 구성 파일을 편집합니다.
sudo nano /etc/ssh/sshd_config비밀번호 로그인 비활성화
키 로그인이 작동하는지 확인한 후에만 비밀번호 로그인을 비활성화하십시오.
# Disable password authentication
PasswordAuthentication no
# Disable empty passwords
PermitEmptyPasswords no
# Disable keyboard-interactive authentication
KbdInteractiveAuthentication no루트 로그인 비활성화
# Completely prohibit root from logging in via SSH
PermitRootLogin no
# Or only allow root to log in with keys (not recommended)
# PermitRootLogin prohibit-password기본 포트 변경
# Use a non-standard port (reduces automated scanning)
Port 2222포트를 변경한 후 방화벽 규칙을 업데이트합니다.
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp로그인 사용자 제한
# Only allow specific users to log in
AllowUsers admin deployer
# Only allow specific groups to log in
AllowGroups sshusers
# Deny specific users
DenyUsers guest test기타 보안 설정
# 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 30구성 적용
# 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 보호
fall2ban은 로그 파일을 모니터링하고 여러 번의 로그인 시도 실패로 IP 주소를 자동으로 금지합니다.
설치 및 구성
# Install
sudo apt install fail2ban
# Start and enable at boot
sudo systemctl enable --now fail2ban로컬 구성 생성
/etc/fail2ban/jail.conf을 직접 편집하지 마십시오. 대신 로컬 구성을 만듭니다.
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 관리
# 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 reload고급 Fail2ban 구성
다른 서비스 보호:
# 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 클라이언트 구성
연결을 단순화하기 위해 클라이언트에서 SSH 구성 파일을 생성합니다.
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_ed25519구성 후 단순화된 연결:
ssh prod
ssh internal2단계 인증
SSH에 Google OTP 2단계 인증을 추가합니다.
# 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 포스트 퀀텀 키 교환
Ubuntu 26.04은 OpenSSH 10.2를 제공합니다. 기본 키 교환은 포스트 퀀텀 하이브리드 방식 mlkem768x25519-sha256(X25519와 결합된 ML-KEM-768)을 선호합니다. “지금 수확 후 해독” 공격.
# 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:"포스트퀀텀 KEX는 양측이 지원할 때만 사용됩니다. 이전 클라이언트/서버(9.0 아래의 OpenSSH)와 상호 운용되는 경우 수동 구성이 필요 없이 자동으로 클래식 curve25519-sha256 알고리즘으로 대체됩니다. 실제 호환성 문제가 없는 한, 실수로 양자 후 보호를 제거하는 것을 방지하려면 KexAlgorithms 기본값을 재정의하지 마십시오.
모니터링 및 감사
# 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 :22보안 체크리스트
변경 사항을 적용하기 전에 다음을 확인하세요.
- 키 인증이 구성 및 테스트되었습니다.
- 백업 접속 방법(콘솔 접속, 다른 사용자 등)이 있습니다.
- 해당 포트 규칙으로 방화벽이 업데이트되었습니다.
- Fail2ban 화이트리스트에는 일반적으로 사용되는 IP가 포함됩니다.
- 이전 터미널을 닫기 전에 새 터미널의 연결을 테스트했습니다.
- SSH 구성 구문은
sshd -t으로 검증되었습니다.