예제 #1
0
파일: security.py 프로젝트: vvring/wazuh
def remove_policies(policy_ids=None):
    """Removes a certain policy from the system

    :param policy_ids: ID of the policy to be removed (All for all policies)
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(
        none_msg='No policy was deleted',
        some_msg='Some policies were not deleted',
        all_msg='All specified policies were deleted')
    with PoliciesManager() as pm:
        for p_id in policy_ids:
            policy = pm.get_policy_id(int(p_id))
            policy_delete = pm.delete_policy(int(p_id))
            if policy_delete == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=int(p_id), error=WazuhError(4008))
            elif policy_delete == SecurityError.RELATIONSHIP_ERROR:
                result.add_failed_item(id_=int(p_id), error=WazuhError(4025))
            elif not policy_delete:
                result.add_failed_item(id_=int(p_id), error=WazuhError(4007))
            elif policy:
                result.affected_items.append(policy)
                result.total_affected_items += 1
                invalid_roles_tokens(roles=policy['roles'])

        result.affected_items = sorted(result.affected_items,
                                       key=lambda i: i['id'])

    return result
예제 #2
0
파일: security.py 프로젝트: thzt16/wazuh
def get_policies(policy_ids, offset=0, limit=common.database_limit, sort_by=None,
                 sort_ascending=True, search_text=None, complementary_search=False, search_in_fields=None):
    """Returns the information of a certain policy

    :param policy_ids: ID of the policy on which the information will be collected (All for all policies)
    :param offset: First item to return
    :param limit: Maximum number of items to return
    :param sort_by: Fields to sort the items by. Format: {"fields":["field1","field2"],"order":"asc|desc"}
    :param sort_ascending: Sort in ascending (true) or descending (false) order
    :param search_text: Text to search
    :param complementary_search: Find items without the text to search
    :param search_in_fields: Fields to search in
    :return: Dictionary: {'items': array of items, 'totalItems': Number of items (without applying the limit)}
    """
    result = AffectedItemsWazuhResult(none_msg='No policy was returned',
                                      some_msg='Some policies were not returned',
                                      all_msg='All specified policies were returned')
    affected_items = list()
    with PoliciesManager() as pm:
        for p_id in policy_ids:
            policy = pm.get_policy_id(int(p_id))
            if policy != SecurityError.POLICY_NOT_EXIST:
                affected_items.append(policy)
            else:
                # Policy id does not exist
                result.add_failed_item(id_=int(p_id), error=WazuhError(4007))

    data = process_array(affected_items, search_text=search_text, search_in_fields=search_in_fields,
                         complementary_search=complementary_search, sort_by=sort_by, sort_ascending=sort_ascending,
                         offset=offset, limit=limit)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result
예제 #3
0
파일: security.py 프로젝트: thzt16/wazuh
def update_policy(policy_id=None, name=None, policy=None):
    """Updates a policy in the system

    :param policy_id: Policy id to be update
    :param name: The new policy name
    :param policy: The new policy
    :return Policy information
    """
    if name is None and policy is None:
        raise WazuhError(4001)
    result = AffectedItemsWazuhResult(none_msg='Policy was not updated',
                                      all_msg='Policy was successfully updated')
    with PoliciesManager() as pm:
        status = pm.update_policy(policy_id=policy_id[0], name=name, policy=policy)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=int(policy_id[0]), error=WazuhError(4013))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=int(policy_id[0]), error=WazuhError(4006))
        elif status == SecurityError.POLICY_NOT_EXIST:
            result.add_failed_item(id_=int(policy_id[0]), error=WazuhError(4007))
        elif status == SecurityError.ADMIN_RESOURCES:
            result.add_failed_item(id_=int(policy_id[0]), error=WazuhError(4008))
        else:
            updated = pm.get_policy_id(int(policy_id[0]))
            result.affected_items.append(updated)
            result.total_affected_items += 1
            invalid_roles_tokens(roles=updated['roles'])

    return result
예제 #4
0
파일: security.py 프로젝트: thzt16/wazuh
def get_user_me():
    """Get the information of the current user

    Returns
    -------
    AffectedItemsWazuhResult with the desired information
    """
    result = AffectedItemsWazuhResult(all_msg='Current user information was returned')
    affected_items = list()
    with AuthenticationManager() as auth:
        user = auth.get_user(common.current_user.get())
        for index, role_id in enumerate(user['roles']):
            with RolesManager() as rm:
                role = rm.get_role_id(role_id=int(role_id))
                role.pop('users')
                for index_r, rule_id in enumerate(role['rules']):
                    with RulesManager() as rum:
                        role['rules'][index_r] = rum.get_rule(rule_id=int(rule_id))
                        role['rules'][index_r].pop('roles')
                for index_p, policy_id in enumerate(role['policies']):
                    with PoliciesManager() as pm:
                        role['policies'][index_p] = pm.get_policy_id(policy_id=int(policy_id))
                        role['policies'][index_p].pop('roles')
                user['roles'][index] = role
        affected_items.append(user) if user else result.add_failed_item(id_=common.current_user.get(),
                                                                        error=WazuhError(5001))

    data = process_array(affected_items)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result
예제 #5
0
def remove_policies(policy_ids=None):
    """Removes a certain policy from the system

    :param policy_ids: ID of the policy to be removed (All for all policies)
    :return Result of operation
    """
    result = AffectedItemsWazuhResult(none_msg='No policies were deleted',
                                      some_msg='Some policies could not be deleted',
                                      all_msg='All specified policies were deleted')
    with PoliciesManager() as pm:
        for p_id in policy_ids:
            policy = pm.get_policy_id(int(p_id))
            if policy != SecurityError.POLICY_NOT_EXIST and int(p_id) not in admin_policy_ids:
                related_users = check_relationships(policy['roles'])
            policy_delete = pm.delete_policy(int(p_id))
            if policy_delete == SecurityError.ADMIN_RESOURCES:
                result.add_failed_item(id_=p_id, error=WazuhError(4008))
            elif not policy_delete:
                result.add_failed_item(id_=p_id, error=WazuhError(4007))
            elif policy:
                result.affected_items.append(policy)
                result.total_affected_items += 1
                invalid_users_tokens(users=list(related_users))
        result.affected_items = sorted(result.affected_items, key=lambda i: i['id'])

    return result
예제 #6
0
파일: decorators.py 프로젝트: zWaR/wazuh
def _expand_resource(resource):
    """This function expand a specified resource depending of its type.
    
    Parameters
    ----------
    resource : str
        Resource to be expanded

    Returns
    -------
    str
        Result of the resource expansion.
    """
    name, attribute, value = resource.split(':')
    resource_type = ':'.join([name, attribute])

    # This is the special case, expand_group can receive * or the name of the group. That's why it' s always called
    if resource_type == 'agent:group':
        return expand_group(value)

    # We need to transform the wildcard * to the resource of the system
    if value == '*':
        if resource_type == 'agent:id':
            return get_agents_info()
        elif resource_type == 'group:id':
            return get_groups()
        elif resource_type == 'role:id':
            with RolesManager() as rm:
                roles = rm.get_roles()
            return {str(role_id.id) for role_id in roles}
        elif resource_type == 'policy:id':
            with PoliciesManager() as pm:
                policies = pm.get_policies()
            return {str(policy_id.id) for policy_id in policies}
        elif resource_type == 'user:id':
            users_system = set()
            with AuthenticationManager() as auth:
                users = auth.get_users()
            for user in users:
                users_system.add(str(user['user_id']))
            return users_system
        elif resource_type == 'rule:id':
            with RulesManager() as rum:
                rules = rum.get_rules()
            return {str(rule_id.id) for rule_id in rules}
        elif resource_type == 'rule:file':
            return expand_rules()
        elif resource_type == 'decoder:file':
            return expand_decoders()
        elif resource_type == 'list:file':
            return expand_lists()
        elif resource_type == 'node:id':
            return set(cluster_nodes.get())
        elif resource_type == '*:*':  # Resourceless
            return {'*'}
        return set()
    # We return the value casted to set
    else:
        return {value}
예제 #7
0
파일: security.py 프로젝트: thzt16/wazuh
def add_policy(name=None, policy=None):
    """Creates a policy in the system

    :param name: The new policy name
    :param policy: The new policy
    :return Policy information
    """
    result = AffectedItemsWazuhResult(none_msg='Policy was not created',
                                      all_msg='Policy was successfully created')
    with PoliciesManager() as pm:
        status = pm.add_policy(name=name, policy=policy)
        if status == SecurityError.ALREADY_EXIST:
            result.add_failed_item(id_=name, error=WazuhError(4009))
        elif status == SecurityError.INVALID:
            result.add_failed_item(id_=name, error=WazuhError(4006))
        else:
            result.affected_items.append(pm.get_policy(name=name))
            result.total_affected_items += 1

    return result
예제 #8
0
def _expand_resource(resource):
    """This function expand a specified resource depending of it type.

    :param resource: Resource to be expanded
    :return expanded_resource: Returns the result of the resource expansion
    """
    name, attribute, value = resource.split(':')
    resource_type = ':'.join([name, attribute])

    # This is the special case, expand_group can receive * or the name of the group. That's why it' s always called
    if resource_type == 'agent:group':
        return expand_group(value)

    # We need to transform the wildcard * to the resource of the system
    if value == '*':
        if resource_type == 'agent:id':
            return get_agents_info()
        elif resource_type == 'group:id':
            return get_groups()
        elif resource_type == 'role:id':
            with RolesManager() as rm:
                roles = rm.get_roles()
            return {str(role_id.id) for role_id in roles}
        elif resource_type == 'policy:id':
            with PoliciesManager() as pm:
                policies = pm.get_policies()
            return {str(policy_id.id) for policy_id in policies}
        elif resource_type == 'user:id':
            users_system = set()
            with AuthenticationManager() as auth:
                users = auth.get_users()
            for user in users:
                users_system.add(user['user_id'])
            return users_system
        elif resource_type == 'rule:id':
            with RulesManager() as rum:
                rules = rum.get_rules()
            return {str(rule_id.id) for rule_id in rules}
        elif resource_type == 'rule:file':
            tags = ['rule_include', 'rule_exclude', 'rule_dir']
            format_rules = format_rule_decoder_file(
                get_ossec_conf(section='ruleset')['ruleset'], {
                    'status': Status.S_ALL.value,
                    'relative_dirname': None,
                    'filename': None
                }, tags)
            return {rule['filename'] for rule in format_rules}
        elif resource_type == 'decoder:file':
            tags = ['decoder_include', 'decoder_exclude', 'decoder_dir']
            format_decoders = format_rule_decoder_file(
                get_ossec_conf(section='ruleset')['ruleset'], {
                    'status': Status.S_ALL.value,
                    'relative_dirname': None,
                    'filename': None
                }, tags)
            return {decoder['filename'] for decoder in format_decoders}
        elif resource_type == 'list:path':
            return {
                os.path.join(cdb_list['relative_dirname'],
                             cdb_list['filename'])
                for cdb_list in iterate_lists(only_names=True)
            }
        elif resource_type == 'node:id':
            return set(cluster_nodes.get())
        elif resource_type == 'file:path':
            return get_files()
        elif resource_type == '*:*':  # Resourceless
            return {'*'}
        return set()
    # We return the value casted to set
    else:
        return {value}
예제 #9
0
def get_policies(policy_ids,
                 offset=0,
                 limit=common.database_limit,
                 sort_by=None,
                 select=None,
                 sort_ascending=True,
                 search_text=None,
                 complementary_search=False,
                 search_in_fields=None):
    """Return the information of a certain policy.

    Parameters
    ----------
    policy_ids : list
        ID of the policy on which the information will be collected (All for all policies)
    offset : int
        First item to return
    limit : int
        Maximum number of items to return
    sort_by : dict
        Fields to sort the items by. Format: {"fields":["field1","field2"],"order":"asc|desc"}
    sort_ascending : bool
        Sort in ascending (true) or descending (false) order
    search_text : str
        Text to search
    select : str
        Select which fields to return (separated by comma)
    complementary_search : bool
        Find items without the text to search
    search_in_fields : list
        Fields to search in

    Returns
    -------
    Policies information
    """
    result = AffectedItemsWazuhResult(
        none_msg='No policy was returned',
        some_msg='Some policies were not returned',
        all_msg='All specified policies were returned')
    affected_items = list()
    with PoliciesManager() as pm:
        for p_id in policy_ids:
            policy = pm.get_policy_id(int(p_id))
            if policy != SecurityError.POLICY_NOT_EXIST:
                affected_items.append(policy)
            else:
                # Policy id does not exist
                result.add_failed_item(id_=int(p_id), error=WazuhError(4007))

    data = process_array(affected_items,
                         search_text=search_text,
                         search_in_fields=search_in_fields,
                         select=select,
                         complementary_search=complementary_search,
                         sort_by=sort_by,
                         sort_ascending=sort_ascending,
                         offset=offset,
                         limit=limit,
                         allowed_sort_fields=SORT_FIELDS,
                         required_fields=REQUIRED_FIELDS)
    result.affected_items = data['items']
    result.total_affected_items = data['totalItems']

    return result