Exemplo n.º 1
0
def get_info() -> Dict:
    """
    Returns manager configuration with cluster details

    :return: Dictionary with information about manager and cluster
    """
    # get name from agent 000
    manager = Agent(id=0)
    manager._load_info_from_DB()

    # read cluster configuration
    cluster_config = read_cluster_config()

    # get manager status
    cluster_info = get_cluster_status()
    # add 'name', 'node_name' and 'node_type' to cluster_info
    for name in ('name', 'node_name', 'node_type'):
        cluster_info[name] = cluster_config[name]

    # merge manager information into an unique dictionary
    manager_info = {
        **Wazuh(common.ossec_path).get_ossec_init(),
        **{
            'name': manager.name,
            'cluster': cluster_info
        }
    }

    return manager_info
Exemplo n.º 2
0
def as_wazuh_object(dct: Dict):
    try:
        if '__callable__' in dct:
            encoded_callable = dct['__callable__']
            funcname = encoded_callable['__name__']
            if '__wazuh__' in encoded_callable:
                # Encoded Wazuh instance method
                wazuh_dict = encoded_callable['__wazuh__']
                wazuh = Wazuh()
                return getattr(wazuh, funcname)
            else:
                # Encoded function or static method
                qualname = encoded_callable['__qualname__'].split('.')
                classname = qualname[0] if len(qualname) > 1 else None
                module_path = encoded_callable['__module__']
                module = import_module(module_path)
                if classname is None:
                    return getattr(module, funcname)
                else:
                    return getattr(getattr(module, classname), funcname)
        elif '__wazuh_exception__' in dct:
            wazuh_exception = dct['__wazuh_exception__']
            return getattr(exception, wazuh_exception['__class__']).from_dict(wazuh_exception['__object__'])
        elif '__wazuh_result__' in dct:
            wazuh_result = dct['__wazuh_result__']
            return getattr(wresults, wazuh_result['__class__']).decode_json(wazuh_result['__object__'])
        elif '__wazuh_datetime__' in dct:
            return datetime.datetime.fromisoformat(dct['__wazuh_datetime__'])
        return dct

    except (KeyError, AttributeError):
        raise exception.WazuhInternalError(1000,
                                           extra_message=f"Wazuh object cannot be decoded from JSON {dct}",
                                           cmd_error=True)
Exemplo n.º 3
0
def get_basic_info():
    """ Wrapper for Wazuh().to_dict

    :return: AffectedItemsWazuhResult.
    """
    result = AffectedItemsWazuhResult(
        all_msg=f"Basic information was successfully read"
        f"{' in specified node' if node_id != 'manager' else ''}",
        some_msg='Could not read basic information in some nodes',
        none_msg=f"Could not read basic information"
        f"{' in specified node' if node_id != 'manager' else ''}")

    try:
        result.affected_items.append(Wazuh().to_dict())
    except WazuhError as e:
        result.add_failed_item(id_=node_id, error=e)
    result.total_affected_items = len(result.affected_items)

    return result
Exemplo n.º 4
0
        raise Exception("Error starting wazuh-clusterd. Minimal Python version required is 2.7. Found version is {0}.{1}".\
            format(version_info[0], version_info[1]))

    import argparse
    import logging
    import logging.handlers
    from os.path import dirname

    # Import framework
    # Search path
    path.append(dirname(argv[0]) + '/../framework')

    # Import and Initialize
    from wazuh import Wazuh

    myWazuh = Wazuh(get_init=True)

    from wazuh import common
except Exception as e:
    print("Error starting wazuh-clusterd: {0}".format(e))
    exit()

# Rest of imports. If an exception is raised, it will be logged using logging.
error_msg = ""
try:
    from signal import signal, SIGINT, SIGTERM
    import asyncore
    import threading
    import time
    import ctypes
    import ctypes.util
