Search in sources :

Example 11 with ErrorInformation

use of password.pwm.error.ErrorInformation in project pwm by pwm-project.

the class ApplicationModeFilter method checkConfigModes.

private static ProcessStatus checkConfigModes(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmApplicationMode mode = pwmApplication.getApplicationMode();
    final PwmURL pwmURL = pwmRequest.getURL();
    if (mode == PwmApplicationMode.NEW) {
        // check if current request is actually for the config url, if it is, just do nothing.
        if (pwmURL.isCommandServletURL() || pwmURL.isRestService()) {
            return ProcessStatus.Continue;
        }
        if (pwmURL.isConfigGuideURL() || pwmURL.isReferenceURL()) {
            return ProcessStatus.Continue;
        } else {
            LOGGER.debug("unable to find a valid configuration, redirecting " + pwmURL + " to ConfigGuide");
            pwmRequest.sendRedirect(PwmServletDefinition.ConfigGuide);
            return ProcessStatus.Halt;
        }
    }
    if (mode == PwmApplicationMode.ERROR) {
        ErrorInformation rootError = ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession()).getStartupErrorInformation();
        if (rootError == null) {
            rootError = new ErrorInformation(PwmError.ERROR_APP_UNAVAILABLE, "Application startup failed.");
        }
        pwmRequest.respondWithError(rootError);
        return ProcessStatus.Halt;
    }
    // allow oauth
    if (pwmURL.isOauthConsumer()) {
        return ProcessStatus.Continue;
    }
    // block if public request and not running or in trial
    if (!PwmConstants.TRIAL_MODE) {
        if (mode != PwmApplicationMode.RUNNING) {
            final boolean permittedURl = pwmURL.isResourceURL() || pwmURL.isIndexPage() || pwmURL.isConfigManagerURL() || pwmURL.isConfigGuideURL() || pwmURL.isCommandServletURL() || pwmURL.isReferenceURL() || pwmURL.isLoginServlet() || pwmURL.isLogoutURL() || pwmURL.isOauthConsumer() || pwmURL.isAdminUrl() || pwmURL.isRestService();
            if (!permittedURl) {
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_APPLICATION_NOT_RUNNING);
                pwmRequest.respondWithError(errorInformation);
                return ProcessStatus.Halt;
            }
        }
    }
    return ProcessStatus.Continue;
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) PwmURL(password.pwm.http.PwmURL) PwmApplicationMode(password.pwm.PwmApplicationMode)

Example 12 with ErrorInformation

use of password.pwm.error.ErrorInformation in project pwm by pwm-project.

the class ConfigAccessFilter method checkAuthentication.

