Skip to content

Commit

Permalink
Replace .wazuh-version index by file regitry (#1509)
Browse files Browse the repository at this point in the history
  • Loading branch information
juankaromo authored and Jesús Ángel committed Jun 21, 2019
1 parent dd3c879 commit d28c657
Show file tree
Hide file tree
Showing 14 changed files with 201 additions and 358 deletions.
4 changes: 1 addition & 3 deletions config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,9 @@
#
# ------------------------------ Advanced indices ------------------------------
#
# Configure .wazuh and .wazuh-version indices shards and replicas.
# Configure .wazuh indices shards and replicas.
#wazuh.shards : 1
#wazuh.replicas : 0
#wazuh-version.shards : 1
#wazuh-version.replicas: 0
#
# --------------------------- Index pattern selector ---------------------------
#
Expand Down
4 changes: 2 additions & 2 deletions public/controllers/misc/health-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export class HealthCheck {
const apiVersion = versionData.data.data;
const setupData = await this.genericReq.request(
'GET',
'/elastic/setup'
'/api/setup'
);
if (!setupData.data.data['app-version'] || !apiVersion) {
this.errorHandler.handle(
Expand All @@ -188,7 +188,7 @@ export class HealthCheck {
if (apiSplit[0] !== appSplit[0] || apiSplit[1] !== appSplit[1]) {
this.errors.push(
'API version mismatch. Expected v' +
setupData.data.data['app-version']
setupData.data.data['app-version']
);
this.results[i].status = 'Error';
} else {
Expand Down
2 changes: 1 addition & 1 deletion public/controllers/settings/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,7 @@ export class SettingsController {
*/
async getAppInfo() {
try {
const data = await this.genericReq.request('GET', '/elastic/setup');
const data = await this.genericReq.request('GET', '/api/setup');
this.appInfo = {};
this.appInfo['app-version'] = data.data.data['app-version'];
this.appInfo['installationDate'] = data.data.data['installationDate'];
Expand Down
4 changes: 2 additions & 2 deletions public/services/resolves/check-timestamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
*/
export async function checkTimestamp(appState, genericReq, $location, wzMisc) {
try {
const data = await genericReq.request('GET', '/elastic/timestamp');
const data = await genericReq.request('GET', '/api/timestamp');
const current = appState.getCreatedAt();
if (data && data.data) {
if (!current) appState.setCreatedAt(data.data.lastRestart);
wzMisc.setLastRestart(data.data.lastRestart);
} else {
wzMisc.setBlankScr('Your .wazuh-version index is empty or corrupt.');
wzMisc.setBlankScr('Your wazuh-version registry is empty or corrupt.');
$location.search('tab', null);
$location.path('/blank-screen');
}
Expand Down
2 changes: 0 additions & 2 deletions public/services/resolves/get-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ export async function getWzConfig($q, genericReq, wazuhConfig) {
timeout: 20000,
'wazuh.shards': 1,
'wazuh.replicas': 0,
'wazuh-version.shards': 1,
'wazuh-version.replicas': 0,
'ip.selector': true,
'ip.ignore': [],
'xpack.rbac.enabled': true,
Expand Down
4 changes: 0 additions & 4 deletions public/utils/config-equivalences.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ export const configEquivalences = {
'wazuh.shards': 'Define the number of shards to use for the .wazuh index.',
'wazuh.replicas':
'Define the number of replicas to use for the .wazuh index.',
'wazuh-version.shards':
'Define the number of shards to use for the .wazuh-version index.',
'wazuh-version.replicas':
'Define the number of replicas to use for the .wazuh-version index.',
'ip.selector':
'Defines if the user is allowed to change the selected index pattern directly from the top menu bar.',
'ip.ignore':
Expand Down
70 changes: 66 additions & 4 deletions server/controllers/wazuh-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { apiRequestList } from '../../util/api-request-list';
import * as ApiHelper from '../lib/api-helper';
import { Queue } from '../jobs/queue';
import querystring from 'querystring';
import fs from 'fs';
import path from 'path';
export class WazuhApiCtrl {
/**
* Constructor
Expand All @@ -39,6 +41,7 @@ export class WazuhApiCtrl {
this.queue = Queue;
this.wzWrapper = new ElasticWrapper(server);
this.monitoringInstance = new Monitoring(server, true);
this.wazuhVersion = path.join(__dirname, '../wazuh-version.json');
}

/**
Expand Down Expand Up @@ -911,7 +914,7 @@ export class WazuhApiCtrl {
if (method === 'DELETE') {
fixedUrl = `${
fullUrl.includes('?') ? fullUrl.split('?')[0] : fullUrl
}?${querystring.stringify(data)}`;
}?${querystring.stringify(data)}`;
}

log('wazuh-api:makeRequest', `${method} ${fixedUrl || fullUrl}`, 'debug');
Expand Down Expand Up @@ -1365,11 +1368,70 @@ export class WazuhApiCtrl {
}

/**
* Get basic syscollector information for given agent.
* This get the timestamp field
* @param {Object} req
* @param {Object} reply
* @returns {Object} Basic syscollector information
* @returns {Object} timestamp field or ErrorResponse
*/
async getTimeStamp(req, reply) {
try {
const source = JSON.parse(fs.readFileSync(this.wazuhVersion, 'utf8'));
if (source.installationDate && source.lastRestart) {
log(
'wazuh-api:getTimeStamp',
`Installation date: ${
source.installationDate
}. Last restart: ${source.lastRestart}`,
'debug'
);
return {
installationDate: source.installationDate,
lastRestart: source.lastRestart
};
} else {
throw new Error('Could not fetch wazuh-version registry');
}
} catch (error) {
log('wazuh-api:getTimeStamp', error.message || error);
return ErrorResponse(
error.message || 'Could not fetch wazuh-version registry',
4001,
500,
reply
);
}
}

/**
* This get the wazuh setup settings
* @param {Object} req
* @param {Object} reply
* @returns {Object} setup info or ErrorResponse
*/
async getSetupInfo(req, reply) {
try {
const source = JSON.parse(fs.readFileSync(this.wazuhVersion, 'utf8'));
return !Object.values(source).length
? { statusCode: 200, data: '' }
: { statusCode: 200, data: source };
} catch (error) {
log('wazuh-api:getSetupInfo', error.message || error);
return ErrorResponse(
`Could not get data from wazuh-version registry due to ${error.message ||
error}`,
4005,
500,
reply
);
}
}

/**
* Get basic syscollector information for given agent.
* @param {Object} req
* @param {Object} reply
* @returns {Object} Basic syscollector information
*/
async getSyscollector(req, reply) {
try {
if (!req.params || !req.headers.id || !req.params.agent) {
Expand Down Expand Up @@ -1405,7 +1467,7 @@ export class WazuhApiCtrl {
const syscollector = {
hardware:
typeof hardwareResponse === 'object' &&
Object.keys(hardwareResponse).length
Object.keys(hardwareResponse).length
? { ...hardwareResponse }
: false,
os:
Expand Down
128 changes: 33 additions & 95 deletions server/controllers/wazuh-elastic.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {

import { Base } from '../reporting/base-query';
import { checkKnownFields } from '../lib/refresh-known-fields';

export class WazuhElasticCtrl {
/**
* Constructor
Expand All @@ -31,44 +32,6 @@ export class WazuhElasticCtrl {
this.wzWrapper = new ElasticWrapper(server);
}

/**
* This get the timestamp field
* @param {Object} req
* @param {Object} reply
* @returns {Object} timestamp field or ErrorResponse
*/
async getTimeStamp(req, reply) {
try {
const data = await this.wzWrapper.getWazuhVersionIndexAsSearch();
const source =
((((data || {}).hits || {}).hits || [])[0] || {})._source || {};

if (source.installationDate && source.lastRestart) {
log(
'wazuh-elastic:getTimeStamp',
`Installation date: ${
data.hits.hits[0]._source.installationDate
}. Last restart: ${data.hits.hits[0]._source.lastRestart}`,
'debug'
);
return {
installationDate: data.hits.hits[0]._source.installationDate,
lastRestart: data.hits.hits[0]._source.lastRestart
};
} else {
throw new Error('Could not fetch .wazuh-version index');
}
} catch (error) {
log('wazuh-elastic:getTimeStamp', error.message || error);
return ErrorResponse(
error.message || 'Could not fetch .wazuh-version index',
4001,
500,
reply
);
}
}

/**
* This retrieve a template from Elasticsearch
* @param {Object} req
Expand Down Expand Up @@ -125,28 +88,28 @@ export class WazuhElasticCtrl {
log(
'wazuh-elastic:getTemplate',
`Template is valid: ${
isIncluded && Array.isArray(isIncluded) && isIncluded.length
? 'yes'
: 'no'
isIncluded && Array.isArray(isIncluded) && isIncluded.length
? 'yes'
: 'no'
}`,
'debug'
);
return isIncluded && Array.isArray(isIncluded) && isIncluded.length
? {
statusCode: 200,
status: true,
data: `Template found for ${req.params.pattern}`
}
statusCode: 200,
status: true,
data: `Template found for ${req.params.pattern}`
}
: {
statusCode: 200,
status: false,
data: `No template found for ${req.params.pattern}`
};
statusCode: 200,
status: false,
data: `No template found for ${req.params.pattern}`
};
} catch (error) {
log('wazuh-elastic:getTemplate', error.message || error);
return ErrorResponse(
`Could not retrieve templates from Elasticsearch due to ${error.message ||
error}`,
error}`,
4002,
500,
reply
Expand Down Expand Up @@ -175,16 +138,16 @@ export class WazuhElasticCtrl {
return filtered.length >= 1
? { statusCode: 200, status: true, data: 'Index pattern found' }
: {
statusCode: 500,
status: false,
error: 10020,
message: 'Index pattern not found'
};
statusCode: 500,
status: false,
error: 10020,
message: 'Index pattern not found'
};
} catch (error) {
log('wazuh-elastic:checkPattern', error.message || error);
return ErrorResponse(
`Something went wrong retrieving index-patterns from Elasticsearch due to ${error.message ||
error}`,
error}`,
4003,
500,
reply
Expand Down Expand Up @@ -247,40 +210,15 @@ export class WazuhElasticCtrl {
typeof data.aggregations['2'].buckets[0] === 'undefined'
? { statusCode: 200, data: '' }
: {
statusCode: 200,
data: data.aggregations['2'].buckets[0].key
};
statusCode: 200,
data: data.aggregations['2'].buckets[0].key
};
} catch (error) {
log('wazuh-elastic:getFieldTop', error.message || error);
return ErrorResponse(error.message || error, 4004, 500, reply);
}
}

/**
* This get the elastic setup settings
* @param {Object} req
* @param {Object} reply
* @returns {Object} setup info or ErrorResponse
*/
async getSetupInfo(req, reply) {
try {
const data = await this.wzWrapper.getWazuhVersionIndexAsSearch();

return data.hits.total.value === 0
? { statusCode: 200, data: '' }
: { statusCode: 200, data: data.hits.hits[0]._source };
} catch (error) {
log('wazuh-elastic:getSetupInfo', error.message || error);
return ErrorResponse(
`Could not get data from elasticsearch due to ${error.message ||
error}`,
4005,
500,
reply
);
}
}

/**
* Checks one by one if the requesting user has enough privileges to use
* an index pattern from the list.
Expand Down Expand Up @@ -433,15 +371,15 @@ export class WazuhElasticCtrl {

defaultStr.includes('wazuh-monitoring')
? (aux_source.kibanaSavedObjectMeta.searchSourceJSON = defaultStr.replace(
/wazuh-monitoring/g,
monitoringPattern[monitoringPattern.length - 1] === '*'
? monitoringPattern
: monitoringPattern + '*'
))
/wazuh-monitoring/g,
monitoringPattern[monitoringPattern.length - 1] === '*'
? monitoringPattern
: monitoringPattern + '*'
))
: (aux_source.kibanaSavedObjectMeta.searchSourceJSON = defaultStr.replace(
/wazuh-alerts/g,
id
));
/wazuh-alerts/g,
id
));
}

// Replace index-pattern for selector visualizations
Expand Down Expand Up @@ -509,7 +447,7 @@ export class WazuhElasticCtrl {
for (const node of nodes) {
query += `.es(index=${pattern_name},q="cluster.name: ${name} AND cluster.node: ${
node.name
}").label("${node.name}"),`;
}").label("${node.name}"),`;
}
query = query.substring(0, query.length - 1);
} else if (title === 'Wazuh App Cluster Overview Manager') {
Expand Down Expand Up @@ -646,8 +584,8 @@ export class WazuhElasticCtrl {
((req || {}).params || {}).pattern === 'all'
? await checkKnownFields(this.wzWrapper, false, false, false, true)
: await this.wzWrapper.updateIndexPatternKnownFields(
req.params.pattern
);
req.params.pattern
);

return { acknowledge: true, output: output };
} catch (error) {
Expand Down
Loading

0 comments on commit d28c657

Please sign in to comment.