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

[RAC][Security Solution] Register Security Detection Rules with Rule Registry #96015

Merged
merged 63 commits into from
May 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
28b1cf1
Swaps out alerting for rule-registry within SecuritySolution and adds…
spong Apr 1, 2021
80206f5
Fixes security reference rule to write alerts again
spong Apr 8, 2021
cf558d8
Fixes alerting passthrough so routes relying on alerting client function
spong Apr 8, 2021
bdffdd5
Initial commit - persistence + hierarchical ref rules
madirey Apr 4, 2021
78b5d2b
Remove threshold for now
madirey Apr 12, 2021
f0c8a7a
Remove hierarchical type
madirey Apr 13, 2021
fde5b14
First implementation of new design
madirey Apr 13, 2021
29d3938
Use scopedClusterClient for query
madirey Apr 14, 2021
254b4a2
Fixup
madirey Apr 14, 2021
7ac738d
Cleanup
madirey Apr 15, 2021
c387f13
Add 5 DE rule types (in progress)
madirey Apr 19, 2021
9c2e0dc
Add custom + eql
madirey Apr 19, 2021
8c90704
Fix typos
madirey Apr 19, 2021
694cec4
Add EQL implementation
madirey Apr 20, 2021
a751d7f
Finish initial threshold implementation
madirey Apr 26, 2021
d5efeb4
Type fixes
madirey Apr 27, 2021
7412abc
ML + threat_match
madirey Apr 27, 2021
959e32a
Adds feature flag for enabling rule-registry within Security Solution
spong Apr 29, 2021
52c76e0
Fixing jest tests and only registering rules with registry if feature…
spong May 3, 2021
c76caae
Fix test types
spong May 3, 2021
29af8f2
Add example unit test for eql rule
madirey Apr 30, 2021
ae7c1d6
minor fixes
madirey Apr 30, 2021
b4f0ff7
Add unit tests, fix bugs
madirey May 3, 2021
733b926
Stubbing tests for custom query + threshold
madirey May 3, 2021
fcdd286
Add threshold tests
madirey May 3, 2021
50d324e
fix test
madirey May 3, 2021
640da91
Fix custom query tests
madirey May 4, 2021
60f8983
rule registry > rule data
dgieselaar Apr 30, 2021
85f16d9
Change indexing strategy
dgieselaar Apr 30, 2021
8d60f13
Fix tests, startup race conditions
dgieselaar May 6, 2021
778e4c6
Get ruleDataClient where it needs to be
madirey May 10, 2021
c3e4c52
Fix rule type registration and unit tests
madirey May 10, 2021
5900380
Fixup security solution server plugin
madirey May 11, 2021
dece3bb
Observability fixup
madirey May 11, 2021
e5f2805
Build api docs
madirey May 11, 2021
f1a13f4
remove observability formatter
madirey May 11, 2021
37c0711
Fix default_config
madirey May 11, 2021
2c491cb
remove console.log statements
dgieselaar May 6, 2021
6b34ed5
Remove extraneous file
madirey May 11, 2021
dc0c494
Prevent race condition when creating/updating the write target
dgieselaar May 12, 2021
21ece9b
Remove ruleRegistry from limits.yml
dgieselaar May 12, 2021
c71e575
Move rule field names to package to limit bundle size impact
dgieselaar May 12, 2021
de8e3db
Undo change to TM, fix ES type
dgieselaar May 12, 2021
5f3ae69
Update readme
dgieselaar May 12, 2021
a59092d
Use .kibana-alerts in tests
dgieselaar May 12, 2021
4ebe61f
Fix tests
madirey May 12, 2021
5ec338b
Fix tests
madirey May 12, 2021
ae89753
Fix test
madirey May 12, 2021
022cf8a
merge master, fix conflicts
madirey May 13, 2021
833b273
Missed a conflict
madirey May 13, 2021
1850bba
And another one
madirey May 13, 2021
41a758e
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
madirey May 13, 2021
855df4e
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 14, 2021
9e213fb
Fixes cypress tests, rule create scripts, updates docs, and replaces …
spong May 14, 2021
14a0f80
Fixing the jester
spong May 15, 2021
222a52a
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 18, 2021
752a7ad
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 19, 2021
05c6a3b
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 24, 2021
670ce49
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 26, 2021
91bede9
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 27, 2021
5201667
Scopes ruleDataService to security-solution and updates timeline to q…
spong May 28, 2021
5c83a41
Fixing the jester
spong May 28, 2021
2a3cbfd
Merge branch 'master' of github.com:elastic/kibana into reference-rul…
spong May 28, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions x-pack/plugins/rule_registry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,6 @@ The following fields are defined in the technical field component template and s
- `kibana.rac.alert.severity.value`: the severity of the alert, as a numerical value, which allows sorting.
- `kibana.rac.alert.evaluation.value`: The measured (numerical value).
- `kibana.rac.alert.threshold.value`: The threshold that was defined (or, in case of multiple thresholds, the one that was exceeded).
- `kibana.rac.alert.ancestors`: the array of ancestors (if any) for the alert.
- `kibana.rac.alert.depth`: the depth of the alert in the ancestral tree (default 0).
- `kibana.rac.alert.building_block_type`: the building block type of the alert (default undefined).
1 change: 1 addition & 0 deletions x-pack/plugins/rule_registry/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export { RuleDataClient } from './rule_data_client';
export { IRuleDataClient } from './rule_data_client/types';
export { getRuleExecutorData, RuleExecutorData } from './utils/get_rule_executor_data';
export { createLifecycleRuleTypeFactory } from './utils/create_lifecycle_rule_type_factory';
export { createPersistenceRuleTypeFactory } from './utils/create_persistence_rule_type_factory';

