Example #1
0
def put_sensor_detector_by_device(sensor_id):
    """
    Set the [sensor]/detectors list on config.yml of the sensor
    """
    # Get the 'plugins' param list, with contains the detector plugins
    # It must be a comma separate list
    plugins = request.form['plugins']
    if plugins is None:
        current_app.logger.error(
            "detector: put_sensor_detector error: Missing parameter 'plugins'")
        return make_bad_request("Missing parameter plugins")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error(
            "detector: put_sensor_detector error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")
    plugins_hash = {}
    try:
        plugins = json.loads(plugins)
        for device_id, plugins in plugins.iteritems():
            ips = get_asset_ip_from_id(device_id)
            if len(ips) > 0:
                plugins_hash[device_id] = {
                    "device_ip":
                    ips[0],  # A device  should never have more than one IP
                    "plugins": plugins
                }
    except Exception, e:
        return make_bad_request("Invalid JSON: %s , p=%s" % ("", str(plugins)))
Example #2
0
def login():
    username = request.args.get('username')
    password = request.args.get('password')
    if username is None:
        return make_bad_request(
            API_i18n.error(i18nmsgs.MISSING_PARAMETER_USERNAME))
    if password is None:
        return make_bad_request(
            API_i18n.error(i18nmsgs.MISSING_PARAMETER_PASSWORD))
    if not is_valid_user(username):
        return make_bad_request(API_i18n.error(i18nmsgs.INVALID_USERNAME))

    if not is_valid_user_password(password):
        return make_bad_request(API_i18n.error(i18nmsgs.INVALID_PASSWORD))
    try:
        user = db.session.query(Users).filter_by(login=username).one()
    except NoResultFound:
        return make_error(
            API_i18n.error(i18nmsgs.INVALID_USERNAME_OR_PASSWORD), 401)
    except MultipleResultsFound:
        return make_error(API_i18n.error(i18nmsgs.TOO_MANY_USERNAMES_MATCHING),
                          500)
    except Exception, e:
        return make_error(
            API_i18n.error(i18nmsgs.TOO_MANY_USERNAMES_MATCHING,
                           {"exception": str(e)}), 500)