@SuppressWarnings("checkstyle:MethodLength")
static ProcessStatus checkAuthentication(final PwmRequest pwmRequest, final ConfigManagerBean configManagerBean) throws IOException, PwmUnrecoverableException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final ConfigurationReader runningConfigReader = ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession()).getConfigReader();
    final StoredConfigurationImpl storedConfig = runningConfigReader.getStoredConfiguration();
    boolean authRequired = false;
    if (storedConfig.hasPassword()) {
        authRequired = true;
    }
    if (PwmApplicationMode.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
        if (!pwmRequest.isAuthenticated()) {
            throw new PwmUnrecoverableException(PwmError.ERROR_AUTHENTICATION_REQUIRED);
        }
        if (!pwmRequest.getPwmSession().getSessionManager().checkPermission(pwmRequest.getPwmApplication(), Permission.PWMADMIN)) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED);
            denyAndError(pwmRequest, errorInformation);
            return ProcessStatus.Halt;
        }
    }
    if (PwmApplicationMode.CONFIGURATION != pwmRequest.getPwmApplication().getApplicationMode()) {
        authRequired = true;
    }
    if (!authRequired) {
        return ProcessStatus.Continue;
    }
    if (!storedConfig.hasPassword()) {
        final String errorMsg = "config file does not have a configuration password";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg, new String[] { errorMsg });
        return denyAndError(pwmRequest, errorInformation);
    }
    if (configManagerBean.isPasswordVerified()) {
        return ProcessStatus.Continue;
    }
    String persistentLoginValue = null;
    boolean persistentLoginAccepted = false;
    boolean persistentLoginEnabled = false;
    if (pwmRequest.getConfig().isDefaultValue(PwmSetting.PWM_SECURITY_KEY)) {
        LOGGER.debug(pwmRequest, "security not available, persistent login not possible.");
    } else {
        persistentLoginEnabled = true;
        final PwmSecurityKey securityKey = pwmRequest.getConfig().getSecurityKey();
        if (PwmApplicationMode.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) {
            persistentLoginValue = SecureEngine.hash(storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH) + pwmSession.getUserInfo().getUserIdentity().toDelimitedKey(), PwmHashAlgorithm.SHA512);
        } else {
            persistentLoginValue = SecureEngine.hash(storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH), PwmHashAlgorithm.SHA512);
        }
        {
            final String cookieStr = pwmRequest.readCookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN);
            if (securityKey != null && cookieStr != null && !cookieStr.isEmpty()) {
                try {
                    final String jsonStr = pwmApplication.getSecureService().decryptStringValue(cookieStr);
                    final PersistentLoginInfo persistentLoginInfo = JsonUtil.deserialize(jsonStr, PersistentLoginInfo.class);
                    if (persistentLoginInfo != null && persistentLoginValue != null) {
                        if (persistentLoginInfo.getExpireDate().isAfter(Instant.now())) {
                            if (persistentLoginValue.equals(persistentLoginInfo.getPassword())) {
                                persistentLoginAccepted = true;
                                LOGGER.debug(pwmRequest, "accepting persistent config login from cookie (expires " + JavaHelper.toIsoDate(persistentLoginInfo.getExpireDate()) + ")");
                            }
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error(pwmRequest, "error examining persistent config login cookie: " + e.getMessage());
                }
                if (!persistentLoginAccepted) {
                    pwmRequest.getPwmResponse().removeCookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, null);
                    LOGGER.debug(pwmRequest, "removing non-working persistent config login cookie");
                }
            }
        }
    }
    final String password = pwmRequest.readParameterAsString("password");
    boolean passwordAccepted = false;
    if (!persistentLoginAccepted) {
        if (password != null && password.length() > 0) {
            if (storedConfig.verifyPassword(password, pwmRequest.getConfig())) {
                passwordAccepted = true;
                LOGGER.trace(pwmRequest, "valid configuration password accepted");
                updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), true);
            } else {
                LOGGER.trace(pwmRequest, "configuration password is not correct");
                pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
                pwmApplication.getIntruderManager().mark(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME, pwmSession.getLabel());
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_PASSWORD_ONLY_BAD);
                updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), false);
                return denyAndError(pwmRequest, errorInformation);
            }
        }
    }
    if ((persistentLoginAccepted || passwordAccepted)) {
        configManagerBean.setPasswordVerified(true);
        pwmApplication.getIntruderManager().convenience().clearAddressAndSession(pwmSession);
        pwmApplication.getIntruderManager().clear(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME);
        if (persistentLoginEnabled && !persistentLoginAccepted && "on".equals(pwmRequest.readParameterAsString("remember"))) {
            final int persistentSeconds = figureMaxLoginSeconds(pwmRequest);
            if (persistentSeconds > 0) {
                final Instant expirationDate = Instant.ofEpochMilli(System.currentTimeMillis() + (persistentSeconds * 1000));
                final PersistentLoginInfo persistentLoginInfo = new PersistentLoginInfo(expirationDate, persistentLoginValue);
                final String jsonPersistentLoginInfo = JsonUtil.serialize(persistentLoginInfo);
                final String cookieValue = pwmApplication.getSecureService().encryptToString(jsonPersistentLoginInfo);
                pwmRequest.getPwmResponse().writeCookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, cookieValue, persistentSeconds);
                LOGGER.debug(pwmRequest, "set persistent config login cookie (expires " + JavaHelper.toIsoDate(expirationDate) + ")");
            }
        }
        if (configManagerBean.getPrePasswordEntryUrl() != null) {
            final String originalUrl = configManagerBean.getPrePasswordEntryUrl();
            configManagerBean.setPrePasswordEntryUrl(null);
            pwmRequest.getPwmResponse().sendRedirect(originalUrl);
            return ProcessStatus.Halt;
        }
        return ProcessStatus.Continue;
    }
    if (configManagerBean.getPrePasswordEntryUrl() == null) {
        configManagerBean.setPrePasswordEntryUrl(pwmRequest.getHttpServletRequest().getRequestURL().toString());
    }
    forwardToJsp(pwmRequest);
    return ProcessStatus.Halt;
}
Also used : PwmApplication(password.pwm.PwmApplication) StoredConfigurationImpl(password.pwm.config.stored.StoredConfigurationImpl) Instant(java.time.Instant) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) ErrorInformation(password.pwm.error.ErrorInformation) PwmSecurityKey(password.pwm.util.secure.PwmSecurityKey) PwmSession(password.pwm.http.PwmSession) ConfigurationReader(password.pwm.config.stored.ConfigurationReader)

Example 13 with ErrorInformation

use of password.pwm.error.ErrorInformation in project pwm by pwm-project.

the class PwmSession method unauthenticateUser.

/**
 * Unauthenticate the pwmSession.
 */
