Search in sources :

Example 1 with PasswordChangeException

use of eu.bcvsolutions.idm.core.api.exception.PasswordChangeException in project CzechIdMng by bcvsolutions.

the class DefaultIdmPasswordPolicyService method validate.

private void validate(IdmPasswordValidationDto passwordValidationDto, List<IdmPasswordPolicyDto> passwordPolicies, boolean prevalidation) {
    Assert.notNull(passwordPolicies, "Password policies are required.");
    Assert.notNull(passwordValidationDto, "Password validation dto is required.");
    IdmIdentityDto identity = passwordValidationDto.getIdentity();
    // default password policy is used when list of password policies is empty, or for get maximum equals password
    IdmPasswordPolicyDto defaultPolicy = this.getDefaultPasswordPolicy(IdmPasswordPolicyType.VALIDATE);
    // if list is empty, get default password policy
    if (passwordPolicies.isEmpty() && !prevalidation) {
        if (defaultPolicy != null) {
            passwordPolicies.add(defaultPolicy);
        }
    }
    // if list with password policies is empty, validate is always true
    if (passwordPolicies.isEmpty()) {
        // this state means that system IdM hasn't default password policy
        return;
    }
    IdmPasswordDto oldPassword = null;
    // For checking with old password identity must has ID (for create doesn't exists ID)
    if (identity != null && identity.getId() != null) {
        oldPassword = passwordService.findOneByIdentity(identity.getId());
    }
    String password = passwordValidationDto.getPassword().asString();
    ZonedDateTime now = ZonedDateTime.now();
    Map<String, Object> errors = new HashMap<>();
    Set<Character> prohibitedChar = new HashSet<>();
    String prohibitedBeginChar = null;
    String prohibitedEndChar = null;
    List<String> policyNames = new ArrayList<String>();
    Map<String, Object> specialCharBase = new HashMap<>();
    Map<String, Object> forbiddenCharBase = new HashMap<>();
    Map<String, Object> forbiddenBeginCharBase = new HashMap<>();
    Map<String, Object> forbiddenEndCharBase = new HashMap<>();
    for (IdmPasswordPolicyDto passwordPolicy : passwordPolicies) {
        if (passwordPolicy.isDisabled()) {
            continue;
        }
        boolean validateNotSuccess = false;
        // check if can change password for minimal age for change
        Integer minPasswordAge = passwordPolicy.getMinPasswordAge();
        boolean enforceMinPasswordAgeValidation = passwordValidationDto.isEnforceMinPasswordAgeValidation();
        if (minPasswordAge != null && oldPassword != null && !oldPassword.isMustChange() && !prevalidation && !securityService.isAdmin() && (// force => checked even when owner and logged user is different
        enforceMinPasswordAgeValidation || Objects.equals(securityService.getCurrentId(), oldPassword.getIdentity()))) {
            LocalDate passwordValidFrom = oldPassword.getValidFrom();
            if (// check can be disabled (by previous change attempt)
            passwordValidFrom != null && passwordValidFrom.plusDays(minPasswordAge).compareTo(now.toLocalDate()) > 0) {
                throw new PasswordChangeException(passwordValidFrom.plusDays(minPasswordAge));
            }
        }
        // minimum rules to fulfill
        Map<String, Object> notPassRules = new HashMap<>();
        int minRulesToFulfill = passwordPolicy.getMinRulesToFulfill() == null ? 0 : passwordPolicy.getMinRulesToFulfill().intValue();
        // check to max password length
        if (!isNull(passwordPolicy.getMaxPasswordLength()) && (password.length() > passwordPolicy.getMaxPasswordLength() || prevalidation)) {
            if (!passwordPolicy.isPasswordLengthRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MAX_LENGTH, Math.min(convertToInt(errors.get(MAX_LENGTH)), passwordPolicy.getMaxPasswordLength()));
            } else if (!(errors.containsKey(MAX_LENGTH) && compareInt(passwordPolicy.getMaxPasswordLength(), errors.get(MAX_LENGTH)))) {
                errors.put(MAX_LENGTH, passwordPolicy.getMaxPasswordLength());
            }
            validateNotSuccess = true;
        }
        // check to minimal password length
        if (!isNullOrZeroValue(passwordPolicy.getMinPasswordLength()) && password.length() < passwordPolicy.getMinPasswordLength()) {
            if (!passwordPolicy.isPasswordLengthRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MIN_LENGTH, Math.max(convertToInt(errors.get(MIN_LENGTH)), passwordPolicy.getMinPasswordLength()));
            } else if (!(errors.containsKey(MIN_LENGTH) && compareInt(errors.get(MIN_LENGTH), passwordPolicy.getMinPasswordLength()))) {
                errors.put(MIN_LENGTH, passwordPolicy.getMinPasswordLength());
            }
            validateNotSuccess = true;
        }
        // check to prohibited characters
        if (!Strings.isNullOrEmpty(passwordPolicy.getProhibitedCharacters()) && !password.matches("[^" + Pattern.quote(passwordPolicy.getProhibitedCharacters()) + "]*")) {
            for (char character : passwordPolicy.getProhibitedCharacters().toCharArray()) {
                if (password.indexOf(character) >= 0) {
                    prohibitedChar.add(character);
                }
            }
            validateNotSuccess = true;
        }
        // check character at the beginning
        prohibitedBeginChar = checkInitialFinalCharForbidden(password, passwordPolicy.getProhibitedBeginCharacters(), true);
        // check character at the end
        prohibitedEndChar = checkInitialFinalCharForbidden(password, passwordPolicy.getProhibitedEndCharacters(), false);
        // check to minimal numbers
        if (!isNullOrZeroValue(passwordPolicy.getMinNumber()) && !password.matches("(.*[" + Pattern.quote(passwordPolicy.getNumberBase()) + "].*){" + passwordPolicy.getMinNumber() + ",}")) {
            if (!passwordPolicy.isNumberRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MIN_NUMBER, Math.max(convertToInt(errors.get(MIN_NUMBER)), passwordPolicy.getMinNumber()));
            } else if (!(errors.containsKey(MIN_NUMBER) && compareInt(errors.get(MIN_NUMBER), passwordPolicy.getMinNumber()))) {
                errors.put(MIN_NUMBER, passwordPolicy.getMinNumber());
            }
            validateNotSuccess = true;
        }
        // check to minimal lower characters
        if (!isNullOrZeroValue(passwordPolicy.getMinLowerChar()) && !password.matches("(.*[" + Pattern.quote(passwordPolicy.getLowerCharBase()) + "].*){" + passwordPolicy.getMinLowerChar() + ",}")) {
            if (!passwordPolicy.isLowerCharRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MIN_LOWER_CHAR, Math.max(convertToInt(errors.get(MIN_LOWER_CHAR)), passwordPolicy.getMinLowerChar()));
            } else if (!(errors.containsKey(MIN_LOWER_CHAR) && compareInt(errors.get(MIN_LOWER_CHAR), passwordPolicy.getMinLowerChar()))) {
                errors.put(MIN_LOWER_CHAR, passwordPolicy.getMinLowerChar());
            }
            validateNotSuccess = true;
        }
        // check to minimal upper character
        if (!isNullOrZeroValue(passwordPolicy.getMinUpperChar()) && !password.matches("(.*[" + Pattern.quote(passwordPolicy.getUpperCharBase()) + "].*){" + passwordPolicy.getMinUpperChar() + ",}")) {
            if (!passwordPolicy.isUpperCharRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MIN_UPPER_CHAR, Math.max(convertToInt(errors.get(MIN_UPPER_CHAR)), passwordPolicy.getMinUpperChar()));
            } else if (!(errors.containsKey(MIN_UPPER_CHAR) && compareInt(errors.get(MIN_UPPER_CHAR), passwordPolicy.getMinUpperChar()))) {
                errors.put(MIN_UPPER_CHAR, passwordPolicy.getMinUpperChar());
            }
            validateNotSuccess = true;
        }
        // check to minimal special character and add special character base
        if (!isNullOrZeroValue(passwordPolicy.getMinSpecialChar()) && !password.matches("(.*[" + Pattern.quote(passwordPolicy.getSpecialCharBase()) + "].*){" + passwordPolicy.getMinSpecialChar() + ",}")) {
            if (!passwordPolicy.isSpecialCharRequired() && passwordPolicy.isEnchancedControl()) {
                notPassRules.put(MIN_SPECIAL_CHAR, Math.max(convertToInt(errors.get(MIN_SPECIAL_CHAR)), passwordPolicy.getMinSpecialChar()));
                specialCharBase.put(passwordPolicy.getName(), passwordPolicy.getSpecialCharBase());
            } else if (!(errors.containsKey(MIN_SPECIAL_CHAR) && compareInt(errors.get(MIN_SPECIAL_CHAR), passwordPolicy.getMinSpecialChar()))) {
                errors.put(MIN_SPECIAL_CHAR, passwordPolicy.getMinSpecialChar());
                specialCharBase.put(passwordPolicy.getName(), passwordPolicy.getSpecialCharBase());
            }
            validateNotSuccess = true;
        }
        // building of character bases of forbidden characters in passwords for password hints
        if (passwordPolicy.getProhibitedCharacters() != null) {
            forbiddenCharBase.put(passwordPolicy.getName(), passwordPolicy.getProhibitedCharacters());
        }
        if (!Strings.isNullOrEmpty(passwordPolicy.getProhibitedBeginCharacters())) {
            forbiddenBeginCharBase.put(passwordPolicy.getName(), passwordPolicy.getProhibitedBeginCharacters());
        }
        if (!Strings.isNullOrEmpty(passwordPolicy.getProhibitedEndCharacters())) {
            forbiddenEndCharBase.put(passwordPolicy.getName(), passwordPolicy.getProhibitedEndCharacters());
        }
        if (!notPassRules.isEmpty() && passwordPolicy.isEnchancedControl()) {
            int notRequiredRules = passwordPolicy.getNotRequiredRules();
            int missingRules = notRequiredRules - notPassRules.size();
            if (missingRules - minRulesToFulfill < 0) {
                errors.put(MIN_RULES_TO_FULFILL_COUNT, minRulesToFulfill - missingRules);
                errors.put(MIN_RULES_TO_FULFILL, notPassRules);
            }
        }
        // if not success we want password policy name
        if (validateNotSuccess && !errors.isEmpty() && !prevalidation) {
            policyNames.add(passwordPolicy.getName());
        }
        // check to similar identity attributes, enhanced control
        if (prevalidation) {
            enhancedControlForSimilar(passwordPolicy, prevalidation, errors);
        } else {
            enhancedControlForSimilar(passwordPolicy, passwordValidationDto, errors);
        }
    // TODO: weak words
    }
    if (!specialCharBase.isEmpty() && prevalidation) {
        errors.put(SPECIAL_CHARACTER_BASE, specialCharBase);
    }
    if (!forbiddenCharBase.isEmpty() && prevalidation) {
        errors.put(FORBIDDEN_CHARACTER_BASE, forbiddenCharBase);
    }
    if (!forbiddenBeginCharBase.isEmpty() && prevalidation) {
        errors.put(FORBIDDEN_BEGIN_CHARACTER_BASE, forbiddenBeginCharBase);
    }
    if (!forbiddenEndCharBase.isEmpty() && prevalidation) {
        errors.put(FORBIDDEN_END_CHARACTER_BASE, forbiddenEndCharBase);
    }
    if (!policyNames.isEmpty() && !prevalidation) {
        String name = prevalidation ? POLICY_NAME_PREVALIDATION : POLICY_NAME;
        errors.put(name, String.join(", ", policyNames));
    }
    if (!prohibitedChar.isEmpty()) {
        errors.put(COINTAIN_PROHIBITED, prohibitedChar.toString());
    }
    if (!Strings.isNullOrEmpty(prohibitedBeginChar)) {
        errors.put(BEGIN_PROHIBITED, prohibitedBeginChar);
    }
    if (!Strings.isNullOrEmpty(prohibitedEndChar)) {
        errors.put(END_PROHIBITED, prohibitedEndChar);
    }
    // in some case (tests) are save identity in one transaction and id doesn't exist
    if (!prevalidation && defaultPolicy != null) {
        Integer maxHistorySimilar = defaultPolicy.getMaxHistorySimilar();
        if (maxHistorySimilar != null && identity != null && identity.getId() != null) {
            boolean checkHistory = passwordHistoryService.checkHistory(passwordValidationDto.getIdentity().getId(), maxHistorySimilar, passwordValidationDto.getPassword());
            if (checkHistory) {
                errors.put(MAX_HISTORY_SIMILAR, maxHistorySimilar);
            }
        }
    }
    if (!errors.isEmpty()) {
        // TODO: password policy audit
        if (prevalidation) {
            throw new ResultCodeException(CoreResultCode.PASSWORD_PREVALIDATION, errors);
        }
        throw new ResultCodeException(CoreResultCode.PASSWORD_DOES_NOT_MEET_POLICY, errors);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) LocalDate(java.time.LocalDate) PasswordChangeException(eu.bcvsolutions.idm.core.api.exception.PasswordChangeException) IdmPasswordPolicyDto(eu.bcvsolutions.idm.core.api.dto.IdmPasswordPolicyDto) ZonedDateTime(java.time.ZonedDateTime) IdmPasswordDto(eu.bcvsolutions.idm.core.api.dto.IdmPasswordDto) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) HashSet(java.util.HashSet)

Aggregations

IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)1 IdmPasswordDto (eu.bcvsolutions.idm.core.api.dto.IdmPasswordDto)1 IdmPasswordPolicyDto (eu.bcvsolutions.idm.core.api.dto.IdmPasswordPolicyDto)1 PasswordChangeException (eu.bcvsolutions.idm.core.api.exception.PasswordChangeException)1 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)1 LocalDate (java.time.LocalDate)1 ZonedDateTime (java.time.ZonedDateTime)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1