wazuh-kibana-app/server/initialize.js

762 lines
36 KiB
JavaScript
Raw Normal View History

2017-10-27 09:07:38 +00:00
const needle = require('needle');
2018-03-12 11:57:14 +00:00
const colors = require('ansicolors');
2017-10-27 09:07:38 +00:00
const blueWazuh = colors.blue('wazuh');
2018-03-12 11:57:14 +00:00
const fs = require('fs');
const yml = require('js-yaml');
const path = require('path');
const { log } = require('./logger');
2017-10-27 09:07:38 +00:00
2018-03-22 14:59:56 +00:00
const KIBANA_TEMPLATE = './integration-files/kibana-template';
const knownFields = require('./integration-files/known-fields')
2018-03-12 11:29:24 +00:00
2018-03-11 17:57:32 +00:00
2017-10-27 09:07:38 +00:00
module.exports = (server, options) => {
2018-03-12 11:29:24 +00:00
log('initialize.js', 'Initializing', 'info');
2018-03-12 10:27:19 +00:00
// Elastic JS Client
const elasticRequest = server.plugins.elasticsearch.getCluster('data');
2016-12-13 15:32:35 +00:00
2018-03-12 11:29:24 +00:00
let objects = {};
let app_objects = {};
let kibana_template = {};
let packageJSON = {};
let configurationFile = {};
2018-03-12 11:29:24 +00:00
let pattern = null;
// Read config from package.json and config.yml
try {
2018-03-12 11:29:24 +00:00
configurationFile = yml.load(fs.readFileSync(path.join(__dirname, '../config.yml'), { encoding: 'utf-8' }));
global.loginEnabled = (configurationFile && typeof configurationFile['login.enabled'] !== 'undefined') ? configurationFile['login.enabled'] : false;
2018-03-12 11:29:24 +00:00
pattern = (configurationFile && typeof configurationFile.pattern !== 'undefined') ? configurationFile.pattern : 'wazuh-alerts-3.x-*';
packageJSON = require('../package.json');
} catch (e) {
2018-03-12 11:57:14 +00:00
log('initialize.js', e.message || e);
server.log([blueWazuh, 'initialize', 'error'], 'Something went wrong while reading the configuration.' + e.message);
}
2018-03-12 11:29:24 +00:00
if (typeof global.sessions === 'undefined') {
global.sessions = {};
}
global.protectedRoute = req => {
2018-03-12 11:29:24 +00:00
if (!loginEnabled) return true;
const session = (req.headers && req.headers.code) ? sessions[req.headers.code] : null;
2018-03-12 11:29:24 +00:00
if (!session) return false;
const timeElapsed = (new Date() - session.created) / 1000;
2018-03-12 11:29:24 +00:00
if (timeElapsed >= session.exp) {
delete sessions[req.payload.code];
return false;
}
return true;
}
2017-09-29 05:26:18 +00:00
2018-01-24 11:54:19 +00:00
let index_pattern = pattern || "wazuh-alerts-3.x-*";
2018-03-15 17:36:35 +00:00
/**
* This function creates a new index pattern with a custom ID.
* @param {*} patternId 'index-pattern:' + id;
* @param {*} id Eg: 'wazuh-alerts'
*/
const createCustomPattern = async (patternId,id) => {
try{
if(!id) return Promise.reject(new Error('No valid id for index pattern'));
if(!patternId) return Promise.reject(new Error('No valid patternId for index pattern'));
const customPatternRegex = new RegExp(/[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}/g);
if(id && customPatternRegex.test(id.trim())){
server.log([blueWazuh, 'initialize', 'info'], 'Custom id detected for index pattern...');
2018-03-23 12:59:16 +00:00
id = (configurationFile && typeof configurationFile.pattern !== 'undefined') ? configurationFile.pattern : 'wazuh-alerts-3.x-*';
patternId = 'index-pattern:' + id.trim();
server.log([blueWazuh, 'initialize', 'info'], 'Modified values to be default values, now checking if default index pattern exists...');
const data = await elasticRequest
.callWithInternalUser('search', {
index: '.kibana',
type: 'doc',
body: {
"query": {
"match": {
"_id":"index-pattern:" + id
}
}
}
});
if(data && data.hits && data.hits.total > 0) {
server.log([blueWazuh, 'initialize', 'info'], 'Default index pattern exists, skipping its creation...');
return id;
}
}
await elasticRequest
.callWithInternalUser('create', {
index: '.kibana',
type: 'doc',
id: patternId,
body: {
"type": 'index-pattern',
"index-pattern": {
"title": id,
"timeFieldName": '@timestamp'
}
}
});
return id;
}catch(error){
return Promise.reject(error)
}
}
2018-03-15 17:36:35 +00:00
/**
* This function checks if an index pattern exists,
* you should check response.hits.total
* @param {*} id Eg: 'wazuh-alerts'
*/
const searchIndexPatternById = async id => {
try {
if(!id) return Promise.reject(new Error('No valid id for search index pattern'))
const data = await elasticRequest
.callWithInternalUser('search', {
index: '.kibana',
type: 'doc',
body: {
"query": {
"match": {
"_id":"index-pattern:" + id
}
}
}
});
return data;
} catch (error) {
return Promise.reject(error);
}
}
2018-03-15 17:36:35 +00:00
/**
* Updates .kibana index known fields
* @param {*} patternId 'index-pattern:' + id
*/
const updateKibanaIndexWithKnownFields = async patternId => {
try {
if(!patternId) return Promise.reject(new Error('No valid patternId for update index pattern'))
const newFields = JSON.stringify(knownFields);
await elasticRequest
.callWithInternalUser('update', {
index: '.kibana',
type: 'doc',
id: patternId,
body: {
doc: {
"type": 'index-pattern',
"index-pattern": {
"fields": newFields,
"fieldFormatMap": '{"data.virustotal.permalink":{"id":"url"},"data.vulnerability.reference":{"id":"url"},"data.url":{"id":"url"}}'
}
}
}
});
return;
} catch (error) {
return Promise.reject(error);
}
}
2018-03-15 17:36:35 +00:00
/**
* Create index pattern for wazuh alerts
2018-03-15 17:36:35 +00:00
* @param {*} id Eg: 'wazuh-alerts'
* @param {*} firstTime Optional, if true it means that is the very first time of execution.
*/
const importAppObjects = async (id,firstTime) => {
try {
2018-03-21 14:47:47 +00:00
const xpack = await elasticRequest.callWithInternalUser('cat.plugins', { });
log('initialize.js importAppObjects', `x-pack enabled: ${typeof xpack === 'string' && xpack.includes('x-pack') ? 'yes' : 'no'}`,'info')
server.log([blueWazuh, 'initialize', 'info'], `x-pack enabled: ${typeof xpack === 'string' && xpack.includes('x-pack') ? 'yes' : 'no'}`);
2018-03-24 11:04:30 +00:00
let patternId = 'index-pattern:' + id;
let indexPatternList = await searchIndexPatternById(id);
if (!firstTime && indexPatternList.hits.total < 1) {
log('initialize.js importAppObjects', 'Wazuh alerts index pattern not found. Creating it...','info')
server.log([blueWazuh, 'initialize', 'info'], 'Wazuh alerts index pattern not found. Creating it...');
id = await createCustomPattern(patternId,id)
firstTime = true;
}
patternId = 'index-pattern:' + id;
if(firstTime && indexPatternList.hits.total < 1){
log('initialize.js importAppObjects', 'Waiting for index pattern creation to complete...','info')
server.log([blueWazuh, 'initialize', 'info'], 'Waiting for index pattern creation to complete...');
let waitTill = new Date(new Date().getTime() + 0.5 * 1000);
while(waitTill > new Date()){
indexPatternList = await searchIndexPatternById(id);
if(indexPatternList.hits.total >= 1) break;
else waitTill = new Date(new Date().getTime() + 0.5 * 1000);
}
server.log([blueWazuh, 'initialize', 'info'], 'Index pattern created...');
}
log('initialize.js importAppObjects', 'Importing/Updating index pattern known fields...','info')
server.log([blueWazuh, 'initialize', 'info'], 'Importing/Updating index pattern known fields...');
await updateKibanaIndexWithKnownFields(patternId)
await elasticRequest.callWithInternalUser('indices.refresh', { index: ['.kibana', index_pattern]})
log('initialize.js importAppObjects', 'App ready to be used.','info')
server.log([blueWazuh, 'initialize', 'info'], 'App ready to be used.');
return;
} catch (error){
log('initialize.js importAppObjects', error.message || error);
server.log([blueWazuh, 'server', 'error'], 'Error importing objects into elasticsearch.' + error.message || error);
}
};
// Create index pattern TODO: remove hardcoded index-patterns ids
2018-04-02 09:23:57 +00:00
const createIndexPattern = async () => {
try {
log('initialize.js createIndexPattern', `Creating index pattern: ${index_pattern}`,'info')
server.log([blueWazuh, 'initialize', 'info'], `Creating index pattern: ${index_pattern}`);
let patternId = 'index-pattern:' + index_pattern;
await elasticRequest.callWithInternalUser('create', {
index: '.kibana',
type: 'doc',
id: patternId,
body: {
type: 'index-pattern',
'index-pattern': {
title: index_pattern,
timeFieldName: '@timestamp'
}
2018-03-12 11:29:24 +00:00
}
});
2018-04-02 09:23:57 +00:00
log('initialize.js createIndexPattern', `Created index pattern: ${index_pattern}`,'info')
server.log([blueWazuh, 'initialize', 'info'], 'Created index pattern: ' + index_pattern);
2018-04-02 09:23:57 +00:00
} catch (error){
log('initialize.js createIndexPattern', error.message || error);
server.log([blueWazuh, 'initialize', 'error'], 'Error creating index-pattern.');
}
};
2017-09-29 05:26:18 +00:00
// Configure Kibana status: Index pattern, default index pattern, default time, import dashboards.
2018-04-02 09:23:57 +00:00
const configureKibana = async type => {
try{
if (type === 'install') {
const data = await elasticRequest.callWithInternalUser('search', {
index: '.kibana',
type: 'doc',
q: `index-pattern.title:"${index_pattern}"`
2018-03-12 11:29:24 +00:00
})
2018-04-02 09:23:57 +00:00
if (data.hits.total >= 1) {
log('initialize.js configureKibana', 'Skipping index-pattern creation. Already exists.','info')
server.log([blueWazuh, 'initialize', 'info'], 'Skipping index-pattern creation. Already exists.');
} else {
return createIndexPattern();
}
}
return;
} catch(error) {
log('initialize.js configureKibana', error.message || error);
server.log([blueWazuh, 'initialize', 'error'], 'Could not reach elasticsearch.');
}
};
2017-09-29 05:26:18 +00:00
// Save Wazuh App setup
2018-04-02 09:23:57 +00:00
const saveConfiguration = async () => {
try{
let shards = 1;
let replicas = 1;
if (configurationFile) {
if (configurationFile["wazuh-version.shards"]) {
shards = configurationFile["wazuh-version.shards"];
}
if (configurationFile["wazuh-version.replicas"]) {
replicas = configurationFile["wazuh-version.replicas"];
}
}
2018-04-02 09:23:57 +00:00
const shard_configuration = {
settings: {
index: {
number_of_shards : shards,
number_of_replicas: replicas
}
}
};
await elasticRequest.callWithInternalUser('indices.create', {
index: '.wazuh-version',
body : shard_configuration
})
const commonDate = new Date().toISOString();
const configuration = {
name : 'Wazuh App',
'app-version' : packageJSON.version,
revision : packageJSON.revision,
installationDate: commonDate,
lastRestart : commonDate
};
2018-04-02 09:23:57 +00:00
try{
await elasticRequest.callWithInternalUser('create', {
index: '.wazuh-version',
type : 'wazuh-version',
id : 1,
body : configuration
})
2018-03-13 11:02:08 +00:00
log('initialize.js saveConfiguration', 'Wazuh configuration inserted','info')
server.log([blueWazuh, 'initialize', 'info'], 'Wazuh configuration inserted');
2018-04-02 09:23:57 +00:00
} catch (error){
2018-03-12 11:29:24 +00:00
log('initialize.js saveConfiguration', error.message || error);
2018-03-13 11:02:08 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Could not insert Wazuh configuration');
2018-04-02 09:23:57 +00:00
}
return;
} catch (error){
2018-03-13 11:02:08 +00:00
log('initialize.js saveConfiguration', error.message || error);
server.log([blueWazuh, 'initialize', 'error'], 'Error creating index .wazuh-version.');
2018-04-02 09:23:57 +00:00
}
};
const checkWazuhIndex = async () => {
try{
const result = await elasticRequest.callWithInternalUser('indices.exists', {
index: '.wazuh'
})
if (!result) {
let shards = 1;
let replicas = 1;
if (configurationFile) {
if (configurationFile["wazuh.shards"]) {
shards = configurationFile["wazuh.shards"];
}
if (configurationFile["wazuh.replicas"]) {
replicas = configurationFile["wazuh.replicas"];
}
}
let configuration = {
"settings": {
"index": {
"number_of_shards": shards,
"number_of_replicas": replicas
}
}
};
try{
await elasticRequest.callWithInternalUser('indices.create', {
index: '.wazuh',
body: configuration
})
2018-03-13 11:02:08 +00:00
log('initialize.js init', 'Index .wazuh created.','info')
server.log([blueWazuh, 'initialize', 'info'], 'Index .wazuh created.');
} catch(error) {
throw new Error('Error creating index .wazuh.');
}
} else { // The .wazuh index exists, we now proceed to check whether it's from an older version
try{
await elasticRequest.callWithInternalUser('get', {
index: ".wazuh",
type: "wazuh-setup",
id: "1"
})
2018-03-13 11:02:08 +00:00
// Reindex!
return reindexOldVersion();
} catch(error) {
2018-03-13 11:02:08 +00:00
if (error.message && error.message !== 'Not Found') {
throw new Error(error.message || error);
2018-03-13 11:02:08 +00:00
}
server.log([blueWazuh, 'initialize', 'info'], 'No older .wazuh index found -> no need to reindex.');
}
}
} catch (error) {
return Promise.reject(error);
}
}
const checkWazuhVersionIndex = async () => {
try {
try{
await elasticRequest.callWithInternalUser('get', {
index: ".wazuh-version",
type: "wazuh-version",
id: "1"
})
} catch (error) {
log('initialize.js init 6', error.message || error);
server.log([blueWazuh, 'initialize', 'info'], '.wazuh-version document does not exist. Initializating configuration...');
// Save Setup Info
await saveConfiguration(index_pattern);
await configureKibana("install");
2018-03-13 11:02:08 +00:00
}
server.log([blueWazuh, 'initialize', 'info'], '.wazuh-version document already exists. Updating version information...');
await elasticRequest.callWithInternalUser('update', {
index: '.wazuh-version',
type : 'wazuh-version',
id : 1,
body : {
doc: {
'app-version': packageJSON.version,
revision : packageJSON.revision,
lastRestart: new Date().toISOString() // Indice exists so we update the lastRestarted date only
}
}
});
2018-01-16 19:02:46 +00:00
server.log([blueWazuh, 'initialize', 'info'], 'Successfully updated version information');
} catch (error) {
return Promise.reject(error);
}
}
// Init function. Check for "wazuh-version" document existance.
const init = async () => {
try {
await Promise.all([
checkWazuhIndex(),
checkWazuhVersionIndex()
]);
} catch (error){
log('initialize.js init()', error.message || error);
server.log([blueWazuh, 'initialize.js init()', 'error'], error.message || error);
return Promise.reject(error)
}
};
2017-10-27 09:07:38 +00:00
const createKibanaTemplate = () => {
2018-03-12 11:57:14 +00:00
log('initialize.js createKibanaTemplate', 'Creating template for .kibana.','info')
server.log([blueWazuh, 'initialize', 'info'], 'Creating template for .kibana.');
2018-03-12 11:29:24 +00:00
try {
kibana_template = require(KIBANA_TEMPLATE);
2018-03-12 11:57:14 +00:00
} catch (error) {
log('initialize.js init 6', error.message || error);
server.log([blueWazuh, 'initialize', 'error'], 'Could not read the .kibana template file.');
server.log([blueWazuh, 'initialize', 'error'], 'Path: ' + KIBANA_TEMPLATE);
2018-03-12 11:57:14 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Exception: ' + error);
}
2018-04-02 09:23:57 +00:00
return elasticRequest.callWithInternalUser('indices.putTemplate',{
name : 'wazuh-kibana',
order : 0,
create: true,
body : kibana_template
});
2017-12-14 12:24:51 +00:00
};
// Does .kibana index exist?
2018-03-12 11:29:24 +00:00
const checkKibanaStatus = () => {
elasticRequest.callWithInternalUser('indices.exists', {
index: ".kibana"
})
2018-03-12 11:29:24 +00:00
.then(data => {
if (data) { // It exists, initialize!
init();
}
else { // No .kibana index created...
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus', 'Didn\'t find .kibana index...','info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'info'], "Didn't find .kibana index...");
2018-03-12 11:29:24 +00:00
elasticRequest.callWithInternalUser('indices.getTemplate',
{
name: 'wazuh-kibana'
})
.then(data => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus', 'No need to create the .kibana template, already exists.','info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'info'], 'No need to create the .kibana template, already exists.');
elasticRequest.callWithInternalUser('indices.create', { index: '.kibana' })
.then(data => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus', 'Successfully created .kibana index.','info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'info'], 'Successfully created .kibana index.');
init();
})
.catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus',error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Error creating .kibana index due to ' + error);
});
})
.catch(error => {
2018-03-12 11:29:24 +00:00
log('initialize.js checkKibanaStatus',
error.message || error
);
createKibanaTemplate()
.then(data => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus', 'Successfully created .kibana template.','info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'info'], 'Successfully created .kibana template.');
elasticRequest.callWithInternalUser('indices.create', { index: '.kibana' })
.then(data => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus', 'Successfully created .kibana index.','info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'info'], 'Successfully created .kibana index.');
init();
})
.catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus',error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Error creating .kibana index due to ' + error);
});
}).catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus',error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Error creating template for .kibana due to ' + error);
});
});
2018-03-12 11:29:24 +00:00
}
})
.catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js checkKibanaStatus',error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'initialize', 'error'], 'Could not check .kibana index due to ' + error);
});
2017-12-05 15:02:09 +00:00
};
// Wait until Elasticsearch js is ready
2018-04-02 09:23:57 +00:00
const checkStatus = async () => {
try{
await server.plugins.elasticsearch.waitUntilReady();
return checkKibanaStatus();
} catch (error){
log('initialize.js checkStatus',error.message || error);
server.log([blueWazuh, 'initialize', 'info'], 'Waiting for elasticsearch plugin to be ready...');
setTimeout(() => checkStatus(), 3000);
}
};
2017-10-27 09:07:38 +00:00
2017-12-05 15:02:09 +00:00
const reachAPI = (wapi_config) => {
// Now, let's see whether they have a 2.x or 3.x version
let id = wapi_config._id;
wapi_config = wapi_config._source;
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'Reaching ' + wapi_config.manager,'info')
2017-12-05 15:02:09 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'Reaching ' + wapi_config.manager);
let decoded_password = Buffer.from(wapi_config.api_password, 'base64').toString("ascii");
if (wapi_config.cluster_info === undefined) { // No cluster_info in the API configuration data -> 2.x version
needle('get', `${wapi_config.url}:${wapi_config.api_port}/version`, {}, {
2018-03-12 11:29:24 +00:00
username: wapi_config.api_user,
password: decoded_password,
2017-12-05 15:02:09 +00:00
rejectUnauthorized: !wapi_config.insecure
})
2018-03-12 11:57:14 +00:00
.then(response => {
log('initialize.js reachAPI', 'API is reachable ' + wapi_config.manager,'info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'API is reachable ' + wapi_config.manager);
if (parseInt(response.body.error) === 0 && response.body.data) {
needle('get', `${wapi_config.url}:${wapi_config.api_port}/cluster/status`, {}, { // Checking the cluster status
username: wapi_config.api_user,
password: decoded_password,
rejectUnauthorized: !wapi_config.insecure
})
.then((response) => {
if (!response.body.error) {
if (response.body.data.enabled === 'yes') { // If cluster mode is active
needle('get', `${wapi_config.url}:${wapi_config.api_port}/cluster/node`, {}, {
username: wapi_config.api_user,
password: decoded_password,
rejectUnauthorized: !wapi_config.insecure
})
.then((response) => {
if (!response.body.error) {
wapi_config.cluster_info = {};
wapi_config.cluster_info.status = 'enabled';
wapi_config.cluster_info.manager = wapi_config.manager;
wapi_config.cluster_info.node = response.body.data.node;
wapi_config.cluster_info.cluster = response.body.data.cluster;
} else if (response.body.error) {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', response.body.error || response.body);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'error'], 'Could not get cluster/node information for ', wapi_config.manager);
}
});
}
else { // Cluster mode is not active
2017-12-05 15:02:09 +00:00
wapi_config.cluster_info = {};
2018-03-12 11:29:24 +00:00
wapi_config.cluster_info.status = 'disabled';
wapi_config.cluster_info.cluster = 'Disabled';
2017-12-05 15:02:09 +00:00
wapi_config.cluster_info.manager = wapi_config.manager;
}
2018-03-12 11:29:24 +00:00
// We filled data for the API, let's insert it now
elasticRequest.callWithInternalUser('update', {
index: '.wazuh',
2018-04-02 09:23:57 +00:00
type : 'wazuh-configuration',
id : id,
2018-03-12 11:29:24 +00:00
body: {
'doc': {
2018-04-02 09:23:57 +00:00
"api_user" : wapi_config.api_user,
2018-03-12 11:29:24 +00:00
"api_password": wapi_config.api_password,
2018-04-02 09:23:57 +00:00
"url" : wapi_config.url,
"api_port" : wapi_config.api_port,
"manager" : wapi_config.manager,
2018-03-12 11:29:24 +00:00
"cluster_info": {
"manager": wapi_config.manager,
2018-04-02 09:23:57 +00:00
"node" : wapi_config.cluster_info.node,
2018-03-12 11:29:24 +00:00
"cluster": wapi_config.cluster_info.cluster,
2018-04-02 09:23:57 +00:00
"status" : wapi_config.cluster_info.status
2018-03-12 11:29:24 +00:00
},
}
}
})
.then(resp => {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'Successfully updated proper cluster information for ' + wapi_config.manager,'info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'Successfully updated proper cluster information for ' + wapi_config.manager);
})
.catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'error'], 'Could not update proper cluster information for ' + wapi_config.manager + 'due to ' + err);
});
} else {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'Could not get cluster/status information for ' + wapi_config.manager)
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'error'], 'Could not get cluster/status information for ' + wapi_config.manager);
}
2017-12-05 15:02:09 +00:00
});
2018-03-12 11:29:24 +00:00
} else {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'The API responded with some kind of error for ' + wapi_config.manager)
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'error'], 'The API responded with some kind of error for ' + wapi_config.manager);
}
2017-12-05 15:02:09 +00:00
})
.catch(error => {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', error.message || error);
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'API is NOT reachable ' + wapi_config.manager);
// We weren't able to reach the API, reorganize data and fill with sample node and cluster name information
elasticRequest.callWithInternalUser('update', {
index: '.wazuh',
type: 'wazuh-configuration',
id: id,
body: {
'doc': {
"api_user": wapi_config.api_user,
"api_password": wapi_config.api_password,
"url": wapi_config.url,
"api_port": wapi_config.api_port,
"manager": wapi_config.manager,
"cluster_info": {
"manager": wapi_config.manager,
"node": "nodata",
"cluster": "nodata",
"status": "disabled"
},
}
}
})
.then(resp => {
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'Successfully updated sample cluster information for ' + wapi_config.manager,'info')
2018-03-12 11:29:24 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'Successfully updated sample cluster information for ' + wapi_config.manager);
})
.catch(error => {
log('initialize.js reachAPI', error.message || error);
server.log([blueWazuh, 'reindex', 'error'], 'Could not update sample cluster information for ' + wapi_config.manager + 'due to ' + err);
});
2017-12-05 15:02:09 +00:00
});
} else { // 3.x version
// Nothing to be done, cluster_info is present
2018-03-12 11:57:14 +00:00
log('initialize.js reachAPI', 'Nothing to be done for ' + wapi_config.manager + ' as it is already a 3.x version.' + wapi_config.manager,'info')
2017-12-05 15:02:09 +00:00
server.log([blueWazuh, 'reindex', 'info'], 'Nothing to be done for ' + wapi_config.manager + ' as it is already a 3.x version.');
}
};
// Reindex a .wazuh index from 2.x-5.x or 3.x-5.x to .wazuh and .wazuh-version in 3.x-6.x
2018-04-02 09:23:57 +00:00
const reindexOldVersion = async () => {
try {
log('initialize.js reindexOldVersion', `Old version detected. Proceeding to reindex.`,'info')
server.log([blueWazuh, 'reindex', 'info'], `Old version detected. Proceeding to reindex.`);
const configuration = {
source: {
index: '.wazuh',
type : 'wazuh-configuration'
},
dest: {
index: '.old-wazuh'
}
};
// Backing up .wazuh index
await elasticRequest.callWithInternalUser('reindex', { body: configuration })
2017-12-05 15:02:09 +00:00
2018-04-02 09:23:57 +00:00
log('initialize.js reindexOldVersion', 'Successfully backed up .wazuh index','info')
// And...this response does not take into acount new index population so...let's wait for it
server.log([blueWazuh, 'reindex', 'info'], 'Successfully backed up .wazuh index');
setTimeout(() => swapIndex(), 3000);
2017-12-05 15:02:09 +00:00
2018-04-02 09:23:57 +00:00
} catch(error) {
log('initialize.js reindexOldVersion', error.message || error);
server.log([blueWazuh, 'reindex', 'error'], 'Could not begin the reindex process: ' + error.message || error);
}
2017-12-05 15:02:09 +00:00
};
2018-04-02 09:23:57 +00:00
const swapIndex = async () => {
try {
// Deleting old .wazuh index
log('initialize.js swapIndex', 'Deleting old .wazuh index','info');
server.log([blueWazuh, 'reindex', 'info'], 'Deleting old .wazuh index.');
await elasticRequest.callWithInternalUser('indices.delete', { index: ".wazuh" })
const configuration = {
"source": {
"index": ".old-wazuh",
"type": "wazuh-configuration"
},
"dest": {
"index": ".wazuh"
},
"script": {
"source": "ctx._id = new Date().getTime()",
"lang": "painless"
2018-03-12 11:29:24 +00:00
}
2018-04-02 09:23:57 +00:00
};
log('initialize.js swapIndex', 'Reindexing into the new .wazuh','info');
server.log([blueWazuh, 'reindex', 'info'], 'Reindexing into the new .wazuh');
// Reindexing from .old-wazuh where the type of document is wazuh-configuration into the new index .wazuh
await elasticRequest.callWithInternalUser('reindex', { body: configuration })
// Now we need to properly replace the cluster_info into the configuration -> improvement: pagination?
// And...this response does not take into acount new index population so...let's wait for it
setTimeout(() => reachAPIs(), 3000);
} catch(error) {
log('initialize.js swapIndex', error.message || error);
server.log([blueWazuh, 'reindex', 'error'], 'Could not reindex the new .wazuh: ' + error.message || error);
}
};
const reachAPIs = async () => {
try{
const data = await elasticRequest.callWithInternalUser('search', { index: ".wazuh" });
for (let item of data.hits.hits) {
reachAPI(item);
}
} catch(error){
log('initialize.js reachAPIs', error.message || error);
server.log([blueWazuh, 'reindex', 'error'], 'Something happened while getting old API configuration data: ' + error.message || error);
}
2017-12-05 15:02:09 +00:00
};
// Check Kibana index and if it is prepared, start the initialization of Wazuh App.
checkStatus();
module.exports = importAppObjects;
2017-11-02 16:49:24 +00:00
};