SSH (Secure Shell) 是管理Linux服务器的标准协议,但默认配置可能存在安全隐患。以下是如何安全配置SSH服务以保护您的CentOS服务器。
首先确保系统及SSH服务是最新版本:
sudo yum update -y
sudo yum install openssh-server openssh-clients -y
编辑SSH配置文件 /etc/ssh/sshd_config
:
sudo vi /etc/ssh/sshd_config
# 更改默认端口(避免自动化攻击)
Port 2222 # 改为1024-65535之间的非标准端口
# 禁用root直接登录
PermitRootLogin no
# 限制用户登录
AllowUsers your_username admin_user
# 或使用用户组
AllowGroups ssh_users
# 禁用密码认证,强制使用密钥
PasswordAuthentication no
# 禁用空密码
PermitEmptyPasswords no
# 限制最大认证尝试次数
MaxAuthTries 3
# 设置登录超时
LoginGraceTime 1m
# 禁用X11转发(除非需要)
X11Forwarding no
# 禁用端口转发(除非需要)
AllowTcpForwarding no
# 限制SSH协议版本(仅使用SSHv2)
Protocol 2
ssh-keygen -t ed25519 -a 100 # 或使用 -t rsa -b 4096
ssh-copy-id -p 2222 your_username@server_ip
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
sudo yum install google-authenticator
google-authenticator
然后在sshd_config
中添加:
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
sudo yum install epel-release
sudo yum install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
配置Fail2Ban监控SSH(编辑/etc/fail2ban/jail.local
):
[sshd]
enabled = true
port = 2222 # 与SSH配置的端口一致
filter = sshd
logpath = /var/log/secure
maxretry = 3
bantime = 1h
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
sudo semanage port -a -t ssh_port_t -p tcp 2222
sudo systemctl restart sshd
sudo systemctl enable sshd
从新终端测试连接:
ssh -p 2222 your_username@server_ip
sudo cat /var/log/secure | grep sshd
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
通过以上配置,您的CentOS服务器的SSH服务将具备企业级安全性,能够有效抵御大多数网络攻击。