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

Create initialization API for privileged user monitoring engine #212259

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* 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.
*/

/*
* NOTICE: Do not edit this file manually.
* This file is automatically generated by the OpenAPI Generator, @kbn/openapi-generator.
*
* info:
* title: Init Privilege Monitoring Engine
* version: 2023-10-31
*/

import { z } from '@kbn/zod';

export type InitMonitoringEngineResponse = z.infer<typeof InitMonitoringEngineResponse>;
export const InitMonitoringEngineResponse = z.object({
acknowledged: z.boolean().optional(),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
openapi: 3.0.0

info:
title: Init Privilege Monitoring Engine
version: 2023-10-31
paths:
/api/entity_analytics/monitoring/engine/init:
post:
x-labels: [ess, serverless]
x-codegen-enabled: true
operationId: InitMonitoringEngine
summary: Initialize the Privilege Monitoring Engine

responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
acknowledged:
type: boolean

Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ import type {
GetEntityStoreStatusRequestQueryInput,
GetEntityStoreStatusResponse,
} from './entity_analytics/entity_store/status.gen';
import type { InitMonitoringEngineResponse } from './entity_analytics/privilege_monitoring/engine/init.gen';
import type { CleanUpRiskEngineResponse } from './entity_analytics/risk_engine/engine_cleanup_route.gen';
import type {
ConfigureRiskEngineSavedObjectRequestBodyInput,
Expand Down Expand Up @@ -1689,6 +1690,18 @@ finalize it.
})
.catch(catchAxiosErrorFormatAndThrow);
}
async initMonitoringEngine() {
this.log.info(`${new Date().toISOString()} Calling API InitMonitoringEngine`);
return this.kbnClient
.request<InitMonitoringEngineResponse>({
path: '/api/entity_analytics/monitoring/engine/init',
headers: {
[ELASTIC_HTTP_VERSION_HEADER]: '2023-10-31',
},
method: 'POST',
})
.catch(catchAxiosErrorFormatAndThrow);
}
/**
* Initializes the Risk Engine by creating the necessary indices and mappings, removing old transforms, and starting the new risk engine
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* 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 {
Logger,
ElasticsearchClient,
SavedObjectsClientContract,
AuditLogger,
IScopedClusterClient,
AnalyticsServiceSetup,
} from '@kbn/core/server';

import type { TaskManagerStartContract } from '@kbn/task-manager-plugin/server';
import type { ApiKeyManager } from './auth/api_key';

interface PrivilegeMonitoringClientOpts {
logger: Logger;
clusterClient: IScopedClusterClient;
namespace: string;
soClient: SavedObjectsClientContract;
taskManager?: TaskManagerStartContract;
auditLogger?: AuditLogger;
kibanaVersion: string;
telemetry?: AnalyticsServiceSetup;
apiKeyManager?: ApiKeyManager;
}

export class PrivilegeMonitoringDataClient {
private apiKeyGenerator?: ApiKeyManager;
private esClient: ElasticsearchClient;

constructor(private readonly opts: PrivilegeMonitoringClientOpts) {
this.esClient = opts.clusterClient.asInternalUser;
this.apiKeyGenerator = opts.apiKeyManager;
}

init() {
return Promise.resolve();
}
}
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 type { KibanaRequest } from '@kbn/core-http-server';
import { generateEntityDiscoveryAPIKey } from '@kbn/entityManager-plugin/server/lib/auth';
import { EntityDiscoveryApiKeyType } from '@kbn/entityManager-plugin/server/saved_objects';
import type { CoreStart } from '@kbn/core-lifecycle-server';
import type { Logger } from '@kbn/logging';
import type { SecurityPluginStart } from '@kbn/security-plugin-types-server';
import type { EncryptedSavedObjectsPluginStart } from '@kbn/encrypted-saved-objects-plugin/server';
import { getFakeKibanaRequest } from '@kbn/security-plugin/server/authentication/api_keys/fake_kibana_request';
import type { EntityDiscoveryAPIKey } from '@kbn/entityManager-plugin/server/lib/auth/api_key/api_key';
import { getSpaceAwareEntityDiscoverySavedObjectId } from '@kbn/entityManager-plugin/server/lib/auth/api_key/saved_object';
import { SavedObjectsErrorHelpers } from '@kbn/core-saved-objects-server';

export interface ApiKeyManager {
generate: () => Promise<void>;
}

export const getApiKeyManager = ({
core,
logger,
security,
encryptedSavedObjects,
request,
namespace,
}: {
core: CoreStart;
logger: Logger;
security: SecurityPluginStart;
encryptedSavedObjects?: EncryptedSavedObjectsPluginStart;
request?: KibanaRequest;
namespace: string;
}) => ({
generate: async () => {
if (!encryptedSavedObjects) {
throw new Error(
'Unable to create API key. Ensure encrypted Saved Object client is enabled in this environment.'
);
} else if (!request) {
throw new Error('Unable to create API key due to invalid request');
} else {
const apiKey = await generateEntityDiscoveryAPIKey(
{
core,
config: {},
logger,
security,
encryptedSavedObjects,
},
request
);

const soClient = core.savedObjects.getScopedClient(request, {
includedHiddenTypes: [EntityDiscoveryApiKeyType.name],
});

await soClient.create(EntityDiscoveryApiKeyType.name, apiKey, {
id: getSpaceAwareEntityDiscoverySavedObjectId(namespace),
overwrite: true,
managed: true,
});
}
},
getApiKey: async () => {
if (!encryptedSavedObjects) {
throw Error(
'Unable to retrieve API key. Ensure encrypted Saved Object client is enabled in this environment.'
);
}
try {
const encryptedSavedObjectsClient = encryptedSavedObjects.getClient({
includedHiddenTypes: [EntityDiscoveryApiKeyType.name],
});
return (
await encryptedSavedObjectsClient.getDecryptedAsInternalUser<EntityDiscoveryAPIKey>(
EntityDiscoveryApiKeyType.name,
getSpaceAwareEntityDiscoverySavedObjectId(namespace)
)
).attributes;
} catch (err) {
if (SavedObjectsErrorHelpers.isNotFoundError(err)) {
return undefined;
}
throw err;
}
},
getRequestFromApiKey: async (apiKey: EntityDiscoveryAPIKey) => {
return getFakeKibanaRequest({
id: apiKey.id,
api_key: apiKey.apiKey,
});
},
getClientFromApiKey: async (apiKey: EntityDiscoveryAPIKey) => {
const fakeRequest = getFakeKibanaRequest({
id: apiKey.id,
api_key: apiKey.apiKey,
});
const clusterClient = core.elasticsearch.client.asScoped(fakeRequest);
const soClient = core.savedObjects.getScopedClient(fakeRequest, {
includedHiddenTypes: [EntityDiscoveryApiKeyType.name],
});
return {
clusterClient,
soClient,
};
},
});
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 type { IKibanaResponse, Logger } from '@kbn/core/server';
import { buildSiemResponse } from '@kbn/lists-plugin/server/routes/utils';
import { transformError } from '@kbn/securitysolution-es-utils';

import type { InitMonitoringEngineResponse } from '../../../../../common/api/entity_analytics/privilege_monitoring/engine/init.gen';
import { API_VERSIONS, APP_ID } from '../../../../../common/constants';
import type { EntityAnalyticsRoutesDeps } from '../../types';

export const initPrivilegeMonitoringEngineRoute = (
router: EntityAnalyticsRoutesDeps['router'],
logger: Logger,
config: EntityAnalyticsRoutesDeps['config']
) => {
router.versioned
.post({
access: 'public',
path: '/api/entity_analytics/monitoring/engine/init',
security: {
authz: {
requiredPrivileges: ['securitySolution', `${APP_ID}-entity-analytics`],
},
},
})
.addVersion(
{
version: API_VERSIONS.public.v1,
validate: {},
},

async (
context,
request,
response
): Promise<IKibanaResponse<InitMonitoringEngineResponse>> => {
const siemResponse = buildSiemResponse(response);
const secSol = await context.securitySolution;

try {
const body = await secSol.getPrivilegeMonitoringDataClient().init();
return response.ok({ body: { acknowledged: true } });
} catch (e) {
const error = transformError(e);
logger.error(`Error initializing privilege monitoring engine: ${error.message}`);
return siemResponse.error({
statusCode: error.statusCode,
body: error.message,
});
}
}
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* 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 { EntityAnalyticsRoutesDeps } from '../../types';

import { initPrivilegeMonitoringEngineRoute } from './init';

export const registerPrivilegeMonitoringRoutes = ({
router,
logger,
getStartServices,
config,
}: EntityAnalyticsRoutesDeps) => {
initPrivilegeMonitoringEngineRoute(router, logger, config);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export const TYPE = 'entity_analytics:monitoring_engine:great_success';
export const VERSION = '1.0.0';
export const TIMEOUT = '10m';
Loading