salehye / laravel-security
🔥 Advanced Security Package for Laravel 12 - The most comprehensive security solution for Laravel applications
Package info
github.com/salehye/laravel-security
Type:laravel-package
pkg:composer/salehye/laravel-security
Fund package maintenance!
Requires
- php: ^8.2|^8.3|^8.4
- laravel/framework: ^11.0|^12.0
- laravel/sanctum: ^4.0|^5.0
- pragmarx/google2fa-laravel: ^2.0
- simplesoftwareio/simple-qrcode: ^4.2
- spatie/laravel-permission: ^6.0
Requires (Dev)
- laravel/pint: ^1.15
- mockery/mockery: ^1.6
- nunomaduro/collision: ^7.0|^8.0
- orchestra/testbench: ^9.0|^10.0
- phpstan/phpstan: ^1.10|^2.0
- phpunit/phpunit: ^10.5|^11.0
README
🔥 Advanced Security Package for Laravel 12 - The most comprehensive security solution for Laravel applications.
Features
🛡️ Comprehensive Protection
- Input Sanitization - Automatic XSS prevention and input cleaning
- SQL Injection Protection - Advanced pattern detection and validation rules
- XSS Protection - Cross-site scripting prevention
- Path Traversal Protection - Directory traversal attack prevention
- Command Injection Protection - Shell command injection prevention
🔐 Authentication & Session Security
- Brute Force Protection - Rate-limited login attempts with progressive delays
- Two-Factor Authentication (2FA) - Built-in 2FA support
- Session Hardening - Session fixation prevention, concurrent session detection
- Suspicious Login Detection - Geographic anomaly detection, impossible travel detection
- Re-authentication - Require password for sensitive operations
🚦 Advanced Rate Limiting
- Smart Rate Limiting - IP, user, route, or combination-based limiting
- Progressive Throttling - Increasing penalties for repeat offenders
- Endpoint-specific Limits - Custom limits per route or endpoint
🔑 API Security
- Request Signing - HMAC-based request integrity verification
- Timestamp Verification - Replay attack prevention
- API Key Management - Scoped API tokens with permissions
- Nonce-based Protection - One-time request tokens
📊 Audit & Logging
- Comprehensive Audit Logs - Track all security events
- Multiple Channels - Database, Log, Slack, SIEM integration
- Real-time Alerts - Instant notifications for critical events
🌐 Security Headers
- Content Security Policy (CSP) - Configurable CSP with nonce support
- HSTS - HTTP Strict Transport Security
- X-Frame-Options - Clickjacking prevention
- X-Content-Type-Options - MIME sniffing prevention
- Referrer-Policy - Referrer information control
Installation
# Install the package composer require salehye/laravel-security # Publish configuration and migrations php artisan vendor:publish --provider="Salehye\LaravelSecurity\SecurityServiceProvider"
Configuration
After publishing, edit config/security.php to customize your security settings:
return [ // Enable/disable the entire security package 'enabled' => env('SECURITY_ENABLED', true), // Input protection settings 'input_protection' => [ 'enabled' => true, 'auto_sanitize' => true, ], // Firewall settings 'firewall' => [ 'enabled' => true, 'auto_block' => true, 'threat_threshold' => 70, ], // Rate limiting 'rate_limiting' => [ 'enabled' => true, 'progressive' => [ 'enabled' => true, 'threshold' => 3, ], ], // Security headers 'headers' => [ 'enabled' => true, 'csp' => [ 'enabled' => true, ], ], ];
Usage
Middleware
The package automatically applies security middleware when auto_protect is enabled. You can also apply middleware manually:
// In app/Http/Kernel.php or bootstrap/app.php protected $middlewareAliases = [ 'security.sanitize' => \Salehye\LaravelSecurity\Http\Middleware\SanitizeInputMiddleware::class, 'security.rate' => \Salehye\LaravelSecurity\Http\Middleware\AdvancedRateLimitMiddleware::class, 'security.headers' => \Salehye\LaravelSecurity\Http\Middleware\SecurityHeadersMiddleware::class, 'security.api' => \Salehye\LaravelSecurity\Http\Middleware\ApiKeyMiddleware::class, ];
Facade
Use the Security facade for easy access to security features:
use Salehye\LaravelSecurity\Facades\Security; // Audit logging Security::audit(auth()->user(), 'updated_settings', $request->all()); // Block an IP Security::blockIp('192.168.1.1', 'Brute force attack'); // Check if IP is blocked if (Security::isBlocked($request->ip())) { abort(403, 'Access denied'); } // Sanitize input $clean = Security::sanitize($request->all()); // Detect threats $threats = Security::detectThreats($request); if (array_filter($threats)) { Security::logThreat('multiple_detections', $threats); } // Session management Security::terminateAllOtherSessions($request);
Validation Rules
The package provides custom validation rules:
use Salehye\LaravelSecurity\Rules\NoSqlInjectionRule; use Salehye\LaravelSecurity\Rules\NoXssRule; use Salehye\LaravelSecurity\Rules\SensitiveDataRule; use Salehye\LaravelSecurity\Rules\PasswordStrengthRule; // In your Form Request public function rules(): array { return [ 'username' => ['required', 'string', new NoSqlInjectionRule()], 'comment' => ['required', 'string', new NoXssRule()], 'data' => [new SensitiveDataRule()], 'password' => ['required', new PasswordStrengthRule()], ]; }
API Protection
Sign your API requests:
use Salehye\LaravelSecurity\Facades\Security; // Generate API key $apiKey = Security::generateApiKey(); // Sign a request $signedRequest = Security::signRequest($data, $apiKey); // On the server side, verify the signature if (!Security::verifySignature($request)) { abort(401, 'Invalid signature'); }
Audit Logging
use Salehye\LaravelSecurity\Facades\Security; // Log events Security::log('user_login', auth()->user(), ['ip' => request()->ip()]); Security::logFailedLogin($email, ['ip' => request()->ip()]); Security::logSensitiveAction('password_change', auth()->user()); Security::logThreat('sql_injection', ['payload' => $request->get('search')]); // Retrieve logs $logs = Security::getLogs(event: 'login', limit: 100); // Clean old logs Security::cleanOldLogs(90); // Keep 90 days
Console Commands
# Run security audit php artisan security:audit # Block an IP php artisan security:block 192.168.1.1 --reason="Brute force" --duration=24 # Unblock an IP php artisan security:unblock 192.168.1.1 # View security report php artisan security:report # Warmup security cache php artisan security:cache:warmup # Clean old audit logs php artisan security:clean-logs --days=90
Events & Listeners
The package fires events for security-related actions:
// Events \Salehye\LaravelSecurity\Events\SuspiciousActivityDetected::class \Salehye\LaravelSecurity\Events\UserBlocked::class \Salehye\LaravelSecurity\Events\LoginAttemptFailed::class \Salehye\LaravelSecurity\Events\RateLimitExceeded::class \Salehye\LaravelSecurity\Events\SensitiveActionPerformed::class
Testing
composer test
Documentation
For detailed documentation, visit the Wiki.
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security-related issues, please email security@example.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
Laravel Package Development
This package is built following Laravel package development conventions and is compatible with Laravel 12.x and PHP 8.4+.