Exemplo n.º 5
0
            print_json("Wazuh-Python Internal Error: uncaught exception: {0}".format(exception_error), 1000)
        if error_wazuh_package == -3:
            print_json(error, error_code)
        exit(0)  # error code 0 shows the msg in the API response.

    if 'function' not in request:
        print_json("Wazuh-Python Internal Error: 'JSON input' must have the 'function' key", 1000)
        exit(1)

    if 'ossec_path' not in request:
        print_json("Wazuh-Python Internal Error: 'JSON input' must have the 'ossec_path' key", 1000)
        exit(1)

    # Main
    try:
        wazuh = Wazuh(ossec_path=request['ossec_path'])

        functions = {
            '/agents/:agent_id': Agent.get_agent,
            '/agents/name/:agent_name': Agent.get_agent_by_name,
            '/agents/:agent_id/key': Agent.get_agent_key,
            '/agents': Agent.get_agents_overview,
            '/agents/summary': Agent.get_agents_summary,
            '/agents/summary/os': Agent.get_os_summary,
            '/agents/outdated': Agent.get_outdated_agents,
            '/agents/:agent_id/upgrade_result': Agent.get_upgrade_result,
            'PUT/agents/:agent_id/upgrade': Agent.upgrade_agent,
            'PUT/agents/:agent_id/upgrade_custom': Agent.upgrade_agent_custom,
            'PUT/agents/:agent_id/restart': Agent.restart_agents,
            'PUT/agents/restart': Agent.restart_agents,
            'PUT/agents/:agent_name': Agent.add_agent,
Exemplo n.º 6
0
def main():
    # Capture Cntrl + C
    signal(SIGINT, signal_handler)

    # Parse arguments
    arguments = {
        'n_args': 0,
        'n_actions': 0,
        'group': None,
        'agent-id': None,
        'list': False,
        'list-files': False,
        'add-group': False,
        'show-group': False,
        'remove-group': False,
        'quiet': False
    }
    try:
        opts, args = getopt(argv[1:], "lcasri:g:qfdh", [
            "list", "list-files", "add-group", "show-group", "remove-group",
            "agent-id=", "group=", "quiet", "debug", "help"
        ])
        arguments['n_args'] = len(opts)
    except GetoptError as err:
        print(str(err) + "\n" + "Try '--help' for more information.")
        exit(1)

    for o, a in opts:
        if o in ("-l", "--list"):
            arguments['list'] = True
            arguments['n_actions'] += 1
        elif o in ("-c", "--list-files"):
            arguments['list-files'] = True
            arguments['n_actions'] += 1
        elif o in ("-a", "--add-group"):
            arguments['add-group'] = True
            arguments['n_actions'] += 1
        elif o in ("-s", "--show-group"):
            arguments['show-group'] = True
            arguments['n_actions'] += 1
        elif o in ("-r", "--remove-group"):
            arguments['remove-group'] = True
            arguments['n_actions'] += 1
        elif o in ("-i", "--agent-id"):
            arguments['agent-id'] = a
        elif o in ("-g", "--group"):
            arguments['group'] = a
        elif o in ("-q", "--quiet"):
            arguments['quiet'] = True
        elif o in ("-d", "--debug"):
            global debug
            debug = True
        elif o in ("-h", "--help"):
            usage()
            exit(0)
        else:
            invalid_option()

    # Initialize framework
    myWazuh = Wazuh(get_init=True)

    # Actions
    if arguments['n_args'] > 5 or arguments['n_actions'] > 1:
        invalid_option("Bad argument combination.")

    # ./agent_groups.py
    if arguments['n_args'] == 0:
        show_groups()
    # ./agent_groups.py -l [ -g group_id ]
    elif arguments['list']:
        if arguments['group']:
            show_agents_with_group(arguments['group'])
        else:
            show_groups()
    # -c -g group_id
    elif arguments['list-files']:
        show_group_files(
            arguments['group']) if arguments['group'] else invalid_option(
                "Missing group.")
    # -a (-i agent_id -g groupd_id | -g group_id) [-q]
    elif arguments['add-group']:
        if arguments['agent-id'] and arguments['group']:
            set_group(arguments['agent-id'], arguments['group'],
                      arguments['quiet'])
        elif arguments['group']:
            create_group(arguments['group'], arguments['quiet'])
        else:
            invalid_option("Missing agent ID or group.")
    # -s -i agent_id
    elif arguments['show-group']:
        show_group(
            arguments['agent-id']
        ) if arguments['agent-id'] else invalid_option("Missing agent ID.")
    # -r (-g group_id | -i agent_id) [-q]
    elif arguments['remove-group']:
        if arguments['agent-id']:
            unset_group(arguments['agent-id'], 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.")
Exemplo n.º 7
0
        'type': 'local_master'
    },

    # Decoders
    '/decoders': {
        'function': Decoder.get_decoders,
        'type': 'local_any'
    },
    '/decoders/files': {
        'function': Decoder.get_decoders_files,
        'type': 'local_any'
    },

    # Managers
    '/manager/info': {
        'function': Wazuh(common.ossec_path).get_ossec_init,
        'type': 'local_any'
    },
    '/manager/status': {
        'function': manager.status,
        'type': 'local_any'
    },
    '/manager/configuration': {
        'function': configuration.get_ossec_conf,
        'type': 'local_any'
    },
    '/manager/stats': {
        'function': stats.totals,
        'type': 'local_any'
    },
    '/manager/stats/hourly': {
Exemplo n.º 8
0
from wazuh.cluster import (__author__, __licence__, __ossec_name__,
                           __version__, client)
from wazuh.cluster import cluster as cluster
from wazuh.cluster import common as c_common
from wazuh.cluster import control as cluster_control
from wazuh.cluster import local_client, local_server, master, server, worker
from wazuh.cluster.cluster import read_config
from wazuh.cluster.dapi import dapi
from wazuh.cluster.dapi import requests_list as rq
from wazuh.configuration import get_ossec_conf
from wazuh.database import Connection
from wazuh.decoder import Decoder
from wazuh.exception import WazuhException
from wazuh.InputValidator import InputValidator
from wazuh.manager import status
from wazuh.ossec_queue import OssecQueue
from wazuh.ossec_socket import OssecSocket, OssecSocketJSON
from wazuh.rule import Rule
from wazuh.syscollector import _get_agent_items, get_item_agent
from wazuh.utils import (WazuhDBQuery, WazuhDBQueryDistinct,
                         WazuhDBQueryGroupBy, WazuhVersion, chmod_r, chown_r,
                         cut_array, execute, get_fields_to_nest, get_hash,
                         load_wazuh_xml, md5, mkdir_with_mode,
                         plain_dict_to_nested_dict, previous_month,
                         search_array, sort_array, tail)
from wazuh.wdb import WazuhDBConnection

my_wazuh = Wazuh(get_init=True)

print("All modules were imported successfully.")
Exemplo n.º 9
0
def main():
    # Check arguments
    if args.list_outdated:
        list_outdated()
        exit(0)

    if not args.agent:
        arg_parser.print_help()
        exit(0)

    if args.silent:
        args.debug = False

    # Capture Ctrl + C
    signal(SIGINT, signal_handler)

    # Initialize framework
    myWazuh = Wazuh(get_init=True)

    agent = Agent(id=args.agent)
    agent._load_info_from_DB()

    agent_info = "{0}/queue/agent-info/{1}-{2}".format(common.ossec_path,
                                                       agent.name, agent.ip)
    if not os.path.isfile(agent_info):
        raise WazuhException(1720)

    # Custom WPK file
    if args.file:
        if args.execute:
            upgrade_command_result = agent.upgrade_custom(
                file_path=args.file,
                installer=args.execute,
                debug=args.debug,
                show_progress=print_progress if not args.silent else None,
                chunk_size=args.chunk_size,
                rl_timeout=args.timeout)
            if not args.silent:
                if not args.debug:
                    print(
                        "\n{0}... Please wait.".format(upgrade_command_result))
                else:
                    print(upgrade_command_result)

            counter = 0
            agent_info_stat = os.stat(agent_info).st_mtime

            sleep(10)
            while agent_info_stat == os.stat(
                    agent_info
            ).st_mtime and counter < common.agent_info_retries:
                sleep(common.agent_info_sleep)
                counter = counter + 1

            if agent_info_stat == os.stat(agent_info).st_mtime:
                raise WazuhException(
                    1716, "Timeout waiting for agent reconnection.")

            upgrade_result = agent.upgrade_result(debug=args.debug)
            if not args.silent:
                print(upgrade_result)
        else:
            print("Error: Need executable filename.")

    # WPK upgrade file
    else:
        prev_ver = agent.version
        upgrade_command_result = agent.upgrade(
            wpk_repo=args.repository,
            debug=args.debug,
            version=args.version,
            force=args.force,
            show_progress=print_progress if not args.silent else None,
            chunk_size=args.chunk_size,
            rl_timeout=args.timeout)
        if not args.silent:
            if not args.debug:
                print("\n{0}... Please wait.".format(upgrade_command_result))
            else:
                print(upgrade_command_result)

        counter = 0
        agent_info_stat = os.stat(agent_info).st_mtime

        while agent_info_stat == os.stat(
                agent_info).st_mtime and counter < common.agent_info_retries:
            sleep(common.agent_info_sleep)
            counter = counter + 1

        if agent_info_stat == os.stat(agent_info).st_mtime:
            raise WazuhException(1716,
                                 "Timeout waiting for agent reconnection.")

        sleep(10)
        upgrade_result = agent.upgrade_result(debug=args.debug)
        if not args.silent:
            if not args.debug:
                agent._load_info_from_DB()
                print("Agent upgraded: {0} -> {1}".format(
                    prev_ver, agent.version))
            else:
                print(upgrade_result)
Exemplo n.º 10
0
#    - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/var/ossec/framework/lib

from sys import path, exit
import json
# cwd = /var/ossec/api/framework/examples
#framework_path = '{0}'.format(path[0][:-9])
# cwd = /var/ossec/api
#framework_path = '{0}/framework'.format(path[0])
# Default path
framework_path = '/var/ossec/api/framework'
path.append(framework_path)

try:
    from wazuh import Wazuh
    from wazuh.agent import Agent
except Exception as e:
    print("No module 'wazuh' found.")
    exit()

if __name__ == "__main__":

    # Creating wazuh object
    # It is possible to specify the ossec path (path argument) or get /etc/ossec-init.conf (get_init argument)
    print("\nWazuh:")
    myWazuh = Wazuh()
    print(myWazuh)

    print("\nAgents:")
    agents = Agent.get_agents_overview()
    print(json.dumps(agents, indent=4, sort_keys=True))
Exemplo n.º 11
0
def main():
    # Capture Ctrl + C
    signal(SIGINT, signal_handler)

    # Initialize framework
    myWazuh = Wazuh(get_init=True)

    # Check arguments
    if args.list_outdated:
        list_outdated()
        exit(0)

    if not args.agent:
        arg_parser.print_help()
        exit(0)

    if args.silent:
        args.debug = False

    use_http = False
    if args.http:
        use_http = True

    agent = Agent(id=args.agent)
    agent._load_info_from_DB()

    agent_info = "{0}/queue/agent-info/{1}-{2}".format(common.ossec_path,
                                                       agent.name, agent.ip)
    if not os.path.isfile(agent_info):
        raise WazuhException(1720)

    # Evaluate if the version is correct
    if args.version is not None:
        pattern = re.compile("v[0-9]+\.[0-9]+\.[0-9]+")
        if not pattern.match(args.version):
            raise WazuhException(1733,
                                 "Version received: {0}".format(args.version))

    if args.chunk_size is not None:
        if args.chunk_size < 1 or args.chunk_size > 64000:
            raise WazuhException(1744,
                                 "Chunk defined: {0}".format(args.chunk_size))

    # Custom WPK file
    if args.file:
        upgrade_command_result = agent.upgrade_custom(
            file_path=args.file,
            installer=args.execute if args.execute else "upgrade.sh",
            debug=args.debug,
            show_progress=print_progress if not args.silent else None,
            chunk_size=args.chunk_size,
            rl_timeout=-1 if args.timeout == None else args.timeout)
        if not args.silent:
            if not args.debug:
                print("\n{0}... Please wait.".format(upgrade_command_result))
            else:
                print(upgrade_command_result)

        counter = 0
        agent_info_stat = os.stat(agent_info).st_mtime

        sleep(10)
        while agent_info_stat == os.stat(
                agent_info).st_mtime and counter < common.agent_info_retries:
            sleep(common.agent_info_sleep)
            counter = counter + 1

        if agent_info_stat == os.stat(agent_info).st_mtime:
            raise WazuhException(1716,
                                 "Timeout waiting for agent reconnection.")

        upgrade_result = agent.upgrade_result(debug=args.debug)
        if not args.silent:
            print(upgrade_result)

    # WPK upgrade file
    else:
        prev_ver = agent.version
        upgrade_command_result = agent.upgrade(
            wpk_repo=args.repository,
            debug=args.debug,
            version=args.version,
            force=args.force,
            show_progress=print_progress if not args.silent else None,
            chunk_size=args.chunk_size,
            rl_timeout=-1 if args.timeout == None else args.timeout,
            use_http=use_http)
        if not args.silent:
            if not args.debug:
                print("\n{0}... Please wait.".format(upgrade_command_result))
            else:
                print(upgrade_command_result)

        counter = 0
        agent_info_stat = os.stat(agent_info).st_mtime

        while agent_info_stat == os.stat(
                agent_info).st_mtime and counter < common.agent_info_retries:
            sleep(common.agent_info_sleep)
            counter = counter + 1

        if agent_info_stat == os.stat(agent_info).st_mtime:
            raise WazuhException(1716,
                                 "Timeout waiting for agent reconnection.")

        sleep(10)
        upgrade_result = agent.upgrade_result(debug=args.debug)
        if not args.silent:
            if not args.debug:
                agent._load_info_from_DB()
                print("Agent upgraded: {0} -> {1}".format(
                    prev_ver, agent.version))
            else:
                print(upgrade_result)