Search in sources :

Example 41 with MacroMachine

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

the class PasswordUtility method setActorPassword.

/**
 * This is the entry point under which all password changes are managed.
 * The following is the general procedure when this method is invoked.
 * <ul>
 * <li> password is checked against PWM password requirement </li>
 * <li> ldap password set is attempted<br/>
 * <br/>if successful:
 * <ul>
 * <li> uiBean is updated with old and new passwords </li>
 * <li> uiBean's password expire flag is set to false </li>
 * <li> any configured external methods are invoked </li>
 * <li> user email notification is sent </li>
 * <li> return true </li>
 * </ul>
 * <br/>if unsuccessful
 * <ul>
 * <li> ssBean is updated with appropriate error </li>
 * <li> return false </li>
 * </ul>
 * </li>
 * </ul>
 *
 * @param newPassword the new password that is being set.
 * @param pwmSession  beanmanager for config and user info lookup
 * @throws com.novell.ldapchai.exception.ChaiUnavailableException if the ldap directory is not unavailable
 * @throws password.pwm.error.PwmUnrecoverableException           if user is not authenticated
 */
public static void setActorPassword(final PwmSession pwmSession, final PwmApplication pwmApplication, final PasswordData newPassword) throws ChaiUnavailableException, PwmUnrecoverableException, PwmOperationalException {
    final UserInfo userInfo = pwmSession.getUserInfo();
    if (!pwmSession.getSessionManager().checkPermission(pwmApplication, Permission.CHANGE_PASSWORD)) {
        final String errorMsg = "attempt to setActorPassword, but user does not have password change permission";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    // but we do it just in case.
    try {
        final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, userInfo.getPasswordPolicy());
        pwmPasswordRuleValidator.testPassword(newPassword, null, userInfo, pwmSession.getSessionManager().getActor(pwmApplication));
    } catch (PwmDataValidationException e) {
        final String errorMsg = "attempt to setActorPassword, but password does not pass local policy validator";
        final ErrorInformation errorInformation = new ErrorInformation(e.getErrorInformation().getError(), errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    // retrieve the user's old password from the userInfoBean in the session
    final PasswordData oldPassword = pwmSession.getLoginInfoBean().getUserCurrentPassword();
    boolean setPasswordWithoutOld = false;
    if (oldPassword == null) {
        if (pwmSession.getSessionManager().getActor(pwmApplication).getChaiProvider().getDirectoryVendor() == DirectoryVendor.ACTIVE_DIRECTORY) {
            setPasswordWithoutOld = true;
        }
    }
    if (!setPasswordWithoutOld) {
        // Check to make sure we actually have an old password
        if (oldPassword == null) {
            final String errorMsg = "cannot set password for user, old password is not available";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD, errorMsg);
            throw new PwmOperationalException(errorInformation);
        }
    }
    final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider();
    setPassword(pwmApplication, pwmSession.getLabel(), provider, userInfo, setPasswordWithoutOld ? null : oldPassword, newPassword);
    // update the session state bean's password modified flag
    pwmSession.getSessionStateBean().setPasswordModified(true);
    // update the login info bean with the user's new password
    pwmSession.getLoginInfoBean().setUserCurrentPassword(newPassword);
    // close any outstanding ldap connections (since they cache the old password)
    pwmSession.getSessionManager().updateUserPassword(pwmApplication, userInfo.getUserIdentity(), newPassword);
    // clear the "requires new password flag"
    pwmSession.getLoginInfoBean().getLoginFlags().remove(LoginInfoBean.LoginFlag.forcePwChange);
    // mark the auth type as authenticatePd now that we have the user's natural password.
    pwmSession.getLoginInfoBean().setType(AuthenticationType.AUTHENTICATED);
    // update the uibean's "password expired flag".
    pwmSession.reloadUserInfoBean(pwmApplication);
    // create a proxy user object for pwm to update/read the user.
    final ChaiUser proxiedUser = pwmSession.getSessionManager().getActor(pwmApplication);
    // update statistics
    {
        pwmApplication.getStatisticsManager().incrementValue(Statistic.PASSWORD_CHANGES);
    }
    // invoke post password change actions
    invokePostChangePasswordActions(pwmSession, newPassword.getStringValue());
    {
        // execute configured actions
        LOGGER.debug(pwmSession, "executing configured actions to user " + proxiedUser.getEntryDN());
        final List<ActionConfiguration> configValues = pwmApplication.getConfig().readSettingAsAction(PwmSetting.CHANGE_PASSWORD_WRITE_ATTRIBUTES);
        if (configValues != null && !configValues.isEmpty()) {
            final LoginInfoBean clonedLoginInfoBean = JsonUtil.cloneUsingJson(pwmSession.getLoginInfoBean(), LoginInfoBean.class);
            clonedLoginInfoBean.setUserCurrentPassword(newPassword);
            final MacroMachine macroMachine = MacroMachine.forUser(pwmApplication, pwmSession.getLabel(), pwmSession.getUserInfo(), clonedLoginInfoBean);
            final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userInfo.getUserIdentity()).setMacroMachine(macroMachine).setExpandPwmMacros(true).createActionExecutor();
            actionExecutor.executeActions(configValues, pwmSession.getLabel());
        }
    }
    // update the current last password update field in ldap
    LdapOperationsHelper.updateLastPasswordUpdateAttribute(pwmApplication, pwmSession.getLabel(), userInfo.getUserIdentity());
}
Also used : LoginInfoBean(password.pwm.bean.LoginInfoBean) UserInfo(password.pwm.ldap.UserInfo) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) PwmPasswordRuleValidator(password.pwm.util.PwmPasswordRuleValidator) PwmDataValidationException(password.pwm.error.PwmDataValidationException) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiUser(com.novell.ldapchai.ChaiUser) PasswordData(password.pwm.util.PasswordData) MacroMachine(password.pwm.util.macro.MacroMachine) List(java.util.List) ArrayList(java.util.ArrayList)

