-
Notifications
You must be signed in to change notification settings - Fork 186
/
saved-objects.js
319 lines (296 loc) · 9.65 KB
/
saved-objects.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
/*
* Wazuh app - Saved Objects management service
* Copyright (C) 2015-2022 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Find more information about this on the LICENSE file.
*/
import { GenericRequest } from './generic-request';
import { KnownFields } from '../utils/known-fields';
import { FieldsStatistics } from '../utils/statistics-fields';
import { FieldsMonitoring } from '../utils/monitoring-fields';
import {
HEALTH_CHECK,
WAZUH_INDEX_TYPE_ALERTS,
WAZUH_INDEX_TYPE_MONITORING,
WAZUH_INDEX_TYPE_STATISTICS,
} from '../../common/constants';
import { satisfyPluginPlatformVersion } from '../../common/semver';
export class SavedObject {
/**
*
* Returns the full list of index patterns
*/
static async getListOfIndexPatterns() {
const savedObjects = await GenericRequest.request(
'GET',
`/api/saved_objects/_find?type=index-pattern&fields=title&fields=fields&per_page=9999`
);
let indexPatterns = ((savedObjects || {}).data || {}).saved_objects || [];
let indexPatternsFields;
if(satisfyPluginPlatformVersion('<7.11')){
indexPatternsFields = indexPatterns.map(indexPattern => indexPattern?.attributes?.fields ? JSON.parse(indexPattern.attributes.fields) : []);
}else if(satisfyPluginPlatformVersion('>=7.11')){
indexPatternsFields = await Promise.all(indexPatterns.map(async indexPattern => {
try{
const {data: {fields}} = await GenericRequest.request(
'GET',
`/api/index_patterns/_fields_for_wildcard?pattern=${indexPattern.attributes.title}`,
{}
);
return fields;
}catch(error){
return [];
}
}));
}
return indexPatterns.map((indexPattern, idx) => ({...indexPattern, _fields: indexPatternsFields[idx]}));
}
/**
*
* Returns the full list of index patterns that are valid
* An index is valid if its fields contain at least these 4 fields: 'timestamp', 'rule.groups', 'agent.id' and 'manager.name'
*/
static async getListOfWazuhValidIndexPatterns(defaultIndexPatterns, where) {
let result = [];
if (where === HEALTH_CHECK) {
const list = await Promise.all(
defaultIndexPatterns.map(
async (pattern) => await SavedObject.getExistingIndexPattern(pattern)
)
);
result = this.validateIndexPatterns(list);
}
if (!result.length) {
const list = await this.getListOfIndexPatterns();
result = this.validateIndexPatterns(list);
}
return result.map((item) => {
return { id: item.id, title: item.attributes.title };
});
}
static validateIndexPatterns(list) {
const requiredFields = [
'timestamp',
'rule.groups',
'manager.name',
'agent.id',
];
return list.filter(item => item && item._fields && requiredFields.every((reqField => item._fields.some(field => field.name === reqField))));
}
static async existsOrCreateIndexPattern(patternID) {
const result = await SavedObject.existsIndexPattern(patternID);
if (!result.data) {
let fields = '';
if (satisfyPluginPlatformVersion('<7.11')) {
fields = await SavedObject.getIndicesFields(patternID, WAZUH_INDEX_TYPE_ALERTS);
}
await this.createSavedObject(
'index-pattern',
patternID,
{
attributes: {
title: patternID,
timeFieldName: 'timestamp',
},
},
fields
);
}
}
/**
*
* Given an index pattern ID, checks if it exists
*/
static async existsIndexPattern(patternID) {
try {
const indexPatternData = await GenericRequest.request(
'GET',
`/api/saved_objects/index-pattern/${patternID}?fields=title&fields=fields`
);
const title = (((indexPatternData || {}).data || {}).attributes || {}).title;
const id = ((indexPatternData || {}).data || {}).id;
if (title) {
return {
data: 'Index pattern found',
status: true,
statusCode: 200,
title,
id,
};
}
} catch (error) {
return ((error || {}).data || {}).message || false
? error.data.message
: error.message || error;
}
}
/**
*
* Given an index pattern ID, checks if it exists
*/
static async getExistingIndexPattern(patternID) {
try {
const indexPatternData = await GenericRequest.request(
'GET',
`/api/saved_objects/index-pattern/${patternID}?fields=title&fields=fields`,
null,
true
);
let indexPatternFields;
if(satisfyPluginPlatformVersion('<7.11')){
indexPatternFields = indexPatternData?.data?.attributes?.fields ? JSON.parse(indexPatternData.data.attributes.fields) : [];
}else if(satisfyPluginPlatformVersion('>=7.11')){
try{
const {data: {fields}} = await GenericRequest.request(
'GET',
`/api/index_patterns/_fields_for_wildcard?pattern=${indexPatternData.data.attributes.title}`,
{}
);
indexPatternFields = fields;
} catch (error) {
indexPatternFields = [];
}
}
return { ...indexPatternData.data, ...{ _fields: indexPatternFields } };
} catch (error) {
if (error && error.response && error.response.status == 404) return false;
return Promise.reject(
((error || {}).data || {}).message || false
? error.data.message
: error.message || `Error getting the '${patternID}' index pattern`
);
}
}
static async createSavedObject(type, id, params, fields = '') {
try {
const result = await GenericRequest.request(
'POST',
`/api/saved_objects/${type}/${id}`,
params
);
if (satisfyPluginPlatformVersion('<7.11') && type === 'index-pattern') {
await this.refreshFieldsOfIndexPattern(id, params.attributes.title, fields);
}
return result;
} catch (error) {
throw ((error || {}).data || {}).message || false
? error.data.message
: error.message || error;
}
}
static async refreshFieldsOfIndexPattern(id, title, fields) {
try {
// same logic as plugin platform when a new index is created, you need to refresh it to see its fields
// we force the refresh of the index by requesting its fields and the assign these fields
await GenericRequest.request(
'PUT',
`/api/saved_objects/index-pattern/${id}`,
{
attributes: {
fields: JSON.stringify(fields),
timeFieldName: 'timestamp',
title: title
},
}
);
} catch (error) {
throw ((error || {}).data || {}).message || false
? error.data.message
: error.message || error;
}
}
/**
* Refresh an index pattern
* Optionally force a new field
*/
static async refreshIndexPattern(pattern, newFields = null) {
try {
const fields = await SavedObject.getIndicesFields(pattern.title, WAZUH_INDEX_TYPE_ALERTS);
if (newFields && typeof newFields == 'object')
Object.keys(newFields).forEach((fieldName) => {
if (this.isValidField(newFields[fieldName])) fields.push(newFields[fieldName]);
});
await this.refreshFieldsOfIndexPattern(pattern.id, pattern.title, fields);
} catch (error) {
return ((error || {}).data || {}).message || false
? error.data.message
: error.message || error;
}
}
/**
* Checks the field has a proper structure
* @param {index-pattern-field} field
*/
static isValidField(field) {
if (field == null || typeof field != 'object') return false;
const isValid = [
'name',
'type',
'esTypes',
'searchable',
'aggregatable',
'readFromDocValues',
].reduce((ok, prop) => {
return ok && Object.keys(field).includes(prop);
}, true);
return isValid;
}
/**
* Creates the 'wazuh-alerts-*' index pattern
*/
static async createWazuhIndexPattern(pattern) {
try {
const fields = satisfyPluginPlatformVersion('<7.11')
? await SavedObject.getIndicesFields(pattern, WAZUH_INDEX_TYPE_ALERTS)
: '';
await this.createSavedObject(
'index-pattern',
pattern,
{
attributes: {
title: pattern,
timeFieldName: 'timestamp',
fieldFormatMap: `{
"data.virustotal.permalink":{"id":"url"},
"data.vulnerability.reference":{"id":"url"},
"data.url":{"id":"url"}
}`,
fields: '[]',
sourceFilters: '[{"value":"@timestamp"}]',
},
},
fields
);
return;
} catch (error) {
throw ((error || {}).data || {}).message || false
? error.data.message
: error.message || error;
}
}
static getIndicesFields = async (pattern, indexType) => {
try {
const response = await GenericRequest.request(
//we check if indices exist before creating the index pattern
'GET',
`/api/index_patterns/_fields_for_wildcard?pattern=${pattern}&meta_fields=_source&meta_fields=_id&meta_fields=_type&meta_fields=_index&meta_fields=_score`,
{}
);
return response.data.fields;
} catch {
switch (indexType) {
case WAZUH_INDEX_TYPE_MONITORING:
return FieldsMonitoring;
case WAZUH_INDEX_TYPE_STATISTICS:
return FieldsStatistics;
case WAZUH_INDEX_TYPE_ALERTS:
return KnownFields;
}
}
};
}