实时安全分析与自动化设备响应流水线:本地开发设置 - 2

实时安全分析与自动化设备响应流水线:本地开发设置 - 2

本指南将构建一个实时安全分析与自动化设备响应流水线的本地开发版本,使用 Kafka、InfluxDB、Spring Boot 规则引擎和模拟防火墙适配器。它专为单台工作站上的开发和技术演示而设计。

Series: 安全运营平台 2026 (22 articles)

  1. …
  2. 5
    实时安全分析与自动化设备响应流水线:本地开发设置 - 2 This article
Dev @ Vertex Macro



安全运营平台

Project Summary(6W 路演框架)

  • Who(目标客户与核心角色):面向大型企业的安全运维团队,由 AI 全栈开发工程师主导核心架构与业务域研发。
  • What(核心产品与痛点解决):企业级一体化安全运营管理平台,解决海量安全告警处理滞后及风险管控分散的痛点,提供网络安全监测、资产管控、漏洞治理与 AI 智能分析一体化能力。
  • Why(核心壁垒与竞争优势):「定时任务 + Redis 缓存 + 未命中实时聚合回填」三层数据供给策略,将核心接口响应压至 50ms 以内;实现从风险识别到防护响应的全自动化闭环。
  • Where(应用场景与部署环境):覆盖企业多场景安全运维、防火墙设备联动及域名安全监测,支持基于 Docker 容器编排的多环境隔离部署与数据源动态切换。
  • When(时效性与实时能力):日均实时处理 10 万+ 条全网安全设备原始告警,支持 5 分钟级定时聚合与缓存刷新,150+ 表万级数据全表聚合任务耗时控制在 3 秒以内。
  • How(技术路径与交付机制):基于微服务架构拆分业务模块、复用公共能力库,构建「Kafka + InfluxDB + 规则引擎」实时分析与设备自动化联动链路。

Business

  • AI:对接 AI Agent 实现攻击路径智能研判、系统/资产/漏洞三维风险评级及自动化整改建议生成。
  • 自动化:通过 IP 黑名单 AI 分析公开接口支撑防火墙设备拉取数据,实现从风险识别到防护响应全程自动化。
  • 高并发:支撑 150+ 张业务表及日均 10 万+ 条告警数据实时处理,核心监测接口响应由 2 秒+ 优化至 50ms 以内,纯 Redis 读取接口 QPS 承载量达 500+。
  • 高可用:缓存失效自动降级查库,保障系统 99.9% 高可用性。
  • 信创:实现达梦数据库 与 PostgreSQL 无缝切换。
  • 提效:通过微服务独立迭代及公共能力库复用大幅提升研发与交付效率。

Tech Stack

  • 后端:Spring Boot 3.2.6
  • 前端:Vue3
  • 数据库:InfluxDB
  • 缓存:Redis
  • 中间件:Kafka,PostgreSQL
  • 容器化:Docker



第 9 步:实现本地防火墙模拟器

创建  src/main/java/com/example/security/service/LocalFirewallService.java :
package com.example.security.service;

import com.example.security.dto.FirewallBlock;
import com.example.security.dto.FirewallBlockRequest;
import org.springframework.stereotype.Service;

import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LocalFirewallService {

private final Map<String, FirewallBlock> blocksByCommand = new ConcurrentHashMap<>();
private final Clock clock = Clock.systemUTC();

public FirewallBlock block(FirewallBlockRequest request) {
return blocksByCommand.computeIfAbsent(request.commandId(), ignored -> {
Instant createdAt = clock.instant();
Instant expiresAt = createdAt.plus(
request.durationMinutes(),
ChronoUnit.MINUTES
);
return new FirewallBlock(
request.commandId(),
request.decisionId(),
request.tenantId(),
request.sourceIp(),
request.reason(),
createdAt,
expiresAt,
"ACTIVE"
);
});
}

public List<FirewallBlock> list() {
return blocksByCommand.values().stream()
.sorted(Comparator.comparing(FirewallBlock::createdAt))
.toList();
}

public void clear() {
blocksByCommand.clear();
}
}
模拟器通过  commandId  对记录进行键值关联。重复相同的命令将返回现有的拦截记录,而不是创建另一个。这模拟了设备边界处的幂等行为。
创建  src/main/java/com/example/security/controller/LocalFirewallController.java :
package com.example.security.controller;

