-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
audit_service.ts
259 lines (238 loc) · 7.54 KB
/
audit_service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
* 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 { Subscription } from 'rxjs';
import { distinctUntilKeyChanged, map } from 'rxjs/operators';
import type {
HttpServiceSetup,
KibanaRequest,
Logger,
LoggerContextConfigInput,
LoggingServiceSetup,
} from 'src/core/server';
import type { SpacesPluginSetup } from '../../../spaces/server';
import type { SecurityLicense, SecurityLicenseFeatures } from '../../common/licensing';
import type { ConfigType } from '../config';
import type { SecurityPluginSetup } from '../plugin';
import type { AuditEvent } from './audit_events';
import { httpRequestEvent } from './audit_events';
export const ECS_VERSION = '1.6.0';
export const RECORD_USAGE_INTERVAL = 60 * 60 * 1000; // 1 hour
/**
* @deprecated
*/
export interface LegacyAuditLogger {
log: (eventType: string, message: string, data?: Record<string, any>) => void;
}
export interface AuditLogger {
log: (event: AuditEvent | undefined) => void;
}
export interface AuditServiceSetup {
asScoped: (request: KibanaRequest) => AuditLogger;
getLogger: (id?: string) => LegacyAuditLogger;
}
interface AuditServiceSetupParams {
license: SecurityLicense;
config: ConfigType['audit'];
logging: Pick<LoggingServiceSetup, 'configure'>;
http: Pick<HttpServiceSetup, 'registerOnPostAuth'>;
getCurrentUser(
request: KibanaRequest
): ReturnType<SecurityPluginSetup['authc']['getCurrentUser']> | undefined;
getSID(request: KibanaRequest): Promise<string | undefined>;
getSpaceId(
request: KibanaRequest
): ReturnType<SpacesPluginSetup['spacesService']['getSpaceId']> | undefined;
recordAuditLoggingUsage(): void;
}
export class AuditService {
/**
* @deprecated
*/
private licenseFeaturesSubscription?: Subscription;
/**
* @deprecated
*/
private allowLegacyAuditLogging = false;
private ecsLogger: Logger;
private usageIntervalId?: NodeJS.Timeout;
constructor(private readonly logger: Logger) {
this.ecsLogger = logger.get('ecs');
}
setup({
license,
config,
logging,
http,
getCurrentUser,
getSID,
getSpaceId,
recordAuditLoggingUsage,
}: AuditServiceSetupParams): AuditServiceSetup {
if (config.enabled && !config.appender) {
this.licenseFeaturesSubscription = license.features$.subscribe(
({ allowLegacyAuditLogging }) => {
this.allowLegacyAuditLogging = allowLegacyAuditLogging;
}
);
}
// Configure logging during setup and when license changes
logging.configure(
license.features$.pipe(
distinctUntilKeyChanged('allowAuditLogging'),
createLoggingConfig(config)
)
);
// Record feature usage at a regular interval if enabled and license allows
if (config.enabled && config.appender) {
license.features$.subscribe((features) => {
clearInterval(this.usageIntervalId!);
if (features.allowAuditLogging) {
recordAuditLoggingUsage();
this.usageIntervalId = setInterval(recordAuditLoggingUsage, RECORD_USAGE_INTERVAL);
if (this.usageIntervalId.unref) {
this.usageIntervalId.unref();
}
}
});
}
/**
* Creates an {@link AuditLogger} scoped to the current request.
*
* @example
* ```typescript
* const auditLogger = securitySetup.audit.asScoped(request);
* auditLogger.log(event);
* ```
*/
const asScoped = (request: KibanaRequest): AuditLogger => {
/**
* Logs an {@link AuditEvent} and automatically adds meta data about the
* current user, space and correlation id.
*
* Guidelines around what events should be logged and how they should be
* structured can be found in: `/x-pack/plugins/security/README.md`
*
* @example
* ```typescript
* const auditLogger = securitySetup.audit.asScoped(request);
* auditLogger.log({
* message: 'User is updating dashboard [id=123]',
* event: {
* action: 'saved_object_update',
* outcome: 'unknown'
* },
* kibana: {
* saved_object: { type: 'dashboard', id: '123' }
* },
* });
* ```
*/
const log: AuditLogger['log'] = async (event) => {
if (!event) {
return;
}
const spaceId = getSpaceId(request);
const user = getCurrentUser(request);
const sessionId = await getSID(request);
const meta: AuditEvent = {
...event,
user:
(user && {
name: user.username,
roles: user.roles as string[],
}) ||
event.user,
kibana: {
space_id: spaceId,
session_id: sessionId,
...event.kibana,
},
trace: { id: request.id },
};
if (filterEvent(meta, config.ignore_filters)) {
const { message, ...eventMeta } = meta;
this.ecsLogger.info(message, eventMeta);
}
};
return { log };
};
/**
* @deprecated
* Use `audit.asScoped(request)` method instead to create an audit logger
*/
const getLogger = (id?: string): LegacyAuditLogger => {
return {
log: (eventType: string, message: string, data?: Record<string, any>) => {
if (!this.allowLegacyAuditLogging) {
return;
}
this.logger.info(message, {
tags: id ? [id, eventType] : [eventType],
eventType,
...data,
});
},
};
};
http.registerOnPostAuth((request, response, t) => {
if (request.auth.isAuthenticated) {
asScoped(request).log(httpRequestEvent({ request }));
}
return t.next();
});
return { asScoped, getLogger };
}
stop() {
if (this.licenseFeaturesSubscription) {
this.licenseFeaturesSubscription.unsubscribe();
this.licenseFeaturesSubscription = undefined;
}
clearInterval(this.usageIntervalId!);
}
}
export const createLoggingConfig = (config: ConfigType['audit']) =>
map<Pick<SecurityLicenseFeatures, 'allowAuditLogging'>, LoggerContextConfigInput>((features) => ({
appenders: {
auditTrailAppender: config.appender ?? {
type: 'console',
layout: {
type: 'pattern',
highlight: true,
},
},
},
loggers: [
{
name: 'audit.ecs',
level: config.enabled && config.appender && features.allowAuditLogging ? 'info' : 'off',
appenders: ['auditTrailAppender'],
},
],
}));
/**
* Evaluates the list of provided ignore rules, and filters out events only
* if *all* rules match the event.
*
* For event fields that can contain an array of multiple values, every value
* must be matched by an ignore rule for the event to be excluded.
*/
export function filterEvent(
event: AuditEvent,
ignoreFilters: ConfigType['audit']['ignore_filters']
) {
if (ignoreFilters) {
return !ignoreFilters.some(
(rule) =>
(!rule.actions || rule.actions.includes(event.event?.action!)) &&
(!rule.categories || event.event?.category?.every((c) => rule.categories?.includes(c))) &&
(!rule.types || event.event?.type?.every((t) => rule.types?.includes(t))) &&
(!rule.outcomes || rule.outcomes.includes(event.event?.outcome!)) &&
(!rule.spaces || rule.spaces.includes(event.kibana?.space_id!))
);
}
return true;
}