export const plugin = (initContext: PluginInitializerContext) =>
new RuleRegistryPlugin(initContext);
4 changes: 2 additions & 2 deletions x-pack/plugins/rule_registry/server/rule_data_client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export class RuleDataClient implements IRuleDataClient {
return clusterClient.bulk(requestWithDefaultParameters).then((response) => {
if (response.body.errors) {
if (
response.body.items.length === 1 &&
response.body.items[0]?.index?.error?.type === 'index_not_found_exception'
response.body.items.length > 0 &&
response.body.items?.[0]?.index?.error?.type === 'index_not_found_exception'
) {
return this.createOrUpdateWriteTarget({ namespace }).then(() => {
return clusterClient.bulk(requestWithDefaultParameters);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* 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 { ESSearchRequest } from 'typings/elasticsearch';
import v4 from 'uuid/v4';
import { Logger } from '@kbn/logging';

import { AlertInstance } from '../../../alerting/server';
import {
AlertInstanceContext,
AlertInstanceState,
AlertTypeParams,
} from '../../../alerting/common';
import { RuleDataClient } from '../rule_data_client';
import { AlertTypeWithExecutor } from '../types';

type PersistenceAlertService<TAlertInstanceContext extends Record<string, unknown>> = (
alerts: Array<Record<string, unknown>>
) => Array<AlertInstance<AlertInstanceState, TAlertInstanceContext, string>>;

type PersistenceAlertQueryService = (
query: ESSearchRequest
) => Promise<Array<Record<string, unknown>>>;

type CreatePersistenceRuleTypeFactory = (options: {
ruleDataClient: RuleDataClient;
logger: Logger;
}) => <
TParams extends AlertTypeParams,
TAlertInstanceContext extends AlertInstanceContext,
TServices extends {
alertWithPersistence: PersistenceAlertService<TAlertInstanceContext>;
findAlerts: PersistenceAlertQueryService;
}
>(
type: AlertTypeWithExecutor<TParams, TAlertInstanceContext, TServices>
) => AlertTypeWithExecutor<TParams, TAlertInstanceContext, any>;

export const createPersistenceRuleTypeFactory: CreatePersistenceRuleTypeFactory = ({
logger,
ruleDataClient,
}) => (type) => {
return {
...type,
executor: async (options) => {
const {
services: { alertInstanceFactory, scopedClusterClient },
} = options;

const currentAlerts: Array<Record<string, unknown>> = [];
const timestamp = options.startedAt.toISOString();

const state = await type.executor({
...options,
services: {
...options.services,
alertWithPersistence: (alerts) => {
alerts.forEach((alert) => currentAlerts.push(alert));
return alerts.map((alert) =>
alertInstanceFactory(alert['kibana.rac.alert.uuid']! as string)
);
},
findAlerts: async (query) => {
const { body } = await scopedClusterClient.asCurrentUser.search({
...query,
body: {
...query.body,
},
ignore_unavailable: true,
});
return body.hits.hits
.map((event: { _source: any }) => event._source!)
.map((event: { [x: string]: any }) => {
const alertUuid = event['kibana.rac.alert.uuid'];
const isAlert = alertUuid != null;
return {
...event,
'event.kind': 'signal',
'kibana.rac.alert.id': '???',
'kibana.rac.alert.status': 'open',
'kibana.rac.alert.uuid': v4(),
'kibana.rac.alert.ancestors': isAlert
? ((event['kibana.rac.alert.ancestors'] as string[]) ?? []).concat([
alertUuid!,
] as string[])
: [],
'kibana.rac.alert.depth': isAlert
? ((event['kibana.rac.alert.depth'] as number) ?? 0) + 1
: 0,
'@timestamp': timestamp,
};
});
},
},
});

const numAlerts = currentAlerts.length;
logger.debug(`Found ${numAlerts} alerts.`);

if (ruleDataClient && numAlerts) {
await ruleDataClient.getWriter().bulk({
body: currentAlerts.flatMap((event) => [{ index: {} }, event]),
});
}

return state;
},
};
};
13 changes: 13 additions & 0 deletions x-pack/plugins/security_solution/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const DEFAULT_TIME_RANGE = 'timepicker:timeDefaults';
export const DEFAULT_REFRESH_RATE_INTERVAL = 'timepicker:refreshIntervalDefaults';
export const DEFAULT_APP_TIME_RANGE = 'securitySolution:timeDefaults';
export const DEFAULT_APP_REFRESH_INTERVAL = 'securitySolution:refreshIntervalDefaults';
export const DEFAULT_ALERTS_INDEX = '.alerts-security-solution';
export const DEFAULT_SIGNALS_INDEX = '.siem-signals';
export const DEFAULT_LISTS_INDEX = '.lists';
export const DEFAULT_ITEMS_INDEX = '.items';
Expand Down Expand Up @@ -148,6 +149,18 @@ export const DEFAULT_TRANSFORMS_SETTING = JSON.stringify(defaultTransformsSettin
*/
export const SIGNALS_ID = `siem.signals`;

/**
* Id's for reference rule types
*/
export const REFERENCE_RULE_ALERT_TYPE_ID = `siem.referenceRule`;
export const REFERENCE_RULE_PERSISTENCE_ALERT_TYPE_ID = `siem.referenceRulePersistence`;

export const CUSTOM_ALERT_TYPE_ID = `siem.customRule`;
export const EQL_ALERT_TYPE_ID = `siem.eqlRule`;
export const INDICATOR_ALERT_TYPE_ID = `siem.indicatorRule`;
export const ML_ALERT_TYPE_ID = `siem.mlRule`;
export const THRESHOLD_ALERT_TYPE_ID = `siem.thresholdRule`;

/**
* Id for the notifications alerting type
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const allowedExperimentalValues = Object.freeze({
trustedAppsByPolicyEnabled: false,
metricsEntitiesEnabled: false,
hostIsolationEnabled: false,
ruleRegistryEnabled: false,
});

type ExperimentalConfigKeys = Array<keyof ExperimentalFeatures>;
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/security_solution/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"actions",
"alerting",
"cases",
"ruleRegistry",
"data",
"dataEnhanced",
"embeddable",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type {
CreateExceptionListItemSchema,
UpdateExceptionListItemSchema,
} from '@kbn/securitysolution-io-ts-list-types';

import { TestProviders } from '../../mock';
import {
useAddOrUpdateException,
UseAddOrUpdateExceptionProps,
Expand Down Expand Up @@ -134,12 +134,16 @@ describe('useAddOrUpdateException', () => {

addOrUpdateItemsArgs = [ruleId, itemsToAddOrUpdate];
render = () =>
renderHook<UseAddOrUpdateExceptionProps, ReturnUseAddOrUpdateException>(() =>
useAddOrUpdateException({
http: mockKibanaHttpService,
onError,
onSuccess,
})
renderHook<UseAddOrUpdateExceptionProps, ReturnUseAddOrUpdateException>(
() =>
useAddOrUpdateException({
http: mockKibanaHttpService,
onError,
onSuccess,
}),
{
wrapper: TestProviders,
}
);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ import { getUpdateAlertsQuery } from '../../../detections/components/alerts_tabl
import {
buildAlertStatusFilter,
buildAlertsRuleIdFilter,
buildAlertStatusFilterRuleRegistry,
} from '../../../detections/components/alerts_table/default_config';
import { getQueryFilter } from '../../../../common/detection_engine/get_query_filter';
import { Index } from '../../../../common/detection_engine/schemas/common/schemas';
import { useIsExperimentalFeatureEnabled } from '../../hooks/use_experimental_features';
import { formatExceptionItemForUpdate, prepareExceptionItemsForBulkClose } from './helpers';
import { useKibana } from '../../lib/kibana';

Expand Down Expand Up @@ -82,6 +84,8 @@ export const useAddOrUpdateException = ({
},
[]
);
// TODO: Once we are past experimental phase this code should be removed
const ruleRegistryEnabled = useIsExperimentalFeatureEnabled('ruleRegistryEnabled');

useEffect(() => {
let isSubscribed = true;
Expand Down Expand Up @@ -127,10 +131,15 @@ export const useAddOrUpdateException = ({
}

if (bulkCloseIndex != null) {
// TODO: Once we are past experimental phase this code should be removed
const alertStatusFilter = ruleRegistryEnabled
? buildAlertStatusFilterRuleRegistry('open')
: buildAlertStatusFilter('open');

const filter = getQueryFilter(
'',
'kuery',
[...buildAlertsRuleIdFilter(ruleId), ...buildAlertStatusFilter('open')],
[...buildAlertsRuleIdFilter(ruleId), ...alertStatusFilter],
bulkCloseIndex,
prepareExceptionItemsForBulkClose(exceptionItemsToAddOrUpdate),
false
Expand Down Expand Up @@ -176,7 +185,14 @@ export const useAddOrUpdateException = ({
isSubscribed = false;
abortCtrl.abort();
};
}, [http, onSuccess, onError, updateExceptionListItem, addExceptionListItem]);
}, [
addExceptionListItem,
http,
onSuccess,
onError,
ruleRegistryEnabled,
updateExceptionListItem,
]);

return [{ isLoading }, addOrUpdateException];
};
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const mockGlobalState: State = {
trustedAppsByPolicyEnabled: false,
metricsEntitiesEnabled: false,
hostIsolationEnabled: false,
ruleRegistryEnabled: false,
},
},
hosts: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ import {
import { FieldHook } from '../../shared_imports';
import { SUB_PLUGINS_REDUCER } from './utils';
import { createSecuritySolutionStorageMock, localStorageMock } from './mock_local_storage';
import { UserPrivilegesProvider } from '../../detections/components/user_privileges';

const state: State = mockGlobalState;

interface Props {
children: React.ReactNode;
children?: React.ReactNode;
store?: Store;
onDragEnd?: (result: DropResult, provided: ResponderProvided) => void;
}
Expand Down Expand Up @@ -59,7 +60,30 @@ const TestProvidersComponent: React.FC<Props> = ({
</I18nProvider>
);

/**
* A utility for wrapping children in the providers required to run most tests
* WITH user privileges provider.
*/
const TestProvidersWithPrivilegesComponent: React.FC<Props> = ({
children,
store = createStore(state, SUB_PLUGINS_REDUCER, kibanaObservable, storage),
onDragEnd = jest.fn(),
}) => (
<I18nProvider>
<MockKibanaContextProvider>
<ReduxStoreProvider store={store}>
<ThemeProvider theme={() => ({ eui: euiDarkVars, darkMode: true })}>
<UserPrivilegesProvider>
<DragDropContext onDragEnd={onDragEnd}>{children}</DragDropContext>
</UserPrivilegesProvider>
</ThemeProvider>
</ReduxStoreProvider>
</MockKibanaContextProvider>
</I18nProvider>
);

export const TestProviders = React.memo(TestProvidersComponent);
export const TestProvidersWithPrivileges = React.memo(TestProvidersWithPrivilegesComponent);

export const useFormFieldMock = <T,>(options?: Partial<FieldHook<T>>): FieldHook<T> => {
return {
Expand Down
Loading