Search in sources :

Example 26 with MacroMachine

use of password.pwm.util.macro.MacroMachine in project pwm by pwm-project.

the class PwmMacroTag method doEndTag.

public int doEndTag() throws JspTagException {
    try {
        final PwmRequest pwmRequest = PwmRequest.forRequest((HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse());
        final MacroMachine macroMachine = pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmRequest.getPwmApplication());
        final String outputValue = macroMachine.expandMacros(value);
        pageContext.getOut().write(outputValue);
    } catch (PwmUnrecoverableException e) {
        LOGGER.error("error while processing PwmMacroTag: " + e.getMessage());
    } catch (Exception e) {
        throw new JspTagException(e.getMessage(), e);
    }
    return EVAL_PAGE;
}
Also used : PwmRequest(password.pwm.http.PwmRequest) MacroMachine(password.pwm.util.macro.MacroMachine) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) JspTagException(javax.servlet.jsp.JspTagException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) JspTagException(javax.servlet.jsp.JspTagException)

Example 27 with MacroMachine

use of password.pwm.util.macro.MacroMachine in project pwm by pwm-project.

the class TokenUtil method initializeAndSendToken.

public static void initializeAndSendToken(final PwmRequest pwmRequest, final TokenInitAndSendRequest tokenInitAndSendRequest) throws PwmUnrecoverableException {
    final Configuration config = pwmRequest.getConfig();
    final UserInfo userInfo = tokenInitAndSendRequest.getUserInfo();
    final Map<String, String> tokenMapData = new LinkedHashMap<>();
    final MacroMachine macroMachine;
    {
        if (tokenInitAndSendRequest.getMacroMachine() != null) {
            macroMachine = tokenInitAndSendRequest.getMacroMachine();
        } else if (tokenInitAndSendRequest.getUserInfo() != null) {
            macroMachine = MacroMachine.forUser(pwmRequest, userInfo.getUserIdentity(), makeTokenDestStringReplacer(tokenInitAndSendRequest.getTokenDestinationItem()));
        } else {
            macroMachine = null;
        }
    }
    if (userInfo != null) {
        final Instant userLastPasswordChange = userInfo.getPasswordLastModifiedTime();
        if (userLastPasswordChange != null) {
            final String userChangeString = JavaHelper.toIsoDate(userLastPasswordChange);
            tokenMapData.put(PwmConstants.TOKEN_KEY_PWD_CHG_DATE, userChangeString);
        }
    }
    if (tokenInitAndSendRequest.getInputTokenData() != null) {
        tokenMapData.putAll(tokenInitAndSendRequest.getInputTokenData());
    }
    final String tokenKey;
    final TokenPayload tokenPayload;
    {
        final TimeDuration tokenLifetime = tokenInitAndSendRequest.getTokenLifetime() == null ? new TimeDuration(config.readSettingAsLong(PwmSetting.TOKEN_LIFETIME), TimeUnit.SECONDS) : tokenInitAndSendRequest.getTokenLifetime();
        try {
            tokenPayload = pwmRequest.getPwmApplication().getTokenService().createTokenPayload(tokenInitAndSendRequest.getTokenType(), tokenLifetime, tokenMapData, userInfo == null ? null : userInfo.getUserIdentity(), tokenInitAndSendRequest.getTokenDestinationItem());
            tokenKey = pwmRequest.getPwmApplication().getTokenService().generateNewToken(tokenPayload, pwmRequest.getSessionLabel());
        } catch (PwmOperationalException e) {
            throw new PwmUnrecoverableException(e.getErrorInformation());
        }
    }
    final EmailItemBean emailItemBean = tokenInitAndSendRequest.getEmailToSend() == null ? null : config.readSettingAsEmail(tokenInitAndSendRequest.getEmailToSend(), pwmRequest.getLocale());
    final String smsMessage = tokenInitAndSendRequest.getSmsToSend() == null ? null : config.readSettingAsLocalizedString(tokenInitAndSendRequest.getSmsToSend(), pwmRequest.getLocale());
    TokenService.TokenSender.sendToken(TokenService.TokenSendInfo.builder().pwmApplication(pwmRequest.getPwmApplication()).userInfo(userInfo).macroMachine(macroMachine).configuredEmailSetting(emailItemBean).tokenDestinationItem(tokenInitAndSendRequest.getTokenDestinationItem()).smsMessage(smsMessage).tokenKey(tokenKey).sessionLabel(pwmRequest.getSessionLabel()).build());
}
Also used : Configuration(password.pwm.config.Configuration) EmailItemBean(password.pwm.bean.EmailItemBean) Instant(java.time.Instant) MacroMachine(password.pwm.util.macro.MacroMachine) UserInfo(password.pwm.ldap.UserInfo) TimeDuration(password.pwm.util.java.TimeDuration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 28 with MacroMachine

use of password.pwm.util.macro.MacroMachine in project pwm by pwm-project.

the class LocaleHelper method getLocalizedMessage.

public static String getLocalizedMessage(final Locale locale, final String key, final Configuration config, final Class bundleClass, final String[] values) {
    String returnValue = null;
    if (config != null) {
        final Map<Locale, String> configuredBundle = config.readLocalizedBundle(bundleClass.getName(), key);
        if (configuredBundle != null) {
            final Locale resolvedLocale = localeResolver(locale, configuredBundle.keySet());
            returnValue = configuredBundle.get(resolvedLocale);
        }
    }
    if (returnValue == null || returnValue.isEmpty()) {
        final ResourceBundle bundle = getMessageBundle(locale, bundleClass);
        if (bundle == null) {
            final String errorMsg = "missing bundle for " + bundleClass.getName();
            LOGGER.warn(errorMsg);
            return errorMsg;
        }
        try {
            returnValue = bundle.getString(key);
        } catch (MissingResourceException e) {
            final String errorMsg = "missing key '" + key + "' for " + bundleClass.getName();
            if (config != null && config.isDevDebugMode()) {
                LOGGER.warn(errorMsg);
            }
            returnValue = key;
        }
    }
    if (values != null) {
        for (int i = 0; i < values.length; i++) {
            if (values[i] != null) {
                final String replaceKey = "%" + (i + 1) + "%";
                returnValue = returnValue.replace(replaceKey, values[i]);
            }
        }
    }
    final MacroMachine macroMachine = MacroMachine.forStatic();
    return macroMachine.expandMacros(returnValue);
}
Also used : Locale(java.util.Locale) MissingResourceException(java.util.MissingResourceException) MacroMachine(password.pwm.util.macro.MacroMachine) ResourceBundle(java.util.ResourceBundle)

Example 29 with MacroMachine

use of password.pwm.util.macro.MacroMachine in project pwm by pwm-project.

the class PwmPasswordRuleValidator method internalPwmPolicyValidator.

@SuppressWarnings("checkstyle:MethodLength")
public List<ErrorInformation> internalPwmPolicyValidator(final String passwordString, final String oldPasswordString, final UserInfo userInfo, final Flag... flags) throws PwmUnrecoverableException {
    final boolean failFast = flags != null && Arrays.asList(flags).contains(Flag.FailFast);
    // null check
    if (passwordString == null) {
        return Collections.singletonList(new ErrorInformation(PwmError.ERROR_UNKNOWN, "empty (null) new password"));
    }
    final List<ErrorInformation> errorList = new ArrayList<>();
    final PwmPasswordPolicy.RuleHelper ruleHelper = policy.getRuleHelper();
    final MacroMachine macroMachine = userInfo == null || userInfo.getUserIdentity() == null ? MacroMachine.forNonUserSpecific(pwmApplication, SessionLabel.SYSTEM_LABEL) : MacroMachine.forUser(pwmApplication, PwmConstants.DEFAULT_LOCALE, SessionLabel.SYSTEM_LABEL, userInfo.getUserIdentity());
    // check against old password
    if (oldPasswordString != null && oldPasswordString.length() > 0 && ruleHelper.readBooleanValue(PwmPasswordRule.DisallowCurrent)) {
        if (oldPasswordString.length() > 0) {
            if (oldPasswordString.equalsIgnoreCase(passwordString)) {
                errorList.add(new ErrorInformation(PwmError.PASSWORD_SAMEASOLD));
            }
        }
        // check chars from old password
        final int maxOldAllowed = ruleHelper.readIntValue(PwmPasswordRule.MaximumOldChars);
        if (maxOldAllowed > 0) {
            if (oldPasswordString.length() > 0) {
                final String lPassword = passwordString.toLowerCase();
                final Set<Character> dupeChars = new HashSet<>();
                // add all dupes to the set.
                for (final char loopChar : oldPasswordString.toLowerCase().toCharArray()) {
                    if (lPassword.indexOf(loopChar) != -1) {
                        dupeChars.add(loopChar);
                    }
                }
                // count the number of (unique) set elements.
                if (dupeChars.size() >= maxOldAllowed) {
                    errorList.add(new ErrorInformation(PwmError.PASSWORD_TOO_MANY_OLD_CHARS));
                }
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    errorList.addAll(basicSyntaxRuleChecks(passwordString, policy, userInfo));
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check against disallowed values;
    if (!ruleHelper.getDisallowedValues().isEmpty()) {
        final String lcasePwd = passwordString.toLowerCase();
        final Set<String> paramValues = new HashSet<>(ruleHelper.getDisallowedValues());
        for (final String loopValue : paramValues) {
            if (loopValue != null && loopValue.length() > 0) {
                final String expandedValue = macroMachine.expandMacros(loopValue);
                if (StringUtils.isNotBlank(expandedValue)) {
                    final String loweredLoop = expandedValue.toLowerCase();
                    if (lcasePwd.contains(loweredLoop)) {
                        errorList.add(new ErrorInformation(PwmError.PASSWORD_USING_DISALLOWED));
                    }
                }
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check disallowed attributes.
    if (!policy.getRuleHelper().getDisallowedAttributes().isEmpty()) {
        final List<String> paramConfigs = policy.getRuleHelper().getDisallowedAttributes(RuleHelper.Flag.KeepThresholds);
        if (userInfo != null) {
            final Map<String, String> userValues = userInfo.getCachedPasswordRuleAttributes();
            for (final String paramConfig : paramConfigs) {
                final String[] parts = paramConfig.split(":");
                final String attrName = parts[0];
                final String disallowedValue = StringUtils.defaultString(userValues.get(attrName));
                final int threshold = parts.length > 1 ? NumberUtils.toInt(parts[1]) : 0;
                if (containsDisallowedValue(passwordString, disallowedValue, threshold)) {
                    LOGGER.trace("password rejected, same as user attr " + attrName);
                    errorList.add(new ErrorInformation(PwmError.PASSWORD_SAMEASATTR));
                }
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    {
        // check password strength
        final int requiredPasswordStrength = ruleHelper.readIntValue(PwmPasswordRule.MinimumStrength);
        if (requiredPasswordStrength > 0) {
            if (pwmApplication != null) {
                final int passwordStrength = PasswordUtility.judgePasswordStrength(pwmApplication.getConfig(), passwordString);
                if (passwordStrength < requiredPasswordStrength) {
                    errorList.add(new ErrorInformation(PwmError.PASSWORD_TOO_WEAK));
                    if (EXTRA_LOGGING) {
                        final String msg = "password rejected, password strength of " + passwordStrength + " is lower than policy requirement of " + requiredPasswordStrength;
                        LOGGER.trace(msg);
                    }
                }
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check regex matches.
    for (final Pattern pattern : ruleHelper.getRegExMatch(macroMachine)) {
        if (!pattern.matcher(passwordString).matches()) {
            errorList.add(new ErrorInformation(PwmError.PASSWORD_INVALID_CHAR));
            if (EXTRA_LOGGING) {
                final String msg = "password rejected, does not match configured regex pattern: " + pattern.toString();
                LOGGER.trace(msg);
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check no-regex matches.
    for (final Pattern pattern : ruleHelper.getRegExNoMatch(macroMachine)) {
        if (pattern.matcher(passwordString).matches()) {
            errorList.add(new ErrorInformation(PwmError.PASSWORD_INVALID_CHAR));
            if (EXTRA_LOGGING) {
                LOGGER.trace("password rejected, matches configured no-regex pattern: " + pattern.toString());
            }
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check char group matches
    if (ruleHelper.readIntValue(PwmPasswordRule.CharGroupsMinMatch) > 0) {
        final List<Pattern> ruleGroups = ruleHelper.getCharGroupValues();
        if (ruleGroups != null && !ruleGroups.isEmpty()) {
            final int requiredMatches = ruleHelper.readIntValue(PwmPasswordRule.CharGroupsMinMatch);
            int matches = 0;
            for (final Pattern pattern : ruleGroups) {
                if (pattern.matcher(passwordString).find()) {
                    matches++;
                }
            }
            if (matches < requiredMatches) {
                errorList.add(new ErrorInformation(PwmError.PASSWORD_NOT_ENOUGH_GROUPS));
            }
        }
        if (failFast && errorList.size() > 1) {
            return errorList;
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check if the password is in the dictionary.
    if (ruleHelper.readBooleanValue(PwmPasswordRule.EnableWordlist)) {
        if (pwmApplication != null) {
            if (pwmApplication.getWordlistManager() != null && pwmApplication.getWordlistManager().status() == PwmService.STATUS.OPEN) {
                final boolean found = pwmApplication.getWordlistManager().containsWord(passwordString);
                if (found) {
                    // LOGGER.trace(pwmSession, "password rejected, in wordlist file");
                    errorList.add(new ErrorInformation(PwmError.PASSWORD_INWORDLIST));
                }
            } else {
            /* noop */
            // LOGGER.warn(pwmSession, "password wordlist checking enabled, but wordlist is not available, skipping wordlist check");
            }
        }
        if (failFast && errorList.size() > 1) {
            return errorList;
        }
    }
    if (failFast && errorList.size() > 1) {
        return errorList;
    }
    // check for shared (global) password history
    if (pwmApplication != null) {
        if (pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.PASSWORD_SHAREDHISTORY_ENABLE) && pwmApplication.getSharedHistoryManager().status() == PwmService.STATUS.OPEN) {
            final boolean found = pwmApplication.getSharedHistoryManager().containsWord(passwordString);
            if (found) {
                // LOGGER.trace(pwmSession, "password rejected, in global shared history");
                errorList.add(new ErrorInformation(PwmError.PASSWORD_INWORDLIST));
            }
        }
        if (failFast && errorList.size() > 1) {
            return errorList;
        }
    }
    return errorList;
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) RuleHelper(password.pwm.config.profile.PwmPasswordPolicy.RuleHelper) ErrorInformation(password.pwm.error.ErrorInformation) PwmPasswordPolicy(password.pwm.config.profile.PwmPasswordPolicy) MacroMachine(password.pwm.util.macro.MacroMachine) HashSet(java.util.HashSet)

Example 30 with MacroMachine

use of password.pwm.util.macro.MacroMachine in project pwm by pwm-project.

the class PwmPasswordRuleValidator method invokeExternalRuleMethods.

public List<ErrorInformation> invokeExternalRuleMethods(final Configuration config, final PwmPasswordPolicy pwmPasswordPolicy, final PasswordData password, final UserInfo userInfo) throws PwmUnrecoverableException {
    final List<ErrorInformation> returnedErrors = new ArrayList<>();
    final String restURL = config.readSettingAsString(PwmSetting.EXTERNAL_PWCHECK_REST_URLS);
    final boolean haltOnError = Boolean.parseBoolean(config.readAppProperty(AppProperty.WS_REST_CLIENT_PWRULE_HALTONERROR));
    final Map<String, Object> sendData = new LinkedHashMap<>();
    if (restURL == null || restURL.isEmpty()) {
        return Collections.emptyList();
    }
    {
        final String passwordStr = password == null ? "" : password.getStringValue();
        sendData.put("password", passwordStr);
    }
    if (pwmPasswordPolicy != null) {
        final LinkedHashMap<String, Object> policyData = new LinkedHashMap<>();
        for (final PwmPasswordRule rule : PwmPasswordRule.values()) {
            policyData.put(rule.name(), pwmPasswordPolicy.getValue(rule));
        }
        sendData.put("policy", policyData);
    }
    if (userInfo != null) {
        final MacroMachine macroMachine = MacroMachine.forUser(pwmApplication, PwmConstants.DEFAULT_LOCALE, SessionLabel.SYSTEM_LABEL, userInfo.getUserIdentity());
        final PublicUserInfoBean publicUserInfoBean = PublicUserInfoBean.fromUserInfoBean(userInfo, pwmApplication.getConfig(), locale, macroMachine);
        sendData.put("userInfo", publicUserInfoBean);
    }
    final String jsonRequestBody = JsonUtil.serializeMap(sendData);
    try {
        final String responseBody = RestClientHelper.makeOutboundRestWSCall(pwmApplication, locale, restURL, jsonRequestBody);
        final Map<String, Object> responseMap = JsonUtil.deserialize(responseBody, new TypeToken<Map<String, Object>>() {
        });
        if (responseMap.containsKey(REST_RESPONSE_KEY_ERROR) && Boolean.parseBoolean(responseMap.get(REST_RESPONSE_KEY_ERROR).toString())) {
            if (responseMap.containsKey(REST_RESPONSE_KEY_ERROR_MSG)) {
                final String errorMessage = responseMap.get(REST_RESPONSE_KEY_ERROR_MSG).toString();
                LOGGER.trace("external web service reported error: " + errorMessage);
                returnedErrors.add(new ErrorInformation(PwmError.PASSWORD_CUSTOM_ERROR, errorMessage, errorMessage, null));
            } else {
                LOGGER.trace("external web service reported error without specifying an errorMessage");
                returnedErrors.add(new ErrorInformation(PwmError.PASSWORD_CUSTOM_ERROR));
            }
        } else {
            LOGGER.trace("external web service did not report an error");
        }
    } catch (PwmOperationalException e) {
        final String errorMsg = "error executing external rule REST call: " + e.getMessage();
        LOGGER.error(errorMsg);
        if (haltOnError) {
            throw new PwmUnrecoverableException(e.getErrorInformation(), e);
        }
        throw new IllegalStateException("http response error code: " + e.getMessage());
    }
    return returnedErrors;
}
Also used : ArrayList(java.util.ArrayList) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PublicUserInfoBean(password.pwm.bean.pub.PublicUserInfoBean) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) PwmPasswordRule(password.pwm.config.profile.PwmPasswordRule) MacroMachine(password.pwm.util.macro.MacroMachine) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

MacroMachine (password.pwm.util.macro.MacroMachine)61 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)20 Locale (java.util.Locale)16 PwmOperationalException (password.pwm.error.PwmOperationalException)15 Configuration (password.pwm.config.Configuration)13 UserInfo (password.pwm.ldap.UserInfo)13 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 PwmApplication (password.pwm.PwmApplication)12 FormConfiguration (password.pwm.config.value.data.FormConfiguration)12 ChaiUser (com.novell.ldapchai.ChaiUser)10 PwmException (password.pwm.error.PwmException)10 List (java.util.List)9 EmailItemBean (password.pwm.bean.EmailItemBean)9 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)8 Map (java.util.Map)8 ActionConfiguration (password.pwm.config.value.data.ActionConfiguration)8 PwmSession (password.pwm.http.PwmSession)8 Instant (java.time.Instant)7