Skip to content

Commit

Permalink
ioc scan business logic
Browse files Browse the repository at this point in the history
  • Loading branch information
eirsep committed Jun 20, 2024
1 parent d71579c commit ec14132
Show file tree
Hide file tree
Showing 23 changed files with 1,309 additions and 285 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,13 @@
import org.opensearch.securityanalytics.threatIntel.action.monitor.SearchThreatIntelMonitorAction;
import org.opensearch.securityanalytics.threatIntel.common.TIFLockService;
import org.opensearch.securityanalytics.threatIntel.feedMetadata.BuiltInTIFMetadataLoader;
import org.opensearch.securityanalytics.threatIntel.iocscan.service.SaIoCScanService;
import org.opensearch.securityanalytics.threatIntel.jobscheduler.TIFJobRunner;
import org.opensearch.securityanalytics.threatIntel.jobscheduler.TIFSourceConfigRunner;
import org.opensearch.securityanalytics.threatIntel.model.SATIFSourceConfig;
import org.opensearch.securityanalytics.threatIntel.model.monitor.ThreatIntelMonitorRunner;
import org.opensearch.securityanalytics.threatIntel.model.monitor.TransportThreatIntelMonitorFanOutAction;
import org.opensearch.securityanalytics.threatIntel.resthandler.RestDeleteTIFSourceConfigAction;
import org.opensearch.securityanalytics.threatIntel.model.monitor.SampleRemoteDocLevelMonitorRunner;
import org.opensearch.securityanalytics.threatIntel.model.monitor.TransportRemoteDocLevelMonitorFanOutAction;
import org.opensearch.securityanalytics.threatIntel.resthandler.RestGetTIFSourceConfigAction;
import org.opensearch.securityanalytics.threatIntel.resthandler.RestIndexTIFSourceConfigAction;
import org.opensearch.securityanalytics.threatIntel.resthandler.RestSearchTIFSourceConfigsAction;
Expand Down Expand Up @@ -196,7 +197,7 @@

import static org.opensearch.securityanalytics.threatIntel.model.SATIFSourceConfig.FEED_SOURCE_CONFIG_FIELD;
import static org.opensearch.securityanalytics.threatIntel.model.TIFJobParameter.THREAT_INTEL_DATA_INDEX_NAME_PREFIX;
import static org.opensearch.securityanalytics.threatIntel.model.monitor.SampleRemoteDocLevelMonitorRunner.THREAT_INTEL_MONITOR_TYPE;
import static org.opensearch.securityanalytics.threatIntel.model.monitor.ThreatIntelMonitorRunner.THREAT_INTEL_MONITOR_TYPE;

