Skip to content

Commit

Permalink
[Security Solution][Endpoint] Add responder scan action (elastic#18…
Browse files Browse the repository at this point in the history
…4723)

## Summary
Adds `scan` response action to Responder.

### Test
1. Add `responseActionScanEnabled` feature flag to
`xpack.securitySolution.enableExperimental`
2. Run ES/Kibana
3. Run `node
x-pack/plugins/security_solution/scripts/endpoint/run_endpoint_agent.js`
to start a VM with Elastic Defend installed.
4. Visit `app/security/administration/endpoints` and click on the
endpoint on the endpoint list.
5. Click on the action kebab menu and open responder. 
6. Click on `Help` to verify that the `scan` action is available for the
endpoint and doesn't have an alert icon next to it.
7. Click on the `+` icon next to `scan` help command to add it to the
input and provide a file path from your VM to scan. Send the request by
clicking the `play` icon or hitting the `return` key.
8. You should see the scan action being carried out and eventually
resulting in either a `Scan complete` or error info.

![Screenshot 2024-06-04 at 11 52
32](https://github.com/elastic/kibana/assets/1849116/4a1a42e5-85d0-407f-962c-7ee40951417e)

![Screenshot 2024-06-04 at 11 58
12](https://github.com/elastic/kibana/assets/1849116/b5911473-f000-4cee-83b4-c79166829d39)

![Screenshot 2024-06-05 at 12 04
59](https://github.com/elastic/kibana/assets/1849116/950d79ed-e69d-4a3c-8bcb-a38fc3d9a91e)

### clip

![scan-command](https://github.com/elastic/kibana/assets/1849116/331deabc-faf4-44e8-8248-e7b86f2add99)


### Checklist

- [x] 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)
- [x] [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
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [x] 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))
- [x] 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))
- [x] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)
  • Loading branch information
ashokaditya authored Jun 11, 2024
1 parent f683520 commit d3fd637
Show file tree
Hide file tree
Showing 11 changed files with 665 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,28 @@ import { merge } from 'lodash';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ENDPOINT_ACTION_RESPONSES_DS, ENDPOINT_ACTIONS_DS } from '../constants';
import { BaseDataGenerator } from './base_data_generator';
import type {
ActionDetails,
EndpointActivityLogAction,
EndpointActivityLogActionResponse,
EndpointPendingActions,
LogsEndpointAction,
LogsEndpointActionResponse,
ProcessesEntry,
EndpointActionDataParameterTypes,
ActionResponseOutput,
ResponseActionGetFileOutputContent,
ResponseActionGetFileParameters,
ResponseActionsExecuteParameters,
ResponseActionExecuteOutputContent,
ResponseActionUploadOutputContent,
ResponseActionUploadParameters,
EndpointActionResponseDataOutput,
WithAllKeys,
ResponseActionScanOutputContent,
ResponseActionsScanParameters,
import {
type ActionDetails,
type ActionResponseOutput,
ActivityLogItemTypes,
type EndpointActionDataParameterTypes,
type EndpointActionResponseDataOutput,
type EndpointActivityLogAction,
type EndpointActivityLogActionResponse,
type EndpointPendingActions,
type LogsEndpointAction,
type LogsEndpointActionResponse,
type ProcessesEntry,
type ResponseActionExecuteOutputContent,
type ResponseActionGetFileOutputContent,
type ResponseActionGetFileParameters,
type ResponseActionScanOutputContent,
type ResponseActionsExecuteParameters,
type ResponseActionsScanParameters,
type ResponseActionUploadOutputContent,
type ResponseActionUploadParameters,
type WithAllKeys,
} from '../types';
import { ActivityLogItemTypes } from '../types';
import {
DEFAULT_EXECUTE_ACTION_TIMEOUT,
RESPONSE_ACTION_API_COMMANDS_NAMES,
Expand Down Expand Up @@ -294,7 +294,7 @@ export class EndpointActionGenerator extends BaseDataGenerator {
ResponseActionsScanParameters
>
).parameters = {
path: '/some/file.txt',
path: '/some/folder/to/scan',
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,21 @@ export const CONSOLE_COMMANDS = {
},
},
},
scan: {
about: i18n.translate('xpack.securitySolution.endpointConsoleCommands.scan.about', {
defaultMessage: 'Scan the host for malware',
}),
args: {
path: {
about: i18n.translate(
'xpack.securitySolution.endpointConsoleCommands.scan.args.path.about',
{
defaultMessage: 'The absolute path to a file or directory to be scanned',
}
),
},
},
},
};