import com.example.security.dto.FirewallBlock;
import com.example.security.dto.FirewallBlockRequest;
import com.example.security.service.LocalFirewallService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/local-firewall")
public class LocalFirewallController {

private final LocalFirewallService firewallService;

public LocalFirewallController(LocalFirewallService firewallService) {
this.firewallService = firewallService;
}

@PostMapping("/blocks")
@ResponseStatus(HttpStatus.CREATED)
public FirewallBlock createBlock(@RequestBody FirewallBlockRequest request) {
return firewallService.block(request);
}

@GetMapping("/blocks")
public List<FirewallBlock> listBlocks() {
return firewallService.list();
}

@DeleteMapping("/blocks")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void clearBlocks() {
firewallService.clear();
}
}
这些端点仅供本地开发使用。绝不能将它们解释为真实的防火墙集成。该模拟器永远不会修改 Linux、macOS、Windows、Docker、路由器或云防火墙的规则。

第 10 步:实现自动化设备响应消费者

创建  src/main/java/com/example/security/service/DeviceResponseConsumer.java :
package com.example.security.service;

import com.example.security.dto.DeviceCommandResult;
import com.example.security.dto.FirewallBlock;
import com.example.security.dto.FirewallBlockRequest;
import com.example.security.dto.ResponseDecision;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.util.UUID;

@Service
public class DeviceResponseConsumer {

private static final Logger log = LoggerFactory.getLogger(DeviceResponseConsumer.class);

private final RestClient restClient;
private final KafkaTemplate<String, Object> kafkaTemplate;
private final String firewallBaseUrl;
private final String resultsTopic;
private final Clock clock = Clock.systemUTC();

public DeviceResponseConsumer(
RestClient restClient,
KafkaTemplate<String, Object> kafkaTemplate,
@Value("${app.firewall.base-url}") String firewallBaseUrl,
@Value("${app.kafka.results-topic}") String resultsTopic
) {
this.restClient = restClient;
this.kafkaTemplate = kafkaTemplate;
this.firewallBaseUrl = firewallBaseUrl;
this.resultsTopic = resultsTopic;
}

@KafkaListener(
topics = "${app.kafka.decisions-topic}",
groupId = "device-response-local"
)
public void execute(ResponseDecision decision) {
String commandId = deterministicCommandId(decision);

FirewallBlockRequest request = new FirewallBlockRequest(
commandId,
decision.decisionId(),
decision.tenantId(),
decision.sourceIp(),
decision.durationMinutes(),
decision.reason()
);

FirewallBlock block = restClient.post()
.uri(firewallBaseUrl + "/blocks")
.body(request)
.retrieve()
.body(FirewallBlock.class);

if (block == null) {
throw new IllegalStateException("Firewall simulator returned no result");
}

Instant completedAt = clock.instant();
DeviceCommandResult result = new DeviceCommandResult(
commandId,
decision.decisionId(),
decision.tenantId(),
decision.targetDeviceId(),
decision.sourceIp(),
decision.action(),
"VERIFIED",
"Temporary source IP block recorded by local firewall simulator",
completedAt
);

String key = result.tenantId() + ":" + result.deviceId();
kafkaTemplate.send(resultsTopic, key, result);

log.info(
"Verified local response command {} for source {}",
result.commandId(),
result.sourceIp()
);
}

private String deterministicCommandId(ResponseDecision decision) {
String seed = decision.decisionId()
+ ":"
+ decision.targetDeviceId()
+ ":"
+ decision.action();
return UUID.nameUUIDFromBytes(
seed.getBytes(StandardCharsets.UTF_8)
).toString();
}
}
响应消费者通过决策、设备和操作创建一个确定性的命令标识符。如果进程中断后 Kafka 重新传递决策,模拟器将收到相同的命令标识符并返回现有结果。
创建  src/main/java/com/example/security/service/DeviceResultConsumer.java :
package com.example.security.service;

import com.example.security.dto.DeviceCommandResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class DeviceResultConsumer {

private static final Logger log = LoggerFactory.getLogger(DeviceResultConsumer.class);

@KafkaListener(
topics = "${app.kafka.results-topic}",
groupId = "device-result-audit-local"
)
public void record(DeviceCommandResult result) {
log.info(
"Command result: commandId={}, decisionId={}, status={}, sourceIp={}, deviceId={}",
result.commandId(),
result.decisionId(),
result.status(),
result.sourceIp(),
result.deviceId()
);
}
}
此消费者代表反馈路径。在更大的系统中,它将更新事件状态、抑制状态、审计存储以及分析师仪表板。对于本地设置,它会记录已验证的结果。

