温馨提示×

ubuntu thinkphp如何防黑客

小樊
36
2026-10-13 10:28:57
栏目: 编程语言

在 Ubuntu + ThinkPHP 环境下,防止黑客攻击需要从 系统层、Web服务层、ThinkPHP框架层、代码层、运维层 多方面入手。下面给你一套实战级防护方案(以 ThinkPHP 5 / 6 为主,也适用于 8)。


一、系统与服务器安全(Ubuntu)

1. 最小权限原则

# 不要用 root 运行 web
useradd -m www

Nginx / PHP-FPM 使用 www 用户运行。

2. 防火墙(UFW)

ufw allow 22
ufw allow 80
ufw allow 443
ufw enable

3. 禁止 root SSH 登录

vim /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no

使用 SSH 密钥登录

4. 定期更新

apt update && apt upgrade -y

二、Web 服务安全(Nginx)

1. 禁止敏感目录访问

location ~ /\. {
    deny all;
}

location ~* /(runtime|vendor|config|env)/ {
    deny all;
}

location ~* \.(log|sql|ini|env)$ {
    deny all;
}

2. 关闭目录遍历

autoindex off;

3. 限制 POST 大小(防大包攻击)

client_max_body_size 8m;

三、ThinkPHP 安全配置(非常重要)

1. 生产环境必须关闭调试

.env

APP_DEBUG = false

2. 隐藏入口文件

Nginx:

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

3. 禁止直接访问 PHP 文件

location ~ ^/.*\.php$ {
    # 只允许 index.php
    if ($fastcgi_script_name !~ ^/index.php$) {
        return 403;
    }
}

四、ThinkPHP 防黑客核心措施

1. 强制使用 CSRF

// middleware
\think\middleware\CheckCsrfToken::class

表单:

<input type="hidden" name="__token__" value="{:token()}">

2. 防 SQL 注入(不要拼 SQL)

❌ 错误:

Db::query("SELECT * FROM user WHERE id = $id");

✅ 正确:

Db::name('user')->where('id', $id)->find();

3. 防 XSS

input('post.content', '', 'htmlspecialchars');

或使用中间件统一过滤。


4. 防文件上传漏洞

validate(['file' => 'fileSize:1024000|fileExt:jpg,png'])

保存路径 不要在前端可控目录


5. 路由白名单

Route::get('user/profile', 'User/profile');

禁止:

Route::any(':controller/:action', ':controller/:action');

五、ThinkPHP 历史漏洞防护

1. 升级 ThinkPHP

composer update topthink/framework

⚠️ 以下版本极危险:

  • ThinkPHP 5.0.x < 5.0.23
  • ThinkPHP 5.1.x < 5.1.31
  • ThinkPHP 6.0 < 6.0.2

2. 删除测试文件

rm public/.htaccess.bak
rm think

六、日志与监控

1. 开启 Nginx / PHP 日志

tail -f /var/log/nginx/access.log
tail -f /var/log/php7.4-fpm.log

2. 防暴力破解

apt install fail2ban

3. 文件完整性监控

apt install aide

七、黑客常见攻击 & 对应防御

攻击方式 防御
SQL注入 ORM / 参数绑定
XSS 输出转义
CSRF Token
文件上传 后缀+内容校验
RCE 升级框架
目录遍历 Nginx 限制
暴力破解 Fail2ban

八、推荐安全组合(生产级)

  • Ubuntu 22.04
  • Nginx + PHP-FPM
  • ThinkPHP 8
  • Cloudflare(防 CC / DDoS)
  • HTTPS(Let’s Encrypt)
  • 每日自动备份

如果你愿意,我可以: ✅ 帮你 检查 ThinkPHP 是否存在漏洞 ✅ 给你一套 Nginx 完整安全配置 ✅ 按你的 ThinkPHP 版本定制防护方案

你用的是 ThinkPHP 几?Ubuntu 几?

0 踩