/
index.js
449 lines (392 loc) · 11.6 KB
/
index.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import asyncIteratorToStream from 'async-iterator-to-stream'
import { alteredAuditRecord, missingAuditRecord } from 'xo-common/api-errors'
import { createGzip } from 'zlib'
import { createLogger } from '@xen-orchestra/log'
import { createSchedule } from '@xen-orchestra/cron'
import { fromCallback } from 'promise-toolbox'
import { pipeline } from 'readable-stream'
import { AlteredRecordError, AuditCore, MissingRecordError, NULL_ID, Storage } from '@xen-orchestra/audit-core'
const log = createLogger('xo:xo-server-audit')
const DEFAULT_BLOCKED_LIST = {
'acl.get': true,
'acl.getCurrentPermissions': true,
'audit.checkIntegrity': true,
'audit.clean': true,
'audit.deleteRange': true,
'audit.generateFingerprint': true,
'audit.getRecords': true,
'backup.list': true,
'backupNg.getAllJobs': true,
'backupNg.getAllLogs': true,
'backupNg.listVmBackups': true,
'cloud.getResourceCatalog': true,
'cloudConfig.getAll': true,
'group.getAll': true,
'host.isHostServerTimeConsistent': true,
'host.isHyperThreadingEnabled': true,
'host.stats': true,
'ipPool.getAll': true,
'job.getAll': true,
'log.get': true,
'metadataBackup.getAllJobs': true,
'network.getBondModes': true,
'pif.getIpv4ConfigurationModes': true,
'plugin.get': true,
'pool.listMissingPatches': true,
'proxy.getAll': true,
'proxy.getApplianceUpdaterState': true,
'remote.getAll': true,
'remote.getAllInfo': true,
'remote.list': true,
'resourceSet.getAll': true,
'role.getAll': true,
'schedule.getAll': true,
'server.getAll': true,
'session.getUser': true,
'session.signIn': true,
'sr.getAllUnhealthyVdiChainsLength': true,
'sr.getVdiChainsInfo': true,
'sr.stats': true,
'system.getMethodsInfo': true,
'system.getServerTimezone': true,
'system.getServerVersion': true,
'user.getAll': true,
'vm.getHaValues': true,
'vm.stats': true,
'xo.getAllObjects': true,
'xoa.check': true,
'xoa.clearCheckCache': true,
'xoa.getApplianceInfo': true,
'xoa.getHVSupportedVersions': true,
'xoa.licenses.get': true,
'xoa.licenses.getAll': true,
'xoa.licenses.getSelf': true,
'xoa.supportTunnel.getState': true,
'xosan.checkSrCurrentState': true,
'xosan.computeXosanPossibleOptions': true,
'xosan.getVolumeInfo': true,
}
const LAST_ID = 'lastId'
// interface Db {
// lastId: string
// [RecordId: string]: {
// data: object
// event: string
// id: strings
// previousId: string
// subject: {
// userId: string
// userIp: string
// userName: string
// }
// time: number
// }
// }
class Db extends Storage {
constructor(db) {
super()
this._db = db
}
async put(record) {
await this._db.put(record.id, record)
}
async del(id) {
await this._db.del(id)
}
get(id) {
return this._db.get(id).catch(error => {
if (!error.notFound) {
throw error
}
})
}
async setLastId(id) {
await this._db.put(LAST_ID, id)
}
getLastId() {
return this.get(LAST_ID)
}
async clean() {
const db = this._db
// delete first so that a new chain can be constructed even if anything else fails
await db.del(LAST_ID)
return new Promise((resolve, reject) => {
let count = 1
const cb = () => {
if (--count === 0) {
resolve()
}
}
const deleteEntry = key => {
++count
db.del(key, cb)
}
db.createKeyStream().on('data', deleteEntry).on('end', cb).on('error', reject)
})
}
}
export const configurationSchema = {
type: 'object',
properties: {
active: {
description: 'Whether to save user actions in the audit log',
type: 'boolean',
},
},
}
const NAMESPACE = 'audit'
class AuditXoPlugin {
constructor({ staticConfig, xo }) {
this._blockedList = {
...DEFAULT_BLOCKED_LIST,
...staticConfig.blockedList,
}
this._cleaners = []
this._xo = xo
const { enabled = true, schedule: { cron = '0 6 * * *', timezone } = {} } = staticConfig.lastHashUpload ?? {}
if (enabled) {
this._uploadLastHashJob = createSchedule(cron, timezone).createJob(() => this._uploadLastHash().catch(log.error))
}
this._auditCore = undefined
this._storage = undefined
this._listeners = {
'xo:audit': this._handleEvent.bind(this),
'xo:postCall': this._handleEvent.bind(this, 'apiCall'),
}
}
configure({ active = false }, { loaded }) {
this._active = active
if (loaded) {
this._addListeners()
}
}
async load() {
const storage = (this._storage = new Db(await this._xo.getStore(NAMESPACE)))
this._auditCore = new AuditCore(storage)
const cleaners = this._cleaners
cleaners.push(() => {
this._auditCore = undefined
this._storage = undefined
})
this._addListeners()
const exportRecords = this._exportRecords.bind(this)
exportRecords.permission = 'admin'
const getRecords = this._getRecords.bind(this)
getRecords.description = 'Get records from a passed record ID'
getRecords.permission = 'admin'
getRecords.params = {
id: { type: 'string', optional: true },
// null is used to bypass the default limit
maxRecords: { type: ['number', 'null'], optional: true },
ndjson: { type: 'boolean', optional: true },
}
const checkIntegrity = this._checkIntegrity.bind(this)
checkIntegrity.description = 'Check records integrity between oldest and newest'
checkIntegrity.permission = 'admin'
checkIntegrity.params = {
newest: { type: 'string', optional: true },
oldest: { type: 'string', optional: true },
}
const generateFingerprint = this._generateFingerprint.bind(this)
generateFingerprint.description = 'Generate a fingerprint of the chain oldest-newest'
generateFingerprint.permission = 'admin'
generateFingerprint.params = {
newest: { type: 'string', optional: true },
oldest: { type: 'string', optional: true },
}
const uploadLastHashJob = this._uploadLastHashJob
if (uploadLastHashJob !== undefined) {
uploadLastHashJob.start()
cleaners.push(() => uploadLastHashJob.stop())
}
const clean = this._storage.clean.bind(this._storage)
clean.permission = 'admin'
clean.description = 'Clean audit database'
const deleteRange = this._deleteRangeAndRewrite.bind(this)
deleteRange.description = 'Delete a range of records and rewrite the records chain'
deleteRange.permission = 'admin'
deleteRange.params = {
newest: { type: 'string' },
oldest: { type: 'string', optional: true },
}
cleaners.push(
this._xo.addApiMethods({
audit: {
checkIntegrity,
clean,
deleteRange,
exportRecords,
generateFingerprint,
getRecords,
},
})
)
}
unload() {
this._removeListeners()
this._cleaners.forEach(cleaner => cleaner())
this._cleaners.length = 0
}
_addListeners(event, listener_) {
this._removeListeners()
if (this._active) {
const listeners = this._listeners
Object.keys(listeners).forEach(event => {
this._xo.addListener(event, listeners[event])
})
}
}
_removeListeners() {
const listeners = this._listeners
Object.keys(listeners).forEach(event => {
this._xo.removeListener(event, listeners[event])
})
}
async _handleEvent(event, { userId, userIp, userName, ...data }) {
try {
if (event !== 'apiCall' || !this._blockedList[data.method]) {
return await this._auditCore.add(
{
userId,
userIp,
userName,
},
event,
data
)
}
} catch (error) {
log.error(error)
}
}
async _getRecords({ id, maxRecords = 10e3, ndjson = false }) {
if (ndjson) {
return this._xo
.registerHttpRequest((req, res) => {
res.set('Content-Type', 'application/json')
return fromCallback(pipeline, this._getRecordsStream(id, maxRecords === null ? undefined : maxRecords), res)
})
.then($getFrom => ({
$getFrom,
}))
}
const records = []
for await (const record of this._auditCore.getFrom(id)) {
records.push(record)
}
return records
}
_exportRecords() {
return this._xo
.registerHttpRequest(
(req, res) => {
res.set({
'content-disposition': 'attachment',
'content-type': 'application/x-gzip',
})
return fromCallback(pipeline, this._getRecordsStream(), createGzip(), res)
},
undefined,
{
suffix: `/audit-records-${new Date().toISOString().replace(/:/g, '_')}.ndjson.gz`,
}
)
.then($getFrom => ({
$getFrom,
}))
}
// See www-xo#344
async _uploadLastHash() {
const xo = this._xo
// In case of non-existent XOA plugin
if (xo.audit === undefined) {
return
}
const lastRecordId = await this._storage.getLastId()
if (lastRecordId === undefined) {
return
}
const chain = await xo.audit.getLastChain()
let lastValidHash
if (chain !== null) {
const hashes = chain.hashes
lastValidHash = hashes[hashes.length - 1]
if (lastValidHash === lastRecordId) {
return
}
// check the integrity of all stored hashes
try {
for (let i = 0; i < hashes.length - 1; ++i) {
await this._checkIntegrity({
oldest: hashes[i],
newest: hashes[i + 1],
})
}
} catch (error) {
if (!missingAuditRecord.is(error) && !alteredAuditRecord.is(error)) {
throw error
}
lastValidHash = undefined
}
}
// generate a valid fingerprint of all stored records in case of a failure integrity check
const { oldest, newest, error } = await this._generateFingerprint({
oldest: lastValidHash,
})
if (lastValidHash === undefined || error !== undefined) {
await xo.audit.startNewChain({ oldest, newest })
} else {
await xo.audit.extendLastChain({ oldest, newest })
}
}
async _checkIntegrity(props) {
const { oldest = NULL_ID, newest = await this._storage.getLastId() } = props
return this._auditCore.checkIntegrity(oldest, newest).catch(error => {
if (error instanceof MissingRecordError) {
throw missingAuditRecord(error)
}
if (error instanceof AlteredRecordError) {
throw alteredAuditRecord(error)
}
throw error
})
}
async _generateFingerprint(props) {
const { oldest = NULL_ID, newest = (await this._storage.getLastId()) ?? NULL_ID } = props
try {
return {
fingerprint: `${oldest}|${newest}`,
newest,
nValid: newest !== NULL_ID ? await this._checkIntegrity({ oldest, newest }) : 0,
oldest,
}
} catch (error) {
if (missingAuditRecord.is(error) || alteredAuditRecord.is(error)) {
return {
error,
fingerprint: `${error.data.id}|${newest}`,
newest,
nValid: error.data.nValid,
oldest: error.data.id,
}
}
throw error
}
}
async _deleteRangeAndRewrite({ newest, oldest = newest }) {
await this._auditCore.deleteRangeAndRewrite(newest, oldest)
if (this._uploadLastHashJob !== undefined) {
await this._uploadLastHash()
}
}
}
AuditXoPlugin.prototype._getRecordsStream = asyncIteratorToStream(async function* (id, maxRecords = Infinity) {
for await (const record of this._auditCore.getFrom(id)) {
if (--maxRecords < 0) {
break
}
yield JSON.stringify(record)
yield '\n'
}
})
export default opts => new AuditXoPlugin(opts)