Example 42 with MacroMachine

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

the class PasswordUtility method sendChangePasswordHelpdeskEmailNotice.

private static void sendChangePasswordHelpdeskEmailNotice(final PwmSession pwmSession, final PwmApplication pwmApplication, final UserInfo userInfo) throws PwmUnrecoverableException {
    final Configuration config = pwmApplication.getConfig();
    final Locale locale = pwmSession.getSessionStateBean().getLocale();
    final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_CHANGEPASSWORD_HELPDESK, locale);
    if (configuredEmailSetting == null) {
        LOGGER.debug(pwmSession, "skipping send change password email for '" + pwmSession.getUserInfo().getUserIdentity() + "' no email configured");
        return;
    }
    final MacroMachine macroMachine = userInfo == null ? null : MacroMachine.forUser(pwmApplication, pwmSession.getLabel(), userInfo, null);
    pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, userInfo, macroMachine);
}
Also used : Locale(java.util.Locale) ActionConfiguration(password.pwm.config.value.data.ActionConfiguration) Configuration(password.pwm.config.Configuration) ChaiConfiguration(com.novell.ldapchai.provider.ChaiConfiguration) EmailItemBean(password.pwm.bean.EmailItemBean) MacroMachine(password.pwm.util.macro.MacroMachine)

Example 43 with MacroMachine

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

the class ActionExecutor method executeWebserviceAction.

private void executeWebserviceAction(final SessionLabel sessionLabel, final ActionConfiguration actionConfiguration) throws PwmOperationalException, PwmUnrecoverableException {
    String url = actionConfiguration.getUrl();
    String body = actionConfiguration.getBody();
    final Map<String, String> headers = new LinkedHashMap<>();
    if (actionConfiguration.getHeaders() != null) {
        headers.putAll(actionConfiguration.getHeaders());
    }
    try {
        // expand using pwm macros
        if (settings.isExpandPwmMacros()) {
            if (settings.getMacroMachine() == null) {
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "executor specified macro expansion but did not supply macro machine"));
            }
            final MacroMachine macroMachine = settings.getMacroMachine();
            url = macroMachine.expandMacros(url);
            body = body == null ? "" : macroMachine.expandMacros(body);
            for (final Map.Entry<String, String> entry : headers.entrySet()) {
                final String headerName = entry.getKey();
                final String headerValue = entry.getValue();
                if (headerValue != null) {
                    headers.put(headerName, macroMachine.expandMacros(headerValue));
                }
            }
        }
        // add basic auth header;
        if (!StringUtil.isEmpty(actionConfiguration.getUsername()) && !StringUtil.isEmpty(actionConfiguration.getPassword())) {
            final String authHeaderValue = new BasicAuthInfo(actionConfiguration.getUsername(), new PasswordData(actionConfiguration.getPassword())).toAuthHeader();
            headers.put(HttpHeader.Authorization.getHttpName(), authHeaderValue);
        }
        final HttpMethod method = HttpMethod.fromString(actionConfiguration.getMethod().toString());
        final PwmHttpClientRequest clientRequest = new PwmHttpClientRequest(method, url, body, headers);
        final PwmHttpClient client;
        {
            if (actionConfiguration.getCertificates() != null) {
                final PwmHttpClientConfiguration clientConfiguration = PwmHttpClientConfiguration.builder().certificates(actionConfiguration.getCertificates()).build();
                client = new PwmHttpClient(pwmApplication, sessionLabel, clientConfiguration);
            } else {
                client = new PwmHttpClient(pwmApplication, sessionLabel);
            }
        }
        final PwmHttpClientResponse clientResponse = client.makeRequest(clientRequest);
        if (clientResponse.getStatusCode() != 200) {
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_SERVICE_UNREACHABLE, "unexpected HTTP status code while calling external web service: " + clientResponse.getStatusCode() + " " + clientResponse.getStatusPhrase()));
        }
    } catch (PwmException e) {
        if (e instanceof PwmOperationalException) {
            throw (PwmOperationalException) e;
        }
        final String errorMsg = "unexpected error during API execution: " + e.getMessage();
        LOGGER.error(errorMsg);
        throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
    }
}
Also used : PwmHttpClientRequest(password.pwm.http.client.PwmHttpClientRequest) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmHttpClientResponse(password.pwm.http.client.PwmHttpClientResponse) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmHttpClient(password.pwm.http.client.PwmHttpClient) PasswordData(password.pwm.util.PasswordData) PwmHttpClientConfiguration(password.pwm.http.client.PwmHttpClientConfiguration) MacroMachine(password.pwm.util.macro.MacroMachine) BasicAuthInfo(password.pwm.util.BasicAuthInfo) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HttpMethod(password.pwm.http.HttpMethod)