public void unauthenticateUser(final PwmRequest pwmRequest) {
    final LocalSessionStateBean ssBean = getSessionStateBean();
    if (getLoginInfoBean().isAuthenticated()) {
        // try to tear out a session normally.
        getUserSessionDataCacheBean().clearPermissions();
        final StringBuilder sb = new StringBuilder();
        sb.append("unauthenticate session from ").append(ssBean.getSrcAddress());
        if (getUserInfo().getUserIdentity() != null) {
            sb.append(" (").append(getUserInfo().getUserIdentity()).append(")");
        }
        // mark the session state bean as no longer being authenticated
        this.getLoginInfoBean().setAuthenticated(false);
        // close out any outstanding connections
        getSessionManager().closeConnections();
        LOGGER.debug(this, sb.toString());
    }
    if (pwmRequest != null) {
        try {
            pwmRequest.getPwmApplication().getSessionStateService().clearLoginSession(pwmRequest);
        } catch (PwmUnrecoverableException e) {
            final String errorMsg = "unexpected error writing removing login cookie from response: " + e.getMessage();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
            LOGGER.error(pwmRequest, errorInformation);
        }
        pwmRequest.getHttpServletRequest().setAttribute(PwmConstants.SESSION_ATTR_BEANS, null);
    }
    userInfo = null;
    loginInfoBean = null;
    userSessionDataCacheBean = null;
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) LocalSessionStateBean(password.pwm.bean.LocalSessionStateBean) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException)

Example 14 with ErrorInformation

use of password.pwm.error.ErrorInformation in project pwm by pwm-project.

the class PwmHttpRequestWrapper method readRequestBodyAsString.

public static String readRequestBodyAsString(final HttpServletRequest httpServletRequest, final int maxChars) throws IOException, PwmUnrecoverableException {
    final StringWriter stringWriter = new StringWriter();
    final Reader readerStream = new InputStreamReader(httpServletRequest.getInputStream(), PwmConstants.DEFAULT_CHARSET);
    try {
        IOUtils.copy(readerStream, stringWriter);
    } catch (Exception e) {
        final String errorMsg = "error reading request body stream: " + e.getMessage();
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
    } finally {
        IOUtils.closeQuietly(readerStream);
    }
    final String stringValue = stringWriter.toString();
    if (stringValue.length() > maxChars) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "input request body is to big, size=" + stringValue.length() + ", max=" + maxChars));
    }
    return stringValue;
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) StringWriter(java.io.StringWriter) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 15 with ErrorInformation

use of password.pwm.error.ErrorInformation in project pwm by pwm-project.

the class LdapOperationsHelper method openProxyChaiProvider.

static ChaiProvider openProxyChaiProvider(final ChaiProviderFactory chaiProviderFactory, final SessionLabel sessionLabel, final LdapProfile ldapProfile, final Configuration config, final StatisticsManager statisticsManager) throws PwmUnrecoverableException {
    LOGGER.trace(sessionLabel, "opening new ldap proxy connection");
    final String proxyDN = ldapProfile.readSettingAsString(PwmSetting.LDAP_PROXY_USER_DN);
    final PasswordData proxyPW = ldapProfile.readSettingAsPassword(PwmSetting.LDAP_PROXY_USER_PASSWORD);
    try {
        return createChaiProvider(chaiProviderFactory, sessionLabel, ldapProfile, config, proxyDN, proxyPW);
    } catch (ChaiUnavailableException e) {
        if (statisticsManager != null) {
            statisticsManager.incrementValue(Statistic.LDAP_UNAVAILABLE_COUNT);
        }
        final StringBuilder errorMsg = new StringBuilder();
        errorMsg.append("error connecting as proxy user: ");
        final PwmError pwmError = PwmError.forChaiError(e.getErrorCode());
        if (pwmError != null && pwmError != PwmError.ERROR_UNKNOWN) {
            errorMsg.append(new ErrorInformation(pwmError, e.getMessage()).toDebugStr());
        } else {
            errorMsg.append(e.getMessage());
        }
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_DIRECTORY_UNAVAILABLE, errorMsg.toString());
        LOGGER.fatal(sessionLabel, "check ldap proxy settings: " + errorInformation.toDebugStr());
        throw new PwmUnrecoverableException(errorInformation);
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PasswordData(password.pwm.util.PasswordData) PwmError(password.pwm.error.PwmError) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException)

Aggregations

ErrorInformation (password.pwm.error.ErrorInformation)325 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)216 PwmOperationalException (password.pwm.error.PwmOperationalException)125 PwmException (password.pwm.error.PwmException)67 UserIdentity (password.pwm.bean.UserIdentity)62 IOException (java.io.IOException)58 PwmApplication (password.pwm.PwmApplication)54 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)53 ChaiUser (com.novell.ldapchai.ChaiUser)38 PwmSession (password.pwm.http.PwmSession)38 LinkedHashMap (java.util.LinkedHashMap)35 Configuration (password.pwm.config.Configuration)33 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)32 Map (java.util.Map)32 Instant (java.time.Instant)30 ArrayList (java.util.ArrayList)30 FormConfiguration (password.pwm.config.value.data.FormConfiguration)29 ServletException (javax.servlet.ServletException)28 RestResultBean (password.pwm.ws.server.RestResultBean)26 UserInfo (password.pwm.ldap.UserInfo)23