温馨提示×

CentOS如何加固SSH安全

小樊
42
2026-07-07 23:26:36
栏目: 智能运维

CentOS(7/8/Stream) 上加固 SSH 安全,可以从 端口、认证、协议、访问控制、审计 等多个层面进行。下面是一套生产环境常见且实用的加固方案,按优先级整理。


一、基础配置加固(最重要)

1. 修改默认 SSH 端口(减少扫描)

vim /etc/ssh/sshd_config
Port 22222

然后重启:

systemctl restart sshd

✅ 注意:

  • 云服务器需同步放行 安全组 / 防火墙端口
  • 不要直接关 22,先测试新端口

2. 禁止 root 直接登录

PermitRootLogin no

✅ 建议:

  • 使用普通用户 + sudo
  • 或仅允许特定 IP 的 root 登录

3. 禁用密码登录,仅使用密钥认证(强烈推荐)

PasswordAuthentication no
PubkeyAuthentication yes

配置密钥登录

ssh-keygen -t ed25519
ssh-copy-id user@server

4. 限制 SSH 用户

AllowUsers user1 user2
# 或
DenyUsers root test

二、协议与加密加固

5. 使用 SSH 协议 2(默认已是)

Protocol 2

6. 禁用弱加密算法(CentOS 7/8 推荐)

Ciphers aes128-ctr,aes192-ctr,aes256-ctr
MACs hmac-sha2-256,hmac-sha2-512
KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512

三、连接与暴力破解防护

7. 限制登录尝试次数

MaxAuthTries 3

8. 设置连接超时

ClientAliveInterval 300
ClientAliveCountMax 2

9. 使用 fail2ban 防暴力破解(强烈推荐)

yum install -y epel-release
yum install -y fail2ban

配置:

vim /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 22222
logpath = /var/log/secure
maxretry = 3
bantime = 3600

启动:

systemctl enable fail2ban
systemctl start fail2ban

四、防火墙 & SELinux

10. 防火墙限制 SSH

firewall-cmd --permanent --add-port=22222/tcp
firewall-cmd --reload

✅ 建议:仅允许指定 IP

firewall-cmd --permanent --add-rich-rule='
  rule family="ipv4" source address="1.2.3.4" port protocol="tcp" port="22222" accept'

11. 保持 SELinux 开启

getenforce

应为:

Enforcing

五、审计与日志

12. 查看 SSH 登录日志

journalctl -u sshd
# 或
/var/log/secure

13. 启用登录告警(可选)

vim /etc/ssh/sshd_config
PrintLastLog yes

六、CentOS 8 / Stream 额外建议

14. 使用 systemd 限制 SSH 资源(防滥用)

[Service]
LimitNOFILE=10000

七、推荐安全配置示例(可直接用)

Port 22222
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers deploy admin

八、加固检查清单 ✅

项目 是否完成
修改 SSH 端口
禁用 root 登录
使用密钥认证
fail2ban 启用
防火墙限制
SELinux 开启

如果你愿意,我可以:

  • 给你一份 CentOS 7 / 8 专用 SSH 加固脚本
  • 根据你的服务器环境(云 / 内网)给出定制方案
  • 帮你检查当前 SSH 配置是否安全

只要告诉我你的 CentOS 版本 + 是否公网服务器 即可。

0