# 编辑SSH配置文件
sudo nano /etc/ssh/sshd_config
# 将以下参数修改为
PermitRootLogin no
# 在sshd_config中修改
Port 2222 # 或其他非标准端口(1024-65535)
# 安装fail2ban
sudo apt install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # RHEL/CentOS
# 配置fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
# 在sshd_config中设置
PasswordAuthentication no
PubkeyAuthentication yes
ssh-keygen -t ed25519 -a 100 # 推荐使用Ed25519
# 或
ssh-keygen -t rsa -b 4096 -o -a 100 # 如果必须使用RSA
# 创建CA证书
ssh-keygen -t rsa -b 4096 -f /etc/ssh/ca_key
# 在sshd_config中添加
TrustedUserCAKeys /etc/ssh/ca_key.pub
# 允许特定用户
AllowUsers user1 user2
# 允许特定组
AllowGroups sshusers
# 允许特定IP访问
AllowUsers user@192.168.1.* user@10.0.0.0/8
# 或使用防火墙规则
sudo ufw allow from 192.168.1.0/24 to any port 2222
# 在sshd_config中添加
KexAlgorithms curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
# 客户端空闲超时
ClientAliveInterval 300
ClientAliveCountMax 2
# 登录宽限期
LoginGraceTime 1m
# 安装Google Authenticator
sudo apt install libpam-google-authenticator
# 配置PAM
sudo nano /etc/pam.d/sshd
# 添加
auth required pam_google_authenticator.so
# 在sshd_config中设置
LogLevel VERBOSE
# 查看失败的登录尝试
sudo grep "Failed password" /var/log/auth.log
# 查看成功登录
sudo grep "Accepted" /var/log/auth.log
# 安装OSSEC
sudo apt install ossec-hids-server
sudo apt update && sudo apt upgrade openssh-server
# 生成新密钥
ssh-keygen -t ed25519 -a 100 -f ~/.ssh/id_ed25519_new
# 将新公钥添加到服务器
ssh-copy-id -i ~/.ssh/id_ed25519_new.pub user@host
记住:任何安全配置更改都应先在测试环境中验证,然后再应用到生产系统。