Skip to content

Commit

Permalink
[8.x] [Cloud Security] Host Name Misconfiguration Datagrid & Refa…
Browse files Browse the repository at this point in the history
…ctor CSP Plugin PHASE 2 (#192535) (#192942)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[Cloud Security] Host Name Misconfiguration Datagrid & Refactor
CSP Plugin PHASE 2
(#192535)](#192535)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Rickyanto
Ang","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-09-14T04:41:41Z","message":"[Cloud
Security] Host Name Misconfiguration Datagrid & Refactor CSP Plugin
PHASE 2 (#192535)\n\nIn an attempt to make Reviewing easier and more
accurate, the\r\nimplementation of Misconfiguration Data grid on
Host.name flyout in\r\nAlerts Page will be split into 2
Phases\r\n\r\nPhase 1: Move Functions, Utils or Helpers, Hooks,
constants to Package\r\nPhase 2: Implementing the feature\r\n\r\nThis is
**Phase 2** of the process\r\n<img width=\"1712\" alt=\"Screenshot
2024-09-11 at 2 16
20 PM\"\r\nsrc=\"https://github.com/user-attachments/assets/29ab56db-8561-486c-ae8d-c254b932cea4\">\r\n\r\nHow
to test:\r\nPre req: In order to test this, you need to generate some
fake alerts.\r\nThis
[repo](https://github.com/elastic/security-documents-generator)\r\nwill
help you do that\r\n1. Generate Some Alerts\r\n2. Use the Reindex API to
get some Findings data in (change the\r\nhost.name field to match the
host.name from alerts generated if you want\r\nto test Findings table in
the left panel flyout)\r\n3. Turn on Risky Entity Score if you want to
test if both Risk\r\nContribution and Insights tabs shows up, follow
this\r\n[guide](https://www.elastic.co/guide/en/security/current/turn-on-risk-engine.html)\r\nto
turn on Risk Entity
Score","sha":"28becfdce90ff5a0cec0345070c301aa7ca338ed","branchLabelMapping":{"^v9.0.0$":"main","^v8.16.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:Cloud
Security","backport:prev-minor","ci:project-deploy-security","v8.16.0"],"title":"[Cloud
Security] Host Name Misconfiguration Datagrid & Refactor CSP Plugin
PHASE
2","number":192535,"url":"https://github.com/elastic/kibana/pull/192535","mergeCommit":{"message":"[Cloud
Security] Host Name Misconfiguration Datagrid & Refactor CSP Plugin
PHASE 2 (#192535)\n\nIn an attempt to make Reviewing easier and more
accurate, the\r\nimplementation of Misconfiguration Data grid on
Host.name flyout in\r\nAlerts Page will be split into 2
Phases\r\n\r\nPhase 1: Move Functions, Utils or Helpers, Hooks,
constants to Package\r\nPhase 2: Implementing the feature\r\n\r\nThis is
**Phase 2** of the process\r\n<img width=\"1712\" alt=\"Screenshot
2024-09-11 at 2 16
20 PM\"\r\nsrc=\"https://github.com/user-attachments/assets/29ab56db-8561-486c-ae8d-c254b932cea4\">\r\n\r\nHow
to test:\r\nPre req: In order to test this, you need to generate some
fake alerts.\r\nThis
[repo](https://github.com/elastic/security-documents-generator)\r\nwill
help you do that\r\n1. Generate Some Alerts\r\n2. Use the Reindex API to
get some Findings data in (change the\r\nhost.name field to match the
host.name from alerts generated if you want\r\nto test Findings table in
the left panel flyout)\r\n3. Turn on Risky Entity Score if you want to
test if both Risk\r\nContribution and Insights tabs shows up, follow
this\r\n[guide](https://www.elastic.co/guide/en/security/current/turn-on-risk-engine.html)\r\nto
turn on Risk Entity
Score","sha":"28becfdce90ff5a0cec0345070c301aa7ca338ed"}},"sourceBranch":"main","suggestedTargetBranches":["8.x"],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/192535","number":192535,"mergeCommit":{"message":"[Cloud
Security] Host Name Misconfiguration Datagrid & Refactor CSP Plugin
PHASE 2 (#192535)\n\nIn an attempt to make Reviewing easier and more
accurate, the\r\nimplementation of Misconfiguration Data grid on
Host.name flyout in\r\nAlerts Page will be split into 2
Phases\r\n\r\nPhase 1: Move Functions, Utils or Helpers, Hooks,
constants to Package\r\nPhase 2: Implementing the feature\r\n\r\nThis is
**Phase 2** of the process\r\n<img width=\"1712\" alt=\"Screenshot
2024-09-11 at 2 16
20 PM\"\r\nsrc=\"https://github.com/user-attachments/assets/29ab56db-8561-486c-ae8d-c254b932cea4\">\r\n\r\nHow
to test:\r\nPre req: In order to test this, you need to generate some
fake alerts.\r\nThis
[repo](https://github.com/elastic/security-documents-generator)\r\nwill
help you do that\r\n1. Generate Some Alerts\r\n2. Use the Reindex API to
get some Findings data in (change the\r\nhost.name field to match the
host.name from alerts generated if you want\r\nto test Findings table in
the left panel flyout)\r\n3. Turn on Risky Entity Score if you want to
test if both Risk\r\nContribution and Insights tabs shows up, follow
this\r\n[guide](https://www.elastic.co/guide/en/security/current/turn-on-risk-engine.html)\r\nto
turn on Risk Entity
Score","sha":"28becfdce90ff5a0cec0345070c301aa7ca338ed"}},{"branch":"8.x","label":"v8.16.0","branchLabelMappingKey":"^v8.16.0$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: Rickyanto Ang <[email protected]>
  • Loading branch information
kibanamachine and animehart authored Sep 19, 2024
1 parent 34546af commit 99af356
Show file tree
Hide file tree
Showing 14 changed files with 636 additions and 134 deletions.
2 changes: 1 addition & 1 deletion x-pack/packages/kbn-cloud-security-posture-common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type {
BaseCspSetupStatus,
CspSetupStatus,
} from './types/status';
export type { CspFinding } from './types/findings';
export type { CspFinding, CspFindingResult } from './types/findings';
export type { BenchmarksCisId } from './types/benchmark';
export * from './constants';
export {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ interface CspFindingCloud {
region?: string;
}

interface CspFindingResult {
export interface CspFindingResult {
evaluation: 'passed' | 'failed';
expected?: Record<string, unknown>;
evidence: Record<string, unknown>;
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 { useQuery } from '@tanstack/react-query';
import { lastValueFrom } from 'rxjs';
import { CspFinding } from '@kbn/cloud-security-posture-common';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { CoreStart } from '@kbn/core/public';
import { showErrorToast } from '../..';
import type {
CspClientPluginStartDeps,
LatestFindingsRequest,
LatestFindingsResponse,
UseMisconfigurationOptions,
} from '../../type';

import { useGetCspBenchmarkRulesStatesApi } from './use_get_benchmark_rules_state_api';
import {
buildMisconfigurationsFindingsQuery,
getMisconfigurationAggregationCount,
} from '../utils/hooks_utils';

export const useMisconfigurationFindings = (options: UseMisconfigurationOptions) => {
const {
data,
notifications: { toasts },
} = useKibana<CoreStart & CspClientPluginStartDeps>().services;
const { data: rulesStates } = useGetCspBenchmarkRulesStatesApi();

return useQuery(
['csp_misconfiguration_findings', { params: options }, rulesStates],
async () => {
const {
rawResponse: { hits, aggregations },
} = await lastValueFrom(
data.search.search<LatestFindingsRequest, LatestFindingsResponse>({
params: buildMisconfigurationsFindingsQuery(options, rulesStates!),
})
);
if (!aggregations) throw new Error('expected aggregations to be defined');

return {
count: getMisconfigurationAggregationCount(aggregations.count.buckets),
rows: hits.hits.map((finding) => ({
result: finding._source?.result,
rule: finding?._source?.rule,
resource: finding?._source?.resource,
})) as Array<Pick<CspFinding, 'result' | 'rule' | 'resource'>>,
};
},
{
enabled: options.enabled && !!rulesStates,
keepPreviousData: true,
onError: (err: Error) => showErrorToast(toasts, err),
}
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,118 +6,22 @@
*/
import { useQuery } from '@tanstack/react-query';
import { lastValueFrom } from 'rxjs';
import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CDR_MISCONFIGURATIONS_INDEX_PATTERN,
LATEST_FINDINGS_RETENTION_POLICY,
CspFinding,
} from '@kbn/cloud-security-posture-common';
import type { CspBenchmarkRulesStates } from '@kbn/cloud-security-posture-common/schema/rules/latest';
import { buildMutedRulesFilter } from '@kbn/cloud-security-posture-common';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { CoreStart } from '@kbn/core/public';
import { showErrorToast } from '../..';
import type { CspClientPluginStartDeps } from '../../type';
import type {
CspClientPluginStartDeps,
LatestFindingsRequest,
LatestFindingsResponse,
UseMisconfigurationOptions,
} from '../../type';
import { useGetCspBenchmarkRulesStatesApi } from './use_get_benchmark_rules_state_api';
import {
buildMisconfigurationsFindingsQuery,
getMisconfigurationAggregationCount,
} from '../utils/hooks_utils';

interface MisconfigurationPreviewBaseEsQuery {
query?: {
bool: {
filter: estypes.QueryDslQueryContainer[];
};
};
}

interface UseMisconfigurationPreviewOptions extends MisconfigurationPreviewBaseEsQuery {
sort: string[][];
enabled: boolean;
pageSize: number;
}

type LatestFindingsRequest = IKibanaSearchRequest<estypes.SearchRequest>;
type LatestFindingsResponse = IKibanaSearchResponse<
estypes.SearchResponse<CspFinding, FindingsAggs>
>;

interface FindingsAggs {
count: estypes.AggregationsMultiBucketAggregateBase<estypes.AggregationsStringRareTermsBucketKeys>;
}

const RESULT_EVALUATION = {
PASSED: 'passed',
FAILED: 'failed',
UNKNOWN: 'unknown',
};

export const getFindingsCountAggQueryMisconfigurationPreview = () => ({
count: {
filters: {
other_bucket_key: RESULT_EVALUATION.UNKNOWN,
filters: {
[RESULT_EVALUATION.PASSED]: { match: { 'result.evaluation': RESULT_EVALUATION.PASSED } },
[RESULT_EVALUATION.FAILED]: { match: { 'result.evaluation': RESULT_EVALUATION.FAILED } },
},
},
},
});

export const getMisconfigurationAggregationCount = (
buckets: estypes.AggregationsBuckets<estypes.AggregationsStringRareTermsBucketKeys>
) => {
return Object.entries(buckets).reduce(
(evaluation, [key, value]) => {
evaluation[key] = (evaluation[key] || 0) + (value.doc_count || 0);
return evaluation;
},
{
[RESULT_EVALUATION.PASSED]: 0,
[RESULT_EVALUATION.FAILED]: 0,
[RESULT_EVALUATION.UNKNOWN]: 0,
}
);
};

export const buildMisconfigurationsFindingsQuery = (
{ query }: UseMisconfigurationPreviewOptions,
rulesStates: CspBenchmarkRulesStates
) => {
const mutedRulesFilterQuery = buildMutedRulesFilter(rulesStates);

return {
index: CDR_MISCONFIGURATIONS_INDEX_PATTERN,
size: 0,
aggs: getFindingsCountAggQueryMisconfigurationPreview(),
ignore_unavailable: false,
query: buildMisconfigurationsFindingsQueryWithFilters(query, mutedRulesFilterQuery),
};
};

const buildMisconfigurationsFindingsQueryWithFilters = (
query: UseMisconfigurationPreviewOptions['query'],
mutedRulesFilterQuery: estypes.QueryDslQueryContainer[]
) => {
return {
...query,
bool: {
...query?.bool,
filter: [
...(query?.bool?.filter ?? []),
{
range: {
'@timestamp': {
gte: `now-${LATEST_FINDINGS_RETENTION_POLICY}`,
lte: 'now',
},
},
},
],
must_not: [...mutedRulesFilterQuery],
},
};
};

export const useMisconfigurationPreview = (options: UseMisconfigurationPreviewOptions) => {
export const useMisconfigurationPreview = (options: UseMisconfigurationOptions) => {
const {
data,
notifications: { toasts },
Expand All @@ -134,10 +38,10 @@ export const useMisconfigurationPreview = (options: UseMisconfigurationPreviewOp
params: buildMisconfigurationsFindingsQuery(options, rulesStates!),
})
);
if (!aggregations) throw new Error('expected aggregations to be defined');

if (!aggregations && !options.ignore_unavailable)
throw new Error('expected aggregations to be defined');
return {
count: getMisconfigurationAggregationCount(aggregations.count.buckets),
count: getMisconfigurationAggregationCount(aggregations?.count?.buckets),
};
},
{
Expand Down
105 changes: 105 additions & 0 deletions x-pack/packages/kbn-cloud-security-posture/src/utils/hooks_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* 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 * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CDR_MISCONFIGURATIONS_INDEX_PATTERN,
LATEST_FINDINGS_RETENTION_POLICY,
} from '@kbn/cloud-security-posture-common';
import type { CspBenchmarkRulesStates } from '@kbn/cloud-security-posture-common/schema/rules/latest';
import { buildMutedRulesFilter } from '@kbn/cloud-security-posture-common';
import type { UseMisconfigurationOptions } from '../../type';

const MISCONFIGURATIONS_SOURCE_FIELDS = ['result.*', 'rule.*', 'resource.*'];
interface AggregationBucket {
doc_count?: number;
}

type AggregationBuckets = Record<string, AggregationBucket>;

const RESULT_EVALUATION = {
PASSED: 'passed',
FAILED: 'failed',
UNKNOWN: 'unknown',
};

export const getFindingsCountAggQueryMisconfiguration = () => ({
count: {
filters: {
other_bucket_key: RESULT_EVALUATION.UNKNOWN,
filters: {
[RESULT_EVALUATION.PASSED]: { match: { 'result.evaluation': RESULT_EVALUATION.PASSED } },
[RESULT_EVALUATION.FAILED]: { match: { 'result.evaluation': RESULT_EVALUATION.FAILED } },
},
},
},
});

export const getMisconfigurationAggregationCount = (
buckets?: estypes.AggregationsBuckets<estypes.AggregationsStringRareTermsBucketKeys>
) => {
const defaultBuckets: AggregationBuckets = {
[RESULT_EVALUATION.PASSED]: { doc_count: 0 },
[RESULT_EVALUATION.FAILED]: { doc_count: 0 },
[RESULT_EVALUATION.UNKNOWN]: { doc_count: 0 },
};

// if buckets are undefined we will use default buckets
const usedBuckets = buckets || defaultBuckets;
return Object.entries(usedBuckets).reduce(
(evaluation, [key, value]) => {
evaluation[key] = (evaluation[key] || 0) + (value.doc_count || 0);
return evaluation;
},
{
[RESULT_EVALUATION.PASSED]: 0,
[RESULT_EVALUATION.FAILED]: 0,
[RESULT_EVALUATION.UNKNOWN]: 0,
}
);
};

export const buildMisconfigurationsFindingsQuery = (
{ query }: UseMisconfigurationOptions,
rulesStates: CspBenchmarkRulesStates,
isPreview = false
) => {
const mutedRulesFilterQuery = buildMutedRulesFilter(rulesStates);

return {
index: CDR_MISCONFIGURATIONS_INDEX_PATTERN,
size: isPreview ? 0 : 500,
aggs: getFindingsCountAggQueryMisconfiguration(),
ignore_unavailable: true,
query: buildMisconfigurationsFindingsQueryWithFilters(query, mutedRulesFilterQuery),
_source: MISCONFIGURATIONS_SOURCE_FIELDS,
};
};

const buildMisconfigurationsFindingsQueryWithFilters = (
query: UseMisconfigurationOptions['query'],
mutedRulesFilterQuery: estypes.QueryDslQueryContainer[]
) => {
return {
...query,
bool: {
...query?.bool,
filter: [
...(query?.bool?.filter ?? []),
{
range: {
'@timestamp': {
gte: `now-${LATEST_FINDINGS_RETENTION_POLICY}`,
lte: 'now',
},
},
},
],
must_not: [...mutedRulesFilterQuery],
},
};
};
27 changes: 27 additions & 0 deletions x-pack/packages/kbn-cloud-security-posture/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import type { FleetStart } from '@kbn/fleet-plugin/public';
import type { UsageCollectionStart } from '@kbn/usage-collection-plugin/public';
import { SharePluginStart } from '@kbn/share-plugin/public';
import { SpacesPluginStart } from '@kbn/spaces-plugin/public';
import { CspFinding } from '@kbn/cloud-security-posture-common';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { IKibanaSearchResponse, IKibanaSearchRequest } from '@kbn/search-types';

import type { BoolQuery } from '@kbn/es-query';
export interface FindingsBaseEsQuery {
Expand Down Expand Up @@ -51,3 +54,27 @@ export interface CspClientPluginStartDeps {
// optional
usageCollection?: UsageCollectionStart;
}

export interface MisconfigurationBaseEsQuery {
query?: {
bool: {
filter: estypes.QueryDslQueryContainer[];
};
};
}

export interface UseMisconfigurationOptions extends MisconfigurationBaseEsQuery {
sort: string[][];
enabled: boolean;
pageSize: number;
ignore_unavailable?: boolean;
}

export type LatestFindingsRequest = IKibanaSearchRequest<estypes.SearchRequest>;
export type LatestFindingsResponse = IKibanaSearchResponse<
estypes.SearchResponse<CspFinding, FindingsAggs>
>;

export interface FindingsAggs {
count: estypes.AggregationsMultiBucketAggregateBase<estypes.AggregationsStringRareTermsBucketKeys>;
}
Loading

0 comments on commit 99af356

Please sign in to comment.