Skip to content

Commit

Permalink
Asset criticality alert enrichment (#171241)
Browse files Browse the repository at this point in the history
## Summary

This will allow analysts to filter alerts by the analyst-defined
criticality of the related host or user.

This introduces two new kibana fields to alerts. These fields allow us
to model the criticality of the alert's most relevant host and user, in
context of analyst workflows.

| field name | type | description | example |
| -- | -- | -- | -- |
| `kibana.alert.host.criticality_level` | keyword | Contains an enum
describing the criticality of the host, as defined by the analyst in a
previously used workflow. Used by analysts to filter alerts by host
criticality. | 'very important' |
| `kibana.alert.user.criticality_level` | keyword | Contains an enum
describing the criticality of the user, as defined by the analyst in a
previously used workflow. Used by analysts to filter alerts by user
criticality. | 'very important' |

## Design
Analysts can assign criticality to their assets. These are stored in the
asset criticality index
(`.asset-criticality.asset-criticality-${space}`). This PR will detect
user names and host names in events, query the asset criticality index
for the associated criticality (if any) and then add that value to the
resulting alert under `kibana.alert.host.criticality_level` or
`kibana.alert.user.criticality_level`

## Design Exploration

### What if we want to filter by other criticalities?
We may want to allow analysts to filter on the criticality of other
entities. For example, alerts can refer to multiple users and multiple
hosts. Also, we may introduce other types of entities, e.g. IP
addresses, files, registry keys.

If we were to follow the same approach as we did here, that could lead
to a mapping explosion if we had a lot. However:

* we don't think we'll add very many classes of entities. less than 8
more.
* we don't necessarily want to filter alerts by other ones.

### Using keyword vs nested or flattened
We could use a flattened or nested field here to store more
criticalities and have them all indexed. However we don't need to sort
or order alerts by their entity's criticalities so we don't see a need.

### KQL support
The fields we proposed here are of `keyword` type. This type of field
works intuitively for KQL and since analyst workflows are the focus of
this change, this lines up well.



##  How to test

until asset criticality UI is not enabled let's create a mapping for
asset criticality and index some docs

```
PUT .asset-criticality.asset-criticality-default
{
  "mappings": {
    "properties": {
      "id_value": {
        "type": "keyword"
      },
      "id_field": {
        "type": "keyword"
      },
      "criticality_level": {
        "type": "keyword"
      },
      "@timestamp": {
        "type": "date"
      },
      "updated_at": {
        "type": "date"
      }
    }
  }
}
```

```
POST .asset-criticality.asset-criticality-default/_doc
{
  "id_field": "user.name",
  "id_value": "User 1",
  "criticality_level": "very important",
  "@timestamp": 1701860267617
}

POST .asset-criticality.asset-criticality-default/_doc
{
  "id_field": "host.name",
  "id_value": "Host 3",
  "criticality_level": "normal",
  "@timestamp": 1701860267617
}
```

Then create rules, which have alerts from events with `host.name` or
`user.name` which match asset criticality documents.

Then add fields to the alerts table, you should see some values in those
columns

<img width="1201" alt="Screenshot 2023-12-07 at 11 24 24"
src="https://github.com/elastic/kibana/assets/7609147/fb8c07bf-4cc6-4273-95b0-34af9d3f2e72">





### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: Nikita Khristinin <nkhristinin@gmail.com>
Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Khristinin Nikita <nikita.khristinin@elastic.co>
  • Loading branch information
4 people committed Dec 22, 2023
1 parent b40cd02 commit cf9ff4d
Show file tree
Hide file tree
Showing 32 changed files with 897 additions and 108 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ const SecurityAlertOptional = rt.partial({
'kibana.alert.flapping_history': schemaBooleanArray,
'kibana.alert.group.id': schemaString,
'kibana.alert.group.index': schemaNumber,
'kibana.alert.host.criticality_level': schemaString,
'kibana.alert.last_detected': schemaDate,
'kibana.alert.maintenance_window_ids': schemaStringArray,
'kibana.alert.new_terms': schemaStringArray,
Expand Down Expand Up @@ -193,6 +194,7 @@ const SecurityAlertOptional = rt.partial({
),
'kibana.alert.time_range': schemaDateRange,
'kibana.alert.url': schemaString,
'kibana.alert.user.criticality_level': schemaString,
'kibana.alert.workflow_assignee_ids': schemaStringArray,
'kibana.alert.workflow_reason': schemaString,
'kibana.alert.workflow_status': schemaString,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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 type { AlertWithCommonFields800 } from '@kbn/rule-registry-plugin/common/schemas/8.0.0';
import type {
ALERT_HOST_CRITICALITY,
ALERT_USER_CRITICALITY,
} from '../../../../../field_maps/field_names';
import type {
Ancestor8120,
BaseFields8120,
EqlBuildingBlockFields8120,
EqlShellFields8120,
NewTermsFields8120,
} from '../8.12.0';

/* DO NOT MODIFY THIS SCHEMA TO ADD NEW FIELDS. These types represent the alerts that shipped in 8.13.0.
Any changes to these types should be bug fixes so the types more accurately represent the alerts from 8.13.0.
If you are adding new fields for a new release of Kibana, create a new sibling folder to this one
for the version to be released and add the field(s) to the schema in that folder.
Then, update `../index.ts` to import from the new folder that has the latest schemas, add the
new schemas to the union of all alert schemas, and re-export the new schemas as the `*Latest` schemas.
*/

export type { Ancestor8120 as Ancestor8130 };

export interface BaseFields8130 extends BaseFields8120 {
[ALERT_HOST_CRITICALITY]: string | undefined;
[ALERT_USER_CRITICALITY]: string | undefined;
}

export interface WrappedFields8130<T extends BaseFields8130> {
_id: string;
_index: string;
_source: T;
}

export type GenericAlert8130 = AlertWithCommonFields800<BaseFields8130>;

export type EqlShellFields8130 = EqlShellFields8120 & BaseFields8130;

export type EqlBuildingBlockFields8130 = EqlBuildingBlockFields8120 & BaseFields8130;

export type NewTermsFields8130 = NewTermsFields8120 & BaseFields8130;

export type NewTermsAlert8130 = NewTermsFields8120 & BaseFields8130;

export type EqlBuildingBlockAlert8130 = AlertWithCommonFields800<EqlBuildingBlockFields8120>;

export type EqlShellAlert8130 = AlertWithCommonFields800<EqlShellFields8130>;

export type DetectionAlert8130 =
| GenericAlert8130
| EqlShellAlert8130
| EqlBuildingBlockAlert8130
| NewTermsAlert8130;
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@ import type { DetectionAlert860 } from './8.6.0';
import type { DetectionAlert870 } from './8.7.0';
import type { DetectionAlert880 } from './8.8.0';
import type { DetectionAlert890 } from './8.9.0';
import type { DetectionAlert8120 } from './8.12.0';
import type {
Ancestor8120,
BaseFields8120,
DetectionAlert8120,
EqlBuildingBlockFields8120,
EqlShellFields8120,
NewTermsFields8120,
WrappedFields8120,
} from './8.12.0';
Ancestor8130,
BaseFields8130,
DetectionAlert8130,
EqlBuildingBlockFields8130,
EqlShellFields8130,
NewTermsFields8130,
WrappedFields8130,
} from './8.13.0';

// When new Alert schemas are created for new Kibana versions, add the DetectionAlert type from the new version
// here, e.g. `export type DetectionAlert = DetectionAlert800 | DetectionAlert820` if a new schema is created in 8.2.0
Expand All @@ -31,14 +32,15 @@ export type DetectionAlert =
| DetectionAlert870
| DetectionAlert880
| DetectionAlert890
| DetectionAlert8120;
| DetectionAlert8120
| DetectionAlert8130;

export type {
Ancestor8120 as AncestorLatest,
BaseFields8120 as BaseFieldsLatest,
DetectionAlert8120 as DetectionAlertLatest,
WrappedFields8120 as WrappedFieldsLatest,
EqlBuildingBlockFields8120 as EqlBuildingBlockFieldsLatest,
EqlShellFields8120 as EqlShellFieldsLatest,
NewTermsFields8120 as NewTermsFieldsLatest,
Ancestor8130 as AncestorLatest,
BaseFields8130 as BaseFieldsLatest,
DetectionAlert8130 as DetectionAlertLatest,
WrappedFields8130 as WrappedFieldsLatest,
EqlBuildingBlockFields8130 as EqlBuildingBlockFieldsLatest,
EqlShellFields8130 as EqlShellFieldsLatest,
NewTermsFields8130 as NewTermsFieldsLatest,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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 { alertsFieldMap840 } from '../8.4.0';
import { ALERT_HOST_CRITICALITY, ALERT_USER_CRITICALITY } from '../field_names';

export const alertsFieldMap8130 = {
...alertsFieldMap840,
/**
* Stores the criticality level for the host, as determined by analysts, in relation to the alert.
* The Criticality level is copied from the asset criticality index.
*/
[ALERT_HOST_CRITICALITY]: {
type: 'keyword',
array: false,
required: false,
},
/**
* Stores the criticality level for the user, as determined by analysts, in relation to the alert.
* The Criticality level is copied from the asset criticality index.
*/
[ALERT_USER_CRITICALITY]: {
type: 'keyword',
array: false,
required: false,
},
} as const;

export type AlertsFieldMap8130 = typeof alertsFieldMap8130;
11 changes: 11 additions & 0 deletions x-pack/plugins/security_solution/common/field_maps/8.13.0/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* 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 type { AlertsFieldMap8130 } from './alerts';
import { alertsFieldMap8130 } from './alerts';
export type { AlertsFieldMap8130 };
export { alertsFieldMap8130 };
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export const ALERT_THRESHOLD_RESULT = `${ALERT_NAMESPACE}.threshold_result` as c
export const ALERT_THRESHOLD_RESULT_COUNT = `${ALERT_THRESHOLD_RESULT}.count` as const;
export const ALERT_NEW_TERMS = `${ALERT_NAMESPACE}.new_terms` as const;
export const ALERT_NEW_TERMS_FIELDS = `${ALERT_RULE_PARAMETERS}.new_terms_fields` as const;
export const ALERT_HOST_CRITICALITY = `${ALERT_NAMESPACE}.host.criticality_level` as const;
export const ALERT_USER_CRITICALITY = `${ALERT_NAMESPACE}.user.criticality_level` as const;

export const ALERT_ORIGINAL_EVENT = `${ALERT_NAMESPACE}.original_event` as const;
export const ALERT_ORIGINAL_EVENT_ACTION = `${ALERT_ORIGINAL_EVENT}.action` as const;
Expand Down
8 changes: 4 additions & 4 deletions x-pack/plugins/security_solution/common/field_maps/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
* 2.0.
*/

import type { AlertsFieldMap840 } from './8.4.0';
import { alertsFieldMap840 } from './8.4.0';
import type { AlertsFieldMap8130 } from './8.13.0';
import { alertsFieldMap8130 } from './8.13.0';
import type { RulesFieldMap } from './8.0.0/rules';
import { rulesFieldMap } from './8.0.0/rules';
export type { AlertsFieldMap840 as AlertsFieldMap, RulesFieldMap };
export { alertsFieldMap840 as alertsFieldMap, rulesFieldMap };
export type { AlertsFieldMap8130 as AlertsFieldMap, RulesFieldMap };
export { alertsFieldMap8130 as alertsFieldMap, rulesFieldMap };
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
*/

import type { EuiDataGridColumn } from '@elastic/eui';
import {
ALERT_HOST_CRITICALITY,
ALERT_USER_CRITICALITY,
} from '../../../../common/field_maps/field_names';
import type { LicenseService } from '../../../../common/license';
import type { ColumnHeaderOptions } from '../../../../common/types';

Expand Down Expand Up @@ -72,6 +76,18 @@ const getBaseColumns = (
id: 'user.risk.calculated_level',
}
: null,
isPlatinumPlus
? {
columnHeaderType: defaultColumnHeaderType,
id: ALERT_HOST_CRITICALITY,
}
: null,
isPlatinumPlus
? {
columnHeaderType: defaultColumnHeaderType,
id: ALERT_USER_CRITICALITY,
}
: null,
{
columnHeaderType: defaultColumnHeaderType,
id: 'process.name',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ import {
ALERT_RULE_THREAT,
ALERT_RULE_EXCEPTIONS_LIST,
ALERT_RULE_IMMUTABLE,
ALERT_HOST_CRITICALITY,
ALERT_USER_CRITICALITY,
} from '../../../../../../common/field_maps/field_names';
import type { CompleteRule, RuleParams } from '../../../rule_schema';
import { commonParamsCamelToSnake, typeSpecificCamelToSnake } from '../../../rule_management';
Expand Down Expand Up @@ -256,6 +258,9 @@ export const buildAlert = (
'kibana.alert.rule.risk_score': params.riskScore,
'kibana.alert.rule.severity': params.severity,
'kibana.alert.rule.building_block_type': params.buildingBlockType,
// asset criticality fields will be enriched before ingestion
[ALERT_HOST_CRITICALITY]: undefined,
[ALERT_USER_CRITICALITY]: undefined,
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ import {
ALERT_RULE_TIMELINE_TITLE,
ALERT_RULE_INDICES,
ALERT_RULE_TIMESTAMP_OVERRIDE,
ALERT_HOST_CRITICALITY,
ALERT_USER_CRITICALITY,
} from '../../../../../../../common/field_maps/field_names';

export const createAlert = (
Expand Down Expand Up @@ -194,6 +196,8 @@ export const createAlert = (
rule_name_override: undefined,
timestamp_override: undefined,
},
[ALERT_HOST_CRITICALITY]: undefined,
[ALERT_USER_CRITICALITY]: undefined,
...data,
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { flatten, chunk } from 'lodash';
import { chunk } from 'lodash';
import { searchEnrichments } from './search_enrichments';
import { makeSingleFieldMatchQuery } from './utils/requests';
import { getEventValue, getFieldValue } from './utils/events';
Expand All @@ -22,12 +22,14 @@ export const createSingleFieldMatchEnrichment: CreateFieldsMatchEnrichment = asy
createEnrichmentFunction,
name,
enrichmentResponseFields,
extraFilters,
}) => {
try {
logger.debug(`Enrichment ${name}: started`);

const eventsWithField = events.filter((event) => getEventValue(event, mappingField.eventField));
const eventsMapByFieldValue = eventsWithField.reduce((acc, event) => {
const eventsToEnrich = events.filter((event) => getEventValue(event, mappingField.eventField));

const eventsMapByFieldValue = eventsToEnrich.reduce((acc, event) => {
const eventFieldValue = getEventValue(event, mappingField.eventField);

if (!eventFieldValue) return {};
Expand All @@ -39,13 +41,15 @@ export const createSingleFieldMatchEnrichment: CreateFieldsMatchEnrichment = asy
}, {} as { [key: string]: typeof events });

const uniqueEventsValuesToSearchBy = Object.keys(eventsMapByFieldValue);

const chunksUniqueEventsValuesToSearchBy = chunk(uniqueEventsValuesToSearchBy, MAX_CLAUSES);

const getAllEnrichment = chunksUniqueEventsValuesToSearchBy
.map((enrichmentValuesChunk) =>
makeSingleFieldMatchQuery({
values: enrichmentValuesChunk,
searchByField: mappingField.enrichmentField,
extraFilters,
})
)
.filter((query) => query.query?.bool?.should?.length > 0)
Expand All @@ -59,11 +63,9 @@ export const createSingleFieldMatchEnrichment: CreateFieldsMatchEnrichment = asy
})
);

const enrichmentsResults = (await Promise.allSettled(getAllEnrichment))
const enrichments = (await Promise.allSettled(getAllEnrichment))
.filter((result) => result.status === 'fulfilled')
.map((result) => (result as PromiseFulfilledResult<EnrichmentType[]>)?.value);

const enrichments = flatten(enrichmentsResults);
.flatMap((result) => (result as PromiseFulfilledResult<EnrichmentType[]>)?.value);

if (enrichments.length === 0) {
logger.debug(`Enrichment ${name}: no enrichment found`);
Expand Down
Loading

0 comments on commit cf9ff4d

Please sign in to comment.