public class SecurityAnalyticsPlugin extends Plugin implements ActionPlugin, MapperPlugin, SearchPlugin, EnginePlugin, ClusterPlugin, SystemIndexPlugin, JobSchedulerExtension, RemoteMonitorRunnerExtension {

Expand Down Expand Up @@ -248,12 +249,11 @@ public class SecurityAnalyticsPlugin extends Plugin implements ActionPlugin, Map
private SATIFSourceConfigService saTifSourceConfigService;

@Override
public Collection<SystemIndexDescriptor> getSystemIndexDescriptors(Settings settings){
public Collection<SystemIndexDescriptor> getSystemIndexDescriptors(Settings settings) {
return Collections.singletonList(new SystemIndexDescriptor(THREAT_INTEL_DATA_INDEX_NAME_PREFIX, "System index used for threat intel data"));
}



@Override
public Collection<Object> createComponents(Client client,
ClusterService clusterService,
Expand Down Expand Up @@ -289,11 +289,12 @@ public Collection<Object> createComponents(Client client,
SecurityAnalyticsRunner.getJobRunnerInstance();
TIFSourceConfigRunner.getJobRunnerInstance().initialize(clusterService, threatIntelLockService, threadPool, saTifSourceConfigManagementService, saTifSourceConfigService);
TIFJobRunner.getJobRunnerInstance().initialize(clusterService, tifJobUpdateService, tifJobParameterService, threatIntelLockService, threadPool, detectorThreatIntelService);

SaIoCScanService ioCScanService = new SaIoCScanService(client, xContentRegistry);
return List.of(
detectorIndices, correlationIndices, correlationRuleIndices, ruleTopicIndices, customLogTypeIndices, ruleIndices,
mapperService, indexTemplateManager, builtinLogTypeLoader, builtInTIFMetadataLoader, threatIntelFeedDataService, detectorThreatIntelService,
tifJobUpdateService, tifJobParameterService, threatIntelLockService, saTifSourceConfigService, saTifSourceConfigManagementService, stix2IOCFetchService);
tifJobUpdateService, tifJobParameterService, threatIntelLockService, saTifSourceConfigService, saTifSourceConfigManagementService, stix2IOCFetchService,
ioCScanService);
}

@Override
Expand Down Expand Up @@ -484,7 +485,7 @@ public List<Setting<?>> getSettings() {
new ActionHandler<>(SAGetTIFSourceConfigAction.INSTANCE, TransportGetTIFSourceConfigAction.class),
new ActionHandler<>(SADeleteTIFSourceConfigAction.INSTANCE, TransportDeleteTIFSourceConfigAction.class),
new ActionHandler<>(SASearchTIFSourceConfigsAction.INSTANCE, TransportSearchTIFSourceConfigsAction.class),
new ActionHandler<>(SampleRemoteDocLevelMonitorRunner.REMOTE_DOC_LEVEL_MONITOR_ACTION_INSTANCE, TransportRemoteDocLevelMonitorFanOutAction.class),
new ActionHandler<>(ThreatIntelMonitorRunner.REMOTE_DOC_LEVEL_MONITOR_ACTION_INSTANCE, TransportThreatIntelMonitorFanOutAction.class),
new ActionHandler<>(ListIOCsAction.INSTANCE, TransportListIOCsAction.class)
);
}
Expand All @@ -509,7 +510,7 @@ public void onFailure(Exception e) {
@Override
public Map<String, RemoteMonitorRunner> getMonitorTypesToMonitorRunners() {
return Map.of(
THREAT_INTEL_MONITOR_TYPE, SampleRemoteDocLevelMonitorRunner.getMonitorRunner()
THREAT_INTEL_MONITOR_TYPE, ThreatIntelMonitorRunner.getMonitorRunner()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -69,8 +70,11 @@ public void ensureLogTypesLoaded() {
private List<LogType> loadBuiltinLogTypes() throws URISyntaxException, IOException {
List<LogType> logTypes = new ArrayList<>();

final String url = Objects.requireNonNull(BuiltinLogTypeLoader.class.getClassLoader().getResource(BASE_PATH)).toURI().toString();
String pathurl = Paths.get(BuiltinLogTypeLoader.class.getClassLoader().getResource(BASE_PATH).toURI()).toString();

final String url = Objects.requireNonNull(BuiltinLogTypeLoader.class.getClassLoader().getResource(BASE_PATH)).toURI().toString();
logger.error("SASHANK Path url is {}", pathurl);
logger.error("SASHANK currently used url is {}", url);
Path dirPath = null;
if (url.contains("!")) {
final String[] paths = url.split("!");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.opensearch.securityanalytics.model;
package org.opensearch.securityanalytics.model.threatintel;

import org.apache.commons.lang3.StringUtils;
import org.opensearch.core.common.io.stream.StreamInput;
Expand All @@ -20,7 +20,7 @@
* IoC Match provides mapping of the IoC Value to the list of docs that contain the ioc in a given execution of IoC_Scan_job
* It's the inverse of an IoC finding which maps a document to list of IoC's
*/
public class IoCMatch implements Writeable, ToXContent {
public class IocMatch implements Writeable, ToXContent {
//TODO implement IoC_Match interface from security-analytics-commons
public static final String ID_FIELD = "id";
public static final String RELATED_DOC_IDS_FIELD = "related_doc_ids";
Expand All @@ -42,7 +42,7 @@ public class IoCMatch implements Writeable, ToXContent {
private final Instant timestamp;
private final String executionId;

public IoCMatch(String id, List<String> relatedDocIds, List<String> feedIds, String iocScanJobId,
public IocMatch(String id, List<String> relatedDocIds, List<String> feedIds, String iocScanJobId,
String iocScanJobName, String iocValue, String iocType, Instant timestamp, String executionId) {
validateIoCMatch(id, iocScanJobId, iocScanJobName, iocValue, timestamp, executionId, relatedDocIds);
this.id = id;
Expand All @@ -56,7 +56,7 @@ public IoCMatch(String id, List<String> relatedDocIds, List<String> feedIds, Str
this.executionId = executionId;
}

public IoCMatch(StreamInput in) throws IOException {
public IocMatch(StreamInput in) throws IOException {
id = in.readString();
relatedDocIds = in.readStringList();
feedIds = in.readStringList();
Expand Down Expand Up @@ -133,7 +133,7 @@ public String getExecutionId() {
return executionId;
}

public static IoCMatch parse(XContentParser xcp) throws IOException {
public static IocMatch parse(XContentParser xcp) throws IOException {
String id = null;
List<String> relatedDocIds = new ArrayList<>();
List<String> feedIds = new ArrayList<>();
Expand Down Expand Up @@ -197,11 +197,11 @@ public static IoCMatch parse(XContentParser xcp) throws IOException {
}
}

return new IoCMatch(id, relatedDocIds, feedIds, iocScanJobId, iocScanName, iocValue, iocType, timestamp, executionId);
return new IocMatch(id, relatedDocIds, feedIds, iocScanJobId, iocScanName, iocValue, iocType, timestamp, executionId);
}

public static IoCMatch readFrom(StreamInput in) throws IOException {
return new IoCMatch(in);
public static IocMatch readFrom(StreamInput in) throws IOException {
return new IocMatch(in);
}


Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ public class IndexThreatIntelMonitorRequest extends ActionRequest implements Ind

private final String id;
private final RestRequest.Method method;
private final ThreatIntelMonitorDto threatIntelMonitor;
private final ThreatIntelMonitorDto monitor;

public IndexThreatIntelMonitorRequest(String id, RestRequest.Method method, ThreatIntelMonitorDto threatIntelMonitor) {
public IndexThreatIntelMonitorRequest(String id, RestRequest.Method method, ThreatIntelMonitorDto monitor) {
super();
this.id = id;
this.method = method;
this.threatIntelMonitor = threatIntelMonitor;
this.monitor = monitor;
}

public IndexThreatIntelMonitorRequest(StreamInput sin) throws IOException {
Expand All @@ -37,7 +37,7 @@ public IndexThreatIntelMonitorRequest(StreamInput sin) throws IOException {
public void writeTo(StreamOutput out) throws IOException {
out.writeString(id);
out.writeEnum(method);
threatIntelMonitor.writeTo(out);
monitor.writeTo(out);
}

@Override
Expand All @@ -53,7 +53,7 @@ public RestRequest.Method getMethod() {
return method;
}

public ThreatIntelMonitorDto getThreatIntelMonitor() {
return threatIntelMonitor;
public ThreatIntelMonitorDto getMonitor() {
return monitor;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package org.opensearch.securityanalytics.threatIntel.iocscan.dao;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.ResourceAlreadyExistsException;
import org.opensearch.action.DocWriteRequest;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.bulk.BulkRequest;
import org.opensearch.action.bulk.BulkResponse;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.support.GroupedActionListener;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.client.Client;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.securityanalytics.SecurityAnalyticsPlugin;
import org.opensearch.securityanalytics.model.threatintel.IocMatch;
import org.opensearch.securityanalytics.settings.SecurityAnalyticsSettings;
import org.opensearch.securityanalytics.threatIntel.common.StashedThreadContext;
import org.opensearch.securityanalytics.util.SecurityAnalyticsException;
import org.opensearch.threadpool.ThreadPool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* Data layer to perform CRUD operations for threat intel ioc match : store in system index.
*/
public class IocMatchService {
//TODO manage index rollover
public static final String INDEX_NAME = ".opensearch-sap-iocmatch";
private static final Logger log = LogManager.getLogger(IocMatchService.class);
private final Client client;
private final ClusterService clusterService;

public IocMatchService(final Client client, final ClusterService clusterService) {
this.client = client;
this.clusterService = clusterService;
}

public void indexIocMatches(List<IocMatch> iocMatches,
final ActionListener<Void> actionListener) {
try {
Integer batchSize = this.clusterService.getClusterSettings().get(SecurityAnalyticsSettings.BATCH_SIZE);
createIndexIfNotExists(ActionListener.wrap(
r -> {
List<BulkRequest> bulkRequestList = new ArrayList<>();
BulkRequest bulkRequest = new BulkRequest(INDEX_NAME);
for (int i = 0; i < iocMatches.size(); i++) {
IocMatch iocMatch = iocMatches.get(i);
try {
IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
.source(iocMatch.toXContent(XContentFactory.jsonBuilder(), ToXContent.EMPTY_PARAMS))
.opType(DocWriteRequest.OpType.CREATE);
bulkRequest.add(indexRequest);
if (
bulkRequest.requests().size() == batchSize
&& i != iocMatches.size() - 1 // final bulk request will be added outside for loop with refresh policy none
) {
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);
bulkRequestList.add(bulkRequest);
bulkRequest = new BulkRequest();
}
} catch (IOException e) {
log.error(String.format("Failed to create index request for ioc match %s moving on to next"), e);
}
}
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
bulkRequestList.add(bulkRequest);
GroupedActionListener<BulkResponse> groupedListener = new GroupedActionListener<>(ActionListener.wrap(bulkResponses -> {
int idx = 0;
for (BulkResponse response : bulkResponses) {
BulkRequest request = bulkRequestList.get(idx);
if (response.hasFailures()) {
log.error("Failed to bulk index {} Ioc Matches. Failure: {}", request.batchSize(), response.buildFailureMessage());
}
}
actionListener.onResponse(null);
}, actionListener::onFailure), bulkRequestList.size());
for (BulkRequest req : bulkRequestList) {
try {
client.bulk(req, groupedListener); //todo why stash context here?
} catch (Exception e) {
log.error("Failed to save ioc matches.", e);
}
}
}, e -> {
log.error("Failed to create System Index");
actionListener.onFailure(e);
}));


} catch (Exception e) {
log.error("Exception saving the threat intel source config in index", e);
actionListener.onFailure(e);
}
}

private String getIndexMapping() {
try {
try (InputStream is = IocMatchService.class.getResourceAsStream("/mappings/ioc_match_mapping.json")) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
return reader.lines().map(String::trim).collect(Collectors.joining());
}
}
} catch (IOException e) {
log.error("Failed to get the threat intel ioc match index mapping", e);
throw new SecurityAnalyticsException("Failed to get the threat intel ioc match index mapping", RestStatus.INTERNAL_SERVER_ERROR, e);
}
}

/**
* Index name: .opensearch-sap-iocmatch
* Mapping: /mappings/ioc_match_mapping.json
*
* @param listener setup listener
*/
public void createIndexIfNotExists(final ActionListener<Void> listener) {
// check if job index exists
try {
if (clusterService.state().metadata().hasIndex(INDEX_NAME) == true) {
listener.onResponse(null);
return;
}
final CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX_NAME).mapping(getIndexMapping())
.settings(SecurityAnalyticsPlugin.TIF_JOB_INDEX_SETTING);
client.admin().indices().create(createIndexRequest, ActionListener.wrap(
r -> {
log.debug("Ioc match index created");
listener.onResponse(null);
}, e -> {
if (e instanceof ResourceAlreadyExistsException) {
log.debug("index {} already exist", INDEX_NAME);
listener.onResponse(null);
return;
}
log.error("Failed to create security analytics threat intel job index", e);
listener.onFailure(e);
}
));
} catch (Exception e) {
log.error("Failure in creating ioc_match index", e);
listener.onFailure(e);
}
}
}
Loading

0 comments on commit ec14132

Please sign in to comment.