Ubuntu 服务器安全加固 20 条军规 – 防止被入侵

为什么服务器安全很重要

服务器暴露在互联网上,每天都有大量扫描和攻击。一次成功的入侵可能导致数据泄露、沦为肉鸡、勒索等严重后果。安全加固是运维的基本功。

1. SSH 安全配置

修改默认端口

sudo nano /etc/ssh/sshd_config
Port 22022  # 改成非默认端口

禁用 root 登录

PermitRootLogin no

使用密钥登录

# 本地生成密钥
ssh-keygen -t ed25519

# 上传公钥到服务器
ssh-copy-id user@your-server

禁用密码登录

PasswordAuthentication no
ChallengeResponseAuthentication no

限制登录 IP

AllowUsers user@你的IP
# 重启 SSH
sudo systemctl restart sshd

2. 用户权限管理

# 创建新用户
sudo adduser username
sudo usermod -aG sudo username

# 检查 sudo 用户
getent group sudo

3. 防火墙配置

# 安装 ufw
sudo apt install ufw

# 允许 SSH(用新端口)
sudo ufw allow 22022/tcp

# 允许 HTTP/HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 启用防火墙
sudo ufw enable

# 查看状态
sudo ufw status verbose

4. 自动更新

# 安装 unattended-upgrades
sudo apt install unattended-upgrades

# 配置自动更新
sudo dpkg-reconfigure unattended-upgrades

5. 安装 Fail2Ban

# 安装
sudo apt install fail2ban

# 启动
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

# 查看状态
sudo fail2ban-client status

6. 文件权限

# 设置 SSH 密钥权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

# 设置网站目录权限
chmod -R 755 /var/www
chmod -R 775 /var/www/wp-content

7. 隐藏敏感信息

# 隐藏 Nginx 版本
sudo nano /etc/nginx/nginx.conf
server_tokens off;

# 隐藏 PHP 版本
sudo nano /etc/php/8.1/fpm/php.ini
expose_php = Off

8. 监控和日志

# 查看登录日志
lastlog
who
cat /var/log/auth.log | grep Failed

# 安装 logwatch 分析日志
sudo apt install logwatch

9. 禁用不必要的服务

# 查看运行中的服务
systemctl list-units --type=service --state=running

# 禁用不需要的服务
sudo systemctl stop service-name
sudo systemctl disable service-name

10. 使用安全的 TLS 配置

# Nginx TLS 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

检查清单

  • SSH 端口已修改
  • root 登录已禁用
  • SSH 密钥已配置
  • 密码登录已禁用
  • 防火墙已启用
  • Fail2Ban 已安装
  • 自动更新已配置
  • 敏感信息已隐藏
  • 日志监控已设置

总结

服务器安全是一个持续的过程,不是配置一次就完事。建议定期审计、检查日志、更新软件,安全无小事。

☁️
阿里云 推荐

想要稳定快速的服务器?推荐使用阿里云 ECS,新用户首年仅需百余元。

💰 佣金比例:7-15%
立即查看 →

Comments

No comments yet. Why don’t you start the discussion?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注