新开一台机器,公网 IP 上线几分钟,/var/log/auth.log 里就开始出现暴力破解的记录了。
1. 先配好密钥
本地:
1
2
| ssh-keygen -t ed25519 -C "laptop"
ssh-copy-id -p 22 user@server
|
先确认用密钥能登录,再进行下一步,不然就把自己锁在外面了。
2. 修改 sshd 配置
Debian 12 支持 sshd_config.d,新建 /etc/ssh/sshd_config.d/10-hardening.conf:
1
2
3
4
5
6
7
8
| Port 2022
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 20
AllowUsers deploy
|
1
| sudo sshd -t && sudo systemctl reload ssh
|
不要关闭当前会话,另开一个终端测试能登录再说。
关于改端口:它不能提高安全性,但能让日志清净很多,看日志时更容易发现真正的问题。
3. fail2ban
1
| sudo apt install fail2ban
|
/etc/fail2ban/jail.d/sshd.local:
1
2
3
4
5
6
7
| [sshd]
enabled = true
port = 2022
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h
|
Debian 12 默认没有 rsyslog,auth.log 不存在,所以要用 backend = systemd 从 journal 里读。
4. 自动安全更新
1
2
| sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
|
5. 防火墙
只放行用到的端口。云厂商的安全组和本机的 nftables 二选一就行,两边都配的话排查问题时容易忘了另一边。