Skip to content

Commit

Permalink
Improve configuration validation
Browse files Browse the repository at this point in the history
  • Loading branch information
nico-stefani committed Apr 22, 2024
1 parent 9b7acf1 commit 16afec2
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 20 deletions.
62 changes: 57 additions & 5 deletions framework/wazuh/core/cluster/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,73 @@
from os import listdir, path, remove, stat, walk
from uuid import uuid4

from jsonschema import ValidationError, validate
from wazuh import WazuhError, WazuhException, WazuhInternalError
from wazuh.core import common
from wazuh.core.cluster.utils import (
AGENT_CHUNK_SIZE,
AGENT_RECONNECTION_STABILITY_TIME,
AGENT_RECONNECTION_TIME,
FREQUENCY,
HAPROXY_HELPER,
HAPROXY_PORT,
HAPROXY_PROTOCOL,
IMBALANCE_TOLERANCE,
REMOVE_DISCONNECTED_NODE_AFTER,
get_cluster_items,
read_config,
)
from wazuh.core.InputValidator import InputValidator
from wazuh.core.cluster.utils import get_cluster_items, read_config
from wazuh.core.utils import blake2b, mkdir_with_mode, get_utc_now, get_date_from_timestamp, to_relative_path
from wazuh.core.utils import blake2b, get_date_from_timestamp, get_utc_now, mkdir_with_mode, to_relative_path

logger = logging.getLogger('wazuh')

# Separators used in compression/decompression functions to delimit files.
FILE_SEP = '|@@//@@|'
PATH_SEP = '|//@@//|'
MIN_PORT = 1024
MAX_PÖRT = 65535


#
# Cluster
#

def validate_haproxy_helper_config(config: dict):
"""Validate the values of the give HAProxy helper configuration.
Parameters
----------
config : dict
Configuration to validate.
Raises
------
WazuhError(3004)
If there any invalid value.
"""
SCHEMA = {
'type': 'object',
'properties': {
HAPROXY_PORT: {'type': 'integer', 'minimum': MIN_PORT, 'maximum': MAX_PÖRT},
HAPROXY_PROTOCOL: {'type': 'string', 'enum': ['http', 'https']},
FREQUENCY: {'type': 'integer', 'minimum': 10},
AGENT_RECONNECTION_STABILITY_TIME: {'type': 'integer', 'minimum': 10},
AGENT_CHUNK_SIZE: {'type': 'integer', 'minimum': 100},
AGENT_RECONNECTION_TIME: {'type': 'integer', 'minimum': 0},
IMBALANCE_TOLERANCE: {'type': 'number', 'minimum': 0, 'exclusiveMinimum': True, 'maximum': 1},
REMOVE_DISCONNECTED_NODE_AFTER: {'type': 'integer', 'minimum': 0},
},
}

try:
validate(config, SCHEMA)
except ValidationError as error:
raise WazuhError(
3004,
f'Invalid value for {error.path.pop()}. {error.message}'
)


def check_cluster_config(config):
"""Verify that cluster configuration is correct.
Expand Down Expand Up @@ -71,8 +121,8 @@ def check_cluster_config(config):
elif not isinstance(config['port'], int):
raise WazuhError(3004, "Port has to be an integer.")

elif not 1024 < config['port'] < 65535:
raise WazuhError(3004, "Port must be higher than 1024 and lower than 65535.")
elif not MIN_PORT < config['port'] < MAX_PÖRT:
raise WazuhError(3004, f"Port must be higher than {MIN_PORT} and lower than {MAX_PÖRT}.")

if len(config['nodes']) > 1:
logger.warning(
Expand All @@ -84,6 +134,8 @@ def check_cluster_config(config):
if len(invalid_elements) != 0:
raise WazuhError(3004, f"Invalid elements in node fields: {', '.join(invalid_elements)}.")

validate_haproxy_helper_config(config.get(HAPROXY_HELPER, {}))


def get_node():
"""Get dict with current active node information.
Expand Down Expand Up @@ -374,7 +426,7 @@ def compress_files(name, list_path, cluster_control_json=None, max_zip_size=None
except zlib.error as e:
raise WazuhError(3001, str(e))
except Exception as e:
result_logs['debug'][file].append(f"Exception raised: " + str(WazuhException(3001, str(e))))
result_logs['debug'][file].append("Exception raised: " + str(WazuhException(3001, str(e))))
update_cluster_control(file, cluster_control_json, exists=False)

try:
Expand Down
2 changes: 1 addition & 1 deletion framework/wazuh/core/cluster/hap_helper/hap_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,4 +536,4 @@ async def start(cls):
except Exception as unexpected_exc:
logger.critical(f'Unexpected exception: {unexpected_exc}', exc_info=True)
finally:
logger.info('Process ended')
logger.info('Task ended')
71 changes: 57 additions & 14 deletions framework/wazuh/core/cluster/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,33 +62,24 @@
}


