Example #1
0
def check_cluster_status():
    """Get whether cluster is enabled in current active configuration.

    Returns
    -------
    bool
        Whether cluster is enabled.
    """
    return not read_config()['disabled']
Example #2
0
def get_node():
    data = {}
    config_cluster = read_config()

    data["node"] = config_cluster["node_name"]
    data["cluster"] = config_cluster["name"]
    data["type"] = config_cluster["node_type"]

    return data
Example #3
0
def read_config_wrapper():
    """ Wrapper for read_config

    :return: AffectedItemsWazuhResult
    """
    result = AffectedItemsWazuhResult(
        all_msg='All selected information was returned',
        none_msg='No information was returned')
    try:
        result.affected_items.append(read_config())
    except WazuhError as e:
        result.add_failed_item(id_=node_id, error=e)
    result.total_affected_items = len(result.affected_items)

    return result
Example #4
0
def get_node():
    """Get dict with current active node information.

    Returns
    -------
    data : dict
        Dict containing current node_name, node_type and cluster_name.
    """
    data = {}
    config_cluster = read_config()

    data["node"] = config_cluster["node_name"]
    data["cluster"] = config_cluster["name"]
    data["type"] = config_cluster["node_type"]

    return data
Example #5
0
def test_read_cluster_config():
    """Verify that read_cluster function returns, in this case, the default configuration."""
    config = utils.read_cluster_config()
    assert config == default_cluster_config

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               side_effect=WazuhError(1001)):
        with pytest.raises(WazuhError, match='.* 3006 .*'):
            utils.read_cluster_config()

    with patch('wazuh.core.configuration.load_wazuh_xml',
               return_value=SystemExit):
        with pytest.raises(SystemExit) as pytest_wrapped_e:
            utils.read_cluster_config(from_import=True)
        assert pytest_wrapped_e.type == SystemExit
        assert pytest_wrapped_e.value.code == 0

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               side_effect=KeyError(1)):
        with pytest.raises(WazuhError, match='.* 3006 .*'):
            utils.read_cluster_config()

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               return_value={'cluster': default_cluster_config}):
        utils.read_config.cache_clear()
        default_cluster_config.pop('hidden')
        default_cluster_config['disabled'] = 'no'
        config = utils.read_cluster_config()
        config_simple = utils.read_config()
        assert config == config_simple
        assert config == default_cluster_config

        default_cluster_config['node_type'] = 'client'
        config = utils.read_cluster_config()
        assert config == default_cluster_config

        default_cluster_config['disabled'] = 'None'
        with pytest.raises(WazuhError, match='.* 3004 .*'):
            utils.read_cluster_config()

        default_cluster_config['disabled'] = 'yes'
        config = utils.read_cluster_config()
        assert config == default_cluster_config

        default_cluster_config['port'] = 'None'
        with pytest.raises(WazuhError, match='.* 3004 .*'):
            utils.read_cluster_config()
Example #6
0
def test_read_cluster_config():
    """Verify that read_cluster function returns, in this case, the default configuration."""
    config = utils.read_cluster_config()
    assert config == default_cluster_config

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               side_effect=WazuhError(1001)):
        with pytest.raises(WazuhError, match='.* 3006 .*'):
            utils.read_cluster_config()

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               side_effect=KeyError(1)):
        with pytest.raises(WazuhError, match='.* 3006 .*'):
            utils.read_cluster_config()

    with patch('wazuh.core.cluster.utils.get_ossec_conf',
               return_value={'cluster': default_cluster_config}):
        default_cluster_config.pop('hidden')
        default_cluster_config['disabled'] = 'no'
        config = utils.read_cluster_config()
        config_simple = utils.read_config()
        assert config == config_simple
        assert config == default_cluster_config

        default_cluster_config['node_type'] = 'client'
        config = utils.read_cluster_config()
        assert config == default_cluster_config

        default_cluster_config['disabled'] = 'None'
        with pytest.raises(WazuhError, match='.* 3004 .*'):
            utils.read_cluster_config()

        default_cluster_config['disabled'] = 'yes'
        config = utils.read_cluster_config()
        assert config == default_cluster_config

        default_cluster_config['port'] = 'None'
        with pytest.raises(WazuhError, match='.* 3004 .*'):
            utils.read_cluster_config()