第 11 步:构建并启动应用程序

编译项目:
mvn clean test
启动应用程序:
mvn spring-boot:run
确认健康状况:
curl -s http://localhost:8080/actuator/health
确认本地防火墙模拟器为空:
curl -s http://localhost:8080/local-firewall/blocks
响应应该是一个空的 JSON 数组。
如果应用程序在 Docker 启动后未能立即连接到 Kafka,请检查容器健康状况,并在 Kafka 变健康后重新启动应用程序:
docker compose ps
docker compose logs kafka
如果 InfluxDB 身份验证失败,请验证  application.yml  中的令牌是否与  compose.yaml  中的  DOCKER_INFLUXDB_INIT_ADMIN_TOKEN  完全匹配。

第 12 步:测试匹配的安全事件

为  tenant-a  发送一个关键(critical)SSH 事件:
curl -i -X POST http://localhost:8080/api/v1/security-events \
-H 'Content-Type: application/json' \
-d '{
"eventId": "event-0001",
"tenantId": "tenant-a",
"deviceId": "firewall-hk-01",
"sourceIp": "203.0.113.50",
"destinationIp": "10.10.20.15",
"destinationPort": 22,
"protocol": "TCP",
"severity": "CRITICAL",
"eventType": "SUSPICIOUS_SSH_ACCESS",
"eventTime": "2026-11-19T10:15:00Z",
"schemaVersion": 1
}'
API 应返回 HTTP 202。异步流随后执行以下工作:
  • Kafka 存储原始事件。
  • 分析消费者将观测数据写入 InfluxDB。
  • 规则引擎匹配关键的 SSH 策略。
  • 发布确定性的响应决策。
  • 响应消费者调用防火墙模拟器。
  • 模拟器记录 30 分钟的拦截。
  • 发布并记录已验证的命令结果。
等待一两秒,检查模拟器:
curl -s http://localhost:8080/local-firewall/blocks
响应应包含针对  203.0.113.50  的一个活动拦截。
检查应用程序日志。它应该包含表明响应决策已发布以及本地响应命令已验证的消息。

第 13 步:验证幂等事件处理

再次发送完全相同的  event-0001  有效负载:
curl -i -X POST http://localhost:8080/api/v1/security-events \
-H 'Content-Type: application/json' \
-d '{
"eventId": "event-0001",
"tenantId": "tenant-a",
"deviceId": "firewall-hk-01",
"sourceIp": "203.0.113.50",
"destinationIp": "10.10.20.15",
"destinationPort": 22,
"protocol": "TCP",
"severity": "CRITICAL",
"eventType": "SUSPICIOUS_SSH_ACCESS",
"eventTime": "2026-11-19T10:15:00Z",
"schemaVersion": 1
}'
再次检查模拟器:
curl -s http://localhost:8080/local-firewall/blocks
针对该确定性命令标识符,应该仍然只有一个拦截记录。事件可以多次传递,但重复传递不会创建多条防火墙记录。
InfluxDB 数据点也使用具有相同标签集的同一事件时间戳。在这个本地模型中,重复写入会更新相同的逻辑数据点,而不是产生额外的序列。更大的设计应该根据源系统的事件身份和时间戳精度来定义幂等性。

第 14 步:测试不得触发响应的事件

发送中等严重程度的 SSH 事件:
curl -i -X POST http://localhost:8080/api/v1/security-events \
-H 'Content-Type: application/json' \
-d '{
"eventId": "event-0002",
"tenantId": "tenant-a",
"deviceId": "firewall-hk-01",
"sourceIp": "203.0.113.60",
"destinationIp": "10.10.20.15",
"destinationPort": 22,
"protocol": "TCP",
"severity": "MEDIUM",
"eventType": "SSH_LOGIN_FAILURE",
"eventTime": "2026-11-19T10:16:00Z",
"schemaVersion": 1
}'
该事件存储在 Kafka 和 InfluxDB 中,但它不会授权自动拦截,因为它低于配置的最低严重程度。
发送到 HTTPS 端口 443 的关键事件:
curl -i -X POST http://localhost:8080/api/v1/security-events \
-H 'Content-Type: application/json' \
-d '{
"eventId": "event-0003",
"tenantId": "tenant-a",
"deviceId": "firewall-hk-01",
"sourceIp": "203.0.113.70",
"destinationIp": "10.10.20.15",
"destinationPort": 443,
"protocol": "TCP",
"severity": "CRITICAL",
"eventType": "SUSPICIOUS_HTTPS_ACCESS",
"eventTime": "2026-11-19T10:17:00Z",
"schemaVersion": 1
}'
此事件不匹配本地 SSH 规则,因为其目标端口不是 22。
从允许列出的源发送关键 SSH 事件:
curl -i -X POST http://localhost:8080/api/v1/security-events \
-H 'Content-Type: application/json' \
-d '{
"eventId": "event-0004",
"tenantId": "tenant-a",
"deviceId": "firewall-hk-01",
"sourceIp": "192.0.2.10",
"destinationIp": "10.10.20.15",
"destinationPort": 22,
"protocol": "TCP",
"severity": "CRITICAL",
"eventType": "APPROVED_SECURITY_SCAN",
"eventTime": "2026-11-19T10:18:00Z",
"schemaVersion": 1
}'
该事件同样不会触发自动拦截。源地址存在于本地允许列表中,这证明了负面证据可以覆盖原本匹配的模式。

