subhashladumor1/laravel-cybershield
Enterprise security intelligence for Laravel: signature-based WAF, adaptive rate limiting, bot fingerprinting, API integrity checks, threat scoring, malware scanning, and forensic loggingβworking together to block modern attacks. Beta; APIs may change.
[!WARNING] β οΈ Beta Version β This package is currently in beta. APIs, configuration keys, and middleware behaviour may change between releases. It is not yet recommended for mission-critical production environments without thorough testing.
We warmly welcome contributors, bug reporters, and feature suggestions! See Contributing below.
Laravel CyberShield is a proactive, multi-layered security intelligence layer for Laravel applications. It combines a signature-based Web Application Firewall (WAF), adaptive rate limiting, bot fingerprinting, API integrity verification, real-time threat scoring, malware scanning, and forensic logging β all working in concert to protect your application from modern threats.
Most security packages are bolt-on afterthoughts. CyberShield is designed from the ground up as a defense-in-depth platform that addresses the entire attack surface of a modern Laravel application.
| Feature | Basic Packages | π‘οΈ CyberShield |
|---|---|---|
| SQL Injection / XSS WAF | β | β |
| Adaptive Rate Limiting (Fibonacci/Exponential) | β | β |
| Headless Browser & Bot Fingerprinting | β | β |
| API HMAC Signatures + Replay Protection | β | β |
| Real-Time IP Threat Scoring (0-100) | β | β |
| Malware & Static Code Analysis | β | β |
| 200+ Modular Middleware Guards | β | β |
| 100+ Blade Security Directives | β | β |
| 60+ Global Security Helper Functions | β | β |
| Data Masking (PII, Cards, Tokens) | β | β |
| Geo-Blocking + TOR/VPN Detection | β | β |
| Network CIDR Whitelist/Blacklist | β | β |
| Forensic Logging & Security Dashboard | β | β |
Response mode: active (block) or log (observe) |
β | β |
Every HTTP request passes through a multi-stage, sequential security pipeline before reaching your application's business logic.
graph TD
User(["π Incoming Traffic"]) --> CS{{"CyberShield Security Pipeline"}}
subgraph "Stage 1: Network Gates"
CS --> WL["β
Whitelist Check\n(Bypass for trusted IPs/CIDRs)"]
WL --> BL["π« Blacklist Check\n(Drop blocked IPs instantly)"]
BL --> GEO["π Geo & TOR Filter\n(Country/Region blocking)"]
end
subgraph "Stage 2: Request Validation"
GEO --> SZ["π Size & Protocol Check\n(Max payload, HTTPS enforce)"]
SZ --> HEADERS["π Header Validation\n(User-Agent, Content-Type, Origin)"]
HEADERS --> BOT["π€ Bot Fingerprinting\n(Honeypot, Pacing, Headless detection)"]
end
subgraph "Stage 3: Threat Inspection"
BOT --> RATE["β±οΈ Adaptive Rate Limiter\n(Linear / Exponential / Fibonacci)"]
RATE --> WAF["π₯ WAF Engine\n(SQLi, XSS, RCE, LFI signatures)"]
WAF --> API["π API Gateway\n(HMAC, Nonce, Timestamp, Cost)"]
end
subgraph "Stage 4: Intelligence"
API --> SCORE["π§ Threat Score Engine\n(0-100 real-time IP risk)"]
SCORE --> LOG["π Forensic Logger\n(DB + File + Dashboard)"]
end
LOG --> APP[["β
Your Application Controller"]]
WAF -->|"Threat Detected\n(active mode)"| BLOCK["π΄ 403/429 Response\n+ IP Quarantine"]
WAF -->|"Threat Detected\n(log mode)"| LOGONLY["π Log Only\n(Passive Monitoring)"]
style CS fill:#9333ea,color:#fff,stroke:#7c3aed
style BLOCK fill:#dc2626,color:#fff,stroke:#b91c1c
style APP fill:#16a34a,color:#fff,stroke:#15803d
CYBERSHIELD_GLOBAL_MODE=active to block threats or log to silently monitor β perfect for onboarding without disruption.Deep-packet inspection engine covering the OWASP Top 10:
UNION SELECT, DROP TABLE, SLEEP(), EXTRACTVALUE()<script>, onerror=, javascript: URIseval(), shell_exec(), system()../etc/passwd, C:\Windows\../ patterns in URIsSEL/**/ECT)Multi-dimensional fingerprinting that goes beyond User-Agent strings:
@secureHoneypot)Three strategies for smart traffic shaping:
Enterprise-grade integrity guarantees for REST/GraphQL APIs:
192.168.1.0/24)CF-IPCountry / X-Country-Code)Artisan-powered static analysis with 11 specialized rule engines:
security_logs table)composer require subhashladumor1/laravel-cybershield
# Publish config file, migrations, and views
php artisan vendor:publish --provider="CyberShield\CyberShieldServiceProvider"
# Or publish selectively:
php artisan vendor:publish --tag=cybershield-config
php artisan vendor:publish --tag=cybershield-migrations
php artisan vendor:publish --tag=cybershield-views
php artisan migrate
php artisan security:base init
Laravel 11+ (bootstrap/app.php):
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
// Option A: Protect all routes globally
$middleware->append(\CyberShield\Http\Middleware\FirewallMiddleware::class);
// Option B: Register route-level aliases
$middleware->alias([
'cybershield.waf' => \CyberShield\Http\Middleware\FirewallMiddleware::class,
'cybershield.bot' => \CyberShield\Http\Middleware\DetectBotMiddleware::class,
'cybershield.rate' => \CyberShield\Http\Middleware\IpRateLimiterMiddleware::class,
]);
})
->create();
Laravel 10 (app/Http/Kernel.php):
protected $middleware = [
// ... other global middleware
\CyberShield\Http\Middleware\FirewallMiddleware::class,
];
protected $middlewareAliases = [
// All 200+ cybershield.* aliases are auto-registered by the ServiceProvider
];
.envCYBERSHIELD_ENABLED=true
CYBERSHIELD_GLOBAL_MODE=active
CYBERSHIELD_ENFORCE_HTTPS=true
CYBERSHIELD_BLOCK_TOR=false
CYBERSHIELD_SIGNATURE_BLOCK_THRESHOLD=medium
All .env keys map to values in config/cybershield.php. Below is the complete reference.
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_ENABLED |
true |
Master on/off switch for the entire package. |
CYBERSHIELD_GLOBAL_MODE |
active |
active = block threats. log = log only (passive/monitor). |
.env Key |
Default | Controls |
|---|---|---|
CYBERSHIELD_REQUEST_SECURITY_ENABLED |
true |
Request structure/header validation. |
CYBERSHIELD_RATE_LIMITING_ENABLED |
true |
All rate limiting strategies. |
CYBERSHIELD_BOT_PROTECTION_ENABLED |
true |
Bot detection & honeypot. |
CYBERSHIELD_NETWORK_SECURITY_ENABLED |
true |
IP/Geo/TOR/Proxy filtering. |
CYBERSHIELD_AUTH_SECURITY_ENABLED |
true |
Session & authentication hardening. |
CYBERSHIELD_API_SECURITY_ENABLED |
true |
API Gateway (HMAC, Nonce, Keys). |
CYBERSHIELD_THREAT_DETECTION_ENABLED |
true |
WAF & threat scoring engine. |
CYBERSHIELD_MONITORING_ENABLED |
true |
Dashboard & forensic logging. |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_MAX_SIZE |
5242880 |
Max request body size in bytes (5MB). |
CYBERSHIELD_ENFORCE_HTTPS |
true |
Force HTTPS on all requests. |
CYBERSHIELD_ALLOWED_ORIGINS |
localhost |
Comma-separated allowed CORS origins. |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_RATE_LIMIT_DRIVER |
cache |
Cache driver for counters (cache, redis). |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_BLOCK_TOR |
false |
Block all TOR exit node traffic. |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_SIGNATURES_PATH |
src/Signatures |
Path to the JSON signature rules directory. |
CYBERSHIELD_CUSTOM_SIGNATURES_PATH |
null |
Path to your own custom JSON signature files. |
CYBERSHIELD_SIGNATURE_BLOCK_THRESHOLD |
medium |
Minimum severity to trigger a block: low, medium, high, critical. |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_API_VERIFY_SIGNATURE |
true |
Enable HMAC-SHA256 request signature check. |
CYBERSHIELD_API_REPLAY_PROTECTION |
true |
Enable Nonce + Timestamp replay prevention. |
CYBERSHIELD_API_AUTO_BLOCK |
true |
Automatically block abusive API clients. |
.env Key |
Default | Description |
|---|---|---|
CYBERSHIELD_LOGGING_ENABLED |
true |
Enable/disable all security logging. |
CYBERSHIELD_LOG_CHANNEL |
stack |
Laravel log channel to write security events to. |
CYBERSHIELD_LOG_FORMAT |
See config | Format string for log entries. |
CYBERSHIELD_LOG_ROTATION |
daily |
Log rotation strategy: daily, weekly. |
CYBERSHIELD_LOG_MAX_SIZE |
5242880 |
Max log file size in bytes (5MB). |
.env Template# βββ CyberShield Core ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_ENABLED=true
CYBERSHIELD_GLOBAL_MODE=active # active | log
# βββ Module Toggles ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_REQUEST_SECURITY_ENABLED=true
CYBERSHIELD_RATE_LIMITING_ENABLED=true
CYBERSHIELD_BOT_PROTECTION_ENABLED=true
CYBERSHIELD_NETWORK_SECURITY_ENABLED=true
CYBERSHIELD_AUTH_SECURITY_ENABLED=true
CYBERSHIELD_API_SECURITY_ENABLED=true
CYBERSHIELD_THREAT_DETECTION_ENABLED=true
CYBERSHIELD_MONITORING_ENABLED=true
# βββ Request Security ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_MAX_SIZE=5242880 # 5MB in bytes
CYBERSHIELD_ENFORCE_HTTPS=true
CYBERSHIELD_ALLOWED_ORIGINS=localhost,yourdomain.com
# βββ Network & Geo βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_BLOCK_TOR=false
# βββ WAF / Signatures ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_SIGNATURES_PATH= # leave blank for default
CYBERSHIELD_CUSTOM_SIGNATURES_PATH= # optional: your custom rules
CYBERSHIELD_SIGNATURE_BLOCK_THRESHOLD=medium # low | medium | high | critical
# βββ API Security ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_API_VERIFY_SIGNATURE=true
CYBERSHIELD_API_REPLAY_PROTECTION=true
CYBERSHIELD_API_AUTO_BLOCK=true
# βββ Rate Limiting βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_RATE_LIMIT_DRIVER=cache # cache | redis
# βββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CYBERSHIELD_LOGGING_ENABLED=true
CYBERSHIELD_LOG_CHANNEL=stack
CYBERSHIELD_LOG_ROTATION=daily
CYBERSHIELD_LOG_MAX_SIZE=5242880
laravel-cybershield/
βββ src/
β βββ Blade/
β β βββ SecurityDirectives.php # 100+ Blade @secure* directives
β β
β βββ Console/
β β βββ Commands/
β β βββ BaseSecurityCommand.php # Shared UI/output helpers for commands
β β βββ DynamicScannerCommand.php# Dynamic behavioral scan command
β β βββ ListMiddlewareCommand.php# Lists all 200 registered middleware
β β βββ SecurityScanCommand.php # Main `security:scan` command
β β
β βββ Core/
β β βββ SecurityKernel.php # Orchestrates the security pipeline
β β βββ ThreatEngine.php # IP threat scoring & quarantine logic
β β βββ WAFEngine.php # Signature matching & payload inspection
β β
β βββ Helpers/
β β βββ security_helpers.php # 60+ global PHP helper functions
β β
β βββ Http/
β β βββ Middleware/ # 200+ modular middleware guards
β β βββ FirewallMiddleware.php # Primary WAF entry point (global)
β β βββ DetectBotMiddleware.php
β β βββ IpRateLimiterMiddleware.php
β β βββ ... (200+ total)
β β
β βββ Logging/
β β βββ LogWriter.php # Structured file + DB logger
β β
β βββ MalwareScanner/
β β βββ MalwareScanner.php # Static analysis for malware patterns
β β
β βββ Models/
β β βββ ThreatLog.php # Eloquent model for security_logs table
β β
β βββ Monitoring/
β β βββ ... # Dashboard data aggregation services
β β
β βββ Providers/
β β βββ CyberShieldServiceProvider.php # Service registration & boot
β β
β βββ RateLimiting/
β β βββ AdvancedRateLimiter.php # Linear/Exponential/Fibonacci engine
β β
β βββ Security/
β β βββ NetworkGuard.php # IP/CIDR/Geo filtering
β β βββ DatabaseIntrusionDetector.php# DB-level injection monitoring
β β βββ Project/
β β βββ Rules/ # 11 static analysis rule engines
β β βββ MalwareRule.php
β β βββ SqlInjectionRule.php
β β βββ XssRule.php
β β βββ ConfigRule.php
β β βββ DependencyRule.php
β β βββ ModelSecurityRule.php
β β βββ FileUploadRule.php
β β βββ BotDetectionRule.php
β β βββ ApiSecurityRule.php
β β βββ AuthSecurityRule.php
β β βββ InfrastructureRule.php
β β
β βββ Signatures/
β β βββ *.json # WAF signature rule files (SQLi, XSS, etc.)
β β
β βββ config/
β β βββ cybershield.php # Main configuration file
β β
β βββ resources/
β β βββ views/ # Blade dashboard views
β β
β βββ routes/
β βββ web.php # Dashboard & API routes
β
βββ docs/ # Comprehensive documentation
β βββ firewall.md
β βββ bot-protection.md
β βββ rate-limiting.md
β βββ api-security.md
β βββ helpers.md
β βββ middleware.md
β βββ blade-directives.md
β βββ commands.md
β βββ ... (19 total docs)
β
βββ composer.json
βββ phpunit.xml
βββ README.md
This example demonstrates securing a payment processing API endpoint against the most common attack vectors.
A POST /api/v1/transactions endpoint processes financial transfers. It's a high-value target for:
Step 1: Route definition with layered middleware
// routes/api.php
use CyberShield\Http\Middleware\FirewallMiddleware;
Route::middleware([
'cybershield.block_blacklisted_ip', // Instant drop for known-bad IPs
'cybershield.detect_tor_network', // Block anonymized attackers
'cybershield.verify_api_key', // Validate X-API-KEY header
'cybershield.verify_api_signature', // HMAC-SHA256 request integrity
'cybershield.verify_api_nonce', // Prevent replay attacks
'cybershield.verify_api_timestamp', // Reject requests older than 60s
'cybershield.detect_sql_injection', // WAF: SQLi detection
'cybershield.api_rate_limiter', // Adaptive throttling
'cybershield.log_security_event', // Forensic audit trail
])->group(function () {
Route::post('/api/v1/transactions', [TransactionController::class, 'store']);
});
Step 2: Controller using helper functions
// app/Http/Controllers/TransactionController.php
class TransactionController extends Controller
{
public function store(Request $request): JsonResponse
{
// Check threat score before processing
if (is_high_risk()) {
block_current_ip('High risk score on financial endpoint');
return response()->json(['error' => 'Access denied.'], 403);
}
// Validate payload is not malicious
$rawPayload = $request->getContent();
if (is_malicious_payload($rawPayload)) {
log_threat_event('malicious_payload', ['endpoint' => 'transactions']);
return response()->json(['error' => 'Invalid payload.'], 422);
}
// Verify HMAC signature from client
$signature = $request->header('X-Signature');
$secret = config('services.payment_gateway.secret');
if (!verify_api_signature($rawPayload, $signature, $secret)) {
return response()->json(['error' => 'Signature mismatch.'], 401);
}
// Mask PII in logs
$logData = [
'account' => mask_card($request->input('card_number')),
'email' => mask_email($request->input('email')),
'ip' => mask_ip(),
];
Log::info('Transaction processed', $logData);
// Process the transaction...
return response()->json(['status' => 'success']);
}
}
Step 3: Secure Blade UI for the dashboard
{{-- resources/views/transactions/index.blade.php --}}
@secureAuth
<div class="transaction-list">
@secureThreatHigh
<div class="alert alert-danger">
β οΈ Unusual activity detected on your account.
Some features have been temporarily restricted.
</div>
@endsecureThreatHigh
<table>
<tr>
<td>Card on file:</td>
<td>@secureMaskCard($user->card_number)</td>
</tr>
<tr>
<td>Email:</td>
<td>@secureMaskEmail($user->email)</td>
</tr>
</table>
@secure2fa
<button class="btn-primary">Make Transfer</button>
@else
<p class="warning">Enable 2FA to initiate transfers.</p>
@endsecure2fa
</div>
@else
<p>Please log in to view transactions.</p>
@endsecureAuth
@secureHoneypot
{{ csrf_field() }}
Step 4: Client-side API call (HMAC generation)
// Example: Generating a signed API request (client SDK)
$payload = json_encode(['amount' => 100, 'to' => 'ACC-9876']);
$nonce = bin2hex(random_bytes(16));
$timestamp = time();
$secret = env('API_SECRET');
// Canonical string: METHOD + URL + PAYLOAD + TIMESTAMP + NONCE
$canonical = 'POST' . '/api/v1/transactions' . $payload . $timestamp . $nonce;
$signature = hash_hmac('sha256', $canonical, $secret);
Http::withHeaders([
'X-API-KEY' => env('API_KEY'),
'X-Signature' => $signature,
'X-Nonce' => $nonce,
'X-Timestamp' => $timestamp,
'Content-Type'=> 'application/json',
])->post('https://yourapp.com/api/v1/transactions', json_decode($payload, true));
Result: This single endpoint is now protected against SQL injection, replay attacks, bot scraping, brute force, IP flooding, and unauthorized access β with full audit logs for every interaction.
| Benefit | Detail |
|---|---|
| π Near-Zero Overhead | Middleware chain adds <2ms latency; stateless checks are sub-millisecond. |
| π§© Plug-and-Play | Auto-discovered via Laravel's package auto-discovery. No manual registration. |
| π§ Highly Configurable | Every behavior configurable via .env or config/cybershield.php. |
| π Modular Architecture | Enable/disable any of the 8 security modules independently. |
| π Observability First | Every decision is logged. Export to CSV/JSON for SIEM tools. |
| π οΈ Developer-Friendly | 60+ global helpers, 100+ Blade directives, 200+ middleware aliases. |
| π Dual Mode | Roll out in log mode first to observe without disrupting production traffic. |
| π Scalable | Redis-backed rate limiting syncs limits across multiple application instances. |
| π International | Geo-blocking, country codes, and IPv4/IPv6 support built in. |
| π CI/CD Ready | security:scan --json produces machine-readable output for build pipelines. |
Our documentation is structured for both quick reference and deep technical dives.
| Document | Description |
|---|---|
| π₯ Web Application Firewall | Signature-based WAF, payload normalization, custom rules. |
| π€ Bot & Automation Defense | Honeypots, headless browser detection, behavioral pacing. |
| β±οΈ Adaptive Rate Limiting | Linear, Exponential, Fibonacci strategies with real examples. |
| π API Security Gateway | HMAC, Nonce, Timestamp, Cost-based API protection. |
| π Network & Geo Intelligence | TOR, VPN, CIDR, country-level filtering. |
| π΅οΈ Threat Intelligence Engine | Scoring logic, quarantine, and auto-block behavior. |
| Document | Description |
|---|---|
| π¬ Project Security Audit | Artisan-powered static analysis for your codebase. |
| ποΈ Malware Scanner | File-level malware pattern detection. |
| ποΈ Architecture Deep-Dive | Internal component design and data flow. |
| Document | Description |
|---|---|
| π¦Ύ Global Security Helpers | Complete reference for 60+ helper functions with examples. |
| π¦ Middleware Catalog | All 200 middleware guards, organized by category, with usage. |
| π Blade Directives | 100+ @secure* directives with full code examples. |
| β¨οΈ Artisan Commands | All security scan, audit, and management commands. |
| π Logging & Forensics | Log channels, formats, rotation and export. |
| π Monitoring Dashboard | Real-time security metrics and visualization. |
| βοΈ Configuration Reference | Complete config/cybershield.php explanation. |
| π Signature Reference | Format and management of WAF signature JSON files. |
This is a beta-stage open-source package β every contribution matters!
We actively encourage the community to help shape CyberShield. Here's how you can get involved:
Open a GitHub Issue and we'll get back to you promptly:
π Open an Issue
Please include:
git checkout -b feature/my-improvementcomposer testmain branchπ Browse open issues β look for good first issue or help wanted labels to find a great starting point.
/docs if your change affects user-facing behaviourHave a question or a wild security feature idea? Start a conversation:
π GitHub Discussions
Built with extreme care for the Laravel community by Subhash Ladumor.
How can I help you explore Laravel packages today?