PHP 怎么PHP 开源WAF

wen PHP项目 4

本文目录导读:

PHP 怎么PHP 开源WAF

  1. 流行的PHP开源WAF
  2. 简单PHP WAF实现示例
  3. 其他推荐的开源WAF
  4. 部署建议

我来为你详细介绍PHP开源WAF(Web应用防火墙)的相关内容。

流行的PHP开源WAF

ModSecurity + PHP

  • 项目地址: https://github.com/SpiderLabs/ModSecurity
  • 特点:
    • 最知名的WAF引擎
    • 支持OWASP Core Rule Set
    • 可作为Apache/Nginx模块
    • PHP可通过第三方扩展集成

php-waf

  • 项目地址: https://github.com/zecool/php-waf
  • 特点:
    • 纯PHP实现
    • 轻量级,易于部署
    • 支持常见的Web攻击防护
    • 可自定义规则

OpenWAF

  • 项目地址: https://github.com/titansec/OpenWAF
  • 特点:
    • 基于Nginx + Lua
    • 支持动态规则更新
    • 性能较好
    • 有PHP接口支持

简单PHP WAF实现示例

<?php
class SimpleWAF {
    private $rules = [];
    private $blacklist = [];
    public function __construct() {
        $this->initRules();
        $this->initBlacklist();
    }
    private function initRules() {
        // SQL注入规则
        $this->rules['sql_injection'] = [
            '/\b(union|select|insert|update|delete|drop|alter)\b/i',
            '/\'|\"|--|#|;|\/\*/',
            '/\b(or|and)\b\s+\d+\s*=\s*\d+/i'
        ];
        // XSS规则
        $this->rules['xss'] = [
            '/<script\b[^>]*>(.*?)<\/script>/is',
            '/javascript\s*:/i',
            '/on\w+\s*=\s*[\'"]?[^\'"]*[\'"]?/i',
            '/<[^>]*\bon\w+\s*=[^>]*>/i'
        ];
        // 路径遍历规则
        $this->rules['path_traversal'] = [
            '/\.\.\//',
            '/\.\.\\\\/',
            '/\.\.%2f/i',
            '/\.\.%5c/i'
        ];
        // 命令注入规则
        $this->rules['command_injection'] = [
            '/\b(exec|system|passthru|shell_exec|popen|proc_open)\s*\(/i',
            '/\||`|;|\$\(|\$\{/',
            '/\b(cmd|powershell|wget|curl)\b/i'
        ];
    }
    private function initBlacklist() {
        $this->blacklist = [
            'blocked_ips' => [],
            'blocked_user_agents' => [
                'sqlmap',
                'nikto',
                'nmap',
                'masscan'
            ]
        ];
    }
    public function check($input) {
        foreach ($this->rules as $type => $patterns) {
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $input)) {
                    $this->logAttack($type, $input);
                    return false;
                }
            }
        }
        return true;
    }
    public function checkRequest() {
        // 检查IP黑名单
        $ip = $_SERVER['REMOTE_ADDR'];
        if (in_array($ip, $this->blacklist['blocked_ips'])) {
            $this->block('Blocked IP');
            return false;
        }
        // 检查User-Agent
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        foreach ($this->blacklist['blocked_user_agents'] as $blocked_ua) {
            if (stripos($ua, $blocked_ua) !== false) {
                $this->block('Blocked User-Agent');
                return false;
            }
        }
        // 检查所有GET/POST参数
        foreach ($_GET as $key => $value) {
            if (!$this->check($value)) {
                $this->block('Malicious input in GET parameter');
                return false;
            }
        }
        foreach ($_POST as $key => $value) {
            if (is_array($value)) {
                // 处理数组参数
                array_walk_recursive($value, function($v) {
                    if (!$this->check($v)) {
                        $this->block('Malicious input in POST parameter');
                        return false;
                    }
                });
            } else {
                if (!$this->check($value)) {
                    $this->block('Malicious input in POST parameter');
                    return false;
                }
            }
        }
        // 检查Cookie
        foreach ($_COOKIE as $key => $value) {
            if (!$this->check($value)) {
                $this->block('Malicious input in Cookie');
                return false;
            }
        }
        // 检查请求头
        foreach (getallheaders() as $key => $value) {
            if (!$this->check($value)) {
                $this->block('Malicious input in Header');
                return false;
            }
        }
        return true;
    }
    private function logAttack($type, $input) {
        $log = sprintf(
            "[%s] Attack: %s | IP: %s | Input: %s\n",
            date('Y-m-d H:i:s'),
            $type,
            $_SERVER['REMOTE_ADDR'],
            substr($input, 0, 200) // 限制日志长度
        );
        // 写入日志文件
        file_put_contents('waf.log', $log, FILE_APPEND | LOCK_EX);
        // 可选:发送告警
        // $this->sendAlert($type, $input);
    }
    private function block($reason) {
        http_response_code(403);
        die(json_encode([
            'error' => true,
            'message' => 'Access Denied',
            'reason' => $reason
        ]));
    }
    public function addCustomRule($pattern, $type = 'custom') {
        if (!isset($this->rules[$type])) {
            $this->rules[$type] = [];
        }
        $this->rules[$type][] = $pattern;
    }
}
// 使用示例
$waf = new SimpleWAF();
// 添加自定义规则
$waf->addCustomRule('/某种攻击模式/i', 'custom_attack');
// 在应用入口处调用
if ($waf->checkRequest()) {
    // 正常请求,继续处理
    // include 'index.php';
} else {
    // 请求被拦截
    exit;
}
?>

其他推荐的开源WAF

WAFer

  • https://github.com/xyu/WAFer
  • 基于C语言的高性能WAF

Nagios WAF

  • https://github.com/NagiosEnterprises/nagioswaf
  • 企业级WAF解决方案

ShadowDaemon

  • https://github.com/zecure/shadowd
  • Web应用程序防火墙守护程序

部署建议

  1. 多层防护

    • 结合Web服务器级别的WAF
    • 应用层WAF
    • 数据库层面的安全措施
  2. 定期更新规则

    • 及时更新攻击特征库
    • 根据业务特点定制规则
  3. 性能优化

    • 使用缓存减少规则匹配次数
    • 合理设置检测深度
  4. 日志监控

    • 记录所有拦截行为
    • 定期分析攻击模式
  5. 误报处理

    • 设置白名单机制
    • 提供暂时放行功能

选择哪种WAF取决于你的具体需求、服务器环境和技术栈,对于简单的PHP应用,可以使用纯PHP实现的WAF;对于高流量网站,建议使用ModSecurity或其他性能更好的方案。

抱歉,评论功能暂时关闭!