第 15 步:在 InfluxDB 中查询安全事件

在容器内部使用 InfluxDB 命令行工具:
docker exec -it security-influxdb influx query \
--host http://localhost:8086 \
--org security-local \
--token local-development-token-change-me \
'from(bucket: "security-events")
|> range(start: -24h)
|> filter(fn: (r) => r._measurement == "security_event")
|> filter(fn: (r) => r.tenant_id == "tenant-a")'
该查询返回消费者写入的事件的面向字段(field-oriented)的行。
仅查询关键观测数据:
docker exec -it security-influxdb influx query \
--host http://localhost:8086 \
--org security-local \
--token local-development-token-change-me \
'from(bucket: "security-events")
|> range(start: -24h)
|> filter(fn: (r) => r._measurement == "security_event")
|> filter(fn: (r) => r.tenant_id == "tenant-a")
|> filter(fn: (r) => r.severity == "CRITICAL")'
基于浏览器的 InfluxDB Data Explorer 可以运行相同的 Flux 查询。选择  security-events  存储桶并通过测量名称、租户、严重程度、设备或事件类型缩小结果范围。
本地规则引擎目前直接评估事件负载。InfluxDB 提供用于调查和未来时间规则的事件时间历史记录。下一个开发迭代可以计算滚动计数(例如五分钟内一个源联系的独立目标数量),并将该派生特征发布回 Kafka 以供规则评估使用。

第 16 步:检查 Kafka 记录和消费者进度

检查原始事件:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic security.events.raw.v1 \
--from-beginning \
--max-messages 4
检查响应决策:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic security.response.decisions.v1 \
--from-beginning \
--max-messages 1
检查命令结果:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic security.response.results.v1 \
--from-beginning \
--max-messages 1
检查消费者组:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--list
描述分析消费者组:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group security-analysis-local
 LAG (延迟)列显示尚未处理的记录数。在本地机器上,在应用程序处理完测试事件后,延迟通常应很快恢复为零。

第 17 步:验证故障和恢复行为

停止 InfluxDB:
docker compose stop influxdb
发送带有新事件标识符的另一个匹配事件。分析消费者无法完成观测数据的写入。Kafka 错误处理程序重试两次,然后将失败的记录发布到死信主题。不应发生任何自动设备响应,因为分析阶段未成功完成。
检查死信主题:
docker exec -it security-kafka \
/opt/bitnami/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic security.events.dead-letter.v1 \
--from-beginning \
--max-messages 1
重新启动 InfluxDB:
docker compose start influxdb
等待直到它变健康:
docker compose ps
在本示例中,死信记录不会被自动重放。自动重放可能会产生重复的故障或意外操作。对于本地开发,请首先纠正依赖项或负载问题,检查死信记录,然后使用新的事件标识符提交新事件。
要在不更改代码的情况下测试设备响应失败,请在决策发布后但在被消费前停止 Spring Boot 应用程序,然后重新启动它。Kafka 会保留该决策,响应消费者在启动后处理它。如果决策再次被传递,确定性的命令标识符可防止出现重复的模拟器记录。

第 18 步:添加专注的规则测试

创建  src/test/java/com/example/security/service/SecurityRuleEngineTest.java :
package com.example.security.service;

import com.example.security.dto.ResponseDecision;
import com.example.security.dto.SecurityEvent;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

