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.
virt/web/app/Services/Cloud/CloudAbuseAlertMessageForma...

201 lines
8.2 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Cloud;
use App\Services\Config;
/** Renders one immutable finding transition into a bounded Telegram message. */
final class CloudAbuseAlertMessageFormatter
{
private const RULE_LABELS = [
'outbound_tcp_syn_sweep' => '对外 TCP SYN 扫描',
'outbound_tcp_port_scan' => '对外 TCP 端口扫描',
'outbound_udp_fanout' => '对外 UDP 扇出',
'inbound_tcp_syn_attack' => '入站 TCP SYN 攻击',
'inbound_tcp_port_scan' => '入站 TCP 端口扫描',
'inbound_udp_flood' => '入站 UDP Flood',
];
private const EVIDENCE_LABELS = [
'tcp_active_flows' => 'TCP 活跃 Flow',
'tcp_new_flows' => 'TCP 新建 Flow',
'tcp_syn_flows' => 'TCP SYN Flow',
'tcp_unreplied_flows' => 'TCP 未应答 Flow',
'udp_active_flows' => 'UDP 活跃 Flow',
'udp_new_flows' => 'UDP 新建 Flow',
'unique_remote_ips' => '唯一远端 IP 数',
'unique_remote_ports' => '唯一远端端口数',
'unique_local_ports' => '唯一本地端口数',
'max_remote_ports_per_remote_ip' => '单远端 IP 最大端口数',
'max_remote_ips_per_remote_port' => '单远端端口最大 IP 数',
'max_local_ports_per_remote_ip' => '单远端 IP 最大本地端口数',
'max_remote_ips_per_local_port' => '单本地端口最大远端 IP 数',
];
public function format(object $event): string
{
$eventId = self::positiveInteger(self::value($event, 'id'), 'event id');
$instanceId = self::positiveInteger(
self::value($event, 'instance_id'),
'instance id'
);
$userId = self::positiveInteger(self::value($event, 'user_id'), 'user id');
$hostId = self::positiveInteger(self::value($event, 'host_id'), 'host id');
$policyRevision = self::positiveInteger(
self::value($event, 'policy_revision'),
'policy revision'
);
$occurredAt = self::positiveInteger(
self::value($event, 'occurred_at'),
'occurred at'
);
$rule = (string) self::value($event, 'rule_code');
$direction = (string) self::value($event, 'direction');
$family = (string) self::value($event, 'ip_family');
$type = (string) self::value($event, 'transition_type');
$from = (string) self::value($event, 'from_severity');
$to = (string) self::value($event, 'to_severity');
$reason = (string) self::value($event, 'resolution_reason');
if (!isset(self::RULE_LABELS[$rule])
|| !in_array($direction, ['inbound', 'outbound'], true)
|| !in_array($family, ['ipv4', 'ipv6', 'mixed'], true)
|| !self::validTransition($type, $from, $to, $reason)) {
throw new \InvalidArgumentException(
'Invalid abuse alert transition snapshot'
);
}
$evidence = self::decodeEvidence(self::value($event, 'evidence_json'));
$resolved = $type === 'resolved';
$title = $resolved
? '✅ 网络风险已恢复'
: ($to === 'high'
? '🔴 网络滥用高风险告警'
: '🟠 网络异常告警');
$transition = [
'opened' => '新触发',
'escalated' => '风险升级',
'resolved' => $reason === 'policy_replaced'
? '策略更新后关闭' : '已恢复',
][$type];
$directionLabel = $direction === 'inbound'
? '入站受攻击' : '出站可疑行为';
$severity = $resolved
? ($from === 'high' ? '高风险已解除' : '可疑状态已解除')
: ($to === 'high' ? '高风险' : '可疑');
$evidenceParts = [];
foreach ($evidence as $key => $count) {
$evidenceParts[] = self::EVIDENCE_LABELS[$key] . ' '
. number_format($count, 0, '.', ',');
}
$lines = [
$title,
'',
'实例:#' . $instanceId,
'用户:#' . $userId,
'宿主机:#' . $hostId,
'发生时间:' . gmdate('Y-m-d H:i:s', $occurredAt) . ' UTC',
'告警:#' . $eventId,
'策略:r' . $policyRevision,
'',
($resolved ? '✅ ' : ($to === 'high' ? '🔴 ' : '🟠 '))
. $transition . ' · ' . self::RULE_LABELS[$rule],
'方向:' . $directionLabel . ' · ' . strtoupper($family)
. ' · ' . $severity,
'证据:' . ($evidenceParts === []
? '未记录聚合计数' : implode(';', $evidenceParts)),
'',
'后台:' . self::adminUrl(
(string) Config::get('baseUrl', ''),
$instanceId
),
'说明:仅包含聚合元数据,不包含通信正文或远端地址明细。',
];
$message = implode("\n", $lines);
if (mb_strlen($message, 'UTF-8') > 4096) {
throw new \LogicException('Abuse alert message exceeded Telegram limit');
}
return $message;
}
private static function validTransition(
string $type,
string $from,
string $to,
string $reason
): bool {
return ($type === 'opened' && $from === 'none'
&& in_array($to, ['suspicious', 'high'], true)
&& $reason === '')
|| ($type === 'escalated' && $from === 'suspicious'
&& $to === 'high' && $reason === '')
|| ($type === 'resolved'
&& in_array($from, ['suspicious', 'high'], true)
&& $to === 'none'
&& in_array($reason, [
'evidence_clear', 'policy_replaced',
], true));
}
/** @return array<string,int> */
private static function decodeEvidence(mixed $json): array
{
if (!is_string($json) || $json === '' || strlen($json) > 16384) {
throw new \InvalidArgumentException('Invalid abuse alert evidence');
}
try {
$value = json_decode($json, true, 8, JSON_THROW_ON_ERROR);
} catch (\JsonException $error) {
throw new \InvalidArgumentException(
'Invalid abuse alert evidence',
0,
$error
);
}
if (!is_array($value) || array_is_list($value)) {
throw new \InvalidArgumentException('Invalid abuse alert evidence');
}
$normalized = [];
foreach ($value as $key => $count) {
if (!is_string($key) || !isset(self::EVIDENCE_LABELS[$key])
|| !is_int($count) || $count < 0) {
throw new \InvalidArgumentException('Invalid abuse alert evidence');
}
$normalized[$key] = $count;
}
ksort($normalized, SORT_STRING);
return $normalized;
}
private static function adminUrl(string $baseUrl, int $instanceId): string
{
$baseUrl = rtrim(trim($baseUrl), '/');
$parts = parse_url($baseUrl);
if ($baseUrl === '' || !is_array($parts)
|| !in_array($parts['scheme'] ?? '', ['http', 'https'], true)
|| empty($parts['host']) || isset($parts['user'])
|| isset($parts['pass']) || isset($parts['query'])
|| isset($parts['fragment'])
|| preg_match('/[\x00-\x20\x7f]/', $baseUrl) === 1) {
throw new \InvalidArgumentException('Invalid administrator base URL');
}
return $baseUrl . '/admin/abuse-monitoring?query=' . $instanceId;
}
private static function positiveInteger(mixed $value, string $label): int
{
if ((!is_int($value) && !is_string($value))
|| preg_match('/^[1-9][0-9]*$/D', (string) $value) !== 1
|| strlen((string) $value) > strlen((string) PHP_INT_MAX)
|| (strlen((string) $value) === strlen((string) PHP_INT_MAX)
&& strcmp((string) $value, (string) PHP_INT_MAX) > 0)) {
throw new \InvalidArgumentException('Invalid abuse alert ' . $label);
}
return (int) $value;
}
private static function value(object $row, string $key): mixed
{
return $row->{$key} ?? null;
}
}