Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Security Solutions][Detection Engine] Adds ability to ignore fields during alert indexing and a workaround for an EQL bug #110927

Merged
merged 11 commits into from
Sep 3, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ kibana_vars=(
xpack.security.session.lifespan
xpack.security.sessionTimeout
xpack.securitySolution.alertMergeStrategy
xpack.securitySolution.alertIgnoreFields
xpack.securitySolution.endpointResultListDefaultFirstPageIndex
xpack.securitySolution.endpointResultListDefaultPageSize
xpack.securitySolution.maxRuleImportExportSize
Expand Down
80 changes: 80 additions & 0 deletions x-pack/plugins/security_solution/server/config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { configSchema } from './config';

describe('config', () => {
describe('alertMergeStrategy', () => {
FrankHassanabad marked this conversation as resolved.
Show resolved Hide resolved
test('should default to an empty array', () => {
expect(configSchema.validate({}).alertIgnoreFields).toEqual([]);
});

test('should accept an array of strings', () => {
expect(
configSchema.validate({ alertIgnoreFields: ['foo.bar', 'mars.bar'] }).alertIgnoreFields
).toEqual(['foo.bar', 'mars.bar']);
});

test('should throw if a non string is being sent in', () => {
expect(
() =>
configSchema.validate({
alertIgnoreFields: 5,
}).alertIgnoreFields
).toThrow('[alertIgnoreFields]: expected value of type [array] but got [number]');
});

test('should throw if we send in an invalid regular expression as a string', () => {
expect(
() =>
configSchema.validate({
alertIgnoreFields: ['/(/'],
}).alertIgnoreFields
).toThrow(
'[alertIgnoreFields]: "Invalid regular expression: /(/: Unterminated group" at array position 0'
);
});

test('should throw with two errors if we send two invalid regular expressions', () => {
expect(
() =>
configSchema.validate({
alertIgnoreFields: ['/(/', '/(invalid/'],
}).alertIgnoreFields
).toThrow(
'[alertIgnoreFields]: "Invalid regular expression: /(/: Unterminated group" at array position 0. "Invalid regular expression: /(invalid/: Unterminated group" at array position 1'
);
});

test('should throw with two errors with a valid string mixed in if we send two invalid regular expressions', () => {
expect(
() =>
configSchema.validate({
alertIgnoreFields: ['/(/', 'valid.string', '/(invalid/'],
}).alertIgnoreFields
).toThrow(
'[alertIgnoreFields]: "Invalid regular expression: /(/: Unterminated group" at array position 0. "Invalid regular expression: /(invalid/: Unterminated group" at array position 2'
);
});

test('should accept a valid regular expression within the string', () => {
expect(
configSchema.validate({
alertIgnoreFields: ['/(.*)/'],
}).alertIgnoreFields
).toEqual(['/(.*)/']);
});

test('should accept two valid regular expressions', () => {
expect(
configSchema.validate({
alertIgnoreFields: ['/(.*)/', '/(.valid*)/'],
}).alertIgnoreFields
).toEqual(['/(.*)/', '/(.valid*)/']);
});
});
});
49 changes: 49 additions & 0 deletions x-pack/plugins/security_solution/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,61 @@ export const configSchema = schema.object({
maxRuleImportPayloadBytes: schema.number({ defaultValue: 10485760 }),
maxTimelineImportExportSize: schema.number({ defaultValue: 10000 }),
maxTimelineImportPayloadBytes: schema.number({ defaultValue: 10485760 }),

/**
* This is used within the merge strategies:
* server/lib/detection_engine/signals/source_fields_merging
*
* For determining which strategy for merging "fields" and "_source" together to get
* runtime fields, constant keywords, etc...
*
* "missingFields" (default) This will only merge fields that are missing from the _source and exist in the fields.
* "noFields" This will turn off all merging of runtime fields, constant keywords from fields.
* "allFields" This will merge and overwrite anything found within "fields" into "_source" before indexing the data.
*/
alertMergeStrategy: schema.oneOf(
[schema.literal('allFields'), schema.literal('missingFields'), schema.literal('noFields')],
{
defaultValue: 'missingFields',
}
),

/**
* This is used within the merge strategies:
* server/lib/detection_engine/signals/source_fields_merging
*
* For determining if we need to ignore particular "fields" and not merge them with "_source" such as
* runtime fields, constant keywords, etc...
*
* This feature and functionality is mostly as "safety feature" meaning that we have had bugs in the past
* where something down the stack unexpectedly ends up in the fields API which causes documents to not
* be indexable. Rather than changing alertMergeStrategy to be "noFields", you can use this array to add
* any problematic values.
*
* You can use plain dotted notation strings such as "host.name" or a regular expression such as "/host\..+/"
*/
alertIgnoreFields: schema.arrayOf(schema.string(), {
defaultValue: [],
validate(ignoreFields) {
const errors = ignoreFields.flatMap((ignoreField, index) => {
if (ignoreField.startsWith('/') && ignoreField.endsWith('/')) {
try {
new RegExp(ignoreField.slice(1, -1));
return [];
} catch (error) {
return [`"${error.message}" at array position ${index}`];
}
} else {
return [];
}
});
if (errors.length !== 0) {
return errors.join('. ');
} else {
return undefined;
}
},
}),
[SIGNALS_INDEX_KEY]: schema.string({ defaultValue: DEFAULT_SIGNALS_INDEX }),

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const createMockConfig = (): ConfigType => ({
endpointResultListDefaultPageSize: 10,
packagerTaskInterval: '60s',
alertMergeStrategy: 'missingFields',
alertIgnoreFields: [],
prebuiltRulesFromFileSystem: true,
prebuiltRulesFromSavedObjects: false,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const createSecurityRuleTypeFactory: CreateSecurityRuleTypeFactory = ({
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
ruleDataService,
}) => (type) => {
Expand Down Expand Up @@ -208,6 +209,7 @@ export const createSecurityRuleTypeFactory: CreateSecurityRuleTypeFactory = ({

const wrapHits = wrapHitsFactory({
logger,
ignoreFields,
mergeStrategy,
ruleSO,
spaceId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ export const buildBulkBody = (
ruleSO: SavedObject<AlertAttributes>,
doc: SignalSourceHit,
mergeStrategy: ConfigType['alertMergeStrategy'],
ignoreFields: ConfigType['alertIgnoreFields'],
applyOverrides: boolean,
buildReasonMessage: BuildReasonMessage
): RACAlert => {
const mergedDoc = getMergeStrategy(mergeStrategy)({ doc });
const mergedDoc = getMergeStrategy(mergeStrategy)({ doc, ignoreFields });
const rule = applyOverrides
? buildRuleWithOverrides(ruleSO, mergedDoc._source ?? {})
: buildRuleWithoutOverrides(ruleSO);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { Logger } from 'kibana/server';

import { SearchAfterAndBulkCreateParams, SignalSourceHit, WrapHits } from '../../signals/types';
import { SearchAfterAndBulkCreateParams, WrapHits } from '../../signals/types';
import { buildBulkBody } from './utils/build_bulk_body';
import { generateId } from '../../signals/utils';
import { filterDuplicateSignals } from '../../signals/filter_duplicate_signals';
Expand All @@ -16,13 +16,15 @@ import { WrappedRACAlert } from '../types';

export const wrapHitsFactory = ({
logger,
ignoreFields,
mergeStrategy,
ruleSO,
spaceId,
}: {
logger: Logger;
ruleSO: SearchAfterAndBulkCreateParams['ruleSO'];
mergeStrategy: ConfigType['alertMergeStrategy'];
ignoreFields: ConfigType['alertIgnoreFields'];
spaceId: string | null | undefined;
}): WrapHits => (events, buildReasonMessage) => {
try {
Expand All @@ -38,8 +40,9 @@ export const wrapHitsFactory = ({
_source: buildBulkBody(
spaceId,
ruleSO,
doc as SignalSourceHit,
doc,
mergeStrategy,
ignoreFields,
true,
buildReasonMessage
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ describe('Indicator Match Alerts', () => {
experimentalFeatures: allowedExperimentalValues,
lists: dependencies.lists,
logger: dependencies.logger,
ignoreFields: [],
mergeStrategy: 'allFields',
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
Expand Down Expand Up @@ -97,6 +98,7 @@ describe('Indicator Match Alerts', () => {
lists: dependencies.lists,
logger: dependencies.logger,
mergeStrategy: 'allFields',
ignoreFields: [],
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
version: '1.0.0',
Expand Down Expand Up @@ -135,6 +137,7 @@ describe('Indicator Match Alerts', () => {
lists: dependencies.lists,
logger: dependencies.logger,
mergeStrategy: 'allFields',
ignoreFields: [],
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
version: '1.0.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const createIndicatorMatchAlertType = (createOptions: CreateRuleOptions)
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
version,
ruleDataService,
Expand All @@ -27,6 +28,7 @@ export const createIndicatorMatchAlertType = (createOptions: CreateRuleOptions)
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
ruleDataService,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ describe('Machine Learning Alerts', () => {
lists: dependencies.lists,
logger: dependencies.logger,
mergeStrategy: 'allFields',
ignoreFields: [],
ml: mlMock,
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,20 @@ import { createSecurityRuleTypeFactory } from '../create_security_rule_type_fact
import { CreateRuleOptions } from '../types';

export const createMlAlertType = (createOptions: CreateRuleOptions) => {
const { lists, logger, mergeStrategy, ml, ruleDataClient, ruleDataService } = createOptions;
const {
lists,
logger,
mergeStrategy,
ignoreFields,
ml,
ruleDataClient,
ruleDataService,
} = createOptions;
const createSecurityRuleType = createSecurityRuleTypeFactory({
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
ruleDataService,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ describe('Custom query alerts', () => {
lists: dependencies.lists,
logger: dependencies.logger,
mergeStrategy: 'allFields',
ignoreFields: [],
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
version: '1.0.0',
Expand Down Expand Up @@ -79,6 +80,7 @@ describe('Custom query alerts', () => {
lists: dependencies.lists,
logger: dependencies.logger,
mergeStrategy: 'allFields',
ignoreFields: [],
ruleDataClient: dependencies.ruleDataClient,
ruleDataService: dependencies.ruleDataService,
version: '1.0.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const createQueryAlertType = (createOptions: CreateRuleOptions) => {
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
version,
ruleDataService,
Expand All @@ -27,6 +28,7 @@ export const createQueryAlertType = (createOptions: CreateRuleOptions) => {
lists,
logger,
mergeStrategy,
ignoreFields,
ruleDataClient,
ruleDataService,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export type CreateSecurityRuleTypeFactory = (options: {
lists: SetupPlugins['lists'];
logger: Logger;
mergeStrategy: ConfigType['alertMergeStrategy'];
ignoreFields: ConfigType['alertIgnoreFields'];
ruleDataClient: IRuleDataClient;
ruleDataService: IRuleDataPluginService;
}) => <
Expand Down Expand Up @@ -124,6 +125,7 @@ export interface CreateRuleOptions {
lists: SetupPlugins['lists'];
logger: Logger;
mergeStrategy: ConfigType['alertMergeStrategy'];
ignoreFields: ConfigType['alertIgnoreFields'];
ml?: SetupPlugins['ml'];
ruleDataClient: IRuleDataClient;
version: string;
Expand Down
Loading