1. 新增数据源oracle,已在application.yml中配置

2. 新增任务状态类,未来将在切换任务状态中使用
3. 新增ProtectLevel实体类,用来存储Template对应的三种防护等级数据
4. Task实体类中删除protectObjectIds,因为MySQL表结构发生修改
5. TaskController新增audit和delete路由,用以审核和删除Task
6. TemplateMapper新增newProtectLevel方法
7.
This commit is contained in:
EnderByEndera
2024-01-08 20:01:20 +08:00
parent 1e9fe37d0d
commit 2b04a7d6ce
26 changed files with 392 additions and 204 deletions

View File

@@ -27,9 +27,11 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3' implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3'
implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-actuator'
compileOnly 'org.projectlombok:lombok' compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools' developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j' runtimeOnly 'com.mysql:mysql-connector-j'
runtimeOnly 'com.oracle.database.jdbc:ojdbc8:19.7.0.0'
annotationProcessor 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.3' testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.3'
@@ -39,6 +41,7 @@ dependencies {
implementation 'cn.dev33:sa-token-spring-boot3-starter:1.37.0' implementation 'cn.dev33:sa-token-spring-boot3-starter:1.37.0'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'com.alibaba:easyexcel:3.3.3' implementation 'com.alibaba:easyexcel:3.3.3'
implementation 'com.baomidou:dynamic-datasource-spring-boot3-starter:4.3.0'
} }
tasks.named('test') { tasks.named('test') {

View File

@@ -1,6 +1,5 @@
package com.realtime.protection; package com.realtime.protection;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@@ -0,0 +1,22 @@
package com.realtime.protection.configuration.entity.defense.template;
import lombok.Data;
@Data
public class ProtectLevel {
private Integer protectLevelId;
private Boolean hasProtectObjectIP = false;
private Boolean hasProtectObjectPort = false;
private Boolean hasPeerIP = false;
private Boolean hasPeerPort = false;
private Boolean hasProtocol = false;
private Boolean hasURL = false;
private Boolean hasDNS = false;
}

View File

@@ -15,30 +15,31 @@ public class Template {
@NotNull(message = "template name should not be empty.") @NotNull(message = "template name should not be empty.")
private String templateName; private String templateName;
@JsonProperty("template_elements")
private List<String> templateElements;
@JsonProperty("default_op")
@NotNull(message = "default_op should not be empty.")
private String defaultOp;
@JsonProperty("template_running_tasks") @JsonProperty("template_running_tasks")
private Integer templateRunningTasks; private Integer templateRunningTasks;
@JsonProperty("template_used") @JsonProperty("template_used")
private Integer templateUsedTimes; private Integer templateUsedTimes;
private Boolean hasProtectObjectIP; @JsonProperty("source_system")
@NotNull(message = "source_system should not be empty. ")
private String sourceSystem;
private Boolean hasProtectObjectPort; @JsonProperty("protect_level_low")
@NotNull(message = "protect_level_low should not be empty. ")
private ProtectLevel protectLevelLow;
private Boolean hasPeerIP; @JsonProperty("protect_level_medium")
@NotNull(message = "protect_level_medium should not be empty. ")
private ProtectLevel protectLevelMedium;
private Boolean hasPeerPort; @JsonProperty("protect_level_high")
@NotNull(message = "protect_level_high should not be empty. ")
private ProtectLevel protectLevelHigh;
private Boolean hasProtocol; private Integer createUserId;
private Boolean hasURL; private String createUsername;
private Boolean hasDNS; private String createDepart;
} }

View File

@@ -55,9 +55,6 @@ public class Task {
@JsonProperty("dynamic_rule_ids") @JsonProperty("dynamic_rule_ids")
private List<Integer> dynamicRuleIds; private List<Integer> dynamicRuleIds;
@JsonProperty("protect_object_ids")
private List<Integer> protectObjectIds;
@JsonProperty("task_status") @JsonProperty("task_status")
private Integer taskStatus; private Integer taskStatus;

View File

@@ -1,4 +1,4 @@
package com.realtime.protection.configuration.utils; package com.realtime.protection.configuration.utils.status;
public class AuditStatusValidator { public class AuditStatusValidator {

View File

@@ -0,0 +1,20 @@
package com.realtime.protection.configuration.utils.status;
import com.realtime.protection.configuration.utils.status.state.State;
public class StatusChanger {
private final State state;
public StatusChanger(State state) {
this.state = state;
}
public static StatusChanger setOriginal(State original) {
return new StatusChanger(original);
}
public Boolean changeState(State newState) {
return this.state.handle(newState);
}
}

View File

@@ -0,0 +1,16 @@
package com.realtime.protection.configuration.utils.status.state;
public class PauseState implements State {
@Override
public Boolean handle(State newState) {
if (!(newState instanceof RunningState)) {
return false;
}
return handleRun();
}
private Boolean handleRun() {
return true;
}
}

View File

@@ -0,0 +1,28 @@
package com.realtime.protection.configuration.utils.status.state;
public class RunningState implements State {
@Override
public Boolean handle(State newState) {
if (newState instanceof RunningState) {
return false;
}
if (newState instanceof PauseState) {
return handlePause();
}
if (newState instanceof StopState) {
return handleStop();
}
return false;
}
private Boolean handlePause() {
return true;
}
private Boolean handleStop() {
return true;
}
}

View File

@@ -0,0 +1,6 @@
package com.realtime.protection.configuration.utils.status.state;
public interface State {
Boolean handle(State newState);
}

View File

@@ -0,0 +1,17 @@
package com.realtime.protection.configuration.utils.status.state;
public class StopState implements State {
@Override
public Boolean handle(State newState) {
if (!(newState instanceof RunningState)) {
return false;
}
return handleRun();
}
public Boolean handleRun() {
return true;
}
}

View File

@@ -42,7 +42,9 @@ public class ProtectObjectController {
} }
@PostMapping("/upload") @PostMapping("/upload")
public ResponseResult uploadFile(MultipartFile uploadFile) throws IOException { public ResponseResult uploadFile(
@NotNull(message = "uploadFile cannot be null") MultipartFile uploadFile
) throws IOException {
EasyExcel.read(uploadFile.getInputStream(), ProtectObject.class, EasyExcel.read(uploadFile.getInputStream(), ProtectObject.class,
new ProjectObjectDataListener(protectObjectService)).sheet().doRead(); new ProjectObjectDataListener(protectObjectService)).sheet().doRead();
return ResponseResult.ok(); return ResponseResult.ok();
@@ -52,11 +54,12 @@ public class ProtectObjectController {
public void downloadTemplate(HttpServletResponse response) throws IOException { public void downloadTemplate(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("防护对象", StandardCharsets.UTF_8).replaceAll("\\+", "%20"); String fileName = URLEncoder.encode("防护对象上传模板", StandardCharsets.UTF_8)
.replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), ProtectObject.class) EasyExcel.write(response.getOutputStream(), ProtectObject.class)
.sheet("防护对象") .sheet("防护对象上传模板")
.doWrite(List.of()); .doWrite(List.of());
} }

View File

@@ -2,9 +2,8 @@ package com.realtime.protection.server.defense.object;
import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.defense.object.ProtectObject; import com.realtime.protection.configuration.entity.defense.object.ProtectObject;
import com.realtime.protection.configuration.utils.AuditStatusValidator; import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.configuration.utils.SqlSessionWrapper; import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -12,12 +11,12 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
@Service @Service
public class ProtectObjectService { public class ProtectObjectService {
private final ProtectObjectMapper protectObjectMapper; private final ProtectObjectMapper protectObjectMapper;
private final SqlSessionWrapper sqlSessionWrapper; private final SqlSessionWrapper sqlSessionWrapper;
private static final Integer batchSize = 100;
public ProtectObjectService(ProtectObjectMapper protectObjectMapper, SqlSessionWrapper sqlSessionWrapper) { public ProtectObjectService(ProtectObjectMapper protectObjectMapper, SqlSessionWrapper sqlSessionWrapper) {
this.protectObjectMapper = protectObjectMapper; this.protectObjectMapper = protectObjectMapper;
@@ -39,10 +38,10 @@ public class ProtectObjectService {
return false; return false;
} }
List<ProtectObject> protectObjectBatch = ListUtils.newArrayListWithExpectedSize(100); List<ProtectObject> protectObjectBatch = ListUtils.newArrayListWithExpectedSize(batchSize);
for (ProtectObject protectObject : protectObjectList) { for (ProtectObject protectObject : protectObjectList) {
protectObjectBatch.add(protectObject); protectObjectBatch.add(protectObject);
if (protectObjectBatch.size() < 100) { if (protectObjectBatch.size() < batchSize) {
continue; continue;
} }
mapper.newProtectObjects(protectObjectBatch); mapper.newProtectObjects(protectObjectBatch);
@@ -81,10 +80,10 @@ public class ProtectObjectService {
boolean success = true; boolean success = true;
Integer result; Integer result;
List<Integer> protectObjectBatch = ListUtils.newArrayListWithExpectedSize(100); List<Integer> protectObjectBatch = ListUtils.newArrayListWithExpectedSize(batchSize);
for (Integer protectObjectId : list) { for (Integer protectObjectId : list) {
protectObjectBatch.add(protectObjectId); protectObjectBatch.add(protectObjectId);
if (protectObjectBatch.size() < 100) { if (protectObjectBatch.size() < batchSize) {
continue; continue;
} }
mapper.deleteProtectObjects(protectObjectBatch); mapper.deleteProtectObjects(protectObjectBatch);

View File

@@ -1,5 +1,6 @@
package com.realtime.protection.server.defense.template; package com.realtime.protection.server.defense.template;
import com.realtime.protection.configuration.entity.defense.template.ProtectLevel;
import com.realtime.protection.configuration.entity.defense.template.Template; import com.realtime.protection.configuration.entity.defense.template.Template;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@@ -10,10 +11,14 @@ import java.util.List;
public interface TemplateMapper { public interface TemplateMapper {
void newTemplate(@Param("template") Template template); void newTemplate(@Param("template") Template template);
void newProtectLevel(@Param("level") ProtectLevel protectLevel);
List<Template> queryTemplates(@Param("template_name") String templateName, List<Template> queryTemplates(@Param("template_name") String templateName,
@Param("page") Integer page, @Param("page") Integer page,
@Param("page_size") Integer pageSize); @Param("page_size") Integer pageSize);
ProtectLevel queryProtectLevel(@Param("level_id") Integer protectLevelId);
Boolean updateTemplateInformation(@Param("template") Template template); Boolean updateTemplateInformation(@Param("template") Template template);
void countTemplateRunningTasks(@Param("template_id") Integer templateId); void countTemplateRunningTasks(@Param("template_id") Integer templateId);

View File

@@ -2,7 +2,9 @@ package com.realtime.protection.server.defense.template;
import com.realtime.protection.configuration.entity.defense.template.Template; import com.realtime.protection.configuration.entity.defense.template.Template;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.beans.Transient;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -11,18 +13,15 @@ public class TemplateService {
private final TemplateMapper templateMapper; private final TemplateMapper templateMapper;
private final String[] permittedOps = new String[]{"阻断", "清洗", "篡改", "反制"};
public TemplateService(TemplateMapper templateMapper) { public TemplateService(TemplateMapper templateMapper) {
this.templateMapper = templateMapper; this.templateMapper = templateMapper;
} }
public Integer newTemplate(Template template) throws IllegalArgumentException { @Transactional
if (!Arrays.asList(permittedOps).contains(template.getDefaultOp())) { public Integer newTemplate(Template template) {
throw new IllegalArgumentException(); templateMapper.newProtectLevel(template.getProtectLevelLow());
} templateMapper.newProtectLevel(template.getProtectLevelMedium());
templateMapper.newProtectLevel(template.getProtectLevelHigh());
setTemplateElements(template);
templateMapper.newTemplate(template); templateMapper.newTemplate(template);
@@ -37,28 +36,11 @@ public class TemplateService {
} }
public Boolean updateTemplate(Integer templateId, Template template) { public Boolean updateTemplate(Integer templateId, Template template) {
setTemplateElements(template);
template.setTemplateId(templateId); template.setTemplateId(templateId);
return templateMapper.updateTemplateInformation(template); return templateMapper.updateTemplateInformation(template);
} }
private void setTemplateElements(Template template) {
for (String choice : template.getTemplateElements()) {
switch (choice) {
case "防护对象IP" -> template.setHasProtectObjectIP(true);
case "防护对象端口" -> template.setHasProtectObjectPort(true);
case "对端IP" -> template.setHasPeerIP(true);
case "对端端口" -> template.setHasPeerPort(true);
case "协议" -> template.setHasProtocol(true);
case "URL" -> template.setHasURL(true);
case "DNS" -> template.setHasDNS(true);
default -> throw new IllegalArgumentException();
}
}
}
public Boolean addTemplateUsedTimes(Integer templateId, Integer addTimes) { public Boolean addTemplateUsedTimes(Integer templateId, Integer addTimes) {
return templateMapper.addTemplateUsedTimes(templateId, addTimes); return templateMapper.addTemplateUsedTimes(templateId, addTimes);
} }

View File

@@ -65,17 +65,28 @@ public class TaskController {
.setData("task_start_time", task.getTaskStartTime()) .setData("task_start_time", task.getTaskStartTime())
.setData("task_end_time", task.getTaskEndTime()) .setData("task_end_time", task.getTaskEndTime())
.setData("task_static_rule_ids", task.getStaticRuleIds()) .setData("task_static_rule_ids", task.getStaticRuleIds())
.setData("task_dynamic_rule_ids", task.getDynamicRuleIds()) .setData("task_dynamic_rule_ids", task.getDynamicRuleIds());
.setData("task_protect_object_ids", task.getProtectObjectIds());
} }
@PostMapping("/{id}/update") @PostMapping("/{id}/update")
public ResponseResult updateTask(@PathVariable("id") @Min(1) Integer taskId, @RequestBody @Valid Task task) { public ResponseResult updateTask(@PathVariable("id") @Min(1) Integer taskId, @RequestBody @Valid Task task) {
task.setTaskId(taskId); task.setTaskId(taskId);
taskService.updateTask(task);
return ResponseResult.ok() return ResponseResult.ok()
.setData("task_id", taskId) .setData("task_id", taskId)
.setData("success", true); .setData("success", taskService.updateTask(task));
}
@GetMapping("/{taskId}/{auditStatus}/audit")
public ResponseResult changeTaskAuditStatus(@PathVariable Integer auditStatus, @PathVariable Integer taskId) {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("success", taskService.changeTaskAuditStatus(taskId, auditStatus));
}
@GetMapping("/{id}/delete")
public ResponseResult deleteTask(@PathVariable("id") Integer taskId) {
return ResponseResult.ok()
.setData("task_id", taskId)
.setData("success", taskService.deleteTask(taskId));
} }
} }

View File

@@ -10,8 +10,6 @@ import java.util.List;
public interface TaskMapper { public interface TaskMapper {
void newTask(@Param("task") Task task); void newTask(@Param("task") Task task);
void newTaskProtectObjectConcat(@Param("task_id") Integer taskId, @Param("proobj_id") Integer proobjId);
void newTaskStaticRuleConcat(@Param("task_id") Integer taskId, void newTaskStaticRuleConcat(@Param("task_id") Integer taskId,
@Param("rule_ids") List<Integer> staticRuleIds); @Param("rule_ids") List<Integer> staticRuleIds);
@@ -24,17 +22,13 @@ public interface TaskMapper {
Task queryTask(@Param("task_id") Integer taskId); Task queryTask(@Param("task_id") Integer taskId);
List<Integer> queryTaskConcatProtectObjectIds(@Param("task_id") Integer taskId);
List<Integer> queryTaskConcatStaticRuleIds(@Param("task_id") Integer taskId);
List<Integer> queryTaskConcatDynamicRuleIds(@Param("task_id") Integer taskId);
void updateTask(@Param("task") Task task); void updateTask(@Param("task") Task task);
void clearTaskProtectObjectConcat(@Param("task_id") Integer taskId);
void clearTaskConnectedStaticRule(@Param("task_id") Integer taskId); void clearTaskConnectedStaticRule(@Param("task_id") Integer taskId);
void clearTaskConnectedDynamicRule(@Param("task_id") Integer taskId); void clearTaskConnectedDynamicRule(@Param("task_id") Integer taskId);
void changeTaskAuditStatus(@Param("task_id") Integer taskId, @Param("audit_status") Integer auditStatus);
Boolean deleteTask(@Param("task_id") Integer taskId);
} }

View File

@@ -1,8 +1,8 @@
package com.realtime.protection.server.task; package com.realtime.protection.server.task;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.realtime.protection.configuration.entity.task.Task; import com.realtime.protection.configuration.entity.task.Task;
import org.apache.ibatis.session.SqlSession; import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -10,38 +10,19 @@ import java.util.List;
@Service @Service
public class TaskService { public class TaskService {
private final SqlSessionFactory sqlSessionFactory;
private final TaskMapper taskMapper; private final TaskMapper taskMapper;
public TaskService(SqlSessionFactory sqlSessionFactory, TaskMapper taskMapper) { public TaskService(TaskMapper taskMapper) {
this.sqlSessionFactory = sqlSessionFactory;
this.taskMapper = taskMapper; this.taskMapper = taskMapper;
} }
@Transactional
public Integer newTask(Task task) { public Integer newTask(Task task) {
SqlSession session = sqlSessionFactory.openSession(false); taskMapper.newTask(task);
TaskMapper taskMapper = session.getMapper(TaskMapper.class);
try {
taskMapper.newTask(task);
task.getProtectObjectIds().forEach( taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
proobjId -> taskMapper.newTaskProtectObjectConcat(task.getTaskId(), proobjId)); taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds());
taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
// taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds());
session.commit();
} catch (Exception e) {
session.rollback();
throw e;
} finally {
session.close();
}
if (task.getTaskId() == null) {
return 0;
}
return task.getTaskId(); return task.getTaskId();
} }
@@ -52,41 +33,32 @@ public class TaskService {
} }
public Task queryTask(Integer id) { public Task queryTask(Integer id) {
SqlSession session = sqlSessionFactory.openSession(false); return taskMapper.queryTask(id);
TaskMapper taskMapper = session.getMapper(TaskMapper.class);
Task task;
try {
task = taskMapper.queryTask(id);
if (task == null) {
return null;
}
task.setProtectObjectIds(taskMapper.queryTaskConcatProtectObjectIds(task.getTaskId()));
// task.setDynamicRuleIds(taskMapper.queryTaskConcatDynamicRuleIds(task.getTaskId()));
task.setStaticRuleIds(taskMapper.queryTaskConcatStaticRuleIds(task.getTaskId()));
session.commit();
} catch (Exception e) {
session.rollback();
throw e;
} finally {
session.close();
}
return task;
} }
@Transactional @Transactional
public void updateTask(Task task) { public Boolean updateTask(Task task) {
taskMapper.updateTask(task); taskMapper.updateTask(task);
taskMapper.clearTaskProtectObjectConcat(task.getTaskId());
taskMapper.clearTaskConnectedStaticRule(task.getTaskId()); taskMapper.clearTaskConnectedStaticRule(task.getTaskId());
// taskMapper.clearTaskConnectedDynamicRule(task.getTaskId()); taskMapper.clearTaskConnectedDynamicRule(task.getTaskId());
task.getProtectObjectIds().forEach(
proobjId -> taskMapper.newTaskProtectObjectConcat(task.getTaskId(), proobjId));
taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds()); taskMapper.newTaskStaticRuleConcat(task.getTaskId(), task.getStaticRuleIds());
// taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds()); taskMapper.newTaskDynamicRuleConcat(task.getTaskId(), task.getDynamicRuleIds());
return true;
}
@Transactional
public Boolean changeTaskAuditStatus(Integer taskId, Integer taskAuditStatus) {
if (AuditStatusValidator.setOriginal(taskMapper.queryTask(taskId).getTaskAuditStatus()).checkValidate(taskAuditStatus))
taskMapper.changeTaskAuditStatus(taskId, taskAuditStatus);
else return false;
return true;
}
public Boolean deleteTask(Integer taskId) {
return taskMapper.deleteTask(taskId);
} }
} }

View File

@@ -4,7 +4,6 @@ import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@Mapper @Mapper
// just for example, not for production environment
public interface LoginMapper { public interface LoginMapper {
Integer login(@Param("username") String username, @Param("password") String password); Integer login(@Param("username") String username, @Param("password") String password);
} }

View File

@@ -3,7 +3,7 @@ package com.realtime.protection.server.whitelist;
import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.ListUtils;
import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject; import com.realtime.protection.configuration.entity.rule.staticrule.StaticRuleObject;
import com.realtime.protection.configuration.entity.whitelist.WhiteListObject; import com.realtime.protection.configuration.entity.whitelist.WhiteListObject;
import com.realtime.protection.configuration.utils.AuditStatusValidator; import com.realtime.protection.configuration.utils.status.AuditStatusValidator;
import com.realtime.protection.configuration.utils.SqlSessionWrapper; import com.realtime.protection.configuration.utils.SqlSessionWrapper;
import com.realtime.protection.server.rule.staticrule.StaticRuleMapper; import com.realtime.protection.server.rule.staticrule.StaticRuleMapper;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;

View File

@@ -3,12 +3,27 @@ server:
spring: spring:
datasource: datasource:
driver-class-name: com.mysql.cj.jdbc.Driver dynamic:
username: root datasource:
password: aiihhbfcsy123!@# mysql:
url: jdbc:mysql://localhost:3306/realtime_protection driver-class-name: com.mysql.cj.jdbc.Driver
hikari: username: root
auto-commit: false password: aiihhbfcsy123!@#
url: jdbc:mysql://192.168.107.89:3306/realtime_protection
hikari:
is-auto-commit: false
oracle:
driver-class-name: oracle.jdbc.driver.OracleDriver
username: z2_509pz
password: 123
url: jdbc:oracle:thin:@//10.26.22.45:1521/ORCL
hikari:
is-auto-commit: false
aop:
enabled: true
primary: mysql
strict: true
grace-destroy: true
mvc: mvc:
servlet: servlet:
path: /api/v1 path: /api/v1
@@ -16,4 +31,4 @@ spring:
default-property-inclusion: non_null default-property-inclusion: non_null
mybatis: mybatis:
mapper-locations: classpath:mappers/*.xml mapper-locations: classpath:mappers/*

View File

@@ -71,6 +71,7 @@
<if test="proobj.protectObjectPort">protect_object_port = #{proobj.protectObjectPort},</if> <if test="proobj.protectObjectPort">protect_object_port = #{proobj.protectObjectPort},</if>
<if test="proobj.protectObjectURL">protect_object_url = #{proobj.protectObjectURL},</if> <if test="proobj.protectObjectURL">protect_object_url = #{proobj.protectObjectURL},</if>
<if test="proobj.protectObjectProtocol">protect_object_protocol = #{proobj.protectObjectProtocol},</if> <if test="proobj.protectObjectProtocol">protect_object_protocol = #{proobj.protectObjectProtocol},</if>
modify_time = NOW()
</set> </set>
<where> <where>
<if test="proobj.protectObjectId != null">protect_object_id = #{proobj.protectObjectId}</if> <if test="proobj.protectObjectId != null">protect_object_id = #{proobj.protectObjectId}</if>

View File

@@ -15,15 +15,10 @@
#{task.taskCreateUserId}, #{task.taskCreateUsername}, #{task.taskCreateDepart}) #{task.taskCreateUserId}, #{task.taskCreateUsername}, #{task.taskCreateDepart})
</insert> </insert>
<insert id="newTaskProtectObjectConcat">
INSERT INTO t_task_project_object(task_id, protect_object_id)
VALUES (#{task_id}, #{proobj_id})
</insert>
<update id="newTaskStaticRuleConcat"> <update id="newTaskStaticRuleConcat">
UPDATE t_static_rule UPDATE t_static_rule
<set> <set>
<if test="task_id != null"> static_rule_used_task_id = #{task_id}, </if> <if test="task_id != null">static_rule_used_task_id = #{task_id},</if>
</set> </set>
<where> <where>
<if test="rule_ids != null and rule_ids.size() > 0"> <if test="rule_ids != null and rule_ids.size() > 0">
@@ -38,7 +33,7 @@
<update id="newTaskDynamicRuleConcat"> <update id="newTaskDynamicRuleConcat">
UPDATE t_dynamic_rule UPDATE t_dynamic_rule
<set> <set>
<if test="task_id != null"> dynamic_rule_used_task_id = #{task_id}, </if> <if test="task_id != null">dynamic_rule_used_task_id = #{task_id},</if>
</set> </set>
<where> <where>
<if test="rule_ids != null and rule_ids.size() > 0"> <if test="rule_ids != null and rule_ids.size() > 0">
@@ -56,16 +51,27 @@
<result column="task_type" property="taskType"/> <result column="task_type" property="taskType"/>
<result column="task_status" property="taskStatus"/> <result column="task_status" property="taskStatus"/>
<result column="task_audit_status" property="taskAuditStatus"/>
<result column="task_start_time" property="taskStartTime"/> <result column="task_start_time" property="taskStartTime"/>
<result column="task_end_time" property="taskEndTime"/> <result column="task_end_time" property="taskEndTime"/>
<result column="task_create_username" property="taskCreateUsername"/> <result column="task_create_username" property="taskCreateUsername"/>
<result column="task_create_depart" property="taskCreateDepart"/> <result column="task_create_depart" property="taskCreateDepart"/>
<collection property="staticRuleIds" ofType="java.lang.Integer">
<id column="static_rule_id"/>
</collection>
<collection property="dynamicRuleIds" ofType="java.lang.Integer">
<id column="dynamic_rule_id"/>
</collection>
</resultMap> </resultMap>
<select id="queryTasks" resultMap="taskMap"> <select id="queryTasks" resultMap="taskMap">
SELECT * FROM t_task SELECT * FROM t_task
LEFT JOIN realtime_protection.t_static_rule tsr on t_task.task_id = tsr.static_rule_used_task_id
LEFT JOIN realtime_protection.t_dynamic_rule tdr on t_task.task_id = tdr.dynamic_rule_used_task_id
<where> <where>
<if test="task_status != null"> <if test="task_status != null">
AND task_status = #{task_status} AND task_status = #{task_status}
@@ -84,22 +90,11 @@
</select> </select>
<select id="queryTask" resultMap="taskMap"> <select id="queryTask" resultMap="taskMap">
SELECT * FROM t_task SELECT *
WHERE task_id = #{task_id} FROM t_task
</select> LEFT JOIN realtime_protection.t_static_rule tsr on t_task.task_id = tsr.static_rule_used_task_id
LEFT JOIN realtime_protection.t_dynamic_rule tdr on t_task.task_id = tdr.dynamic_rule_used_task_id
<select id="queryTaskConcatProtectObjectIds" resultType="java.lang.Integer"> WHERE t_task.task_id = #{task_id}
SELECT protect_object_id FROM t_task_project_object
WHERE task_id = #{task_id}
</select>
<select id="queryTaskConcatDynamicRuleIds" resultType="java.lang.Integer">
<!-- todo: will be written after fulfilling t_dynamic_rule table -->
</select>
<select id="queryTaskConcatStaticRuleIds" resultType="java.lang.Integer">
SELECT static_rule_id FROM t_static_rule
WHERE static_rule_used_task_id = #{task_id}
</select> </select>
<update id="updateTask"> <update id="updateTask">
@@ -115,11 +110,6 @@
WHERE task_id = #{task.taskId} WHERE task_id = #{task.taskId}
</update> </update>
<update id="clearTaskProtectObjectConcat">
DELETE FROM t_task_project_object
WHERE task_id = #{task_id}
</update>
<update id="clearTaskConnectedStaticRule"> <update id="clearTaskConnectedStaticRule">
UPDATE t_static_rule UPDATE t_static_rule
SET static_rule_used_task_id = null SET static_rule_used_task_id = null
@@ -127,6 +117,19 @@
</update> </update>
<update id="clearTaskConnectedDynamicRule"> <update id="clearTaskConnectedDynamicRule">
<!-- todo: will be written after fulfilling t_dynamic_rule table --> UPDATE t_dynamic_rule
SET dynamic_rule_used_task_id = null
WHERE dynamic_rule_used_task_id = #{task_id}
</update> </update>
<update id="changeTaskAuditStatus">
UPDATE t_task
SET task_audit_status = #{audit_status}
WHERE task_id = #{task_id}
</update>
<delete id="deleteTask">
DELETE FROM t_task
WHERE task_id = #{task_id}
</delete>
</mapper> </mapper>

View File

@@ -4,20 +4,24 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.realtime.protection.server.defense.template.TemplateMapper"> <mapper namespace="com.realtime.protection.server.defense.template.TemplateMapper">
<insert id="newTemplate" useGeneratedKeys="true" keyProperty="templateId"> <insert id="newTemplate" useGeneratedKeys="true" keyProperty="templateId">
INSERT INTO t_strategy_template(strategy_template_name, INSERT INTO t_strategy_template(strategy_template_name, strategy_template_source_system,
has_protect_object_ip, has_protect_object_port, strategy_template_low_level_id, strategy_template_medium_level_id,
has_peer_ip, has_peer_port, strategy_template_high_level_id,
has_protocol, has_url, has_dns, strategy_template_create_user_id, strategy_template_create_username,
strategy_template_create_user_id, strategy_template_create_depart)
strategy_template_create_username, strategy_template_create_depart, VALUE (#{template.templateName}, #{template.sourceSystem},
default_op) #{template.protectLevelLow.protectLevelId}, #{template.protectLevelMedium.protectLevelId},
VALUE (#{template.templateName}, #{template.protectLevelHigh.protectLevelId},
#{template.hasProtectObjectIP}, #{template.hasProtectObjectPort}, #{template.createUserId}, #{template.createUsername}, #{template.createDepart})
#{template.hasPeerIP}, #{template.hasPeerPort}, </insert>
#{template.hasProtocol}, #{template.hasURL}, #{template.hasDNS},
0, <insert id="newProtectLevel" useGeneratedKeys="true" keyProperty="protectLevelId">
#{template.templateName}, #{template.templateName}, INSERT INTO t_protect_level(has_protect_object_ip, has_protect_object_port,
#{template.defaultOp}) has_protocol, has_url, has_dns,
has_peer_ip, has_peer_port)
VALUE (#{level.hasProtectObjectIP}, #{level.hasProtectObjectPort},
#{level.hasProtocol}, #{level.hasURL}, #{level.hasDNS},
#{level.hasPeerIP}, #{level.hasPeerPort})
</insert> </insert>
<resultMap id="templateMap" type="com.realtime.protection.configuration.entity.defense.template.Template"> <resultMap id="templateMap" type="com.realtime.protection.configuration.entity.defense.template.Template">
@@ -25,35 +29,87 @@
<result column="strategy_template_name" property="templateName"/> <result column="strategy_template_name" property="templateName"/>
<result column="strategy_template_used_times" property="templateUsedTimes"/> <result column="strategy_template_used_times" property="templateUsedTimes"/>
<result column="strategy_template_running_tasks" property="templateRunningTasks"/> <result column="strategy_template_running_tasks" property="templateRunningTasks"/>
<result column="strategy_template_low_level_id" property="protectLevelLow.protectLevelId"/>
<result column="strategy_template_medium_level_id" property="protectLevelMedium.protectLevelId"/>
<result column="strategy_template_high_level_id" property="protectLevelHigh.protectLevelId"/>
<association property="protectLevelLow"
javaType="com.realtime.protection.configuration.entity.defense.template.ProtectLevel">
<id column="protect_level_id" property="protectLevelId"/>
<result column="has_protect_object_ip" property="hasProtectObjectIP"/>
<result column="has_protect_object_port" property="hasProtectObjectPort"/>
<result column="has_peer_ip" property="hasPeerIP"/>
<result column="has_peer_port" property="hasPeerPort"/>
<result column="has_protocol" property="hasProtocol"/>
<result column="has_url" property="hasURL"/>
<result column="has_dns" property="hasDNS"/>
</association>
<association property="protectLevelMedium"
javaType="com.realtime.protection.configuration.entity.defense.template.ProtectLevel">
<id column="protect_level_id" property="protectLevelId"/>
<result column="has_protect_object_ip" property="hasProtectObjectIP"/>
<result column="has_protect_object_port" property="hasProtectObjectPort"/>
<result column="has_peer_ip" property="hasPeerIP"/>
<result column="has_peer_port" property="hasPeerPort"/>
<result column="has_protocol" property="hasProtocol"/>
<result column="has_url" property="hasURL"/>
<result column="has_dns" property="hasDNS"/>
</association>
<association property="protectLevelHigh"
javaType="com.realtime.protection.configuration.entity.defense.template.ProtectLevel">
<id column="protect_level_id" property="protectLevelId"/>
<result column="has_protect_object_ip" property="hasProtectObjectIP"/>
<result column="has_protect_object_port" property="hasProtectObjectPort"/>
<result column="has_peer_ip" property="hasPeerIP"/>
<result column="has_peer_port" property="hasPeerPort"/>
<result column="has_protocol" property="hasProtocol"/>
<result column="has_url" property="hasURL"/>
<result column="has_dns" property="hasDNS"/>
</association>
</resultMap>
<resultMap id="protectLevelMap" type="com.realtime.protection.configuration.entity.defense.template.ProtectLevel">
<id column="protect_level_id" property="protectLevelId"/>
<result column="has_protect_object_ip" property="hasProtectObjectIP"/>
<result column="has_protect_object_port" property="hasProtectObjectPort"/>
<result column="has_peer_ip" property="hasPeerIP"/>
<result column="has_peer_port" property="hasPeerPort"/>
<result column="has_protocol" property="hasProtocol"/>
<result column="has_url" property="hasURL"/>
<result column="has_dns" property="hasDNS"/>
</resultMap> </resultMap>
<select id="queryTemplates" resultMap="templateMap"> <select id="queryTemplates" resultMap="templateMap">
SELECT * FROM t_strategy_template <!-- 关联查询 -->
SELECT * FROM t_strategy_template AS tst
LEFT JOIN realtime_protection.t_protect_level low_tpl on low_tpl.protect_level_id =
tst.strategy_template_low_level_id
LEFT JOIN realtime_protection.t_protect_level medium_tpl on medium_tpl.protect_level_id =
tst.strategy_template_medium_level_id
LEFT JOIN realtime_protection.t_protect_level high_tpl on high_tpl.protect_level_id =
tst.strategy_template_high_level_id
<where> <where>
<if test="template_name != null"> <if test="template_name != null">
AND strategy_template_name LIKE CONCAT('%', #{template_name}, '%') AND tst.strategy_template_name LIKE CONCAT('%', #{template_name}, '%')
</if> </if>
</where> </where>
LIMIT ${(page - 1) * page_size}, #{page_size} LIMIT ${(page - 1) * page_size}, #{page_size}
</select> </select>
<select id="queryProtectLevel" resultMap="protectLevelMap">
SELECT *
FROM t_protect_level
WHERE protect_level_id = #{level_id}
</select>
<update id="updateTemplateInformation"> <update id="updateTemplateInformation">
UPDATE t_strategy_template UPDATE t_strategy_template
<set> <set>
<!-- update template name and default op --> <if test="template.templateName != null">strategy_template_name = #{template.templateName},</if>
<if test="template.templateName != null">strategy_template_name = #{template.templateName}, </if> <if test="template.sourceSystem != null">strategy_template_source_system = #{template.sourceSystem},</if>
<if test="template.defaultOp != null">default_op = #{template.defaultOp},</if> modify_time = NOW()
<!-- update template elements -->
<if test="template.hasProtectObjectIP != null">has_protect_object_ip = #{template.hasProtectObjectIP},</if>
<if test="template.hasProtectObjectPort != null">
has_protect_object_port = {template.hasProtectObjectPort},
</if>
<if test="template.hasPeerIP != null">has_peer_ip = #{template.hasPeerIP},</if>
<if test="template.hasPeerPort != null">has_peer_port = #{template.hasPeerPort},</if>
<if test="template.hasProtocol != null">has_protocol = #{template.hasProtocol},</if>
<if test="template.hasURL != null">has_url = #{template.hasURL},</if>
<if test="template.hasDNS != null">has_dns = #{template.hasDNS},</if>
</set> </set>
<where> <where>
AND strategy_template_id = #{template.templateId} AND strategy_template_id = #{template.templateId}

View File

@@ -1,5 +1,6 @@
package com.realtime.protection.server.defense.template; package com.realtime.protection.server.defense.template;
import com.realtime.protection.configuration.entity.defense.template.ProtectLevel;
import com.realtime.protection.configuration.entity.defense.template.Template; import com.realtime.protection.configuration.entity.defense.template.Template;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -23,26 +24,36 @@ class TemplateServiceTest {
@BeforeEach @BeforeEach
void mockTemplate() { void mockTemplate() {
template = new Template(); template = new Template();
template.setTemplateName("反射型DDOS攻击"); template.setTemplateName("反射型DDOS攻击");
template.setTemplateElements(List.of("对端IP", "协议", "URL")); template.setSourceSystem("xxxx系统");
template.setDefaultOp("阻断");
ProtectLevel protectLevelLow = new ProtectLevel();
protectLevelLow.setHasPeerPort(true);
ProtectLevel protectLevelMedium = new ProtectLevel();
protectLevelMedium.setHasProtectObjectIP(true);
ProtectLevel protectLevelHigh = new ProtectLevel();
protectLevelHigh.setHasDNS(true);
template.setProtectLevelLow(protectLevelLow);
template.setProtectLevelMedium(protectLevelMedium);
template.setProtectLevelHigh(protectLevelHigh);
} }
@Test @Test
void testNewTemplateSuccess() { void testNewTemplate() {
Integer templateId = templateService.newTemplate(template); Integer templateId = templateService.newTemplate(template);
assertTrue(templateId > 0); assertTrue(templateId > 0);
} }
@Test @Test
void testNewTemplateIllegalArgument() { void testQueryTemplate() {
template.setTemplateElements(List.of("DDNS")); List<Template> templates = templateService.queryTemplates("DDOS", 1, 5);
assertThrows(IllegalArgumentException.class, () -> { System.out.println(templates);
Integer templateId = templateService.newTemplate(template);
assertTrue(templateId > 0);
});
} }
@Test @Test

View File

@@ -38,13 +38,13 @@ class TaskServiceTest {
task.setDynamicRuleIds(List.of()); task.setDynamicRuleIds(List.of());
task.setTaskCreateUserId(1); task.setTaskCreateUserId(1);
task.setTaskCreateUsername("xxx"); task.setTaskCreateUsername("xxx");
task.setTaskCreateDepart("xxx"); task.setTaskCreateDepart("xxx");;
task.setProtectObjectIds(List.of(1));
} }
@Test @Test
void testNewTaskSuccess() { void testNewTaskSuccess() {
assertDoesNotThrow(() -> {Integer taskId = taskService.newTask(task); assertTrue(taskId > 0);}); assertDoesNotThrow(() -> {Integer taskId = taskService.newTask(task); assertTrue(taskId > 0);});
assertTrue(task.getTaskId() > 0);
} }
@Test @Test
@@ -58,8 +58,36 @@ class TaskServiceTest {
@Test @Test
void testQueryTasks() { void testQueryTasks() {
List<Task> tasks = taskService.queryTasks(null, null, null, null, 1, 5); List<Task> tasks = taskService.queryTasks(null, null, null, null, 1, 10);
assertEquals(5, tasks.size());
assertTrue(tasks.get(0).getTaskId() > 0); assertTrue(tasks.get(0).getTaskId() > 0);
} }
@Test
void testUpdateTasks() {
task.setStaticRuleIds(List.of(6, 7, 8));
task.setTaskId(26);
task.setTaskName("修改测试");
assertTrue(taskService.updateTask(task));
assertEquals("修改测试", taskService.queryTask(26).getTaskName());
}
@Test
void testDeleteTask() {
int testNum = taskService.queryTasks(null, null, null, null, 1, 10)
.get(0).getTaskId();
assertTrue(taskService.deleteTask(testNum));
assertFalse(taskService.deleteTask(235235));
}
@Test
void testChangeAuditStatus() {
int testNum = taskService.queryTasks(null, null, null, null, 1, 1)
.get(0).getTaskId();
assertTrue(taskService.changeTaskAuditStatus(testNum, 2));
assertFalse(taskService.changeTaskAuditStatus(testNum, 0));
assertFalse(taskService.changeTaskAuditStatus(testNum, 1));
}
} }