Example #1
0
def signal_handler(signal, frame):
    print ("Interrupted")
    exit(1)
signal.signal(signal.SIGINT, signal_handler)

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

    # Import Wazuh and Initialize
    from wazuh import Wazuh
    from wazuh.exception import WazuhException

    myWazuh = Wazuh(get_init=True)

    # Import cluster
    from wazuh.cluster.cluster import read_config, check_cluster_config, get_status_json
    from wazuh.cluster.control import check_cluster_status, get_nodes, get_healthcheck, get_agents, sync, get_files

except Exception as e:
    print("Error importing 'Wazuh' package.\n\n{0}\n".format(e))
    exit()

logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

def get_parser(type):
    if type == "master":
        class WazuhHelpFormatter(argparse.ArgumentParser):
            def format_help(self):
Example #2
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,
        'replace-group': False,
        'show-group': False,
        'show-sync': False,
        'remove-group': False,
        'quiet': False
    }
    try:
        opts, args = getopt(argv[1:], "lcafsSri:g:qdh", [
            "list", "list-files", "add-group", "replace-group", "show-group",
            "show-sync", "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 ("-f", "--replace-group"):
            arguments['replace-group'] = True
        elif o in ("-s", "--show-group"):
            arguments['show-group'] = True
            arguments['n_actions'] += 1
        elif o in ("-S", "--show-sync"):
            arguments['show-sync'] = 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] [-e]
    elif arguments['add-group']:
        if arguments['agent-id'] and arguments['group']:
            set_group(arguments['agent-id'], arguments['group'],
                      arguments['quiet'], arguments['replace-group'])
        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.")
    # -S -i agent_id
    elif arguments['show-sync']:
        show_synced_agent(
            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['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.")
Example #3
0
            print_json("Wazuh-Python Internal Error: wazuh-framework not found.", 1000)
        if error_wazuh_package == -2:
            print_json("Wazuh-Python Internal Error: uncaught exception: {0}".format(exception_error), 1000)
        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/:agent_id/key': Agent.get_agent_key,
            '/agents': Agent.get_agents_overview,
            '/agents/summary': Agent.get_agents_summary,
            'PUT/agents/:agent_id/restart': Agent.restart_agents,
            'PUT/agents/restart': Agent.restart_agents,
            'PUT/agents/:agent_name': Agent.add_agent,
            'POST/agents': Agent.add_agent,
            'POST/agents/insert': Agent.insert_agent,
            'DELETE/agents/:agent_id': Agent.remove_agent,

            '/decoders': Decoder.get_decoders,
            '/decoders/files': Decoder.get_decoders_files,
Example #4
0
    # Decoders
    '/decoders': {
        'function': Decoder.get_decoders,
        'type': 'local_any',
        'is_async': False
    },
    '/decoders/files': {
        'function': Decoder.get_decoders_files,
        'type': 'local_any',
        'is_async': False
    },

    # Managers
    '/manager/info': {
        'function': Wazuh(common.ossec_path).get_ossec_init,
        'type': 'local_any',
        'is_async': False
    },
    '/manager/status': {
        'function': manager.status,
        'type': 'local_any',
        'is_async': False
    },
    '/manager/configuration': {
        'function': configuration.get_ossec_conf,
        'type': 'local_any',
        'is_async': False
    },
    '/manager/configuration/validation': {
        'function': manager.validation,
Example #5
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.")
Example #6
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)
Example #7
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))
Example #8
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)