Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check wazuh version #693

Merged
merged 6 commits into from
May 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 65 additions & 9 deletions SplunkAppForWazuh/appserver/controllers/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from splunk.appserver.mrsparkle.lib.decorators import expose_page
from db import database
from log import log
from requestsbak.exceptions import ConnectionError


def getSelfConfStanza(file, stanza):
Expand Down Expand Up @@ -309,13 +310,27 @@ def check_connection(self, **kwargs):
url = opt_base_url + ":" + opt_base_port
auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password)
verify = False
request_manager = self.session.get(
url + '/agents/000?select=name', auth=auth, timeout=20, verify=verify).json()
request_cluster = self.session.get(
url + '/cluster/status', auth=auth, timeout=20, verify=verify).json()
request_cluster_name = self.session.get(
url + '/cluster/node', auth=auth, timeout=20, verify=verify).json()
try:
# Checks in the first request if the credentials are ok
request_manager = self.session.get(
url + '/agents/000?select=name', auth=auth, timeout=20, verify=verify)
if request_manager.status_code == 401:
self.logger.error("Cannot connect to API; Invalid credentials.")
return jsonbak.dumps({"status": "400", "error": "Invalid credentials, please check the username and password."})
request_manager = request_manager.json()
request_cluster = self.session.get(
url + '/cluster/status', auth=auth, timeout=20, verify=verify).json()
request_cluster_name = self.session.get(
url + '/cluster/node', auth=auth, timeout=20, verify=verify).json()
except ConnectionError as e:
self.logger.error("Cannot connect to API : %s" % (e))
return jsonbak.dumps({"status": "400", "error": "Unreachable API, please check the URL and port."})
output = {}
try:
self.check_wazuh_version(kwargs)
except Exception as e:
error = {"status": 400, "error": str(e)}
return jsonbak.dumps(error)
daemons_ready = self.check_daemons(url, auth, verify, opt_cluster)
# Pass the cluster status instead of always False
if not daemons_ready:
Expand All @@ -328,12 +343,52 @@ def check_connection(self, **kwargs):
except Exception as e:
if not daemons_ready:
self.logger.error("Cannot connect to API; Wazuh not ready yet.")
return jsonbak.dumps({"status": "200", "error": 3099, "message": "Wazuh not ready yet."})
return jsonbak.dumps({"status": 200, "error": 3099, "message": "Wazuh not ready yet."})
else:
self.logger.error("Cannot connect to API : %s" % (e))
return jsonbak.dumps({"status": "400", "error": "Cannot connect to the API"})
return jsonbak.dumps({"status": 400, "error": "Cannot connect to the API"})
return result

def check_wazuh_version(self, kwargs):
"""Check Wazuh version

Parameters
----------
kwargs : dict
The request's parameters
"""
try:
opt_username = kwargs["user"]
opt_password = kwargs["pass"]
opt_base_url = kwargs["ip"]
opt_base_port = kwargs["port"]
url = opt_base_url + ":" + opt_base_port
auth = requestsbak.auth.HTTPBasicAuth(opt_username, opt_password)
verify = False

wazuh_version = self.session.get(
url + '/version', auth=auth, timeout=20, verify=verify).json()
wazuh_version = wazuh_version['data']
wazuh_version = wazuh_version.split('v')[1]

app_version = cli.getConfStanza(
'package',
'app')
app_version = app_version['version']

v_split = wazuh_version.split('.')
a_split = app_version.split('.')

wazuh_version = str(v_split[0]+"."+v_split[1])
app_version = str(a_split[0]+"."+a_split[1])
if wazuh_version != app_version:
raise Exception("Unexpected Wazuh version. App version: %s, Wazuh version: %s" % (app_version, wazuh_version))
except Exception as e:
self.logger.error("Error when checking Wazuh version: %s" % (e))
raise e