export const CONFIRM_WARNING_MODAL_LABELS = (entryType: string) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
/*
* 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 React from 'react';
import { waitFor } from '@testing-library/react';
import type { HttpFetchOptionsWithPath } from '@kbn/core-http-browser';

import {
ENDPOINT_CAPABILITIES,
type EndpointCapabilities,
} from '../../../../../../common/endpoint/service/response_actions/constants';
import {
type AppContextTestRender,
createAppRootMockRenderer,
} from '../../../../../common/mock/endpoint';
import { responseActionsHttpMocks } from '../../../../mocks/response_actions_http_mocks';
import {
ConsoleManagerTestComponent,
getConsoleManagerMockRenderResultQueriesAndActions,
} from '../../../console/components/console_manager/mocks';

import {
getEndpointConsoleCommands,
type GetEndpointConsoleCommandsOptions,
} from '../../lib/console_commands_definition';
import { enterConsoleCommand } from '../../../console/mocks';
import { SCAN_ROUTE } from '../../../../../../common/endpoint/constants';
import { getEndpointAuthzInitialStateMock } from '../../../../../../common/endpoint/service/authz/mocks';
import type {
EndpointPrivileges,
ResponseActionScanOutputContent,
} from '../../../../../../common/endpoint/types';
import {
INSUFFICIENT_PRIVILEGES_FOR_COMMAND,
UPGRADE_AGENT_FOR_RESPONDER,
} from '../../../../../common/translations';
import { endpointActionResponseCodes } from '../../lib/endpoint_action_response_codes';

jest.mock('../../../../../common/components/user_privileges');

describe('When using scan action from response actions console', () => {
let render: (
capabilities?: EndpointCapabilities[]
) => Promise<ReturnType<AppContextTestRender['render']>>;
let renderResult: ReturnType<AppContextTestRender['render']>;
let apiMocks: ReturnType<typeof responseActionsHttpMocks>;
let consoleManagerMockAccess: ReturnType<
typeof getConsoleManagerMockRenderResultQueriesAndActions
>;
let endpointPrivileges: EndpointPrivileges;
let getConsoleCommandsOptions: GetEndpointConsoleCommandsOptions;
let mockedContext: AppContextTestRender;

beforeEach(() => {
mockedContext = createAppRootMockRenderer();

mockedContext.setExperimentalFlag({ responseActionScanEnabled: true });
apiMocks = responseActionsHttpMocks(mockedContext.coreStart.http);
endpointPrivileges = {
...getEndpointAuthzInitialStateMock(),
loading: false,
canWriteScanOperations: true,
};

getConsoleCommandsOptions = {
agentType: 'endpoint',
endpointAgentId: 'agent-a',
endpointCapabilities: [...ENDPOINT_CAPABILITIES],
endpointPrivileges,
};

render = async (capabilities: EndpointCapabilities[] = [...ENDPOINT_CAPABILITIES]) => {
renderResult = mockedContext.render(
<ConsoleManagerTestComponent
registerConsoleProps={() => {
return {
consoleProps: {
'data-test-subj': 'test',
commands: getEndpointConsoleCommands({
...getConsoleCommandsOptions,
endpointCapabilities: capabilities,
}),
},
};
}}
/>
);

consoleManagerMockAccess = getConsoleManagerMockRenderResultQueriesAndActions(renderResult);

await consoleManagerMockAccess.clickOnRegisterNewConsole();
await consoleManagerMockAccess.openRunningConsole();

return renderResult;
};
});

it('should show an error if the `scan` capability is not present in the endpoint', async () => {
await render([]);
enterConsoleCommand(renderResult, 'scan --path="one/two"');

expect(renderResult.getByTestId('test-validationError-message').textContent).toEqual(
UPGRADE_AGENT_FOR_RESPONDER('endpoint', 'scan')
);
});

it('should show an error if the `scan` is not authorized', async () => {
endpointPrivileges.canWriteScanOperations = false;
await render();
enterConsoleCommand(renderResult, 'scan --path="one/two"');

expect(renderResult.getByTestId('test-validationError-message').textContent).toEqual(
INSUFFICIENT_PRIVILEGES_FOR_COMMAND
);
});

it('should show an error if `scan` is entered without `--path` argument', async () => {
await render();
enterConsoleCommand(renderResult, 'scan');

expect(renderResult.getByTestId('test-badArgument-message').textContent).toEqual(
'Missing required arguments: --path'
);
});

it('should show error if `--path` is empty string', async () => {
await render();
enterConsoleCommand(renderResult, 'scan --path=""');

expect(renderResult.getByTestId('test-badArgument-message').textContent).toEqual(
'Argument --path must have a value'
);
});

it('should call the `scan` api with the expected payload', async () => {
await render();
enterConsoleCommand(renderResult, 'scan --path="one/two"');

await waitFor(() => {
expect(apiMocks.responseProvider.scan).toHaveBeenCalledWith({
body: '{"agent_type":"endpoint","endpoint_ids":["agent-a"],"parameters":{"path":"one/two"}}',
path: SCAN_ROUTE,
version: '2023-10-31',
});
});
});

it('should only accept one `--comment`', async () => {
await render();
enterConsoleCommand(renderResult, 'scan --path="one/two" --comment "one" --comment "two"');

expect(renderResult.getByTestId('test-badArgument-message').textContent).toEqual(
'Argument can only be used once: --comment'
);
});

it('should display pending message', async () => {
await render();
enterConsoleCommand(renderResult, 'scan --path="one/two"');

await waitFor(() => {
expect(renderResult.getByTestId('scan-pending').textContent).toEqual(
'File path scan is in progress.'
);
});
});

it('should display action completion info', async () => {
const actionDetailsApiResponseMock: ReturnType<typeof apiMocks.responseProvider.actionDetails> =
{
data: {
...apiMocks.responseProvider.actionDetails({
path: '/agent-a',
} as HttpFetchOptionsWithPath).data,
completedAt: new Date().toISOString(),
command: 'scan',
outputs: {
'agent-a': {
type: 'json',
content: {
code: 'ra_scan_success_done',
} as unknown as ResponseActionScanOutputContent,
},
},
},
};

apiMocks.responseProvider.actionDetails.mockReturnValue(actionDetailsApiResponseMock);

await render();
enterConsoleCommand(renderResult, 'scan --path="one/two"');

await waitFor(() => {
expect(apiMocks.responseProvider.actionDetails).toHaveBeenCalled();
});

await waitFor(() => {
expect(renderResult.getByTestId('scan-success').textContent).toEqual('Scan complete');
});
});

it.each([
'ra_scan_error_not-found',
'ra_scan_error_scan_invalid-input',
'ra_scan_error_scan-queue-quota',
])('should show detailed error if `scan` failure returned code: %s', async (outputCode) => {
const mockData = apiMocks.responseProvider.actionDetails({
path: '/api/endpoint/action/agent-a',
}).data;

const actionDetailsApiResponseMock: ReturnType<typeof apiMocks.responseProvider.actionDetails> =
{
data: {
...mockData,
id: '123',
completedAt: new Date().toISOString(),
command: 'scan',
outputs: {
'agent-a': {
type: 'json',
content: {
code: outputCode,
} as unknown as ResponseActionScanOutputContent,
},
},
errors: ['error message'],
wasSuccessful: false,
status: 'failed',
agentState: {
'agent-a': {
...mockData.agentState['agent-a'],
wasSuccessful: false,
errors: ['error message'],
},
},
parameters: {
path: '/error/path',
},
},
};

apiMocks.responseProvider.actionDetails.mockReturnValue(actionDetailsApiResponseMock);
await render();
enterConsoleCommand(renderResult, 'scan --path="/error/path"');

await waitFor(() => {
expect(renderResult.getByTestId('scan-actionFailure').textContent).toMatch(
// RegExp below taken from: https://github.com/sindresorhus/escape-string-regexp/blob/main/index.js
new RegExp(endpointActionResponseCodes[outputCode].replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'))
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* 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 { memo, useMemo } from 'react';
import { i18n } from '@kbn/i18n';
import type { ScanActionRequestBody } from '../../../../../common/api/endpoint';
import { useConsoleActionSubmitter } from '../hooks/use_console_action_submitter';
import type { ActionRequestComponentProps } from '../types';
import { useSendScanRequest } from '../../../hooks/response_actions/use_send_scan_request';

export const ScanActionResult = memo<
ActionRequestComponentProps<{
path: string[];
}>
>(({ command, setStore, store, status, setStatus, ResultComponent }) => {
const actionCreator = useSendScanRequest();

const actionRequestBody = useMemo<undefined | ScanActionRequestBody>(() => {
const endpointId = command.commandDefinition?.meta?.endpointId;
const { path, comment } = command.args.args;
const agentType = command.commandDefinition?.meta?.agentType;

return endpointId
? {
agent_type: agentType,
endpoint_ids: [endpointId],
comment: comment?.[0],
parameters: {
path: path[0],
},
}
: undefined;
}, [
command.args.args,
command.commandDefinition?.meta?.agentType,
command.commandDefinition?.meta?.endpointId,
]);

return useConsoleActionSubmitter<ScanActionRequestBody>({
ResultComponent,
setStore,
store,
status,
setStatus,
actionCreator,
actionRequestBody,
dataTestSubj: 'scan',
pendingMessage: i18n.translate('xpack.securitySolution.scanAction.pendingMessage', {
defaultMessage: 'File path scan is in progress.',
}),
}).result;
});

ScanActionResult.displayName = 'ScanActionResult';
Loading

0 comments on commit d3fd637

Please sign in to comment.