Skip to content

Commit

Permalink
add tests for testing threat intel feed integration with detectors
Browse files Browse the repository at this point in the history
Signed-off-by: Surya Sashank Nistala <[email protected]>
  • Loading branch information
eirsep committed Oct 16, 2023
1 parent 1830ec9 commit dababa8
Show file tree
Hide file tree
Showing 2 changed files with 158 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public class Detector implements Writeable, ToXContentObject {

private String name;

private Boolean threatIntelEnabled;

private Boolean enabled;

private Schedule schedule;
Expand Down Expand Up @@ -116,8 +118,6 @@ public class Detector implements Writeable, ToXContentObject {

private final String type;

private final Boolean threatIntelEnabled;

public Detector(String id, Long version, String name, Boolean enabled, Schedule schedule,
Instant lastUpdateTime, Instant enabledTime, String logType,
User user, List<DetectorInput> inputs, List<DetectorTrigger> triggers, List<String> monitorIds,
Expand Down Expand Up @@ -609,6 +609,10 @@ public void setWorkflowIds(List<String> workflowIds) {
this.workflowIds = workflowIds;
}

public void setThreatIntelEnabled(boolean threatIntelEnabled) {
this.threatIntelEnabled = threatIntelEnabled;
}

public List<String> getWorkflowIds() {
return workflowIds;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -1054,10 +1055,10 @@ public void testCreateDetector_verifyWorkflowCreation_success_WithoutGroupByRule
verifyWorkflow(detectorMap, monitorIds, 2);
}

public void testCreateDetector_threatIntelEnabled() throws IOException {
public void testCreateDetector_threatIntelEnabled_updateDetectorWithNewThreatIntel() throws IOException {
String tifdString1 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"abc\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";
String tifdString2 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"xyz\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";
String feedIndex = ".opendsearch-sap-threatintel";
String feedIndex = ".opensearch-sap-threatintel";
indexDoc(feedIndex, "1", tifdString1);
indexDoc(feedIndex, "2", tifdString2);
updateClusterSetting(ENABLE_WORKFLOW_USAGE.getKey(), "true");
Expand Down Expand Up @@ -1095,6 +1096,121 @@ public void testCreateDetector_threatIntelEnabled() throws IOException {
"}";
SearchResponse response = executeSearchAndGetResponse(DetectorMonitorConfig.getRuleIndex(randomDetectorType()), request, true);

assertEquals(2, response.getHits().getTotalHits().value);

assertEquals("Create detector failed", RestStatus.CREATED, restStatus(createResponse));
Map<String, Object> responseBody = asMap(createResponse);

String detectorId = responseBody.get("_id").toString();
request = "{\n" +
" \"query\" : {\n" +
" \"match\":{\n" +
" \"_id\": \"" + detectorId + "\"\n" +
" }\n" +
" }\n" +
"}";
List<SearchHit> hits = executeSearch(Detector.DETECTORS_INDEX, request);
SearchHit hit = hits.get(0);
Map<String, Object> detectorMap = (HashMap<String, Object>)(hit.getSourceAsMap().get("detector"));
List inputArr = (List) detectorMap.get("inputs");


List<String> monitorIds = ((List<String>) (detectorMap).get("monitor_id"));
assertEquals(1, monitorIds.size());

assertNotNull("Workflow not created", detectorMap.get("workflow_ids"));
assertEquals("Number of workflows not correct", 1, ((List<String>) detectorMap.get("workflow_ids")).size());

// Verify workflow
verifyWorkflow(detectorMap, monitorIds, 1);

indexDoc(index, "1", randomDoc(5, 3, "abc"));
indexDoc(index, "2", randomDoc(5, 3, "xyz"));
indexDoc(index, "3", randomDoc(5, 3, "klm"));
String workflowId = ((List<String>) detectorMap.get("workflow_ids")).get(0);

Response executeResponse = executeAlertingWorkflow(workflowId, Collections.emptyMap());

List<Map<String, Object>> monitorRunResults = (List<Map<String, Object>>) entityAsMap(executeResponse).get("monitor_run_results");
assertEquals(1, monitorRunResults.size());

Map<String, Object> docLevelQueryResults = ((List<Map<String, Object>>) ((Map<String, Object>) monitorRunResults.get(0).get("input_results")).get("results")).get(0);
int noOfSigmaRuleMatches = docLevelQueryResults.size();
assertEquals(2, noOfSigmaRuleMatches);
String threatIntelDocLevelQueryId = docLevelQueryResults.keySet().stream().filter(id -> id.contains(detector.getName() + "_threat_intel")).findAny().get();
ArrayList<String> docs = (ArrayList<String>) docLevelQueryResults.get(threatIntelDocLevelQueryId);
assertEquals(docs.size(),2);

//update threat intel
String tifdString3 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"klm\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";

indexDoc(feedIndex, "3", tifdString3);

Response updateResponse = makeRequest(client(), "PUT", SecurityAnalyticsPlugin.DETECTOR_BASE_URI + "/" + detectorId, Collections.emptyMap(), toHttpEntity(detector));

assertEquals("Update detector failed", RestStatus.OK, restStatus(updateResponse));

Map<String, Object> updateResponseBody = asMap(updateResponse);
detectorId = updateResponseBody.get("_id").toString();

indexDoc(index, "4", randomDoc(5, 3, "klm"));

executeResponse = executeAlertingWorkflow(workflowId, Collections.emptyMap());

monitorRunResults = (List<Map<String, Object>>) entityAsMap(executeResponse).get("monitor_run_results");
assertEquals(1, monitorRunResults.size());

docLevelQueryResults = ((List<Map<String, Object>>) ((Map<String, Object>) monitorRunResults.get(0).get("input_results")).get("results")).get(0);
noOfSigmaRuleMatches = docLevelQueryResults.size();
assertEquals(2, noOfSigmaRuleMatches);
threatIntelDocLevelQueryId = docLevelQueryResults.keySet().stream().filter(id -> id.contains(detector.getName() + "_threat_intel")).findAny().get();
docs = (ArrayList<String>) docLevelQueryResults.get(threatIntelDocLevelQueryId);
assertEquals(docs.size(),1);
}



public void testCreateDetectorthreatIntelDisabled_updateDetectorWithThreatIntelEnabled() throws IOException {
String tifdString1 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"abc\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";
String tifdString2 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"xyz\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";
String feedIndex = ".opensearch-sap-threatintel";
indexDoc(feedIndex, "1", tifdString1);
indexDoc(feedIndex, "2", tifdString2);
updateClusterSetting(ENABLE_WORKFLOW_USAGE.getKey(), "true");
String index = createTestIndex(randomIndex(), windowsIndexMapping());

// Execute CreateMappingsAction to add alias mapping for index
Request createMappingRequest = new Request("POST", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
createMappingRequest.setJsonEntity(
"{ \"index_name\":\"" + index + "\"," +
" \"rule_topic\":\"" + randomDetectorType() + "\", " +
" \"partial\":true" +
"}"
);

Response createMappingResponse = client().performRequest(createMappingRequest);

assertEquals(HttpStatus.SC_OK, createMappingResponse.getStatusLine().getStatusCode());

String testOpCode = "Test";

String randomDocRuleId = createRule(randomRule());
List<DetectorRule> detectorRules = List.of(new DetectorRule(randomDocRuleId));
DetectorInput input = new DetectorInput("windows detector for security analytics", List.of("windows"), detectorRules,
Collections.emptyList());
Detector detector = randomDetectorWithInputsAndThreatIntel(List.of(input), false);

Response createResponse = makeRequest(client(), "POST", SecurityAnalyticsPlugin.DETECTOR_BASE_URI, Collections.emptyMap(), toHttpEntity(detector));

String request = "{\n" +
" \"query\" : {\n" +
" \"match_all\":{\n" +
" }\n" +
" }\n" +
"}";
SearchResponse response = executeSearchAndGetResponse(DetectorMonitorConfig.getRuleIndex(randomDetectorType()), request, true);

assertEquals(1, response.getHits().getTotalHits().value);

assertEquals("Create detector failed", RestStatus.CREATED, restStatus(createResponse));
Expand Down Expand Up @@ -1129,7 +1245,40 @@ public void testCreateDetector_threatIntelEnabled() throws IOException {
String workflowId = ((List<String>) detectorMap.get("workflow_ids")).get(0);

Response executeResponse = executeAlertingWorkflow(workflowId, Collections.emptyMap());
assertNotNull(executeResponse);

List<Map<String, Object>> monitorRunResults = (List<Map<String, Object>>) entityAsMap(executeResponse).get("monitor_run_results");
assertEquals(1, monitorRunResults.size());

Map<String, Object> docLevelQueryResults = ((List<Map<String, Object>>) ((Map<String, Object>) monitorRunResults.get(0).get("input_results")).get("results")).get(0);
int noOfSigmaRuleMatches = docLevelQueryResults.size();
assertEquals(1, noOfSigmaRuleMatches);


//update threat intel
String tifdString3 = "{ \"type\": \"feed\",\"ioc_type\": \"ip\", \"ioc_value\": \"klm\", \"feed_id\": \"feed\", \"timestamp\": 1633344000000 }";

indexDoc(feedIndex, "3", tifdString3);
detector.setThreatIntelEnabled(true);
Response updateResponse = makeRequest(client(), "PUT", SecurityAnalyticsPlugin.DETECTOR_BASE_URI + "/" + detectorId, Collections.emptyMap(), toHttpEntity(detector));

assertEquals("Update detector failed", RestStatus.OK, restStatus(updateResponse));

Map<String, Object> updateResponseBody = asMap(updateResponse);
detectorId = updateResponseBody.get("_id").toString();

indexDoc(index, "4", randomDoc(5, 3, "klm"));

executeResponse = executeAlertingWorkflow(workflowId, Collections.emptyMap());

monitorRunResults = (List<Map<String, Object>>) entityAsMap(executeResponse).get("monitor_run_results");
assertEquals(1, monitorRunResults.size());

docLevelQueryResults = ((List<Map<String, Object>>) ((Map<String, Object>) monitorRunResults.get(0).get("input_results")).get("results")).get(0);
noOfSigmaRuleMatches = docLevelQueryResults.size();
assertEquals(2, noOfSigmaRuleMatches);
String threatIntelDocLevelQueryId = docLevelQueryResults.keySet().stream().filter(id -> id.contains(detector.getName() + "_threat_intel")).findAny().get();
ArrayList<String> docs = (ArrayList<String>) docLevelQueryResults.get(threatIntelDocLevelQueryId);
assertEquals(docs.size(),1);
}

public void testCreateDetector_verifyWorkflowCreation_success_WithGroupByRulesInTrigger() throws IOException {
Expand Down

0 comments on commit dababa8

Please sign in to comment.