You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
495 lines
19 KiB
PHP
495 lines
19 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\SiteSecurityEvent;
|
|
use DateTimeImmutable;
|
|
use DateTimeZone;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
|
|
class SiteSecurityEventService
|
|
{
|
|
private const REASON_LABELS = [
|
|
'path_traversal' => '目录穿越探测',
|
|
'credential_probe' => '敏感文件探测',
|
|
'software_probe' => '常见程序探测',
|
|
'executable_probe' => '可执行脚本探测',
|
|
'unusual_method' => '异常请求方法',
|
|
'protected_area' => '受限区域访问',
|
|
'access_denied' => '访问被拒绝',
|
|
'method_not_allowed' => '请求方法不允许',
|
|
'not_found' => '页面不存在',
|
|
];
|
|
|
|
private const RISK_LABELS = [
|
|
'critical' => '严重',
|
|
'high' => '高风险',
|
|
'medium' => '中风险',
|
|
'low' => '低风险',
|
|
];
|
|
|
|
public static function record(
|
|
ServerRequestInterface $request,
|
|
ResponseInterface $response,
|
|
array $identity,
|
|
array $userContext,
|
|
$classification = null
|
|
) {
|
|
if (!is_array($classification)) {
|
|
$classification = self::classify($request, $response, $userContext);
|
|
}
|
|
if ($classification === null) {
|
|
return false;
|
|
}
|
|
|
|
$now = time();
|
|
$path = self::sanitizedPath($request);
|
|
$host = self::requestHost($request);
|
|
$ip = self::text($request->getServerParam('REMOTE_ADDR', ''), 64);
|
|
$ipHash = hash_hmac(
|
|
'sha256',
|
|
date('Y-m-d', $now) . '|' . $ip,
|
|
(string) Config::get('key', 'site-security')
|
|
);
|
|
$userId = isset($userContext['user_id']) ? max(0, (int) $userContext['user_id']) : 0;
|
|
$visitorId = self::identifier(isset($identity['visitor_id']) ? $identity['visitor_id'] : '');
|
|
$sessionId = self::identifier(isset($identity['session_id']) ? $identity['session_id'] : '');
|
|
$sourceKey = $userId > 0
|
|
? 'user:' . $userId
|
|
: ($ip !== '' ? 'ip:' . $ipHash : 'visitor:' . $visitorId);
|
|
$dedupePath = $classification['reason_code'] === 'not_found' ? '*' : $path;
|
|
$bucket = (int) floor($now / 300);
|
|
$method = self::requestMethod($request);
|
|
$eventKey = hash('sha256', implode('|', [
|
|
$classification['reason_code'],
|
|
$sourceKey,
|
|
$host,
|
|
$dedupePath,
|
|
$method,
|
|
(int) $classification['status_code'],
|
|
$bucket,
|
|
]));
|
|
$userAgent = self::text($request->getHeaderLine('User-Agent'), 500);
|
|
$device = self::deviceDetails($userAgent);
|
|
|
|
$payload = [
|
|
'event_key' => $eventKey,
|
|
'user_id' => $userId,
|
|
'visitor_id' => $visitorId,
|
|
'session_id' => $sessionId,
|
|
'site_host' => $host,
|
|
'request_path' => $path,
|
|
'request_method' => $method,
|
|
'status_code' => (int) $classification['status_code'],
|
|
'reason_code' => $classification['reason_code'],
|
|
'risk_level' => $classification['risk_level'],
|
|
'ip_address' => $ip,
|
|
'ip_hash' => $ipHash,
|
|
'user_agent' => $userAgent,
|
|
'browser' => $device['browser'],
|
|
'operating_system' => $device['operating_system'],
|
|
'device_type' => $device['device_type'],
|
|
'hit_count' => 1,
|
|
'first_seen_at' => $now,
|
|
'last_seen_at' => $now,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
];
|
|
|
|
try {
|
|
if (SiteSecurityEvent::query()->insertOrIgnore($payload) > 0) {
|
|
return true;
|
|
}
|
|
|
|
$connection = (new SiteSecurityEvent())->getConnection();
|
|
return $connection->table('site_security_events')
|
|
->where('event_key', $eventKey)
|
|
->update([
|
|
'request_path' => $path,
|
|
'hit_count' => $connection->raw('hit_count + 1'),
|
|
'last_seen_at' => $now,
|
|
'updated_at' => $now,
|
|
]) > 0;
|
|
} catch (\Throwable $exception) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public static function classify(
|
|
ServerRequestInterface $request,
|
|
ResponseInterface $response,
|
|
array $userContext = []
|
|
) {
|
|
$status = max(0, min(999, (int) $response->getStatusCode()));
|
|
$method = self::requestMethod($request);
|
|
$rawPath = self::requestTargetPath($request);
|
|
$decodedPath = self::decodedPath($rawPath);
|
|
|
|
if (self::containsTraversal($rawPath, $decodedPath)) {
|
|
return self::classification('path_traversal', 'critical', $status);
|
|
}
|
|
if (self::isCredentialProbe($decodedPath)) {
|
|
return self::classification('credential_probe', 'high', $status);
|
|
}
|
|
if (self::isSoftwareProbe($decodedPath)) {
|
|
return self::classification('software_probe', 'high', $status);
|
|
}
|
|
if (self::isExecutableProbe($decodedPath)) {
|
|
return self::classification('executable_probe', 'high', $status);
|
|
}
|
|
if (!in_array($method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], true)) {
|
|
return self::classification('unusual_method', 'high', $status);
|
|
}
|
|
|
|
$lowerPath = strtolower(self::normalizedPath($request->getUri()->getPath(), 500));
|
|
if (($lowerPath === '/admin' || strpos($lowerPath, '/admin/') === 0)
|
|
&& in_array($status, [301, 302, 303, 307, 308], true)) {
|
|
$location = strtolower($response->getHeaderLine('Location'));
|
|
if (strpos($location, '/auth/login') === 0 || strpos($location, '/user') === 0) {
|
|
$risk = !empty($userContext['user_id']) ? 'medium' : 'low';
|
|
return self::classification('protected_area', $risk, $status);
|
|
}
|
|
}
|
|
|
|
if (in_array($status, [401, 403], true)) {
|
|
return self::classification('access_denied', 'medium', $status);
|
|
}
|
|
if ($status === 405) {
|
|
return self::classification('method_not_allowed', 'medium', $status);
|
|
}
|
|
if ($status === 404 && !self::isStaticNoise($decodedPath)) {
|
|
return self::classification('not_found', 'low', $status);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static function report($from, $to, array $filters = [], $page = 1, $perPage = 50, $ensureTables = true)
|
|
{
|
|
if ($ensureTables) {
|
|
SiteAnalyticsService::ensureTables();
|
|
} elseif (!SiteAnalyticsService::tablesAvailable()) {
|
|
throw new \RuntimeException('网站统计数据表尚未创建');
|
|
}
|
|
list($from, $to) = SiteAnalyticsService::normalizeDateRange($from, $to);
|
|
$filters = self::normalizeFilters($filters);
|
|
$page = max(1, (int) $page);
|
|
$perPage = max(10, min(100, (int) $perPage));
|
|
|
|
$timezone = self::timezone();
|
|
$start = (new DateTimeImmutable($from, $timezone))->setTime(0, 0, 0)->getTimestamp();
|
|
$end = (new DateTimeImmutable($to, $timezone))->modify('+1 day')->setTime(0, 0, 0)->getTimestamp();
|
|
$query = SiteSecurityEvent::where('last_seen_at', '>=', $start)
|
|
->where('last_seen_at', '<', $end);
|
|
self::applyFilters($query, $filters, (bool) $ensureTables);
|
|
|
|
$records = (int) (clone $query)->count();
|
|
$totalHits = (int) (clone $query)->sum('hit_count');
|
|
$affectedUsers = (int) (clone $query)
|
|
->where('user_id', '>', 0)
|
|
->distinct()
|
|
->count('user_id');
|
|
$highRiskHits = (int) (clone $query)
|
|
->whereIn('risk_level', ['critical', 'high'])
|
|
->sum('hit_count');
|
|
$totalPages = max(1, (int) ceil($records / $perPage));
|
|
if ($page > $totalPages) {
|
|
$page = $totalPages;
|
|
}
|
|
|
|
$rows = (clone $query)
|
|
->orderBy('last_seen_at', 'desc')
|
|
->orderBy('id', 'desc')
|
|
->forPage($page, $perPage)
|
|
->get();
|
|
|
|
$events = [];
|
|
foreach ($rows as $row) {
|
|
$events[] = [
|
|
'id' => (int) $row->id,
|
|
'user_id' => (int) $row->user_id,
|
|
'site_host' => (string) $row->site_host,
|
|
'request_path' => (string) $row->request_path,
|
|
'request_method' => (string) $row->request_method,
|
|
'status_code' => (int) $row->status_code,
|
|
'reason_code' => (string) $row->reason_code,
|
|
'reason_label' => self::reasonLabel($row->reason_code),
|
|
'risk_level' => (string) $row->risk_level,
|
|
'risk_label' => self::riskLabel($row->risk_level),
|
|
'ip_address' => (string) $row->ip_address,
|
|
'browser' => (string) $row->browser,
|
|
'operating_system' => (string) $row->operating_system,
|
|
'device_type' => (string) $row->device_type,
|
|
'hit_count' => (int) $row->hit_count,
|
|
'first_seen_at_text' => date('Y-m-d H:i:s', (int) $row->first_seen_at),
|
|
'last_seen_at_text' => date('Y-m-d H:i:s', (int) $row->last_seen_at),
|
|
];
|
|
}
|
|
|
|
return [
|
|
'from' => $from,
|
|
'to' => $to,
|
|
'summary' => [
|
|
'records' => $records,
|
|
'total_hits' => $totalHits,
|
|
'affected_users' => $affectedUsers,
|
|
'high_risk_hits' => $highRiskHits,
|
|
],
|
|
'filters' => $filters,
|
|
'reason_ranking' => self::reasonRanking($query),
|
|
'events' => $events,
|
|
'pagination' => [
|
|
'page' => $page,
|
|
'per_page' => $perPage,
|
|
'total' => $records,
|
|
'total_pages' => $totalPages,
|
|
],
|
|
];
|
|
}
|
|
|
|
|
|
public static function reasonLabel($reason)
|
|
{
|
|
$reason = (string) $reason;
|
|
return isset(self::REASON_LABELS[$reason]) ? self::REASON_LABELS[$reason] : $reason;
|
|
}
|
|
|
|
public static function riskLabel($risk)
|
|
{
|
|
$risk = (string) $risk;
|
|
return isset(self::RISK_LABELS[$risk]) ? self::RISK_LABELS[$risk] : $risk;
|
|
}
|
|
|
|
private static function applyFilters($query, array $filters, $allowSensitiveSearch)
|
|
{
|
|
if ($filters['risk'] !== '') {
|
|
$query->where('risk_level', $filters['risk']);
|
|
}
|
|
if ($filters['status'] > 0) {
|
|
$query->where('status_code', $filters['status']);
|
|
}
|
|
if ($filters['actor'] === 'user') {
|
|
$query->where('user_id', '>', 0);
|
|
} elseif ($filters['actor'] === 'anonymous') {
|
|
$query->where('user_id', 0);
|
|
}
|
|
if ($filters['keyword'] !== '') {
|
|
$keyword = '%' . addcslashes($filters['keyword'], '\\%_') . '%';
|
|
$numericUserId = ctype_digit($filters['keyword']) ? (int) $filters['keyword'] : 0;
|
|
$query->where(function ($nested) use ($keyword, $numericUserId, $allowSensitiveSearch) {
|
|
$nested->where('reason_code', 'like', $keyword);
|
|
if ($allowSensitiveSearch) {
|
|
$nested->orWhere('request_path', 'like', $keyword)
|
|
->orWhere('site_host', 'like', $keyword)
|
|
->orWhere('ip_address', 'like', $keyword);
|
|
}
|
|
if ($numericUserId > 0) {
|
|
$nested->orWhere('user_id', $numericUserId);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
private static function normalizeFilters(array $filters)
|
|
{
|
|
$risk = isset($filters['risk']) ? strtolower(trim((string) $filters['risk'])) : '';
|
|
if (!isset(self::RISK_LABELS[$risk])) {
|
|
$risk = '';
|
|
}
|
|
$status = isset($filters['status']) ? (int) $filters['status'] : 0;
|
|
if (!in_array($status, [0, 301, 302, 303, 307, 308, 401, 403, 404, 405], true)) {
|
|
$status = 0;
|
|
}
|
|
$actor = isset($filters['actor']) ? strtolower(trim((string) $filters['actor'])) : '';
|
|
if (!in_array($actor, ['', 'user', 'anonymous'], true)) {
|
|
$actor = '';
|
|
}
|
|
return [
|
|
'risk' => $risk,
|
|
'status' => $status,
|
|
'actor' => $actor,
|
|
'keyword' => self::text(isset($filters['keyword']) ? $filters['keyword'] : '', 100),
|
|
];
|
|
}
|
|
|
|
private static function reasonRanking($query)
|
|
{
|
|
$rows = (clone $query)
|
|
->select('reason_code')
|
|
->selectRaw('SUM(hit_count) AS hit_count')
|
|
->groupBy('reason_code')
|
|
->orderBy('hit_count', 'desc')
|
|
->limit(10)
|
|
->get();
|
|
$result = [];
|
|
foreach ($rows as $row) {
|
|
$result[] = [
|
|
'reason_code' => (string) $row->reason_code,
|
|
'label' => self::reasonLabel($row->reason_code),
|
|
'count' => (int) $row->hit_count,
|
|
];
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
private static function classification($reason, $risk, $status)
|
|
{
|
|
return [
|
|
'reason_code' => (string) $reason,
|
|
'risk_level' => (string) $risk,
|
|
'status_code' => (int) $status,
|
|
];
|
|
}
|
|
|
|
private static function requestTargetPath(ServerRequestInterface $request)
|
|
{
|
|
$target = (string) $request->getRequestTarget();
|
|
$question = strpos($target, '?');
|
|
if ($question !== false) {
|
|
$target = substr($target, 0, $question);
|
|
}
|
|
return $target === '' ? (string) $request->getUri()->getPath() : $target;
|
|
}
|
|
|
|
private static function decodedPath($path)
|
|
{
|
|
$decoded = rawurldecode((string) $path);
|
|
$decodedAgain = rawurldecode($decoded);
|
|
return strtolower(str_replace('\\', '/', $decodedAgain));
|
|
}
|
|
|
|
private static function containsTraversal($rawPath, $decodedPath)
|
|
{
|
|
$raw = strtolower((string) $rawPath);
|
|
return strpos($decodedPath, '../') !== false
|
|
|| strpos($decodedPath, "\0") !== false
|
|
|| strpos($raw, '%00') !== false
|
|
|| strpos($decodedPath, '/etc/passwd') !== false
|
|
|| strpos($decodedPath, '/proc/self') !== false
|
|
|| strpos($decodedPath, 'windows/win.ini') !== false;
|
|
}
|
|
|
|
private static function isCredentialProbe($path)
|
|
{
|
|
return preg_match('#(?:^|/)\.(?:env(?:\.[^/]*)?|git|svn|hg)(?:/|$)#i', $path) === 1
|
|
|| preg_match('#(?:^|/)(?:composer\.(?:json|lock)|package(?:-lock)?\.json|yarn\.lock|pnpm-lock\.yaml|\.htaccess|\.htpasswd|id_rsa|authorized_keys|config\.php)(?:/|$)#i', $path) === 1
|
|
|| preg_match('#(?:^|/)(?:backup|dump|database|db)[^/]*\.(?:sql|zip|tar|gz|bak|old)(?:$|/)#i', $path) === 1;
|
|
}
|
|
|
|
private static function isSoftwareProbe($path)
|
|
{
|
|
return preg_match('#(?:^|/)(?:wp-admin|wp-login\.php|xmlrpc\.php|phpmyadmin|pma|adminer(?:\.php)?|vendor/phpunit|cgi-bin|actuator|server-status|solr|jenkins|boaform)(?:/|$)#i', $path) === 1;
|
|
}
|
|
|
|
private static function isExecutableProbe($path)
|
|
{
|
|
return preg_match('/\.(?:php[0-9]?|phtml|phar|asp|aspx|jsp|cgi)(?:\/|$)/i', $path) === 1;
|
|
}
|
|
|
|
private static function isStaticNoise($path)
|
|
{
|
|
return preg_match('/\.(?:css|js|map|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|eot|mp3|mp4|webm|pdf|xml|txt|json|webmanifest)$/i', $path) === 1
|
|
|| strpos($path, '/.well-known/acme-challenge/') === 0;
|
|
}
|
|
|
|
private static function sanitizedPath(ServerRequestInterface $request)
|
|
{
|
|
$path = self::normalizedPath($request->getUri()->getPath(), 500);
|
|
$path = preg_replace('#^(/link)/[^/]+#i', '$1/{redacted}', $path);
|
|
$path = preg_replace('#^(/password/token)/[^/]+#i', '$1/{redacted}', $path);
|
|
return $path === null ? '/' : $path;
|
|
}
|
|
|
|
private static function normalizedPath($path, $limit)
|
|
{
|
|
$path = '/' . ltrim((string) $path, '/');
|
|
$path = preg_replace('/[\x00-\x1F\x7F]/', '', $path);
|
|
if ($path === null || $path === '') {
|
|
return '/';
|
|
}
|
|
return self::text($path, $limit);
|
|
}
|
|
|
|
private static function requestMethod(ServerRequestInterface $request)
|
|
{
|
|
return self::text(strtoupper((string) $request->getMethod()), 12);
|
|
}
|
|
|
|
private static function requestHost(ServerRequestInterface $request)
|
|
{
|
|
$host = $request->getUri()->getHost();
|
|
if ($host === '') {
|
|
$host = preg_replace('/:\d+$/', '', trim($request->getHeaderLine('Host')));
|
|
}
|
|
return SiteAnalyticsService::normalizeHost($host);
|
|
}
|
|
|
|
private static function identifier($value)
|
|
{
|
|
$value = strtolower((string) $value);
|
|
return preg_match('/^[a-f0-9]{32}$/D', $value) === 1 ? $value : str_repeat('0', 32);
|
|
}
|
|
|
|
private static function deviceDetails($userAgent)
|
|
{
|
|
$ua = strtolower((string) $userAgent);
|
|
if (strpos($ua, 'micromessenger') !== false) {
|
|
$browser = 'WeChat';
|
|
} elseif (strpos($ua, 'edg/') !== false || strpos($ua, 'edge/') !== false) {
|
|
$browser = 'Edge';
|
|
} elseif (strpos($ua, 'firefox/') !== false) {
|
|
$browser = 'Firefox';
|
|
} elseif (strpos($ua, 'chrome/') !== false || strpos($ua, 'crios/') !== false) {
|
|
$browser = 'Chrome';
|
|
} elseif (strpos($ua, 'safari/') !== false) {
|
|
$browser = 'Safari';
|
|
} else {
|
|
$browser = 'Other';
|
|
}
|
|
|
|
if (strpos($ua, 'iphone') !== false || strpos($ua, 'ipad') !== false || strpos($ua, 'ipod') !== false) {
|
|
$operatingSystem = 'iOS';
|
|
} elseif (strpos($ua, 'android') !== false) {
|
|
$operatingSystem = 'Android';
|
|
} elseif (strpos($ua, 'windows') !== false) {
|
|
$operatingSystem = 'Windows';
|
|
} elseif (strpos($ua, 'mac os') !== false || strpos($ua, 'macintosh') !== false) {
|
|
$operatingSystem = 'macOS';
|
|
} elseif (strpos($ua, 'linux') !== false) {
|
|
$operatingSystem = 'Linux';
|
|
} else {
|
|
$operatingSystem = 'Other';
|
|
}
|
|
|
|
if (strpos($ua, 'ipad') !== false || strpos($ua, 'tablet') !== false) {
|
|
$deviceType = 'tablet';
|
|
} elseif (strpos($ua, 'mobile') !== false || strpos($ua, 'iphone') !== false || strpos($ua, 'android') !== false) {
|
|
$deviceType = 'mobile';
|
|
} else {
|
|
$deviceType = 'desktop';
|
|
}
|
|
return [
|
|
'browser' => $browser,
|
|
'operating_system' => $operatingSystem,
|
|
'device_type' => $deviceType,
|
|
];
|
|
}
|
|
|
|
private static function text($value, $limit)
|
|
{
|
|
$value = trim((string) $value);
|
|
$value = preg_replace('/[\x00-\x1F\x7F]/', '', $value);
|
|
if ($value === null) {
|
|
return '';
|
|
}
|
|
return function_exists('mb_substr')
|
|
? mb_substr($value, 0, (int) $limit, 'UTF-8')
|
|
: substr($value, 0, (int) $limit);
|
|
}
|
|
|
|
private static function timezone()
|
|
{
|
|
return new DateTimeZone((string) Config::get('timeZone', date_default_timezone_get()));
|
|
}
|
|
}
|