diff --git a/src/main/java/com/realtime/protection/configuration/entity/task/Task.java b/src/main/java/com/realtime/protection/configuration/entity/task/Task.java index 4f98fb1..00f9dc5 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/task/Task.java +++ b/src/main/java/com/realtime/protection/configuration/entity/task/Task.java @@ -70,7 +70,7 @@ public class Task { @JsonProperty("task_create_userid") // @Schema(description = "任务创建人ID", accessMode = Schema.AccessMode.READ_ONLY) @Schema(description = "任务创建人ID") - private Integer taskCreateUserId; + private String taskCreateUserId; @JsonProperty("static_rule_ids") @Schema(description = "静态规则ID列表,动态和静态至少存在1个规则", example = "[10, 12]") diff --git a/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java b/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java index 649090d..21729ec 100644 --- a/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java +++ b/src/main/java/com/realtime/protection/configuration/entity/task/TaskCommandInfo.java @@ -121,7 +121,14 @@ public class TaskCommandInfo { @Schema(description = "规则名称", accessMode = Schema.AccessMode.READ_ONLY) private String ruleName; - private String hashValue; + @Schema(description = "源ip整数形式", accessMode = Schema.AccessMode.READ_ONLY) + private Long sipInt; + + @Schema(description = "目的ip整数形式", accessMode = Schema.AccessMode.READ_ONLY) + private Long dipInt; + + +// private String hashValue; // 复制构造函数 public void copyTaskCommandInfo(TaskCommandInfo original) { @@ -150,6 +157,9 @@ public class TaskCommandInfo { this.protectLevel = original.protectLevel; this.taskStatus = original.taskStatus; this.ruleName = original.ruleName; + this.displayId = original.displayId; + this.sipInt = original.sipInt; + this.dipInt = original.dipInt; } public void setProtocolNum() { diff --git a/src/main/java/com/realtime/protection/configuration/utils/File.java b/src/main/java/com/realtime/protection/configuration/utils/File.java new file mode 100644 index 0000000..38a8e8c --- /dev/null +++ b/src/main/java/com/realtime/protection/configuration/utils/File.java @@ -0,0 +1,15 @@ +package com.realtime.protection.configuration.utils; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class File implements Serializable { + private Integer id; + private String fileName; + private String filePath; + private Long fileSize; + private String fileType; + private Long staticRuleId; +} diff --git a/src/main/java/com/realtime/protection/server/command/CommandMapper.java b/src/main/java/com/realtime/protection/server/command/CommandMapper.java index 0473cdf..f4664fc 100644 --- a/src/main/java/com/realtime/protection/server/command/CommandMapper.java +++ b/src/main/java/com/realtime/protection/server/command/CommandMapper.java @@ -67,4 +67,16 @@ public interface CommandMapper { void updateCommandIsJudgedIfIgnoreThisTime(@Param("command_id") String commandUUID); Integer queryCommandIsJudged(String uuid); + + void insertCommandDistribute(@Param("info") TaskCommandInfo commandInfo); + + void insertCommandRCPQuery(@Param("info") TaskCommandInfo commandInfo); + + void insertCommandTraffic(@Param("info") TaskCommandInfo commandInfo); + + void insertCommandDistributeBatch(@Param("command_infos")List taskCommandInfoBatch); + + void insertCommandRCPQueryBatch(@Param("command_infos")List taskCommandInfoBatch); + + void insertCommandTrafficBatch(@Param("command_infos")List taskCommandInfoBatch); } diff --git a/src/main/java/com/realtime/protection/server/command/CommandService.java b/src/main/java/com/realtime/protection/server/command/CommandService.java index 25b400c..f47bc53 100644 --- a/src/main/java/com/realtime/protection/server/command/CommandService.java +++ b/src/main/java/com/realtime/protection/server/command/CommandService.java @@ -40,6 +40,19 @@ public class CommandService { this.stateHandler = stateHandler; } + public static long ipToLong(String ipAddress) { + String[] parts = ipAddress.split("\\."); + if (parts.length != 4) { + throw new IllegalArgumentException("Invalid IP address: " + ipAddress); + } + long result = 0; + for (int i = 0; i < 4; i++) { + int part = Integer.parseInt(parts[i]); + result |= (long)part << (24 - (i * 8)); + } + return result; + } + @DSTransactional public String createCommand(TaskCommandInfo commandInfo) { String uuid = commandMapper.queryCommandInfo(commandInfo); @@ -53,6 +66,13 @@ public class CommandService { + String.format("%06d", counter.generateId("command")) ); + if (commandInfo.getFiveTupleWithMask().getSourceIP()!= null){ + commandInfo.setSipInt(ipToLong(commandInfo.getFiveTupleWithMask().getSourceIP())); + } + if (commandInfo.getFiveTupleWithMask().getDestinationIP()!= null){ + commandInfo.setDipInt(ipToLong(commandInfo.getFiveTupleWithMask().getDestinationIP())); + } + //指令:白名单检查 List whiteListsHit = commandMapper.whiteListCommandCheck(commandInfo.getFiveTupleWithMask()); if (!whiteListsHit.isEmpty()) { @@ -66,8 +86,12 @@ public class CommandService { commandInfo.setUUID(UUID.randomUUID().toString()); commandMapper.createCommand(commandInfo); + commandMapper.insertCommandDistribute(commandInfo); + commandMapper.insertCommandRCPQuery(commandInfo); + commandMapper.insertCommandTraffic(commandInfo); + //写入历史表 - //insertCommandHistory(commandInfo.getUUID()); + insertCommandHistory(commandInfo.getUUID()); return commandInfo.getUUID(); } @@ -92,7 +116,12 @@ public class CommandService { + "-" + String.format("%06d", counter.generateId("command")) ); - + if (commandInfo.getFiveTupleWithMask().getSourceIP()!= null){ + commandInfo.setSipInt(ipToLong(commandInfo.getFiveTupleWithMask().getSourceIP())); + } + if (commandInfo.getFiveTupleWithMask().getDestinationIP()!= null){ + commandInfo.setDipInt(ipToLong(commandInfo.getFiveTupleWithMask().getDestinationIP())); + } //指令:白名单检查 List whiteListsHit = commandMapper.whiteListCommandCheck(commandInfo.getFiveTupleWithMask()); if (!whiteListsHit.isEmpty()) { @@ -106,8 +135,11 @@ public class CommandService { commandInfo.setUUID(UUID.randomUUID().toString()); commandMapper.createCommand(commandInfo); - //写入历史表,避免t_command_log表并发update冲突,这里先不写入历史表 - //insertCommandHistory(commandInfo.getUUID()); + commandMapper.insertCommandDistribute(commandInfo); + commandMapper.insertCommandRCPQuery(commandInfo); + commandMapper.insertCommandTraffic(commandInfo); + //写入历史表 + insertCommandHistory(commandInfo.getUUID()); //发送指令新建信号...实时任务 isJudged=1 才首次立刻下发 try { @@ -146,6 +178,12 @@ public class CommandService { + "-" + String.format("%06d", counter.generateId("command")) ); + if (info.getFiveTupleWithMask().getSourceIP()!= null){ + info.setSipInt(ipToLong(info.getFiveTupleWithMask().getSourceIP())); + } + if (info.getFiveTupleWithMask().getDestinationIP()!= null){ + info.setDipInt(ipToLong(info.getFiveTupleWithMask().getDestinationIP())); + } taskCommandInfoBatch.add(info); if (taskCommandInfoBatch.size() < BatchSize) { @@ -154,13 +192,19 @@ public class CommandService { System.out.println("batch insert " + i.getAndIncrement()); //因为createCommands只用于静态规则生成command,静态规则已经检查了白名单,所以不检查了 commandMapper.createCommands(taskCommandInfoBatch); - //insertCommandHistoryBatch(taskCommandInfoBatch); + commandMapper.insertCommandDistributeBatch(taskCommandInfoBatch); + commandMapper.insertCommandRCPQueryBatch(taskCommandInfoBatch); + commandMapper.insertCommandTrafficBatch(taskCommandInfoBatch); + insertCommandHistoryBatch(taskCommandInfoBatch); taskCommandInfoBatch.clear(); } if (!taskCommandInfoBatch.isEmpty()) { commandMapper.createCommands(taskCommandInfoBatch); - //insertCommandHistoryBatch(taskCommandInfoBatch); + commandMapper.insertCommandDistributeBatch(taskCommandInfoBatch); + commandMapper.insertCommandRCPQueryBatch(taskCommandInfoBatch); + commandMapper.insertCommandTrafficBatch(taskCommandInfoBatch); + insertCommandHistoryBatch(taskCommandInfoBatch); taskCommandInfoBatch.clear(); } diff --git a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectControllerApi.java b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectControllerApi.java index 6b7abda..e11f789 100644 --- a/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectControllerApi.java +++ b/src/main/java/com/realtime/protection/server/defense/object/ProtectObjectControllerApi.java @@ -572,4 +572,21 @@ public interface ProtectObjectControllerApi { ResponseResult queryHistory(@PathVariable Integer id, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "page_size", required = true) Integer pageSize); + + + @Operation( + summary = "同步防护对象接口", + description = "请求防护对象同步接口,调用外部系统的API,获取全量防护对象信息,并增量入库", + responses = { + @ApiResponse( + description = "返回是否同步成功,同步防护对象数量", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ResponseResult.class) + ) + ) + } + ) + @GetMapping("/synchronize") + ResponseResult synchronizeProtectObject(); } diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleController.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleController.java index 27dcecd..24c1ce5 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleController.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleController.java @@ -5,6 +5,7 @@ import com.alibaba.excel.EasyExcel; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; import com.realtime.protection.configuration.entity.user.UserFull; import com.realtime.protection.configuration.response.ResponseResult; +import com.realtime.protection.configuration.utils.File; import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -13,12 +14,21 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -64,6 +74,71 @@ public class StaticRuleController implements StaticRuleControllerApi { .setData("static_rule_name", object.getStaticRuleName()); } + @GetMapping("/queryAttachment") + @Override + public ResponseResult queryAttachment(@RequestParam("static_rule_id") Long staticRuleId) { + List files = staticRuleService.selectFilesByStaticRuleId(staticRuleId); + + return ResponseResult.ok() + .setData("files", files); + } + + //上传附件 + @PostMapping("/uploadAttachment") + @Override + public ResponseResult uploadAttachment(@RequestParam("static_rule_id") Long staticRuleId, + MultipartFile file) throws IOException { + + String uploadPath = "d:\\"; + //获取文件上传名称 + String fileName=file.getOriginalFilename(); + //获取文件保存全路径 + String savePath=uploadPath+"/"+fileName; + //获取文件大小 + Long fileSize=file.getSize(); + //获取文件类型 + String fileType=file.getContentType(); + java.io.File newFile=new java.io.File(savePath); + //TODO 注意要将文件保存到本地路径中 + file.transferTo(newFile); + File saveFile=new File(); + saveFile.setFileName(fileName); + saveFile.setFileSize(fileSize); + saveFile.setFileType(fileType); + saveFile.setFilePath(savePath); + saveFile.setStaticRuleId(staticRuleId); + staticRuleService.saveFile(saveFile); + + return ResponseResult.ok(); + } + + + + //文件下载 + @GetMapping("downAttachment") + @Override + public ResponseEntity downFile(@RequestParam Integer id) throws MalformedURLException, UnsupportedEncodingException { + //首先根据id,从数据库获取文件信息 + File downFile=staticRuleService.selectFileById(id); + if (downFile!=null){ + String path= downFile.getFilePath(); + //本地路径地址转为url编码路径 + URI urlPath= Paths.get(path).toUri(); + Resource resource=new UrlResource(urlPath); + if (resource.exists()){ + HttpHeaders headers=new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM+""); + headers.add(HttpHeaders.CONTENT_LENGTH,downFile.getFileSize()+""); + //注意文件名处要改为URL编码 + headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + + URLEncoder.encode(downFile.getFileName(), "utf-8") + "\""); + return ResponseEntity.ok().headers(headers).body(resource); + } + } + return ResponseEntity.notFound().build(); + } + + //以Excel方式批量导入静态规则 @PostMapping("/upload") @Override diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleControllerApi.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleControllerApi.java index 5bbc177..2b861e1 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleControllerApi.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleControllerApi.java @@ -14,10 +14,14 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; @@ -58,6 +62,102 @@ public interface StaticRuleControllerApi { ) ResponseResult newStaticRuleObject(@RequestBody @Valid StaticRuleObject object, HttpServletRequest request); + @Operation( + summary = "查询静态规则的附件信息", + description = "查询静态规则的所有附件信息", + responses = { + @io.swagger.v3.oas.annotations.responses.ApiResponse( + description = "返回静态规则的所有附件信息", + content = @Content( + mediaType = "application/json", + schema = @Schema( + implementation = ResponseResult.class), + examples = @ExampleObject( + name = "查询静态规则的附件信息", + value = """ + { + { + "code": 200, + "message": "请求成功", + "data": { + "files": [ + { + "id": 3, + "fileName": "系统角色.docx", + "filePath": null, + "fileSize": 10915, + "fileType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "staticRuleId": 1819 + }, + { + "id": 4, + "fileName": "权限.txt", + "filePath": null, + "fileSize": 100, + "fileType": "text/plain", + "staticRuleId": 1819 + } + ] + }, + "another": null + } + }""", + description = "static_rule_id:静态规则id" + + "id:文件id" + "fileName:文件名" + "filePath:文件路径" + + "fileSize:文件大小" + "fileType:文件类型" + "staticRuleId:静态规则id" + ) + ) + ) + }, + parameters = { + @Parameter(name = "static_rule_id", description = "静态规则id") + } + ) + @GetMapping("/queryAttachment") + ResponseResult queryAttachment(@RequestParam("static_rule_id") Long staticRuleId); + + //上传附件 + @Operation( + summary = "上传附件", + description = "以文件方式上传附件", + responses = { + @io.swagger.v3.oas.annotations.responses.ApiResponse( + description = "返回上传结果", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ResponseResult.class) + ) + ) + }, + parameters = { + @Parameter(name = "static_rule_id", description = "静态规则id"), + } + + ) + @PostMapping("/uploadAttachment") + ResponseResult uploadAttachment(@RequestParam("static_rule_id") Long staticRuleId, + MultipartFile file) throws IOException; + + //文件下载 + @Operation( + summary = "下载附件", + description = "下载附件", + responses = { + @io.swagger.v3.oas.annotations.responses.ApiResponse( + description = "返回下载结果", + content = @Content( + mediaType = "application/octet-stream", + schema = @Schema(implementation = ResponseEntity.class) + ) + ) + }, + parameters = { + @Parameter(name = "id", description = "文件") + } + ) + @GetMapping("downAttachment") + ResponseEntity downFile(@RequestParam Integer id) throws MalformedURLException, UnsupportedEncodingException; + @Operation( summary = "批量导入静态规则", description = "以Excel文件方式批量导入静态规则", diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleDataListener.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleDataListener.java index ecece26..def7708 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleDataListener.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleDataListener.java @@ -5,6 +5,7 @@ import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.util.ListUtils; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; import com.realtime.protection.configuration.entity.user.UserFull; +import com.realtime.protection.configuration.utils.enums.RuleEnum; import lombok.extern.slf4j.Slf4j; import java.util.List; @@ -29,13 +30,28 @@ public class StaticRuleDataListener implements ReadListener { if (!staticRuleService.isIpMaskValid(object.getStaticRuleSip(),object.getStaticRuleMsip()) || !staticRuleService.isIpMaskValid(object.getStaticRuleDip(),object.getStaticRuleMdip()) ){ - throw new IllegalArgumentException("IP和IP掩码不匹配!静态规则名称:" + + log.info("IP和IP掩码不匹配!静态规则名称:" + object.getStaticRuleName() + ",源ip:" + object.getStaticRuleSip() + ",源ip掩码:" + object.getStaticRuleMsip() + ",目的ip:" + object.getStaticRuleDip() + ",目的ip掩码:" + object.getStaticRuleMdip() ); + return; } + + try { + if (!RuleEnum.checkValidate(object)) { + log.info("静态规则不符合指定的配置方法,请参考规则模板以配置静态规则"+object); + } + } catch (IllegalAccessException e) { + return; + } + if (object.getStaticRuleSport()>=5 && object.getStaticRuleSport()<=10){ + log.info("静态规则格式错误"+object); + return; + } + + if (user != null) { object.setStaticRuleCreateUsername(user.name); object.setStaticRuleCreateUserId(Integer.valueOf(user.uid)); diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleMapper.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleMapper.java index 0afe67e..17e4bcb 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleMapper.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleMapper.java @@ -1,6 +1,7 @@ package com.realtime.protection.server.rule.staticrule; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; +import com.realtime.protection.configuration.utils.File; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -83,5 +84,11 @@ public interface StaticRuleMapper { Integer queryDuplicateStaticRule(StaticRuleObject object); + void saveFile(File saveFile); + + File selectFileById(Integer id); + + List selectFilesByStaticRuleId(Long staticRuleId); + // boolean queryStaticRuleRepeat(StaticRuleObject object); } diff --git a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java index 019794d..29a7f18 100644 --- a/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java +++ b/src/main/java/com/realtime/protection/server/rule/staticrule/StaticRuleService.java @@ -4,6 +4,7 @@ import com.alibaba.excel.util.ListUtils; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; import com.realtime.protection.configuration.entity.whitelist.WhiteListObject; import com.realtime.protection.configuration.utils.Counter; +import com.realtime.protection.configuration.utils.File; import com.realtime.protection.configuration.utils.SqlSessionWrapper; import com.realtime.protection.configuration.utils.enums.RuleEnum; import com.realtime.protection.configuration.utils.enums.audit.AuditStatusEnum; @@ -434,4 +435,16 @@ public class StaticRuleService { public Integer queryDuplicateStaticRule(StaticRuleObject object) { return staticRuleMapper.queryDuplicateStaticRule(object); } + + public void saveFile(File saveFile) { + staticRuleMapper.saveFile(saveFile); + } + + public File selectFileById(Integer id) { + return staticRuleMapper.selectFileById(id); + } + + public List selectFilesByStaticRuleId(Long staticRuleId) { + return staticRuleMapper.selectFilesByStaticRuleId(staticRuleId); + } } diff --git a/src/main/java/com/realtime/protection/server/task/TaskController.java b/src/main/java/com/realtime/protection/server/task/TaskController.java index dede71e..55351cb 100644 --- a/src/main/java/com/realtime/protection/server/task/TaskController.java +++ b/src/main/java/com/realtime/protection/server/task/TaskController.java @@ -25,7 +25,13 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import java.util.Base64; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -66,13 +72,17 @@ public class TaskController implements TaskControllerApi { UserFull user = (UserFull) session.getAttribute("user"); if (user != null) { task.setTaskCreateUsername(user.name); - task.setTaskCreateUserId(Integer.valueOf(user.uid)); + task.setTaskCreateUserId(user.uid); task.setTaskCreateDepart(user.getOrgName()); task.setAuditUserDepartCode(user.getOrgCode()); } //事件类型的用户权限校验、动作逻辑性校验 taskService.eventTypeValid(task); + //冲突性 + taskService.chongtuValid(task); + + Long taskId = taskService.newTask(task); @@ -88,12 +98,33 @@ public class TaskController implements TaskControllerApi { .setData("task_id", 0) .setData("success", false); } - + private boolean verifyHmac(String data, String signature, String key) throws NoSuchAlgorithmException, InvalidKeyException { + Mac mac = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA256"); + mac.init(secretKeySpec); + byte[] hmacBytes = mac.doFinal(data.getBytes()); + String expectedSignature = Base64.getEncoder().encodeToString(hmacBytes); + System.out.println(expectedSignature); + return expectedSignature.equals(signature); + } // API推送Endpoint @Override @PostMapping("/api/new") - public ResponseResult newTaskWithAPI(@RequestBody @Valid TaskCommandInfo taskCommandInfo) { + public ResponseResult newTaskWithAPI(@RequestBody @Valid TaskCommandInfo taskCommandInfo, + @Autowired HttpServletRequest request) throws NoSuchAlgorithmException, InvalidKeyException { + + + String signature = request.getHeader("X-Signature"); + if (signature == null){ + throw new IllegalArgumentException("HMAC签名值为空,认证失败"); + } + String data = String.valueOf(taskCommandInfo.hashCode()); + String apiKey = "gyusygwefweuu2135634"; + if (!verifyHmac(data, signature, apiKey)) { + throw new IllegalArgumentException("HMAC签名校验失败,认证失败"+String.valueOf(taskCommandInfo.hashCode())); + } Long taskId = taskService.newTaskUsingCommandInfo(taskCommandInfo); +// Long taskId =45377L; if (taskId <= 0) { return ResponseResult.invalid() .setData("taskId", -1) @@ -231,7 +262,8 @@ public class TaskController implements TaskControllerApi { public ResponseResult setCommandJudged(@PathVariable Integer isJudged, @PathVariable String commandId) { return ResponseResult.ok() - .setData("success", commandService.setCommandJudged(commandId, isJudged)) +// .setData("success", commandService.setCommandJudged(commandId, isJudged)) + .setData("success", true) .setData("command_id", commandId); } @@ -354,7 +386,7 @@ public class TaskController implements TaskControllerApi { // Files.write(path, file.getBytes()); // Here you can add logic to send the file to a server or process it as needed - + if(true) {throw new IllegalArgumentException("DNS报文校验失败");} return ResponseEntity.status(HttpStatus.OK).body("文件发送处置服务器成功: " + file.getOriginalFilename()); } @@ -379,4 +411,16 @@ public class TaskController implements TaskControllerApi { .setData("alert", taskService.auditInfoNotification(userId)); } + @Override + @PostMapping("/result/{systemName}") + public ResponseResult receiveOtherSystemResult(@PathVariable String systemName, + @RequestBody Map auditInfo){ + + return ResponseResult.ok() + .setData("success", true) + .setData("task_id", auditInfo.get("task_id")); + } + + + } \ No newline at end of file diff --git a/src/main/java/com/realtime/protection/server/task/TaskControllerApi.java b/src/main/java/com/realtime/protection/server/task/TaskControllerApi.java index df985a3..3c10190 100644 --- a/src/main/java/com/realtime/protection/server/task/TaskControllerApi.java +++ b/src/main/java/com/realtime/protection/server/task/TaskControllerApi.java @@ -21,6 +21,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; import java.time.LocalDate; import java.util.List; import java.util.Map; @@ -102,9 +104,11 @@ public interface TaskControllerApi { }, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "任务推送信息") ) - ResponseResult newTaskWithAPI(@RequestBody @Valid TaskCommandInfo taskCommandInfo) throws DorisStartException; + ResponseResult newTaskWithAPI(@RequestBody @Valid TaskCommandInfo taskCommandInfo, + @Autowired HttpServletRequest request) throws NoSuchAlgorithmException, InvalidKeyException ; - @GetMapping("/query") + + @GetMapping("/query") @Operation( summary = "查询任务", description = "按页和搜索内容查询任务相关信息", @@ -715,8 +719,8 @@ public interface TaskControllerApi { @Operation( - summary = "上传pcap文件", - description = "上传pcap文件", + summary = "报文接收", + description = "报文接收", responses = { @io.swagger.v3.oas.annotations.responses.ApiResponse( description = "返回是否成功", @@ -727,8 +731,8 @@ public interface TaskControllerApi { value = """ { "code": 200, - "message": "文件上传处置服务器成功", - "data": "success" + "message": "报文接收成功", + "data": "false" } """ ), @@ -738,7 +742,7 @@ public interface TaskControllerApi { ) }, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( - description = "Excel文件") + description = "PCAP文件") ) @PostMapping("/send-pcap") ResponseEntity uploadPcap(MultipartFile file); @@ -842,4 +846,47 @@ public interface TaskControllerApi { ) @GetMapping("/auditinfo/alert/{userid}") ResponseResult auditInfoNotification(@PathVariable String userId); + + + + @Operation( + summary = "接收外部业务系统处置结果", + description = "接收外部业务系统处置结果,根据规范设计字段接收处置结果", + responses = { + @io.swagger.v3.oas.annotations.responses.ApiResponse( + description = "返回是否接收认证成功", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = ResponseResult.class) + ) + ) + }, + requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( + description = "字典,key是处置结果字段,value是字段对应值", + content = @Content( + mediaType = "application/json", + schema = @Schema(implementation = Map.class), + examples = @ExampleObject( + name = "example", + value = """ + { + "task_id": "44315", + "task_name":"静态task测试s", + "is_effective":true, + "effective_time":"2024-06-17 23:11:29", + "other":"" + + } + """ + ) + + ) + ), + parameters = { + @Parameter(name = "systemName", description = "系统名称", example = "DDoS检测系统、有害信息监测系统"), + } + ) + @PostMapping("/result/{systemName}") + ResponseResult receiveOtherSystemResult(@PathVariable String systemName, + @RequestBody Map auditInfo); } diff --git a/src/main/java/com/realtime/protection/server/task/TaskService.java b/src/main/java/com/realtime/protection/server/task/TaskService.java index 09d1562..ef7cfd2 100644 --- a/src/main/java/com/realtime/protection/server/task/TaskService.java +++ b/src/main/java/com/realtime/protection/server/task/TaskService.java @@ -59,6 +59,8 @@ public class TaskService { // task.setTaskCreateUsername("xxx"); // task.setTaskCreateDepart("xxx"); +// eventTypeValid(task); + task.setTaskDisplayId( "RW-" @@ -634,4 +636,16 @@ public class TaskService { return tasksNotification; } + + public void chongtuValid(Task task) { + if (task.getTaskAct().equals("23") && + task.getEventType().equals("APT") && + task.getTaskType()==1 + ){ + throw new IllegalArgumentException("任务冲突,任务类型:静态。任务动作:阻断+23(丢弃重定向)" + + "事件类型:APT攻击 ,开始时间"+task.getTaskStartTime()+"结束时间:"+task.getTaskEndTime()); + } + + + } } diff --git a/src/main/resources/config/application-test.yml b/src/main/resources/config/application-test.yml index 4bf748f..49dadc7 100644 --- a/src/main/resources/config/application-test.yml +++ b/src/main/resources/config/application-test.yml @@ -16,8 +16,8 @@ spring: mysql: driver-class-name: com.mysql.cj.jdbc.Driver username: root - password: aiihhbfcsy123!@# - url: jdbc:mysql://192.168.107.89:3306/realtime_protection?serverTimezone=Asia/Shanghai + password: 5346208 + url: jdbc:mysql://192.168.107.49:3306/realtime_protection?serverTimezone=Asia/Shanghai hikari: is-auto-commit: false doris: diff --git a/src/main/resources/mappers/CommandMapper.xml b/src/main/resources/mappers/CommandMapper.xml index 0cedcb2..56fb82d 100644 --- a/src/main/resources/mappers/CommandMapper.xml +++ b/src/main/resources/mappers/CommandMapper.xml @@ -3,13 +3,38 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> + + + + + + + + + + + + + + + + + + + + + + + + - insert into t_command(COMMAND_ID, TASK_ID, TASK_ACT, TASKNAME, EVENTTYPE, DEPARTMENT, DISTRIBUTEPOINT, FREQUENCY, - ADDR_TYPE, SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL, - MASK_SRC_IP, MASK_SRC_PORT, MASK_DST_IP, MASK_DST_PORT, MASK_PROTOCOL, VALID_TIME, - INVALID_TIME, IS_VALID, IS_JUDGED, - SEND_TIMES, SUCCESS_TIMES, CREATE_TIME, LAST_UPDATE, IS_DELETED, - TASKTYPE, RULE_ID, display_id,RULE_NAME) + insert into t_command_status(COMMAND_ID, TASK_ID, TASK_ACT, TASKNAME, EVENTTYPE, DEPARTMENT, DISTRIBUTEPOINT, FREQUENCY, + ADDR_TYPE, SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL, + MASK_SRC_IP, MASK_SRC_PORT, MASK_DST_IP, MASK_DST_PORT, MASK_PROTOCOL, VALID_TIME, + INVALID_TIME, IS_VALID, IS_JUDGED, + CREATE_TIME, LAST_UPDATE, IS_DELETED, + TASKTYPE, RULE_ID, display_id,RULE_NAME, + sip_int, dip_int) values (#{info.UUID}, #{info.taskId}, #{info.taskAct}, #{info.taskName}, #{info.eventType}, #{info.taskCreateDepart}, #{info.distributePoint}, #{info.frequency}, DEFAULT, @@ -21,20 +46,63 @@ #{info.fiveTupleWithMask.maskProtocol}, #{info.startTime}, #{info.endTime}, #{info.isValid}, #{info.isJudged}, - 0, 0, NOW(), NOW(), FALSE, #{info.taskType}, #{info.ruleId}, #{info.displayId}, - #{info.ruleName} - ) + #{info.ruleName}, #{info.sipInt}, #{info.dipInt} + ) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into t_command_distribute(COMMAND_ID,display_id,SEND_TIMES, SUCCESS_TIMES ) + values (#{info.UUID}, #{info.displayId}, 0, 0) + + + + insert into t_command_rcp_query(COMMAND_ID,display_id ) + values (#{info.UUID}, #{info.displayId}) + + + + insert into t_command_traffic(COMMAND_ID,display_id ) + values (#{info.UUID}, #{info.displayId}) + - insert into t_command( + insert into t_command_status( COMMAND_ID, TASK_ID, TASK_ACT, TASKNAME, EVENTTYPE, DEPARTMENT, DISTRIBUTEPOINT, FREQUENCY, ADDR_TYPE, SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL, MASK_SRC_IP, MASK_SRC_PORT, MASK_DST_IP, MASK_DST_PORT, MASK_PROTOCOL, VALID_TIME, INVALID_TIME, IS_VALID, IS_JUDGED, - SEND_TIMES, SUCCESS_TIMES, CREATE_TIME, LAST_UPDATE, IS_DELETED, - TASKTYPE, RULE_ID, display_id,RULE_NAME) + CREATE_TIME, LAST_UPDATE, IS_DELETED, + TASKTYPE, RULE_ID, display_id,RULE_NAME, + sip_int, dip_int) values (#{info.UUID}, #{info.taskId}, #{info.taskAct}, #{info.taskName}, #{info.eventType}, #{info.taskCreateDepart}, #{info.distributePoint}, @@ -48,13 +116,34 @@ #{info.fiveTupleWithMask.maskProtocol}, #{info.startTime}, #{info.endTime}, #{info.isValid}, #{info.isJudged}, - 0, 0, NOW(), NOW(), FALSE, #{info.taskType}, #{info.ruleId}, #{info.displayId}, - #{info.ruleName} + #{info.ruleName}, #{info.sipInt}, #{info.dipInt} ) + + insert into t_command_distribute(COMMAND_ID,display_id,SEND_TIMES, SUCCESS_TIMES ) + values + + (#{info.UUID}, #{info.displayId}, 0, 0) + + + + insert into t_command_rcp_query(COMMAND_ID,display_id ) + values + + (#{info.UUID}, #{info.displayId}) + + + + insert into t_command_traffic(COMMAND_ID,display_id ) + values + + (#{info.UUID}, #{info.displayId}) + + + insert into t_command( @@ -64,10 +153,10 @@ IS_JUDGED, SEND_TIMES, SUCCESS_TIMES,FIRST_SEND_TIME,LAST_SEND_TIME ,CREATE_TIME, LAST_UPDATE, IS_DELETED, TASKTYPE, RULE_ID, display_id,RULE_NAME,RCP_HIT_COUNT,TOTAL_PACKET_NUM,TOTAL_BYTE_NUM, - EFFECTIVE_EQUIPMENT_NUM, - AVERAGE_LATENCY,MAX_LATENCY,MIN_LATENCY, - c2s_pkt_num,s2c_pkt_num,c2s_byte_num,s2c_byte_num,session_num, - first_effect_time,last_rcp_query_time,last_traffic_query_time) + EFFECTIVE_EQUIPMENT_NUM, + AVERAGE_LATENCY,MAX_LATENCY,MIN_LATENCY, + c2s_pkt_num,s2c_pkt_num,c2s_byte_num,s2c_byte_num,session_num, + first_effect_time,last_rcp_query_time,last_traffic_query_time) values (#{info.UUID}, #{info.taskId}, #{info.taskAct}, #{info.taskName}, #{info.eventType}, #{info.taskCreateDepart}, #{info.distributePoint}, @@ -84,7 +173,7 @@ 1, 1,NOW(), NOW(), NOW(), NOW(), FALSE, #{info.taskType}, #{info.ruleId}, #{info.displayId}, #{info.ruleName},#{session_num}*4,#{session_num}*4,#{byte_num}, - 1,null,null,null,#{session_num}*4,0,#{byte_num},0,#{session_num},DATE_ADD(NOW(), INTERVAL 10 SECOND), + 1,null,null,null,#{session_num}*4,0,#{byte_num},0,#{session_num},DATE_ADD(NOW(), INTERVAL 10 SECOND), DATE_ADD(NOW(), INTERVAL 10 SECOND),DATE_ADD(NOW(), INTERVAL 10 SECOND) ) @@ -92,11 +181,11 @@ insert into t_command_whitelist_hit(COMMAND_ID, TASK_ID, TASK_ACT, TASKNAME, EVENTTYPE, DEPARTMENT, DISTRIBUTEPOINT, FREQUENCY, - ADDR_TYPE, SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL, - MASK_SRC_IP, MASK_SRC_PORT, MASK_DST_IP, MASK_DST_PORT, MASK_PROTOCOL, VALID_TIME, - INVALID_TIME, IS_VALID, IS_JUDGED, - SEND_TIMES, SUCCESS_TIMES, CREATE_TIME, LAST_UPDATE, IS_DELETED, - TASKTYPE, RULE_ID, display_id) + ADDR_TYPE, SRC_IP, SRC_PORT, DST_IP, DST_PORT, PROTOCOL, + MASK_SRC_IP, MASK_SRC_PORT, MASK_DST_IP, MASK_DST_PORT, MASK_PROTOCOL, VALID_TIME, + INVALID_TIME, IS_VALID, IS_JUDGED, + SEND_TIMES, SUCCESS_TIMES, CREATE_TIME, LAST_UPDATE, IS_DELETED, + TASKTYPE, RULE_ID, display_id) values (#{info.UUID}, #{info.taskId}, #{info.taskAct}, #{info.taskName}, #{info.eventType}, #{info.taskCreateDepart}, #{info.distributePoint}, #{info.frequency}, DEFAULT, @@ -114,117 +203,6 @@ - insert into t_command_log( - effective_time, - expire_time, - TASK_ID, - RULE_ID, - COMMAND_ID, - TASKTYPE, - ADDR_TYPE, - SRC_IP, - SRC_PORT, - DST_IP, - DST_PORT, - PROTOCOL, - MASK_SRC_IP, - MASK_SRC_PORT, - MASK_DST_IP, - MASK_DST_PORT, - MASK_PROTOCOL, - TASK_ACT, - EVENTTYPE, - TASKNAME, - DISTRIBUTEPOINT, - DEPARTMENT, - FREQUENCY, - VALID_TIME, - INVALID_TIME, - IS_VALID, - IS_JUDGED, - SEND_TIMES, - SUCCESS_TIMES, - FIRST_SEND_TIME, - LAST_SEND_TIME, - CREATE_TIME, - LAST_UPDATE, - IS_DELETED, - RULE_NAME, - RCP_HIT_COUNT, - TOTAL_PACKET_NUM, - TOTAL_BYTE_NUM, - EFFECTIVE_EQUIPMENT_NUM, - AVERAGE_LATENCY, - MAX_LATENCY, - MIN_LATENCY, - c2s_pkt_num, - s2c_pkt_num, - c2s_byte_num, - s2c_byte_num, - display_id, - session_num, - first_effect_time, - last_rcp_query_time, - last_traffic_query_time, - log_uuid - ) - select - NOW(), - NULL, - TASK_ID, - RULE_ID, - COMMAND_ID, - TASKTYPE, - ADDR_TYPE, - SRC_IP, - SRC_PORT, - DST_IP, - DST_PORT, - PROTOCOL, - MASK_SRC_IP, - MASK_SRC_PORT, - MASK_DST_IP, - MASK_DST_PORT, - MASK_PROTOCOL, - TASK_ACT, - EVENTTYPE, - TASKNAME, - DISTRIBUTEPOINT, - DEPARTMENT, - FREQUENCY, - VALID_TIME, - INVALID_TIME, - IS_VALID, - IS_JUDGED, - SEND_TIMES, - SUCCESS_TIMES, - FIRST_SEND_TIME, - LAST_SEND_TIME, - CREATE_TIME, - LAST_UPDATE, - IS_DELETED, - RULE_NAME, - RCP_HIT_COUNT, - TOTAL_PACKET_NUM, - TOTAL_BYTE_NUM, - EFFECTIVE_EQUIPMENT_NUM, - AVERAGE_LATENCY, - MAX_LATENCY, - MIN_LATENCY, - c2s_pkt_num, - s2c_pkt_num, - c2s_byte_num, - s2c_byte_num, - display_id, - session_num, - first_effect_time, - last_rcp_query_time, - last_traffic_query_time, - #{log_id} - from t_command - where COMMAND_ID = #{command_id} - - insert into t_command_log( effective_time, expire_time, @@ -277,7 +255,9 @@ first_effect_time, last_rcp_query_time, last_traffic_query_time, - log_uuid + log_uuid, + sip_int, + dip_int ) select NOW(), @@ -331,7 +311,124 @@ first_effect_time, last_rcp_query_time, last_traffic_query_time, - COMMAND_ID + #{log_id}, + sip_int, + dip_int + from t_command + where COMMAND_ID = #{command_id} + + + insert into t_command_log( + effective_time, + expire_time, + TASK_ID, + RULE_ID, + COMMAND_ID, + TASKTYPE, + ADDR_TYPE, + SRC_IP, + SRC_PORT, + DST_IP, + DST_PORT, + PROTOCOL, + MASK_SRC_IP, + MASK_SRC_PORT, + MASK_DST_IP, + MASK_DST_PORT, + MASK_PROTOCOL, + TASK_ACT, + EVENTTYPE, + TASKNAME, + DISTRIBUTEPOINT, + DEPARTMENT, + FREQUENCY, + VALID_TIME, + INVALID_TIME, + IS_VALID, + IS_JUDGED, + SEND_TIMES, + SUCCESS_TIMES, + FIRST_SEND_TIME, + LAST_SEND_TIME, + CREATE_TIME, + LAST_UPDATE, + IS_DELETED, + RULE_NAME, + RCP_HIT_COUNT, + TOTAL_PACKET_NUM, + TOTAL_BYTE_NUM, + EFFECTIVE_EQUIPMENT_NUM, + AVERAGE_LATENCY, + MAX_LATENCY, + MIN_LATENCY, + c2s_pkt_num, + s2c_pkt_num, + c2s_byte_num, + s2c_byte_num, + display_id, + session_num, + first_effect_time, + last_rcp_query_time, + last_traffic_query_time, + log_uuid, + sip_int, + dip_int + ) + select + NOW(), + NULL, + TASK_ID, + RULE_ID, + COMMAND_ID, + TASKTYPE, + ADDR_TYPE, + SRC_IP, + SRC_PORT, + DST_IP, + DST_PORT, + PROTOCOL, + MASK_SRC_IP, + MASK_SRC_PORT, + MASK_DST_IP, + MASK_DST_PORT, + MASK_PROTOCOL, + TASK_ACT, + EVENTTYPE, + TASKNAME, + DISTRIBUTEPOINT, + DEPARTMENT, + FREQUENCY, + VALID_TIME, + INVALID_TIME, + IS_VALID, + IS_JUDGED, + SEND_TIMES, + SUCCESS_TIMES, + FIRST_SEND_TIME, + LAST_SEND_TIME, + CREATE_TIME, + LAST_UPDATE, + IS_DELETED, + RULE_NAME, + RCP_HIT_COUNT, + TOTAL_PACKET_NUM, + TOTAL_BYTE_NUM, + EFFECTIVE_EQUIPMENT_NUM, + AVERAGE_LATENCY, + MAX_LATENCY, + MIN_LATENCY, + c2s_pkt_num, + s2c_pkt_num, + c2s_byte_num, + s2c_byte_num, + display_id, + session_num, + first_effect_time, + last_rcp_query_time, + last_traffic_query_time, + COMMAND_ID, + sip_int, + dip_int from t_command where COMMAND_ID IN @@ -348,6 +445,7 @@ + @@ -357,7 +455,7 @@ - + @@ -405,7 +503,7 @@ FROM t_command AND TASK_ID = #{task_id} --- AND IS_DELETED = FALSE + -- AND IS_DELETED = FALSE AND SRC_IP = #{src_ip} AND DST_IP = #{dst_ip} AND SRC_PORT = #{src_port} @@ -450,7 +548,7 @@ update t_command_log set expire_time = NOW() where COMMAND_ID = #{command_id} - and expire_time = NULL + and expire_time = NULL update t_command_log @@ -459,7 +557,7 @@ #{command_id} - and expire_time = NULL + and expire_time = NULL update t_command diff --git a/src/main/resources/mappers/StaticRuleMapper.xml b/src/main/resources/mappers/StaticRuleMapper.xml index 72e2d87..6ff6e4c 100644 --- a/src/main/resources/mappers/StaticRuleMapper.xml +++ b/src/main/resources/mappers/StaticRuleMapper.xml @@ -186,6 +186,14 @@ #{id} + + insert into t_static_rule_file( + file_name, file_path, file_size, file_type, static_rule_id + ) + values ( + #{fileName}, #{filePath}, #{fileSize}, #{fileType}, #{staticRuleId} + ) + @@ -600,6 +608,26 @@ + + + + + + + + + + + + \ No newline at end of file