class SecurityRuleEngineTest {

private final SecurityRuleEngine engine = new SecurityRuleEngine(
22,
"HIGH",
30,
"tenant-a"
);

@Test
void authorizesCriticalSshEvent() {
SecurityEvent event = event(
"event-test-1",
"tenant-a",
"203.0.113.50",
22,
"CRITICAL"
);

Optional<ResponseDecision> result = engine.evaluate(event);

assertThat(result).isPresent();
assertThat(result.orElseThrow().action())
.isEqualTo("TEMPORARY_IP_BLOCK");
assertThat(result.orElseThrow().durationMinutes())
.isEqualTo(30);
}

@Test
void ignoresMediumSeverityEvent() {
SecurityEvent event = event(
"event-test-2",
"tenant-a",
"203.0.113.60",
22,
"MEDIUM"
);

assertThat(engine.evaluate(event)).isEmpty();
}

@Test
void ignoresAllowlistedSource() {
SecurityEvent event = event(
"event-test-3",
"tenant-a",
"192.0.2.10",
22,
"CRITICAL"
);

assertThat(engine.evaluate(event)).isEmpty();
}

@Test
void createsSameDecisionIdForSameEventAndRuleVersion() {
SecurityEvent event = event(
"event-test-4",
"tenant-a",
"203.0.113.70",
22,
"HIGH"
);

String first = engine.evaluate(event).orElseThrow().decisionId();
String second = engine.evaluate(event).orElseThrow().decisionId();

assertThat(first).isEqualTo(second);
}

private SecurityEvent event(
String eventId,
String tenantId,
String sourceIp,
int destinationPort,
String severity
) {
return new SecurityEvent(
eventId,
tenantId,
"firewall-hk-01",
sourceIp,
"10.10.20.15",
destinationPort,
"TCP",
severity,
"SUSPICIOUS_ACCESS",
Instant.parse("2026-11-19T10:15:00Z"),
Instant.parse("2026-11-19T10:15:01Z"),
1
);
}
}
运行测试:
mvn test
这些测试验证本地策略边界和确定性决策标识符。它们仅是开发测试,并非生产验收测试。

第 19 步:安全地调整本地规则

如果需要演示另一种协议,请更改  application.yml  中的目标端口规则:
app:
rules:
blocked-port: 3389
这会将测试策略从 SSH 更改为远程桌面协议(RDP)。在发送新的测试事件之前,请重新启动应用程序。
更改最低严重程度:
app:
rules:
minimum-severity: CRITICAL
只有关键事件才会授权响应。
更改临时拦截持续时间:
app:
rules:
block-duration-minutes: 10
模拟器将为新创建的命令记录十分钟的到期时间。现有的内存内拦截记录不会改变。
当规则逻辑发生实质性变化时,请在  SecurityRuleEngine  中递增  RULE_VERSION 。版本将成为确定性决策标识符和审计上下文的一部分。更改后的规则不应静默重复使用早期决策模型的身份。
保持允许列表为私有且明确。对于本地示例,出于可读性考虑,允许列表被硬编码。在大型开发项目中,将其存储在带有所有者、审核日期和过期策略的版本化配置源中。

第 20 步:重置并停止本地环境

清除所有模拟的防火墙拦截记录:
curl -i -X DELETE http://localhost:8080/local-firewall/blocks
按  Ctrl+C  停止 Spring Boot 应用程序。
在保留本地数据的同时停止 Kafka 和 InfluxDB:
docker compose stop
稍后重启容器:
docker compose start
移除容器,同时保留它们的命名卷:
docker compose down
移除容器以及所有本地的 Kafka 和 InfluxDB 数据:
docker compose down -v
删除卷后,下一次执行  docker compose up -d  将重新初始化 Kafka 主题和 InfluxDB。
完整的本地流水线演示了无需更改真实网络设备即可实现的完整闭环。安全观测数据通过 API 进入,Kafka 保留和分发事件,InfluxDB 存储事件的时间历史记录,规则引擎评估显式策略,响应消费者创建幂等命令,防火墙模拟器记录临时拦截,结果作为经验证的反馈通过 Kafka 返回。这种解耦提供了一个安全的开发基础,可在后续迭代中添加更丰富的时间分析、资产上下文、漏洞上下文、AI 辅助调查以及供应商特定的设备适配器。

Series: 安全运营平台 2026 (22 articles)

  1. …
  2. 5
    实时安全分析与自动化设备响应流水线:本地开发设置 - 2 This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article