Example 44 with MacroMachine

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

the class OtpService method createRawRecoveryCodes.

private List<String> createRawRecoveryCodes(final int numRecoveryCodes, final SessionLabel sessionLabel) throws PwmUnrecoverableException {
    final MacroMachine macroMachine = MacroMachine.forNonUserSpecific(pwmApplication, sessionLabel);
    final String configuredTokenMacro = settings.getRecoveryTokenMacro();
    final List<String> recoveryCodes = new ArrayList<>();
    while (recoveryCodes.size() < numRecoveryCodes) {
        final String code = macroMachine.expandMacros(configuredTokenMacro);
        recoveryCodes.add(code);
    }
    return recoveryCodes;
}
Also used : ArrayList(java.util.ArrayList) MacroMachine(password.pwm.util.macro.MacroMachine)

Example 45 with MacroMachine

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

the class ClientApiServlet method makeClientData.

private static Map<String, Object> makeClientData(final PwmApplication pwmApplication, final PwmSession pwmSession, final HttpServletRequest request, final HttpServletResponse response, final String pageUrl) throws ChaiUnavailableException, PwmUnrecoverableException {
    final Locale userLocale = pwmSession.getSessionStateBean().getLocale();
    final Configuration config = pwmApplication.getConfig();
    final TreeMap<String, Object> settingMap = new TreeMap<>();
    settingMap.put("client.ajaxTypingTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_TIMEOUT)));
    settingMap.put("client.ajaxTypingWait", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_WAIT)));
    settingMap.put("client.activityMaxEpsRate", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_ACTIVITY_MAX_EPS_RATE)));
    settingMap.put("client.js.enableHtml5Dialog", Boolean.parseBoolean(config.readAppProperty(AppProperty.CLIENT_JS_ENABLE_HTML5DIALOG)));
    settingMap.put("client.locale", LocaleHelper.getBrowserLocaleString(pwmSession.getSessionStateBean().getLocale()));
    settingMap.put("client.pwShowRevertTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_PW_SHOW_REVERT_TIMEOUT)));
    settingMap.put("enableIdleTimeout", config.readSettingAsBoolean(PwmSetting.DISPLAY_IDLE_TIMEOUT));
    settingMap.put("pageLeaveNotice", config.readSettingAsLong(PwmSetting.SECURITY_PAGE_LEAVE_NOTICE_TIMEOUT));
    settingMap.put("setting-showHidePasswordFields", pwmApplication.getConfig().readSettingAsBoolean(password.pwm.config.PwmSetting.DISPLAY_SHOW_HIDE_PASSWORD_FIELDS));
    settingMap.put("setting-displayEula", PwmConstants.ENABLE_EULA_DISPLAY);
    settingMap.put("setting-showStrengthMeter", config.readSettingAsBoolean(PwmSetting.PASSWORD_SHOW_STRENGTH_METER));
    {
        long idleSeconds = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
        if (pageUrl == null || pageUrl.isEmpty()) {
            LOGGER.warn(pwmSession, "request to /client data did not include pageUrl");
        } else {
            try {
                final PwmURL pwmURL = new PwmURL(new URI(pageUrl), request.getContextPath());
                final TimeDuration maxIdleTime = IdleTimeoutCalculator.idleTimeoutForRequest(pwmURL, pwmApplication, pwmSession);
                idleSeconds = maxIdleTime.getTotalSeconds();
            } catch (Exception e) {
                LOGGER.error(pwmSession, "error determining idle timeout time for request: " + e.getMessage());
            }
        }
        settingMap.put("MaxInactiveInterval", idleSeconds);
    }
    settingMap.put("paramName.locale", config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE));
    settingMap.put("runtimeNonce", pwmApplication.getRuntimeNonce());
    settingMap.put("applicationMode", pwmApplication.getApplicationMode());
    final String contextPath = request.getContextPath();
    settingMap.put("url-context", contextPath);
    settingMap.put("url-logout", contextPath + PwmServletDefinition.Logout.servletUrl());
    settingMap.put("url-command", contextPath + PwmServletDefinition.PublicCommand.servletUrl());
    settingMap.put("url-resources", contextPath + "/public/resources" + pwmApplication.getResourceServletService().getResourceNonce());
    settingMap.put("url-restservice", contextPath + "/public/rest");
    {
        String passwordGuideText = pwmApplication.getConfig().readSettingAsLocalizedString(PwmSetting.DISPLAY_PASSWORD_GUIDE_TEXT, pwmSession.getSessionStateBean().getLocale());
        final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication);
        passwordGuideText = macroMachine.expandMacros(passwordGuideText);
        settingMap.put("passwordGuideText", passwordGuideText);
    }
    {
        final List<String> formTypeOptions = new ArrayList<>();
        for (final FormConfiguration.Type type : FormConfiguration.Type.values()) {
            formTypeOptions.add(type.toString());
        }
        settingMap.put("formTypeOptions", formTypeOptions);
    }
    {
        final List<String> actionTypeOptions = new ArrayList<>();
        for (final ActionConfiguration.Type type : ActionConfiguration.Type.values()) {
            actionTypeOptions.add(type.toString());
        }
        settingMap.put("actionTypeOptions", actionTypeOptions);
    }
    {
        final List<String> epsTypes = new ArrayList<>();
        for (final EpsStatistic loopEpsType : EpsStatistic.values()) {
            epsTypes.add(loopEpsType.toString());
        }
        settingMap.put("epsTypes", epsTypes);
    }
    {
        final List<String> epsDurations = new ArrayList<>();
        for (final Statistic.EpsDuration loopEpsDuration : Statistic.EpsDuration.values()) {
            epsDurations.add(loopEpsDuration.toString());
        }
        settingMap.put("epsDurations", epsDurations);
    }
    {
        final Map<String, String> localeInfo = new LinkedHashMap<>();
        final Map<String, String> localeDisplayNames = new LinkedHashMap<>();
        final Map<String, String> localeFlags = new LinkedHashMap<>();
        final List<Locale> knownLocales = new ArrayList<>(pwmApplication.getConfig().getKnownLocales());
        knownLocales.sort(LocaleHelper.localeComparator(PwmConstants.DEFAULT_LOCALE));
        for (final Locale locale : knownLocales) {
            final String flagCode = pwmApplication.getConfig().getKnownLocaleFlagMap().get(locale);
            localeFlags.put(locale.toString(), flagCode);
            localeInfo.put(locale.toString(), locale.getDisplayName(PwmConstants.DEFAULT_LOCALE) + " - " + locale.getDisplayLanguage(userLocale));
            localeDisplayNames.put(locale.toString(), locale.getDisplayLanguage());
        }
        settingMap.put("localeInfo", localeInfo);
        settingMap.put("localeDisplayNames", localeDisplayNames);
        settingMap.put("localeFlags", localeFlags);
        settingMap.put("defaultLocale", PwmConstants.DEFAULT_LOCALE.toString());
    }
    if (pwmApplication.getConfig().readSettingAsEnum(PwmSetting.LDAP_SELECTABLE_CONTEXT_MODE, SelectableContextMode.class) != SelectableContextMode.NONE) {
        final Map<String, Map<String, String>> ldapProfiles = new LinkedHashMap<>();
        for (final String ldapProfile : pwmApplication.getConfig().getLdapProfiles().keySet()) {
            final Map<String, String> contexts = pwmApplication.getConfig().getLdapProfiles().get(ldapProfile).getSelectableContexts(pwmApplication);
            ldapProfiles.put(ldapProfile, contexts);
        }
        settingMap.put("ldapProfiles", ldapProfiles);
    }
    return settingMap;
}
Also used : Locale(java.util.Locale) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ActionConfiguration(password.pwm.config.value.data.ActionConfiguration) Configuration(password.pwm.config.Configuration) PwmURL(password.pwm.http.PwmURL) SelectableContextMode(password.pwm.config.option.SelectableContextMode) TreeMap(java.util.TreeMap) URI(java.net.URI) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) MacroMachine(password.pwm.util.macro.MacroMachine) TimeDuration(password.pwm.util.java.TimeDuration) List(java.util.List) ArrayList(java.util.ArrayList) EpsStatistic(password.pwm.svc.stats.EpsStatistic) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

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