Example #7
0
    try:
        debug_mode = configuration.get_internal_options_value(
            'wazuh_clusterd', 'debug', 2, 0) or args.debug_level
    except Exception:
        debug_mode = 0

    # set correct permissions on cluster.log file
    if os.path.exists('{0}/logs/cluster.log'.format(common.wazuh_path)):
        os.chown('{0}/logs/cluster.log'.format(common.wazuh_path),
                 common.wazuh_uid(), common.wazuh_gid())
        os.chmod('{0}/logs/cluster.log'.format(common.wazuh_path), 0o660)

    main_logger = set_logging(foreground_mode=args.foreground,
                              debug_mode=debug_mode)

    cluster_configuration = cluster_utils.read_config(
        config_file=args.config_file)
    if cluster_configuration['disabled']:
        sys.exit(0)
    cluster_items = cluster_utils.get_cluster_items()
    try:
        wazuh.core.cluster.cluster.check_cluster_config(cluster_configuration)
    except Exception as e:
        main_logger.error(e)
        sys.exit(1)

    if args.test_config:
        sys.exit(0)

    cluster_status = wazuh.core.cluster.utils.get_cluster_status()
    if cluster_status['running'] == 'yes':
        main_logger.error("Cluster is already running.")
Example #8
0
def decode_token(token):
    """Decode a jwt formatted token and add processed policies.
    Raise an Unauthorized exception in case validation fails.

    Parameters
    ----------
    token : str
        JWT formatted token

    Returns
    -------
    Dict payload ot the token
    """
    try:
        # Decode JWT token with local secret
        payload = jwt.decode(token,
                             generate_keypair()[1],
                             algorithms=[JWT_ALGORITHM],
                             audience='Wazuh API REST')

        # Check token and add processed policies in the Master node
        dapi = DistributedAPI(f=check_token,
                              f_kwargs={
                                  'username': payload['sub'],
                                  'roles': tuple(payload['rbac_roles']),
                                  'token_nbf_time': payload['nbf'],
                                  'run_as': payload['run_as'],
                                  'origin_node_type':
                                  read_config()['node_type']
                              },
                              request_type='local_master',
                              is_async=False,
                              wait_for_complete=False,
                              logger=logging.getLogger('wazuh-api'))
        data = raise_if_exc(
            pool.submit(asyncio.run,
                        dapi.distribute_function()).result()).to_dict()

        if not data['result']['valid']:
            raise Unauthorized
        payload['rbac_policies'] = data['result']['policies']
        payload['rbac_policies']['rbac_mode'] = payload.pop('rbac_mode')

        # Detect local changes
        dapi = DistributedAPI(f=get_security_conf,
                              request_type='local_master',
                              is_async=False,
                              wait_for_complete=False,
                              logger=logging.getLogger('wazuh-api'))
        result = raise_if_exc(
            pool.submit(asyncio.run, dapi.distribute_function()).result())

        current_rbac_mode = result['rbac_mode']
        current_expiration_time = result['auth_token_exp_timeout']
        if payload['rbac_policies']['rbac_mode'] != current_rbac_mode \
                or (payload['exp'] - payload['nbf']) != current_expiration_time:
            raise Unauthorized

        return payload
    except JWTError as e:
        raise Unauthorized from e
Example #9
0
            unset_group(arguments['agent-id'], arguments['group'],
                        arguments['quiet'])
        elif arguments['group']:
            remove_group(arguments['group'], arguments['quiet'])
        else:
            invalid_option("Missing agent ID or group.")
    else:
        invalid_option("Bad argument combination.")


if __name__ == "__main__":
    logger = logging.basicConfig(level=logging.INFO,
                                 format='%(levelname)s: %(message)s')

    try:
        cluster_config = read_config()
        executable_name = "agent_groups"
        master_ip = cluster_config['nodes'][0]
        if cluster_config['node_type'] != 'master' and not cluster_config[
                'disabled']:
            raise WazuhError(3019, {
                "EXECUTABLE_NAME": executable_name,
                "MASTER_IP": master_ip
            })
        main()

    except WazuhError as e:
        print("Error {0}: {1}".format(e.code, e.message))
        if debug:
            raise
    except Exception as e:
Example #10
0
def check_cluster_status():
    """
    Function to check if cluster is enabled
    """
    return read_config()['disabled']