插件窝 干货文章 SSH安全加固:保护Linux SysOps环境免受攻击

SSH安全加固:保护Linux SysOps环境免受攻击

bash SSH sudo 密钥 906    来源:    2025-04-11

SSH安全加固指南:保护Linux SysOps环境

1. 基本SSH安全措施

1.1 禁用root直接登录

# 编辑SSH配置文件
sudo nano /etc/ssh/sshd_config

# 将以下参数修改为
PermitRootLogin no

1.2 更改默认SSH端口

# 在sshd_config中修改
Port 2222  # 或其他非标准端口(1024-65535)

1.3 限制登录尝试次数

# 安装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

2. 认证强化

2.1 强制使用密钥认证

# 在sshd_config中设置
PasswordAuthentication no
PubkeyAuthentication yes

2.2 生成SSH密钥对

ssh-keygen -t ed25519 -a 100  # 推荐使用Ed25519
# 或
ssh-keygen -t rsa -b 4096 -o -a 100  # 如果必须使用RSA

2.3 使用证书认证(高级)

# 创建CA证书
ssh-keygen -t rsa -b 4096 -f /etc/ssh/ca_key

# 在sshd_config中添加
TrustedUserCAKeys /etc/ssh/ca_key.pub

3. 访问控制

3.1 限制用户访问

# 允许特定用户
AllowUsers user1 user2

# 允许特定组
AllowGroups sshusers

3.2 IP地址限制

# 允许特定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

4. 高级安全配置

4.1 加密算法限制

# 在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

4.2 会话超时设置

# 客户端空闲超时
ClientAliveInterval 300
ClientAliveCountMax 2

# 登录宽限期
LoginGraceTime 1m

4.3 使用多因素认证(MFA)

# 安装Google Authenticator
sudo apt install libpam-google-authenticator

# 配置PAM
sudo nano /etc/pam.d/sshd
# 添加
auth required pam_google_authenticator.so

5. 监控与审计

5.1 启用详细日志

# 在sshd_config中设置
LogLevel VERBOSE

5.2 定期检查日志

# 查看失败的登录尝试
sudo grep "Failed password" /var/log/auth.log

# 查看成功登录
sudo grep "Accepted" /var/log/auth.log

5.3 使用OSSEC进行入侵检测

# 安装OSSEC
sudo apt install ossec-hids-server

6. 定期维护

6.1 更新SSH服务

sudo apt update && sudo apt upgrade openssh-server

6.2 定期轮换密钥

# 生成新密钥
ssh-keygen -t ed25519 -a 100 -f ~/.ssh/id_ed25519_new

# 将新公钥添加到服务器
ssh-copy-id -i ~/.ssh/id_ed25519_new.pub user@host

实施后检查清单

  1. 测试所有配置更改是否生效
  2. 验证备份管理员访问方法
  3. 确保所有授权用户都能正常连接
  4. 检查防火墙规则是否正确
  5. 确认监控系统能够捕获SSH相关事件

记住:任何安全配置更改都应先在测试环境中验证,然后再应用到生产系统。