定制 senza1dio/security-shield 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

senza1dio/security-shield

Composer 安装命令:

composer require senza1dio/security-shield

包简介

Security Middleware for PHP - Honeypot, Scanner Detection, Rate Limiting, Resilience Patterns

README 文档

README

PHP Version License

Security Middleware for PHP 8.1+

Honeypot, scanner detection, and resilience patterns for PHP applications.

What This Package Does

  • Honeypot System - 69 trap endpoints to catch scanners (/.env, /wp-admin, etc.)
  • Scanner Detection - Identifies sqlmap, nikto, masscan by signatures
  • Rate Limiting - 4 algorithms: sliding window, token bucket, leaky bucket, fixed window
  • IP Scoring - Accumulates threat scores based on behavior
  • Bot Verification - DNS-based verification for Googlebot, Bingbot
  • Geo-Blocking - Country-level restrictions via external GeoIP provider

What This Package Does NOT Do

  • Not a WAF - No SQL injection, XSS, or OWASP Top 10 detection
  • Not DDoS Protection - Cannot handle volumetric attacks (use Cloudflare/AWS Shield)
  • Not ML-Based - No machine learning, just signature and statistical detection
  • Not Penetration Tested - Has not undergone professional security audit

Use alongside a real WAF (ModSecurity, Cloudflare) for production.

Architecture

Resilience Patterns

Pattern Description Storage Required
Circuit Breaker Fail fast when dependency is down Redis (distributed) or none (local)
Retry Policy Exponential backoff with jitter None
Fallback Chain Try providers in order until success None
Bulkhead Limit concurrent executions Redis

Observability

Component Format Notes
Tracing OpenTelemetry-compatible W3C traceparent context propagation
Metrics Prometheus text format Counters, gauges, histograms
Health JSON + HTTP status Liveness/readiness for Kubernetes

Anomaly Detection

Detector What It Detects
Statistical Values outside Z-score threshold
Rate Request rate spikes/drops
Pattern Unusual paths, methods, user agents
Time-Based Activity during unusual hours

Installation

composer require senza1dio/security-shield

Quick Start

Option 1: No Dependencies (Development/Testing)

<?php
use Senza1dio\SecurityShield\Middleware\SecurityMiddleware;
use Senza1dio\SecurityShield\Config\SecurityConfig;
use Senza1dio\SecurityShield\Storage\NullStorage;

// In-memory storage - NO Redis/Database required
$config = (new SecurityConfig())
    ->setStorage(new NullStorage());

$security = new SecurityMiddleware($config);

if (!$security->handle($_SERVER)) {
    http_response_code(403);
    exit('Access Denied');
}

Note: NullStorage loses data between requests. Use for testing only.

Option 2: Database Storage (Production without Redis)

<?php
use Senza1dio\SecurityShield\Storage\DatabaseStorage;

// Use your existing database - NO Redis required
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');

$config = (new SecurityConfig())
    ->setStorage(new DatabaseStorage($pdo));

$security = new SecurityMiddleware($config);

if (!$security->handle($_SERVER)) {
    http_response_code(403);
    exit('Access Denied');
}

Option 3: Redis Storage (Recommended for Production)

<?php
use Senza1dio\SecurityShield\Storage\RedisStorage;

// Fastest option - requires ext-redis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$config = (new SecurityConfig())
    ->setStorage(new RedisStorage($redis));

$security = new SecurityMiddleware($config);

if (!$security->handle($_SERVER)) {
    http_response_code(403);
    exit('Access Denied');
}

Usage Examples

Circuit Breaker

use Senza1dio\SecurityShield\Resilience\CircuitBreaker;

$breaker = new CircuitBreaker('redis', $storage, [
    'failure_threshold' => 5,    // Open after 5 failures
    'recovery_timeout' => 30,    // Try again after 30s
    'half_open_max_calls' => 3,  // Allow 3 test calls
]);

// State logged to error_log on transitions
$result = $breaker->call(
    fn() => $redis->get('key'),
    fn() => 'fallback-value'
);

Limitation: In PHP-FPM, each worker has independent in-memory state if Redis unavailable.

Retry Policy

use Senza1dio\SecurityShield\Resilience\RetryPolicy;

$policy = RetryPolicy::exponentialBackoffWithJitter(
    maxAttempts: 5,
    baseDelay: 1.0,
    maxDelay: 30.0
);

// Delays: ~1s, ~2s, ~4s, ~8s (with random jitter)
$result = $policy->execute(fn() => $api->call());

Rate Limiting

use Senza1dio\SecurityShield\RateLimiting\RateLimiter;

// Token bucket: 100 tokens, refills 10/second
$limiter = RateLimiter::tokenBucket($storage, 100, 10);

$result = $limiter->attempt('user:123');
if (!$result->allowed) {
    // $result->retryAfter contains seconds to wait
    http_response_code(429);
    exit;
}

Health Checks

use Senza1dio\SecurityShield\Health\HealthCheck;
use Senza1dio\SecurityShield\Health\Checks\RedisHealthCheck;

$health = new HealthCheck();
$health->addCheck('redis', new RedisHealthCheck($redis));

