laikait/laika-shield
GitHub: laikait/laika-shield
专为 Laika 框架设计的零依赖 PHP 防火墙中间件,集成了 IP 过滤、速率限制及 SQL 注入与 XSS 攻击检测功能。
Stars: 1 | Forks: 0
# 🛡️ Laika Shield
**Laika Shield** 是一个功能强大、零依赖的防火墙中间件,专为 [Laika PHP Framework](https://github.com/laikait/laika-framework) 打造。
[](https://github.com/laikait/laika-shield/actions)
[](https://php.net)
[](LICENSE)
## ✨ 功能特性
| 功能 | 描述 |
|---|---|
| 🌍 国家级封锁 | 通过 MaxMind GeoLite2 封锁或允许整个国家 |
| 🚫 IP 封锁 | 封锁单个 IP 或 CIDR 范围 |
| ✅ IP 白名单 | 仅允许特定的 IP/范围访问 |
| 🔢 IP 版本过滤 | 仅允许 IPv4 或 IPv6 连接 |
| ⏱️ 速率限制 | 限制每个 IP 在时间窗口内的请求数 |
| 💉 SQL 注入检测 | 封锁常见的 SQLi 攻击 payload |
| 🐛 XSS 检测 | 封锁跨站脚本 (XSS) 攻击尝试 |
| 🔍 请求过滤 | 根据 HTTP 方法、URI、User-Agent、headers 和 body 大小进行过滤 |
## 📦 安装
```
composer require laikait/laika-shield
```
## 🚀 快速开始
### 1. 发布配置文件
将 `vendor/laikait/laika-shield/src/Storage/config.sample.php` 复制到你项目的 `Storage/` 目录。
### 2. 注册为中间件
在你的 Laika 应用程序引导文件或中间件管道中:
```
use Laika\Shield\Http\ShieldMiddleware;
$config = require __DIR__ . '/../Storage/config.sample.php';
$middleware = new ShieldMiddleware($config);
$middleware->handle(function () {
// Your controller / next middleware
});
```
### 3. 或者使用静态 API
```
use Laika\Shield\Shield;
use Laika\Shield\Config;
// Auto-loads defaults from Config — no argument needed
Shield::boot();
// Or pass a custom config array
Shield::boot(Config::get());
```
### 4. 或者使用流式构建器
```
use Laika\Shield\Shield;
(new Shield())
->trustProxy()
->blockCountries('/path/to/GeoLite2-Country.mmdb', blocklist: ['CN', 'RU'])
->blockIps(['1.2.3.4', '10.10.0.0/16'])
->allowIps(['203.0.113.0/24'])
->requireIpVersion(4) // IPv4 only
->rateLimit(maxHits: 100, windowSecs: 60)
->detectSqlInjection(skipKeys: ['password'])
->detectXss(skipKeys: ['html_content'])
->filterRequests(
blockedMethods: ['TRACE', 'CONNECT'],
blockedUserAgentPatterns: ['/sqlmap/i', '/nikto/i'],
)
->run();
```
## ⚙️ 配置参考
```
// Storage/config.sample.php
return [
// Country blocking (requires MaxMind GeoLite2-Country.mmdb)
'country' => [
'db' => '/path/to/GeoLite2-Country.mmdb',
'blocklist' => ['CN', 'RU'], // block these countries
'allowlist' => [], // when non-empty, ONLY these countries allowed
],
// Trust proxy headers (X-Forwarded-For, CF-Connecting-IP, etc.)
'trust.proxy' => false,
// IP blocking and allowlisting
'ip' => [
'blocklist' => ['1.2.3.4', '192.168.100.0/24'],
'allowlist' => [], // when non-empty, ONLY these IPs are allowed
],
// Only allow IPv4 (4) or IPv6 (6). null = both allowed.
'ip.version' => null,
// Rate limiting
'rate.limit' => [
'max.hits' => 60, // requests
'window' => 60, // seconds
'storage.dir' => null, // defaults to sys_get_temp_dir()
],
// SQL injection detection
'sql.injection' => [
'skip.keys' => [], // input keys to skip
'scan.body' => true, // also scan raw body (JSON, XML)
'strict' => true, // also block standalone DML (SELECT/INSERT/UPDATE/DELETE/DROP)
],
// XSS detection
'xss' => [
'skip.keys' => [],
'scan.headers' => false,
'scan.body' => true,
],
// Request filtering
'request.filter' => [
'blocked.methods' => ['TRACE', 'CONNECT'],
'blocked.uri.patterns' => ['/\/\.env$/i'],
'blocked.user.agents' => ['/sqlmap/i', '/nikto/i'],
'headers.required' => [],
'blocked.header.values' => [],
'content.length.max' => null,
'content.length.min' => null,
],
];
```
## 🔧 Config 类
`Config` 类提供了一个流式 API,用于在运行时加载和修改默认配置——而无需直接编辑配置文件。
```
use Laika\Shield\Config;
use Laika\Shield\Shield;
// Top-level scalar
Config::add('trust.proxy', true);
// Top-level array merge
Config::add('ip', ['blocklist' => ['1.2.3.4', '10.0.0.0/8']]);
// Sub-key update (simplest way to change a nested value)
Config::add('rate.limit', 'max.hits', 30);
Config::add('sql.injection', 'skip.keys', ['password', 'token']);
Config::add('xss', 'skip.keys', ['content', 'body']);
Config::add('request.filter', 'content.length.max', 2048);
// Boot uses Config automatically when no array is passed
Shield::boot();
```
### Config API
| 方法 | 描述 |
|---|---|
| `Config::add(string $key, mixed $value)` | 设置或合并顶层配置键 |
| `Config::add(string $key, string $subKey, mixed $value)` | 设置或合并特定的子键 |
| `Config::get()` | 返回完整的配置数组 |
| `Config::get(string $key)` | 返回单个键的值 |
| `Config::has(string $key)` | 检查键是否存在 |
| `Config::keys()` | 返回所有顶层配置键 |
| `Config::reset()` | 重置单例(在测试中很有用) |
## 🏗️ 架构
```
src/
├── Shield.php # Main firewall engine (static + fluent API)
├── Config.php # Runtime configuration manager
├── Interfaces/
│ ├── FirewallInterface.php # Core Firewall Interface
│ ├── RuleInterface.php # Individual Rule Interface
│ └── DetectorInterface.php # Pattern Detector Interface
├── Rules/
│ ├── IpRule.php # IP blocking / allowlisting
│ ├── IpVersionRule.php # IPv4 / IPv6 enforcement
│ ├── RateLimitRule.php # Rate limiting
│ ├── CountryRule.php # Country blocking / allowlisting
│ ├── SqlInjectionRule.php # SQL injection protection
│ ├── XssRule.php # XSS protection
│ └── RequestFilterRule.php # General request filtering
├── Detectors/
│ ├── GeoIpDetector.php # MaxMind GeoLite2 country resolver
│ ├── SqlInjectionDetector.php # SQLi regex patterns engine
│ └── XssDetector.php # XSS regex patterns engine
├── Http/
│ └── ShieldMiddleware.php # Laika MMC middleware integration
├── Support/
│ ├── IpHelper.php # IP validation, CIDR, version detection
│ ├── RateLimiter.php # File-based rate limit store
│ └── RequestHelper.php # Request data extraction helpers
├── Exceptions/
│ ├── FirewallException.php # Base firewall exception (HTTP 403)
│ └── RateLimitExceededException.php # Rate limit exception (HTTP 429)
└── Storage/
└── config.sample.php # Default configuration template
```
## 🔌 编写自定义规则
实现 `RuleInterface` 以创建你自己的防火墙规则:
```
use Laika\Shield\Interfaces\RuleInterface;
class CountryBlockRule implements RuleInterface
{
public function passes(): bool
{
// Your logic here
return true;
}
public function message(): string
{
return 'Access Denied From Your Country.';
}
public function statusCode(): int
{
return 403;
}
public function additionalHeader(): void
{
return;
}
}
// Register it
(new Shield())
->addRule(new CountryBlockRule())
->run();
```
## 🧪 运行测试
```
composer install
vendor/bin/phpunit
```
## 🌐 IP 版本检测
Shield 提供了 `IpHelper` 用于独立的 IP 工具:
```
use Laika\Shield\Support\IpHelper;
IpHelper::version('8.8.8.8'); // 4
IpHelper::version('2001:db8::1'); // 6
IpHelper::version('invalid'); // null
IpHelper::isV4('192.168.1.1'); // true
IpHelper::isV6('::1'); // true
IpHelper::isPrivate('10.0.0.1'); // true
IpHelper::isLoopback('127.0.0.1'); // true
IpHelper::inCidr('192.168.1.5', '192.168.1.0/24'); // true
// Resolve real client IP (proxy-aware)
$ip = IpHelper::resolve(trustProxy: true);
```
## 📄 许可证
MIT © [Laika IT](https://github.com/laikait)
标签:CIDR, CISA项目, DOE合作, ffuf, GeoLite2, IPv4, IPv6, IP 地址批量处理, IP封禁, Laika框架, OpenVAS, PHP, PowerShell, Rate Limiting, SQL注入检测, Streamlit, WAF, Web安全, XSS防护, 中间件, 地理封锁, 网络安全, 蓝队分析, 访问控制, 请求过滤, 防SQL注入, 防XSS, 防火墙, 限流, 隐私保护, 零依赖