跳到主要内容

服务器安全加固

本教程介绍如何对你的 GoMami VPS 进行基本的安全加固,降低被入侵的风险。

SSH 安全加固

1. 使用 SSH 密钥登录

首先确保已配置 SSH 密钥 并能正常使用密钥登录。

2. 禁用密码登录

确认密钥登录正常后,禁用密码登录:

# 编辑 SSH 配置
nano /etc/ssh/sshd_config

修改以下配置:

PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin prohibit-password
# 重启 SSH 服务
systemctl restart sshd
警告

禁用密码登录前务必确认密钥登录正常,否则可能导致无法连接服务器。如果被锁定,可通过 VNC 控制台 恢复。

3. 修改 SSH 端口

将默认的 22 端口改为其他端口,减少暴力扫描:

# 编辑配置
nano /etc/ssh/sshd_config
Port 2222
# 防火墙放行新端口
ufw allow 2222/tcp

# 重启 SSH
systemctl restart sshd
信息

修改端口后,连接时需要指定端口号:ssh -p 2222 root@your_server_ip

4. 限制登录尝试

安装 fail2ban 自动封禁暴力破解 IP:

# 安装
apt install -y fail2ban

# 创建自定义配置
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = 2222
maxretry = 5
bantime = 3600
findtime = 600
EOF

# 启动
systemctl start fail2ban
systemctl enable fail2ban

# 查看封禁状态
fail2ban-client status sshd

防火墙配置

UFW(Ubuntu / Debian)

# 安装(通常已预装)
apt install -y ufw

# 默认策略
ufw default deny incoming
ufw default allow outgoing

# 放行必要端口
ufw allow 2222/tcp # SSH(如果修改了端口)
ufw allow 80/tcp # HTTP
ufw allow 443/tcp # HTTPS

# 启用防火墙
ufw enable

# 查看规则
ufw status verbose

firewalld(CentOS / AlmaLinux)

# 启动防火墙
systemctl start firewalld
systemctl enable firewalld

# 放行端口
firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https

# 重载规则
firewall-cmd --reload

# 查看规则
firewall-cmd --list-all

系统更新

定期更新系统是最重要的安全措施之一:

# Ubuntu / Debian
apt update && apt upgrade -y

# CentOS / AlmaLinux
dnf update -y

启用自动安全更新

# Ubuntu / Debian
apt install -y unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades

创建非 root 用户

建议创建普通用户进行日常操作,仅在需要时使用 sudo:

# 创建用户
adduser deploy

# 添加到 sudo 组
usermod -aG sudo deploy

# 为新用户配置 SSH 密钥
mkdir -p /home/deploy/.ssh
cp ~/.ssh/authorized_keys /home/deploy/.ssh/
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys

安全检查清单

项目状态
SSH 密钥登录已配置[ ]
密码登录已禁用[ ]
SSH 端口已修改[ ]
fail2ban 已安装并运行[ ]
防火墙已启用[ ]
系统已更新到最新[ ]
自动安全更新已启用[ ]
非 root 用户已创建[ ]

下一步