def check_daemons(self, url, auth, verify, check_cluster):
""" Request to check the status of this daemons: execd, modulesd, wazuhdb and clusterd

Expand Down Expand Up @@ -367,4 +422,5 @@ def check_daemons(self, url, auth, verify, check_cluster):
return wazuh_ready
except Exception as e:
self.logger.error("Error checking daemons: %s" % (e))
raise e
raise e
return
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ define(['../../module'], function(controllers) {
this.notification.showSuccessToast('Connection established')
if (!this.scope.$$phase) this.scope.$digest()
} catch (err) {
this.notification.showErrorToast('Unreachable API')
this.notification.showErrorToast(err || 'Unreachable API')
}
}

Expand Down Expand Up @@ -201,7 +201,7 @@ define(['../../module'], function(controllers) {
this.scope.edit = false
this.notification.showSuccessToast('Updated API')
} catch (err) {
this.notification.showErrorToast('Cannot update API')
this.notification.showErrorToast(err || 'Cannot update API')
}
this.savingApi = false
}
Expand All @@ -221,7 +221,7 @@ define(['../../module'], function(controllers) {
this.scope.$emit('updatedAPI', () => {})
if (!this.scope.$$phase) this.scope.$digest()
} catch (err) {
this.notification.showErrorToast('Could not select manager')
this.notification.showErrorToast(err || 'Could not select manager')
}
}

Expand Down Expand Up @@ -279,7 +279,11 @@ define(['../../module'], function(controllers) {
if (!this.scope.$$phase) this.scope.$digest()
this.notification.showSuccessToast('New API was added')
} catch (err) {
this.notification.showErrorToast(err.message)
if (err.startsWith('Unexpected Wazuh version')) {
this.scope.validatingError.push(err)
} else {
this.notification.showErrorToast(err.message || err || 'Cannot save the API.')
}
}
this.savingApi = false
}
Expand Down
21 changes: 17 additions & 4 deletions SplunkAppForWazuh/appserver/static/js/run/run.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
define(['./module'], function(module) {
define(['./module'], function (module) {
'use strict'
module.run([
'$rootScope',
'$state',
'$transitions',
'$navigationService',
'$currentDataService',
function(
'$notificationService',
function (
$rootScope,
$state,
$transitions,
$navigationService,
$currentDataService
$currentDataService,
$notificationService
) {
//Go to last state or to a specified tab if "currentTab" param is specified in the url
$navigationService.manageState()
Expand All @@ -27,7 +29,7 @@ define(['./module'], function(module) {
)
$currentDataService.addFilter(
`{"index":"${
$currentDataService.getIndex().index
$currentDataService.getIndex().index
}", "implicit":true}`
)
// If change the primary state and do not receive an error the two below code lines clear the warning message
Expand All @@ -54,6 +56,17 @@ define(['./module'], function(module) {
// Check secondary states when Wazuh is not ready to prevent change the state
$transitions.onBefore({}, async trans => {
const to = trans.to().name

try {
if (!to.startsWith('settings')) {
await $currentDataService.checkWazuhVersion()
}
} catch (error) {
$notificationService.showErrorToast(error || 'Unexpected Wazuh Version.')
$state.go('settings.api')
return false
}

if (
to !== 'overview' &&
to !== 'manager' &&
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
define(['../module'], function(module) {
define(['../module'], function (module) {
'use strict'
module.service('$apiMgrService', function(
module.service('$apiMgrService', function (
$requestService,
$apiIndexStorageService,
$splunkStoreService
Expand Down Expand Up @@ -222,24 +222,24 @@ define(['../module'], function(module) {
const clusterEnabled = api.filterType === 'cluster.name'
const checkConnectionEndpoint = `/manager/check_connection?ip=${
api.url
}&port=${
}&port=${
api.portapi
}&user=${user}&pass=${pass}&cluster=${clusterEnabled}`
}&user=${user}&pass=${pass}&cluster=${clusterEnabled}`
const result = await $requestService.httpReq(
'GET',
checkConnectionEndpoint
)
if (result.data.status === 400 || result.data.error) {
if (result.data.error === 3099) {
throw new Error('ERROR3099 - Wazuh not ready yet.')
throw 'ERROR3099 - Wazuh not ready yet.'
} else {
throw new Error('Unreachable API.')
throw result.data.error || 'Unreachable API.'
}
}
return result
}
// Otherwise throw a new error
throw new Error('Missing API fields.')
throw 'Missing API fields.'
} catch (err) {
return Promise.reject(err)
}
Expand Down Expand Up @@ -313,6 +313,39 @@ define(['../module'], function(module) {
}
}


/**
* Checks if the Splunk Version are the same that the Wazuh version
*/
const checkWazuhVersion = async () => {
try {
const wazuhVersion = await $requestService.apiReq('/version')
const appVersion = await $requestService.httpReq(
'GET',
'/manager/app_info'
)
if (
wazuhVersion.data &&
wazuhVersion.data.data &&
!wazuhVersion.data.error &&
appVersion.data &&
appVersion.data.version &&
!appVersion.data.error
) {
const wv = wazuhVersion.data.data
const av = appVersion.data.version
const wazuhSplit = wv.split('v')[1].split('.')
const appSplit = av.split('.')

if (wazuhSplit[0] !== appSplit[0] || wazuhSplit[1] !== appSplit[1]) {
throw `Unexpected Wazuh version. App version: ${appSplit[0]}.${appSplit[1]}, Wazuh version: ${wazuhSplit[0]}.${wazuhSplit[1]}`
}
}
} catch (error) {
return Promise.reject(error)
}
}

return {
checkApiConnection: checkApiConnection,
checkPollingState: checkPollingState,
Expand All @@ -330,7 +363,8 @@ define(['../module'], function(module) {
setIndex: setIndex,
getApi: getApi,
setApi: setApi,
addApi: addApi
addApi: addApi,
checkWazuhVersion: checkWazuhVersion
}
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,17 @@ define(['../module'], function(module) {
}
}

/**
* Checks if the Splunk Version are the same that the Wazuh version
*/
const checkWazuhVersion = async () => {
try {
return await $apiMgrService.checkWazuhVersion()
} catch (error) {
return Promise.reject(error)
}
}

return {
getPollintState: getPollintState,
getBaseUrl: getBaseUrl,
Expand Down Expand Up @@ -248,7 +259,8 @@ define(['../module'], function(module) {
setExtensions: setExtensions,
addApi: addApi,
isAdmin: isAdmin,
getReportingStatus: getReportingStatus
getReportingStatus: getReportingStatus,
checkWazuhVersion: checkWazuhVersion
}
})
})