def validate_haproxy_helper_config(helper_config: dict) -> dict:
"""Validate HAProxy helper configuration section.
def parse_haproxy_helper_integer_values(helper_config: dict) -> dict:
"""Parse HAProxy helper integer values.
Parameters
----------
helper_config : dict
Configuration to validate.
Configuration to parse.
Returns
-------
dict
Validated configuration for HAProxy Helper.
Parsed configuration with integer values.
Raises
------
WazuhError (3004)
If some value has an invalid type.
"""
# If any value is missing from user's cluster configuration, add the default one.
for value_name in set(HELPER_DEFAULTS.keys()) - set(helper_config.keys()):
helper_config[value_name] = HELPER_DEFAULTS[value_name]

if helper_config[HAPROXY_DISABLED] == NO:
helper_config[HAPROXY_DISABLED] = False
elif helper_config[HAPROXY_DISABLED] == YES:
helper_config[HAPROXY_DISABLED] = True

for field in [
HAPROXY_PORT,
FREQUENCY,
Expand All @@ -102,13 +93,65 @@ def validate_haproxy_helper_config(helper_config: dict) -> dict:
helper_config[field] = int(helper_config[field])
except ValueError:
raise WazuhError(3004, extra_message=f"HAProxy Helper {field} must be an integer.")
return helper_config


def parse_haproxy_helper_float_values(helper_config: dict) -> dict:
"""Parse HAProxy helper float values.
Parameters
----------
helper_config : dict
Configuration to parse.
Returns
-------
dict
Parsed configuration with float values.
Raises
------
WazuhError (3004)
If some value has an invalid type.
"""
for field in [IMBALANCE_TOLERANCE]:
if helper_config.get(field):
try:
helper_config[field] = float(helper_config[field])
except ValueError:
raise WazuhError(3004, extra_message=f"HAProxy Helper {field} must be a float.")
return helper_config


def parse_haproxy_helper_config(helper_config: dict) -> dict:
"""Parse HAProxy helper configuration section.
Parameters
----------
helper_config : dict
Configuration to parse.
Returns
-------
dict
Parsed configuration for HAProxy Helper.
Raises
------
WazuhError (3004)
If some value has an invalid type.
"""
# If any value is missing from user's cluster configuration, add the default one.
for value_name in set(HELPER_DEFAULTS.keys()) - set(helper_config.keys()):
helper_config[value_name] = HELPER_DEFAULTS[value_name]

if helper_config[HAPROXY_DISABLED] == NO:
helper_config[HAPROXY_DISABLED] = False
elif helper_config[HAPROXY_DISABLED] == YES:
helper_config[HAPROXY_DISABLED] = True

helper_config = parse_haproxy_helper_integer_values(helper_config)
helper_config = parse_haproxy_helper_float_values(helper_config)

return helper_config

Expand Down Expand Up @@ -178,7 +221,7 @@ def read_cluster_config(config_file=common.OSSEC_CONF, from_import=False) -> typ
config_cluster['node_type'] = 'worker'

if config_cluster.get(HAPROXY_HELPER):
config_cluster[HAPROXY_HELPER] = validate_haproxy_helper_config(config_cluster[HAPROXY_HELPER])
config_cluster[HAPROXY_HELPER] = parse_haproxy_helper_config(config_cluster[HAPROXY_HELPER])

return config_cluster

Expand Down

0 comments on commit 16afec2

Please sign in to comment.