// Returns HealthResult with HTTP status code
$result = $health->readiness();

header('Content-Type: application/json');
http_response_code($result->getHttpStatusCode());
echo $result->toJson();

Distributed Tracing

use Senza1dio\SecurityShield\Telemetry\Tracer;
use Senza1dio\SecurityShield\Telemetry\SpanKind;

$tracer = new Tracer('my-service', '1.0.0');

// Extract parent context from incoming request
$parentContext = $tracer->extractContext(getallheaders());

$span = $tracer->startSpanFromContext('handle-request', $parentContext, SpanKind::SERVER);
$span->setAttribute('http.method', $_SERVER['REQUEST_METHOD']);

// ... process request ...

$span->setStatus(SpanStatus::OK);
$tracer->endSpan($span);
$tracer->flush(); // Export spans

Hot-Reload Configuration

use Senza1dio\SecurityShield\Config\ConfigProvider;

$config = new ConfigProvider($storage, [
    'cache_ttl' => 60,  // Reload from Redis every 60s
]);

$config->setDefaults(['threshold' => 50]);

// Update from anywhere - all instances pick up changes
$config->setRemote('threshold', 100);

// Later reads get new value after cache expires
$value = $config->get('threshold'); // 100

Note: Changes propagate on cache expiry, not instantly.

Notifications

use Senza1dio\SecurityShield\Notifications\NotificationManager;
use Senza1dio\SecurityShield\Notifications\TelegramNotifier;
use Senza1dio\SecurityShield\Notifications\SlackNotifier;

$manager = new NotificationManager();
$manager->addChannel(new TelegramNotifier($botToken, $chatId));
$manager->addChannel(new SlackNotifier($webhookUrl));

// Send to all channels
$result = $manager->broadcast('Security Alert', 'IP banned: 1.2.3.4', [
    'reason' => 'Honeypot access',
]);

// Check results
if (!$result->allSuccessful()) {
    foreach ($result->getErrors() as $channel => $error) {
        error_log("Notification to {$channel} failed: {$error}");
    }
}

Configuration Validation

use Senza1dio\SecurityShield\Config\ConfigValidator;

$validator = ConfigValidator::create()
    ->required()
    ->type('integer')
    ->min(1)
    ->max(1000);

$result = $validator->validate($value);
if (!$result->valid) {
    throw new InvalidArgumentException($result->error);
}

Requirements

  • PHP 8.1+ (uses enums, readonly properties)
  • ext-json

Optional Extensions

  • ext-redis (for RedisStorage - recommended for production)
  • ext-pdo (for DatabaseStorage)
  • ext-curl (for notification channels, GeoIP)

Storage Backends

Choose the right storage for your use case:

Backend Use Case Dependencies Performance Persistence
NullStorage Testing, Development ✅ None ~0.001ms ❌ No (in-memory)
DatabaseStorage Production (no Redis) ext-pdo ~1-5ms ✅ Yes (MySQL/PostgreSQL)
RedisStorage Production (recommended) ext-redis ~0.05ms ✅ Yes (distributed)

When to Use Each Backend

NullStorage - Development/Testing Only

$config = (new SecurityConfig())->setStorage(new NullStorage());
  • ✅ Zero setup, no dependencies
  • ✅ Perfect for unit tests
  • ❌ Data lost between requests
  • ❌ NOT for production

DatabaseStorage - Production without Redis

$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$config = (new SecurityConfig())->setStorage(new DatabaseStorage($pdo));
  • ✅ No extra infrastructure needed
  • ✅ Uses existing database
  • ✅ Persistent across servers
  • ⚠️ Slower than Redis (1-5ms vs 0.05ms)

RedisStorage - Production (Best Performance)

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$config = (new SecurityConfig())->setStorage(new RedisStorage($redis));
  • ✅ Ultra-fast (~0.05ms)
  • ✅ Distributed state across servers
  • ✅ Built-in TTL expiration
  • ⚠️ Requires Redis server

Known Limitations

  1. No Persistence in NullStorage - Data lost between requests
  2. Clock Skew - Rate limiting assumes synchronized clocks
  3. Memory Growth - Tracer spans queue in memory until flush
  4. Blocking Operations - SMTP notifications block during send
  5. No Clustering - Each PHP worker has independent memory state

Error Handling

All network operations log errors to error_log():

  • SMTP failures
  • Webhook failures
  • Redis connection issues
  • Circuit breaker state changes

Configure PHP error_log to capture these in production.

Testing

composer install
composer test          # PHPUnit tests
composer stan          # PHPStan level 8
composer cs-check      # Code style check

License

MIT License - see LICENSE

senza1dio/security-shield 适用场景与选型建议

senza1dio/security-shield 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 3, 最近一次更新时间为 2026 年 01 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「security」 「middleware」 「Honeypot」 「rate-limiting」 「prometheus」 「circuit-breaker」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 senza1dio/security-shield 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 senza1dio/security-shield 我们能提供哪些服务?
定制开发 / 二次开发

基于 senza1dio/security-shield 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 44
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 0
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-24