54 lines
1.8 KiB
PHP
54 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Middlewares;
|
|
|
|
use App\Core\Request;
|
|
use App\Core\Response;
|
|
|
|
class SecurityMiddleware
|
|
{
|
|
/**
|
|
* Applies OWASP security headers and sanitizes incoming body/query parameters
|
|
* to protect against XSS and basic Injection.
|
|
*/
|
|
public function handle(Request $request, Response $response): void
|
|
{
|
|
// 1. Set OWASP Security Headers
|
|
$response->setHeader('X-Frame-Options', 'DENY'); // Prevent Clickjacking
|
|
$response->setHeader('X-XSS-Protection', '1; mode=block'); // Prevent Cross-Site Scripting (XSS)
|
|
$response->setHeader('X-Content-Type-Options', 'nosniff'); // Prevent MIME-sniffing
|
|
$response->setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload'); // HSTS
|
|
$response->setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; object-src 'none';"); // CSP
|
|
|
|
// 2. Input Sanitization to prevent XSS (Recursive)
|
|
$body = $request->getBody();
|
|
if (is_array($body)) {
|
|
$request->setBody($this->sanitizeArray($body));
|
|
}
|
|
|
|
$query = $request->getQueryParams();
|
|
if (is_array($query)) {
|
|
$request->setQueryParams($this->sanitizeArray($query));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Recursively sanitize input arrays
|
|
*/
|
|
private function sanitizeArray(array $data): array
|
|
{
|
|
$sanitized = [];
|
|
foreach ($data as $key => $value) {
|
|
if (is_array($value)) {
|
|
$sanitized[$key] = $this->sanitizeArray($value);
|
|
} elseif (is_string($value)) {
|
|
// Strip HTML tags and convert special characters to HTML entities
|
|
$sanitized[$key] = htmlspecialchars(strip_tags(trim($value)), ENT_QUOTES, 'UTF-8');
|
|
} else {
|
|
$sanitized[$key] = $value;
|
|
}
|
|
}
|
|
return $sanitized;
|
|
}
|
|
}
|