Example #3
0
def put_sensor_detector(sensor_id):
    """
    Set the [sensor]/detectors list on ossim_setup.conf of the sensor
    """
    # Get the 'plugins' param list, with contains the detector plugins
    # It must be a comma separate list
    plugins = request.args.get('plugins')
    if plugins is None:
        current_app.logger.error("detector: put_sensor_detector error: Missing parameter 'plugins'")
        return make_bad_request("Missing parameter plugins")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("detector: put_sensor_detector error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    (success, data) = set_sensor_detectors(sensor_ip, plugins)
    if not success:
        current_app.logger.error("detector: put_sensor_detector error %s" % data)
        return make_error("Error setting sensor detector plugins", 500)

    # Now launch reconfig task
    job = alienvault_reconfigure.delay(sensor_ip)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #4
0
def put_sensor_detector(sensor_id):
    """
    Set the [sensor]/detectors list on ossim_setup.conf of the sensor
    """
    # Get the 'plugins' param list, with contains the detector plugins
    # It must be a comma separate list
    plugins = request.args.get('plugins')
    if plugins is None:
        current_app.logger.error(
            "detector: put_sensor_detector error: Missing parameter 'plugins'")
        return make_bad_request("Missing parameter plugins")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error(
            "detector: put_sensor_detector error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    (success, data) = set_sensor_detectors(sensor_ip, plugins)
    if not success:
        current_app.logger.error("detector: put_sensor_detector error %s" %
                                 data)
        return make_error("Error setting sensor detector plugins", 500)

    # Now launch reconfig task
    job = alienvault_reconfigure.delay(sensor_ip)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #5
0
def put_sensor_interface(sensor_id):
    """
    Set the [sensor]/interfaces list on ossim_setup.conf of the sensor
    """
    # Get the 'ifaces' param list, with contains the ifaces
    # It must be a comma separate list
    ifaces = request.args.get('ifaces')
    if ifaces is None:
        current_app.logger.error("interfaces: put_sensor_interface error: Missing parameter 'ifaces'")
        return make_bad_request("Missing parameter ifaces")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("interfaces: put_sensor_interface  error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    # Call the ansible module to obtain the [sensor]/iface
    (success, data) = set_sensor_interfaces(sensor_ip, ifaces)
    if not success:
        current_app.logger.error("interfaces: put_sensor_interfaces_from_conf error: %s" % data)
        return make_error("Error setting sensor interfaces", 500)

    # Now launch reconfig task
    job = alienvault_reconfigure.delay(sensor_ip)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #6
0
def put_sensor_detector_by_device(sensor_id):
    """
    Set the [sensor]/detectors list on config.yml of the sensor
    """
    # Get the 'plugins' param list, with contains the detector plugins
    # It must be a comma separate list
    plugins = request.form['plugins']
    if plugins is None:
        current_app.logger.error("detector: put_sensor_detector error: Missing parameter 'plugins'")
        return make_bad_request("Missing parameter plugins")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("detector: put_sensor_detector error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")
    plugins_hash = {}
    try:
        plugins = json.loads(plugins)
        for device_id, plugins in plugins.iteritems():
            ips = get_asset_ip_from_id(device_id)
            if len(ips) > 0:
                plugins_hash[device_id] = {"device_ip": ips[0],  # A device  should never have more than one IP
                                           "plugins": plugins}
    except Exception, e:
        return make_bad_request("Invalid JSON: %s , p=%s" % ("", str(plugins)))
Example #7
0
def get_ossec_check(sensor_id):
    """Creates a new preconfigured agent and return the local path
    :param sensor_id: Sensor id
    :param agent_id: Agent id. Must be a string that match [0-9]{1,4}
    :param agent_type: Type of agent to be generated.
    """
    agent_ip = request.args.get("agent_ip", None)
    agent_name = request.args.get("agent_name", None)
    check_type = request.args.get("check_type", None)
    if check_type not in ["lastscan", "lastip"]:
        return make_bad_request(
            "Invalid check_type value. Allowed values are(lastscan, lastip)")
    if check_type == 'lastip':
        if agent_name is None:
            return make_bad_request(
                "Agent name not specified. Allowed characters are [^a-zA-Z0-9_\\-()]+"
            )
        if re.match(r"[a-zA-Z0-9_\-\(\)]+", agent_name) is None:
            return make_bad_request(
                "Invalid agent name. Allowed characters are [^a-zA-Z0-9_\\-()]+"
            )
    elif not is_valid_ipv4(agent_ip):
        return make_bad_request(
            "Invalid agent_ip value. It should be a valid IP v4 dotted address"
        )
    (result, data) = ossec_get_check(sensor_id=sensor_id,
                                     agent_ip=agent_ip,
                                     agent_name=agent_name,
                                     check_type=check_type)
    if result:
        return make_ok(check=data)
    return make_error(data, 500)
Example #8
0
def ossec_control_interface(sensor_id, operation, option):
    if operation not in ["start", "stop", "restart", "enable", "disable", "status", "status"]:
        return make_bad_request("Invalid operation. Allowed values are: ['start','stop','restart','enable','disable','status']")
    if operation in ["enable", "disable"]:
        if option not in ["client-syslog", "agentless", "debug"]:
            return make_bad_request("Invalid option value. Allowed values are: ['client-syslog','agentless','debug']")

    (result, data) = apimethod_ossec_control(sensor_id, operation, option)
    if result:
        return make_ok(general_status=data['general_status'], service_status=data['service_status'], stdout=data['stdout'], raw_output_status=data['raw_output_status'])
    else:
        return make_error(data, 500)
Example #9
0
def get_ossec_rules_filenames(sensor_id):
    (ret, admin_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not ret:
        current_app.logger.error("sensor: auth_sensor error: " + str(admin_ip))
        return make_bad_request(sensor_id)

    (success, data) = get_ossec_rule_filenames(admin_ip)
    if not success:
        current_app.logger.error("sensor: Can't get  sensor networks for  " + str(sensor_id) + " msg: " + str(data))
        return make_bad_request(sensor_id)
    else:
        return make_ok(rules=data)
Example #10
0
def ossec_control_interface(sensor_id, operation, option):
    if operation not in ["start", "stop", "restart", "enable", "disable", "status", "status"]:
        return make_bad_request("Invalid operation. Allowed values are: ['start','stop','restart','enable','disable','status']")
    if operation in ["enable", "disable"]:
        if option not in ["client-syslog", "agentless", "debug"]:
            return make_bad_request("Invalid option value. Allowed values are: ['client-syslog','agentless','debug']")

    (result, data) = apimethod_ossec_control(sensor_id, operation, option)
    if result:
        return make_ok(general_status=data['general_status'], service_status=data['service_status'], stdout=data['stdout'], raw_output_status=data['raw_output_status'])
    else:
        return make_error(data, 500)
Example #11
0
def get_ossec_rules_filenames(sensor_id):
    (ret, admin_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not ret:
        current_app.logger.error("sensor: auth_sensor error: " + str(admin_ip))
        return make_bad_request(sensor_id)

    (success, data) = get_ossec_rule_filenames(admin_ip)
    if not success:
        current_app.logger.error("sensor: Can't get  sensor networks for  " +
                                 str(sensor_id) + " msg: " + str(data))
        return make_bad_request(sensor_id)
    else:
        return make_ok(rules=data)
Example #12
0
def set_sensor_network(sensor_id):
    netlist = request.args.get('nets').split(",")
    (ret, admin_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not ret:
        current_app.logger.error("sensor: auth_sensor error: " + str(admin_ip))
        return make_bad_request(sensor_id)

    (success, data) = set_sensor_networks(admin_ip, netlist)
    if not success:
        current_app.logger.error("sensor: Can't set sensor networks to " + str(netlist))
        return make_bad_request(sensor_id)
    # Launch configure
    job = alienvault_reconfigure.delay(admin_ip)
    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #13
0
def put_system_network_interface(system_id, iface):
    promisc = request.args.get("promisc")
    if promisc is not None:
        if not is_json_boolean(promisc):
            current_app.logger.error("network: put_system_network_interface error: Bad param 'promisc='%s'" % promisc)
            return make_bad_request("Bad param 'promisc=%s'" % promisc)
    else:
        current_app.logger.error("network: put_system_network_interface error: Missing parameter 'promisc'")
        return make_bad_request("Missing parameters")

    (success, msg) = put_interface(system_id, iface, is_json_true(promisc))
    if not success:
        current_app.logger.error("network: put_system_network_interface error: " + str(msg))
        return make_error(msg, 500)

    return make_ok()
Example #14
0
def get_sensor_detector_by_device(sensor_id):
    """
    Return the [sensor]/plugin list for a given sensor
    :param sensor_id: The sensor which we want to get the data
    :param device_id: Filter by device (canonical uuid)
    """
    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error(
            "detector: get_sensor_detector: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    device_id = request.args.get('device_id', None)

    # Now call the ansible module to obtain the [sensor]/iface
    (success, data) = get_sensor_detectors_from_yaml(sensor_ip)
    if not success:
        current_app.logger.error(
            "detector: get_sensor_detector_by_device: %s" % str(data))
        return make_error("Error getting sensor plugins", 500)
    try:
        yaml_data = get_plugin_get_request_from_yml(
            data['contacted'][sensor_ip]['plugins'], device_id)
    except:
        return make_error(
            "Something wrong while parsing the yml file. %s" % data, 500)
    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(plugins=yaml_data)
Example #15
0
def get_service_status(sensor_id):
    (success, data) = get_service_status_by_id(sensor_id)
    if not success:
        current_app.logger.error("sensor: Can't get services status " + str(sensor_id) + " msg: " + str(data))
        return make_bad_request(sensor_id)
    else:
        return make_ok(**data)
Example #16
0
def ossec_add_new_agent(sensor_id):
    """
    Call API method to run ossec_create_new_agent script
    """

    agent_name = request.args.get('agent_name', None)
    agent_ip = request.args.get('agent_ip', None)
    asset_id = request.args.get('asset_id', None)

    # Check valid input
    valid_str = re.compile('^[-.\w]+$')
    if not valid_str.match(agent_name) or not (is_valid_ipv4(agent_ip) or is_valid_ipv4_cidr(agent_ip)):
        return make_bad_request("Invalid agent name or address")

    # Now call the api method to create the new agent - If everything is right it returns the agent id of the new agent
    (success, data) = api_ossec_add_new_agent(sensor_id, agent_name, agent_ip, asset_id)
    if not success:
        current_app.logger.error("ossec_agent: error creating new agent: " + str(data))
        return make_error(data, 500)

    # Now we get the agent detail
    try:
        agent_id = data
        (success, data) = apimethod_ossec_get_agent_from_db(sensor_id, agent_id)
    except APIException as e:
        return make_error_from_exception(e)

    if success:
        return make_ok(agent_detail=data)
    else:
        return make_error(data, 500)
Example #17
0
def set_sensor_network(sensor_id):
    netlist = request.args.get('nets').split(",")
    (ret, admin_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not ret:
        current_app.logger.error("sensor: auth_sensor error: " + str(admin_ip))
        return make_bad_request(sensor_id)

    (success, data) = set_sensor_networks(admin_ip, netlist)
    if not success:
        current_app.logger.error("sensor: Can't set sensor networks to " +
                                 str(netlist))
        return make_bad_request(sensor_id)
    # Launch configure
    job = alienvault_reconfigure.delay(admin_ip)
    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #18
0
def get_service_status(sensor_id):
    (success, data) = get_service_status_by_id(sensor_id)
    if not success:
        current_app.logger.error("sensor: Can't get services status " +
                                 str(sensor_id) + " msg: " + str(data))
        return make_bad_request(sensor_id)
    else:
        return make_ok(**data)
Example #19
0
def run_ossec_control(sensor_id, operation):
    option = request.args.get('option')
    if operation not in ["start", "stop", "restart", "enable", "disable"]:
        return make_bad_request(
            "Invalid operation. Allowed values are: ['start','stop','restart','enable','disable']"
        )

    return ossec_control_interface(sensor_id, operation, option)
Example #20
0
def get_data_status_messages():
    """Retrieves a list of current_status messages matching the given criteria"""
    component_id = request.args.get('component_id')
    component_type = request.args.get('component_type')
    message_id = request.args.get('message_id', None)
    search = request.args.get('search', None)
    order_desc = is_json_true(request.args.get('order_desc'))
    only_unread = is_json_true(request.args.get('only_unread'))

    level = request.args.get('level')
    if level is not None:
        level = level.split(',')
        valid_levels = ["info","warning","error"]
        if not set(level).issubset(valid_levels):
            return make_bad_request("Invalid parameter level. Allowed valeus are %s" % str(valid_levels))

    page = request.args.get('page', 1)
    if page is not None:
        if not is_valid_integer(page):
            return make_bad_request("The parameter page (%s) is not a valid integer value" % str(page))
        page = int(page)

    page_row = request.args.get('page_rows', 50)
    if page_row is not None:
        page_row = int(page_row)

    message_type = request.args.get('message_type', None)
    if message_type is not None:
        message_type = message_type.split(',')

    orderby = request.args.get('order_by')
    if orderby not in ['creation_time', 'component_type', 'message_level', 'message_type', 'message_title', '', None]:
        return make_bad_request("Invalid parameter order by. Allowed values are ('creation_time','component_type','"
                                "message_level','message_type','message_title','')")

    (success, data) = get_status_messages(component_id=component_id, message_level=level, order_by=orderby,
                                          page=page, page_row=page_row, order_desc=order_desc,
                                          component_type=component_type, message_id=message_id,
                                          message_type=message_type, search=search, only_unread=only_unread,
                                          login_user=current_user.login,
                                          is_admin=current_user.is_admin)

    if not success:
        return make_error(data, 500)
    return make_ok(**data)
Example #21
0
        def check_accepts(*args, **kwargs):
            url_params = dict(kwargs, **request.args.to_dict())
            if request.method == "POST":
                #We need to load also the url params or they won't be validated 
                #url_params = {} 
                for key in request.form.keys():
                    url_params[key] = request.form[key]

            url_constraints = url
            invalid_params = [x for x in url_params.keys() if x not in url_constraints.keys()]
            if invalid_params != []:
                return make_bad_request("URL contains parameters not included in the constraint")
            for key, item in url_constraints.items():
                try:
                    # Composite check, with 'values', 'type', and/or 'optional' parameters.
                    if type(item) == dict:
                        obj = item['type'](url_params[key])
                        del obj

                    # Simple check, only with 'type'
                    elif type(item) == type:
                        if item == str:
                            if type(url_params[key]) != str and type(url_params[key]) != unicode:
                                return make_bad_request("URL parameter %s does not meet the simple 'type' constraint" % str(key)[:20])
                        elif item == uuid.UUID:
                            try:
                                u = uuid.UUID(url_params[key])
                                #The uuid should be in its canonical form XXXXXXXX-YYYY-ZZZZ-DDDD-HHHHHHHHHHHH
                                #>>> import uuid
                                #>>> print uuid.UUID("8219d0ff--cf8-0-11-e3-b-84d-000c29764e58")
                                #8219d0ff-cf80-11e3-b84d-000c29764e58
                                if valid_canonical_uuid.match(url_params[key]) is None:
                                    return make_bad_request("URL parameter %s does not meet the simple 'type' constraint" % str(key)[:20])
                            except ValueError:
                                return  make_bad_request("URL parameter %s does not meet the simple 'type' constraint" % str(key)[:20])
                        elif type(url_params[key]) != item:
                            return make_bad_request("URL parameter %s does not meet the simple 'type' constraint" % str(key)[:20])
                    else:
                        # Default case
                        return make_bad_request("Invalid type for the item")
                except (TypeError, ValueError), e:
                    if hasattr(item, '__iter__'):
                        # If the 'type' check fails, try for defined values.
                        if ('values' in item and item['values'] == []) or \
                           ('values' in item and url_params[key] not in item['values']) or \
                           ('values' not in item):
                            return make_bad_request("URL parameter %s does not meet the 'type' constraint" % str(key)[:20])

                except KeyError, e:
                    # Only check the values / optional params if the items is iterable
                    if hasattr(item, '__iter__'):
                        # Ignore the parameter if 'optional' is set to 'True' or is not setted at all.
                        if ('optional' in item and item['optional'] != True and key not in url_params) or \
                           ('optional' not in item and key not in url_params):
                            return make_bad_request("URL parameter %s does not meet the 'optional' constraint" % str(key)[:20])
Example #22
0
def get_ossec_check(sensor_id):
    """Get additional information(Last syscheck or rootcheck date and/or last IP used) about an agent
    :param sensor_id: Sensor id
    """
    agent_name = request.args.get("agent_name", None)
    check_type = request.args.get("check_type", None)

    if check_type not in ["lastscan", "lastip"]:
        return make_bad_request("Invalid check_type value. Allowed values are(lastscan, lastip)")
    if agent_name is None:
        return make_bad_request("Agent name not specified. Allowed characters are [^a-zA-Z0-9_\\-()]+")
    if re.match(r"[a-zA-Z0-9_\-\(\)]+", agent_name) is None:
        return make_bad_request("Invalid agent name. Allowed characters are [^a-zA-Z0-9_\\-()]+")

    (result, data) = ossec_get_check(sensor_id=sensor_id, agent_name=agent_name, check_type=check_type)
    if result:
        return make_ok(check=data)
    return make_error(data, 500)
Example #23
0
def get_ossec_preconfigured_agent(sensor_id):
    """Creates a new preconfigured agent and return the local path
    :param sensor_id: Sensor id
    :param agent_id: Agent id. Must be a string that match [0-9]{1,4}
    :param agent_type: Type of agent to be generated.
    """
    agent_id = request.args.get("agent_id", None)
    agent_type = request.args.get("agent_type", None)
    if agent_type not in ["windows", "unix"]:
        return make_bad_request("Invalid agent_type value. Allowed values are(unix,windows)")
    if re.match(r"^[0-9]{1,4}$", agent_id) is None:
        return make_bad_request("Invalid agent_id value. Allowed values are [0-9]{1,4}")

    (result, data) = ossec_get_preconfigured_agent(sensor_id, agent_id, agent_type)
    if result:
        return make_ok(path=data)

    return make_error(data, 500)
def get_configuration_rule_file(sensor_id):
    rule_filename = request.args.get("rule")
    if rule_filename is None or rule_filename == "":
        return make_bad_request("Invalid rule filename <%s>" % rule_filename)
    (success, data) = apimethod_get_configuration_rule_file(sensor_id, rule_filename)
    if not success:
        return make_error(data, 500)
    else:
        return make_ok(local_path=str(data))
def put_configuration_rule_file(sensor_id):
    rule_filename = request.args.get("rule")
    if rule_filename not in ['local_rules.xml','rules_config.xml']:
        return make_bad_request("Invalid value for rule name. Allowed values are ['local_rules.xml','rules_config.xml'] ")
    (success, data) = apimethod_put_ossec_configuration_file(sensor_id,rule_filename)
    if not success:
        return make_error(data, 500)
    else:
        return make_ok(message=str(data))
Example #26
0
def get_ossec_preconfigured_agent(sensor_id):
    """Creates a new preconfigured agent and return the local path
    :param sensor_id: Sensor id
    :param agent_id: Agent id. Must be a string that match [0-9]{1,4}
    :param agent_type: Type of agent to be generated.
    """
    agent_id = request.args.get("agent_id", None)
    agent_type = request.args.get("agent_type", None)
    if agent_type not in ["windows", "unix"]:
        return make_bad_request("Invalid agent_type value. Allowed values are(unix,windows)")
    if re.match(r"^[0-9]{1,4}$", agent_id) is None:
        return make_bad_request("Invalid agent_id value. Allowed values are [0-9]{1,4}")

    (result, data) = ossec_get_preconfigured_agent(sensor_id, agent_id, agent_type)
    if result:
        return make_ok(path=data)

    return make_error(data, 500)
Example #27
0
        def check_accepts(*args, **kwargs):
            url_params = dict(kwargs, **request.args.to_dict())
            if request.method == "POST":
                for key in request.form.keys():
                    url_params[key] = request.form[key]

            url_constraints = url
            invalid_params = [x for x in url_params.keys() if x not in url_constraints.keys()]
            if invalid_params != []:
                return make_bad_request("URL contains parameters not included in the constraint")
            for key, item in url_constraints.items():
                try:
                    # Composite check, with 'values', 'type', and/or 'optional' parameters.
                    item_is_dict = type(item) == dict
                    if item_is_dict:
                        if (key not in url_params and 'optional' in item and item['optional'] is True):
                            continue
                        item_type = item.get('type', None)
                    else:
                        item_type = item

                    item_value = url_params[key]
                    # UUID exception. 'local' value allowed
                    if item_type == uuid.UUID and item_value in ['local']:
                        continue

                    if item_type:
                        obj = item_type(item_value)
                        del obj

                    # Check allowed values except for UUID
                    if item_is_dict and item_type != uuid.UUID and \
                       'values' in item and item_value not in item['values']:
                            return make_bad_request("URL parameter %s does not meet the allowed values" % str(key)[:20])

                except (ValueError, TypeError) as e:
                    return make_bad_request("Invalid type %s" % str(key))
                except KeyError as e:
                    return make_bad_request("Missing parameter %s" % str(key))
                except Exception as e:
                    app.logger.error(str(e))
                    return make_bad_request("Paramerter verification failure")

            return func(*args, **kwargs)
Example #28
0
def support(system_id):
    ticket = request.args.get('ticket')
    if ticket is None:
        return make_bad_request("Missing param ticket")

    (success, data) = get_support_info (system_id, ticket)
    if not success:
        return make_error (data, 500)

    return make_ok (**data)
def get_configuration_rule_file(sensor_id):
    rule_filename = request.args.get("rule")
    if rule_filename is None or rule_filename == "":
        return make_bad_request("Invalid rule filename <%s>" % rule_filename)
    (success,
     data) = apimethod_get_configuration_rule_file(sensor_id, rule_filename)
    if not success:
        return make_error(data, 500)
    else:
        return make_ok(local_path=str(data))
Example #30
0
def add_system():
    if not is_valid_ipv4(request.form['system_ip']):
        return make_bad_request("Bad system_ip: %s" % request.form['system_ip'])

    (success, system_data) = system.add_system_from_ip(request.form['system_ip'],
                                                       request.form['password'])
    if not success:
        current_app.logger.error("system: add_system error: " + str(system_data))
        return make_error(system_data, 500)

    return make_ok(**system_data)
Example #31
0
def login():
    username = request.args.get('username')
    password = request.args.get('password')
    if username is None:
        return make_bad_request(API_i18n.error(i18nmsgs.MISSING_PARAMETER_USERNAME))
    if password is None:
        return make_bad_request(API_i18n.error(i18nmsgs.MISSING_PARAMETER_PASSWORD))
    if not is_valid_user(username):
        return make_bad_request(API_i18n.error(i18nmsgs.INVALID_USERNAME))

    if not is_valid_user_password(password):
        return make_bad_request(API_i18n.error(i18nmsgs.INVALID_PASSWORD))
    try:
        user = db.session.query(Users).filter_by(login=username).one()
    except NoResultFound:
        return make_error(API_i18n.error(i18nmsgs.INVALID_USERNAME_OR_PASSWORD), 401)
    except MultipleResultsFound:
        return make_error(API_i18n.error(i18nmsgs.TOO_MANY_USERNAMES_MATCHING), 500)
    except Exception, e:
        return make_error(API_i18n.error(i18nmsgs.TOO_MANY_USERNAMES_MATCHING, {"exception": str(e)}), 500)
def put_configuration_rule_file(sensor_id):
    rule_filename = request.args.get("rule")
    if rule_filename not in ['local_rules.xml', 'rules_config.xml']:
        return make_bad_request(
            "Invalid value for rule name. Allowed values are ['local_rules.xml','rules_config.xml'] "
        )
    (success,
     data) = apimethod_put_ossec_configuration_file(sensor_id, rule_filename)
    if not success:
        return make_error(data, 500)
    else:
        return make_ok(message=str(data))
Example #33
0
def put_system_network_interface(system_id, iface):
    promisc = request.args.get("promisc")
    if promisc is not None:
        if not is_json_boolean(promisc):
            current_app.logger.error(
                "network: put_system_network_interface error: Bad param 'promisc='%s'"
                % promisc)
            return make_bad_request("Bad param 'promisc=%s'" % promisc)
    else:
        current_app.logger.error(
            "network: put_system_network_interface error: Missing parameter 'promisc'"
        )
        return make_bad_request("Missing parameters")

    (success, msg) = put_interface(system_id, iface, is_json_true(promisc))
    if not success:
        current_app.logger.error(
            "network: put_system_network_interface error: " + str(msg))
        return make_error(msg, 500)

    return make_ok()
Example #34
0
def upload():
    try:
        plugin_file = request.form['plugin_file']
        vendor = request.form.get('vendor', '')
        model = request.form.get('model', '')
        if not model:
            return make_bad_request("Model cannot be null")
        if not vendor:
            return make_bad_request("Vendor cannot be null")
        version = request.form.get('version', '-')
        overwrite = request.form.get('overwrite', False)
        product_type = request.form.get('product_type', '')
        data = apimethod_upload_plugin(plugin_file=plugin_file,
                                       model=model,
                                       vendor=vendor,
                                       version=version,
                                       overwrite=overwrite,
                                       product_type=product_type)
    except APIException as e:
        return make_error_from_exception(e)
    return make_ok(**data)
Example #35
0
def set_system_interfaces_roles(system_id):
    try:
        interfaces = loads(request.args.get("interfaces", None))
    except ValueError:
        current_app.logger.error("network: Bad 'interfaces' parameter. Must be a correct url encoded string or bad json data")
        return make_bad_request("Bad parameter data")

    (success, data) = set_interfaces_roles(system_id, interfaces)
    if not success:
        return make_error(data, 500)

    return make_ok(jobid=data)
Example #36
0
def upload():
    try:
        plugin_file = request.form['plugin_file']
        vendor = request.form.get('vendor', '')
        model = request.form.get('model', '')
        if not model:
            return make_bad_request("Model cannot be null")
        if not vendor:
            return make_bad_request("Vendor cannot be null")
        version = request.form.get('version', '-')
        overwrite = request.form.get('overwrite', False)
        product_type = request.form.get('product_type', '')
        data = apimethod_upload_plugin(plugin_file=plugin_file,
                                       model=model,
                                       vendor=vendor,
                                       version=version,
                                       overwrite=overwrite,
                                       product_type=product_type)
    except APIException as e:
        return make_error_from_exception(e)
    return make_ok(**data)
Example #37
0
def set_data_status_message(status_message_id):
    """Sets the status message as viewed/suppressed"""
    viewed = request.args.get('viewed', None)
    suppressed = request.args.get('suppressed', None)
    if viewed is None and suppressed is None:
        return make_bad_request("Missing parameter. viewed or suppressed are required")
    if viewed not in ['true', 'false', None]:
        return make_bad_request("Invalid value for parameter viewed")
    if suppressed not in ['true', 'false', None]:
        return make_bad_request("Invalid value for parameter suppressed")

    if viewed is not None:
        viewed = True if viewed == 'true' else False
        (success, data) = set_status_message_as_viewed(status_message_id, viewed)
        if not success:
            return make_error(data, 500)
    if suppressed is not None:
        suppressed = True if suppressed == 'true' else False
        (success, data) = set_status_message_as_suppressed(status_message_id, suppressed)
        if not success:
            return make_error(data, 500)
    return make_ok()
Example #38
0
def get_ossec_check(sensor_id):
    """Creates a new preconfigured agent and return the local path
    :param sensor_id: Sensor id
    :param agent_id: Agent id. Must be a string that match [0-9]{1,4}
    :param agent_type: Type of agent to be generated.
    """
    agent_ip = request.args.get("agent_ip", None)
    agent_name = request.args.get("agent_name", None)
    check_type = request.args.get("check_type", None)
    if check_type not in ["lastscan", "lastip"]:
        return make_bad_request("Invalid check_type value. Allowed values are(lastscan, lastip)")
    if check_type == 'lastip':
        if agent_name is None:
            return make_bad_request("Agent name not specified. Allowed characters are [^a-zA-Z0-9_\\-()]+")
        if re.match(r"[a-zA-Z0-9_\-\(\)]+", agent_name) is None:
            return make_bad_request("Invalid agent name. Allowed characters are [^a-zA-Z0-9_\\-()]+")
    elif not is_valid_ipv4(agent_ip):
        return make_bad_request("Invalid agent_ip value. It should be a valid IP v4 dotted address")
    (result, data) = ossec_get_check(sensor_id=sensor_id, agent_ip=agent_ip, agent_name=agent_name, check_type=check_type)
    if result:
        return make_ok(check=data)
    return make_error(data, 500)
Example #39
0
def set_system_interfaces_roles(system_id):
    try:
        interfaces = loads(request.args.get("interfaces", None))
    except ValueError:
        current_app.logger.error(
            "network: Bad 'interfaces' parameter. Must be a correct url encoded string or bad json data"
        )
        return make_bad_request("Bad parameter data")

    (success, data) = set_interfaces_roles(system_id, interfaces)
    if not success:
        return make_error(data, 500)

    return make_ok(jobid=data)
Example #40
0
def get_data_status_messages():

    component_id = request.args.get('component_id')
    component_type = request.args.get('component_type')
    message_id = request.args.get('message_id', None)

    level = request.args.get('level')
    if level is not None:
        level = level.split(',')
    order_desc = request.args.get('order_desc')

    page = request.args.get('page', 1)
    if page is not None:
        if not is_valid_integer(page):
            return make_error(
                "The parameter page (%s) is not a valid integer value" %
                str(page), 500)
        page = int(page)

    if message_id is not None:
        if not is_valid_integer(message_id):
            return make_error(
                "The parameter message_id (%s) is not a valid integer value" %
                str(message_id), 500)
        message_id = int(message_id)

    page_row = request.args.get('page_rows', 50)
    if page_row is not None:
        page_row = int(page_row)

    orderby = request.args.get('order_by')

    if orderby not in ['creation_time', 'component_type', 'level', '', None]:
        return make_bad_request(
            "Invalid parameter order by. Allowed values are ('creation_time','component_type','level','')"
        )

    (success, data) = get_status_messages(component_id=component_id,
                                          level=level,
                                          orderby=orderby,
                                          page=page,
                                          page_row=page_row,
                                          order_desc=order_desc,
                                          component_type=component_type,
                                          message_id=message_id)
    if not success:
        return make_error(data, 500)

    return make_ok(**data)
Example #41
0
def ossec_delete_agent(sensor_id, agent_id):
    """
    Call API method to run ossec_delete_agent script
    """

    # Check valid input
    if not is_valid_ossec_agent_id(agent_id):
        return make_bad_request("Invalid agent ID")

    # Now call the api method to create the new agent
    (success, data) = api_ossec_delete_agent(sensor_id, agent_id)
    if not success:
        current_app.logger.error("ossec_agent: error deleting agent: " + str(data))
        return make_error(data, 500)

    return make_ok(messages=data)
Example #42
0
def post_enable_tunnel(system_id):
    """
        Handle the url
        POST /av/api/1.0/system/<system_id>/support/tunnel

        Args:
            system_id (str): String with system id (uuid) or local
    """
    case_id = request.form.get('ticket')
    if case_id is None:
        return make_bad_request("Missing param ticket")
    success, result = connect_tunnel(system_id, case_id)
    if not success:
        api_log.error("Failed API call: remote addr = %s, host addr = %s, blueprint = %s, URL = %s method = %s result = %s" % (request.remote_addr, request.host, request.blueprint, request.base_url, request.method, str(result)))
        return make_error(result,  500)
    return make_ok()
Example #43
0
def bp_get_sensor_plugins_detector_enabled(sensor_id):
    """
    Return the [sensor]/plugin list from ossim_setup.conf of sensor
    """
    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("detector: get_sensor_detector: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    # Now call the ansible module to obtain the [sensor]/iface
    (success, data) = get_sensor_detectors(sensor_ip)
    if not success:
        current_app.logger.error("detector: get_sensor_detector: %s" % str(data))
        return make_error("Error getting sensor plugins", 500)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(plugins=data)
Example #44
0
def get_sensor_interface(sensor_id):
    """
    Return the [sensor]/interfaces list from ossim_setup.conf of sensor
    """
    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("interfaces: get_sensor_interface  error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    # Now call the ansible module to obtain the [sensor]/iface
    (success, data) = get_sensor_interfaces(sensor_ip)
    if not success:
        current_app.logger.error("interfaces: get_sensor_interfaces_from_conf error: %s" % data)
        return make_error("Error getting sensor interfaces", 500)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(interfaces=data)
Example #45
0
def post_system_backup(system_id):
    """
    Launch a configuration backup
    """
    backup_type = request.form.get('type', '')
    if backup_type not in ["configuration"]:
        return make_bad_request("Backup type not allowed")

    try:
        job = backup_configuration_for_system_id.delay(system_id=system_id, method="manual")
        if job is None:
            return make_error('Something bad happened running the backup', 500)
    except AlreadyQueued:
        error_msg = "There is an existing backup task running"
        return make_error(error_msg, 500)

    return make_ok(job_id=job.id)
Example #46
0
def ossec_delete_agentless(sensor_id):
    """
    Call API method to run ossec_delete_agentless script
    """

    agent_ip = request.args.get('agent_ip', None)

    # Check valid input
    if not is_valid_ipv4(agent_ip):
        return make_bad_request("Invalid agent IP")

    # Now call the api method to create the new agent
    (success, data) = api_ossec_delete_agentless(sensor_id, agent_ip)
    if not success:
        current_app.logger.error("ossec_agent: error deleting agentless queue: " + str(data))
        return make_error(data, 500)

    return make_ok(messages=data)
Example #47
0
def delete_system_backups(system_id):
    """
    Delete the backups specified from the system
    """
    backup_type = request.args.get('type', '')
    try:
        backup_list = json.loads(request.args.get('backups', None))
    except ValueError:
        return make_bad_request("backups not valid")

    success, msg = delete_backups(system_id=system_id,
                                  backup_type=backup_type,
                                  backup_list=backup_list)

    if not success:
        return make_error("Error deleting backups: %s" % msg, 500)

    return make_ok()
Example #48
0
def get_system_backup_file(system_id, backup_name):
    """
    Get a backup file from a remote system.
    """
    backup_type = request.args.get('type', '')
    if backup_type not in ["configuration"]:
        return make_bad_request("Backup type not allowed")

    # Create file first.
    dst_file_path = "/var/alienvault/backup/downloaded/%s" % backup_name

    if os.path.exists(dst_file_path):
        os.remove(dst_file_path)
    try:
        with open(dst_file_path, 'w'):
            os.utime(dst_file_path, None)
    except Exception, e:
        return make_error('Cannot create destination file "%s": %s' % (dst_file_path, str(e)), 500)