Search in sources :

Example 1 with PwmSession

use of password.pwm.http.PwmSession in project pwm by pwm-project.

the class RequestInitializationFilter method checkAndInitSessionState.

private void checkAndInitSessionState(final HttpServletRequest request) throws PwmUnrecoverableException {
    final ContextManager contextManager = ContextManager.getContextManager(request.getSession());
    final PwmApplication pwmApplication = contextManager.getPwmApplication();
    {
        // destroy any outdated sessions
        final HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            final String sessionPwmAppNonce = (String) httpSession.getAttribute(PwmConstants.SESSION_ATTR_PWM_APP_NONCE);
            if (sessionPwmAppNonce == null || !sessionPwmAppNonce.equals(pwmApplication.getRuntimeNonce())) {
                LOGGER.debug("invalidating http session created with non-current servlet context");
                httpSession.invalidate();
            }
        }
    }
    {
        // handle pwmSession init and assignment.
        final HttpSession httpSession = request.getSession();
        if (httpSession.getAttribute(PwmConstants.SESSION_ATTR_PWM_SESSION) == null) {
            final PwmSession pwmSession = PwmSession.createPwmSession(pwmApplication);
            PwmSessionWrapper.sessionMerge(pwmApplication, pwmSession, httpSession);
        }
    }
}
Also used : PwmApplication(password.pwm.PwmApplication) HttpSession(javax.servlet.http.HttpSession) ContextManager(password.pwm.http.ContextManager) PwmSession(password.pwm.http.PwmSession)

Example 2 with PwmSession

use of password.pwm.http.PwmSession in project pwm by pwm-project.

the class AbstractPwmServlet method handleRequest.

private void handleRequest(final HttpServletRequest req, final HttpServletResponse resp, final HttpMethod method) throws ServletException, IOException {
    try {
        final PwmRequest pwmRequest = PwmRequest.forRequest(req, resp);
        if (!method.isIdempotent() && !pwmRequest.getURL().isCommandServletURL()) {
            Validator.validatePwmFormID(pwmRequest);
            try {
                Validator.validatePwmRequestCounter(pwmRequest);
            } catch (PwmOperationalException e) {
                if (e.getError() == PwmError.ERROR_INCORRECT_REQ_SEQUENCE) {
                    final ErrorInformation errorInformation = e.getErrorInformation();
                    final PwmSession pwmSession = PwmSessionWrapper.readPwmSession(req);
                    LOGGER.error(pwmSession, errorInformation.toDebugStr());
                    pwmRequest.respondWithError(errorInformation, false);
                    return;
                }
                throw e;
            }
        }
        // check for incorrect method type.
        final ProcessAction processAction = readProcessAction(pwmRequest);
        if (processAction != null) {
            if (!processAction.permittedMethods().contains(method)) {
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "incorrect request method " + method.toString() + " on request to " + pwmRequest.getURLwithQueryString());
                LOGGER.error(pwmRequest.getPwmSession(), errorInformation.toDebugStr());
                pwmRequest.respondWithError(errorInformation, false);
                return;
            }
        }
        this.processAction(pwmRequest);
    } catch (Exception e) {
        final PwmRequest pwmRequest;
        try {
            pwmRequest = PwmRequest.forRequest(req, resp);
        } catch (Exception e2) {
            try {
                LOGGER.fatal("exception occurred, but exception handler unable to load request instance; error=" + e.getMessage(), e);
            } catch (Exception e3) {
                e3.printStackTrace();
            }
            throw new ServletException(e);
        }
        final PwmUnrecoverableException pue = convertToPwmUnrecoverableException(e, pwmRequest);
        if (processUnrecoverableException(req, resp, pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), pue)) {
            return;
        }
        outputUnrecoverableException(pwmRequest, pue);
        clearModuleBeans(pwmRequest);
    }
}
Also used : ServletException(javax.servlet.ServletException) ErrorInformation(password.pwm.error.ErrorInformation) PwmRequest(password.pwm.http.PwmRequest) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmSession(password.pwm.http.PwmSession) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 3 with PwmSession

use of password.pwm.http.PwmSession in project pwm by pwm-project.

the class AuthenticationFilter method processFilter.

public void processFilter(final PwmApplicationMode mode, final PwmRequest pwmRequest, final PwmFilterChain chain) throws IOException, ServletException {
    final PwmURL pwmURL = pwmRequest.getURL();
    if (pwmURL.isPublicUrl() && !pwmURL.isLoginServlet()) {
        chain.doFilter();
        return;
    }
    try {
        final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
        final PwmSession pwmSession = pwmRequest.getPwmSession();
        if (pwmApplication.getApplicationMode() == PwmApplicationMode.NEW) {
            if (pwmRequest.getURL().isConfigGuideURL()) {
                chain.doFilter();
                return;
            }
        }
        if (pwmApplication.getApplicationMode() == PwmApplicationMode.CONFIGURATION) {
            if (pwmRequest.getURL().isConfigManagerURL()) {
                chain.doFilter();
                return;
            }
        }
        // user is already authenticated
        if (pwmSession.isAuthenticated()) {
            this.processAuthenticatedSession(pwmRequest, chain);
        } else {
            this.processUnAuthenticatedSession(pwmRequest, chain);
        }
    } catch (PwmUnrecoverableException e) {
        LOGGER.error(e.getErrorInformation());
        pwmRequest.respondWithError(e.getErrorInformation(), true);
    }
}
Also used : PwmApplication(password.pwm.PwmApplication) PwmURL(password.pwm.http.PwmURL) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmSession(password.pwm.http.PwmSession)

Example 4 with PwmSession

use of password.pwm.http.PwmSession in project pwm by pwm-project.

the class AuthenticationFilter method processAuthenticatedSession.

private void processAuthenticatedSession(final PwmRequest pwmRequest, final PwmFilterChain chain) throws IOException, ServletException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    // read the basic auth info out of the header (if it exists);
    if (pwmRequest.getConfig().readSettingAsBoolean(PwmSetting.BASIC_AUTH_ENABLED)) {
        final BasicAuthInfo basicAuthInfo = BasicAuthInfo.parseAuthHeader(pwmApplication, pwmRequest);
        final BasicAuthInfo originalBasicAuthInfo = pwmSession.getLoginInfoBean().getBasicAuth();
        // check to make sure basic auth info is same as currently known user in session.
        if (basicAuthInfo != null && originalBasicAuthInfo != null && !(originalBasicAuthInfo.equals(basicAuthInfo))) {
            // if we read here then user is using basic auth, and header has changed since last request
            // this means something is screwy, so log out the session
            // read the current user info for logging
            final UserInfo userInfo = pwmSession.getUserInfo();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, "basic auth header user '" + basicAuthInfo.getUsername() + "' does not match currently logged in user '" + userInfo.getUserIdentity() + "', session will be logged out");
            LOGGER.info(pwmRequest, errorInformation);
            // log out their user
            pwmSession.unauthenticateUser(pwmRequest);
            // send en error to user.
            pwmRequest.respondWithError(errorInformation, true);
            return;
        }
    }
    // check status of oauth expiration
    if (pwmSession.getLoginInfoBean().getOauthExp() != null) {
        final OAuthSettings oauthSettings = OAuthSettings.forSSOAuthentication(pwmRequest.getConfig());
        final OAuthMachine oAuthMachine = new OAuthMachine(oauthSettings);
        if (oAuthMachine.checkOAuthExpiration(pwmRequest)) {
            pwmRequest.respondWithError(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "oauth access token has expired"));
            return;
        }
    }
    handleAuthenticationCookie(pwmRequest);
    if (forceRequiredRedirects(pwmRequest) == ProcessStatus.Halt) {
        return;
    }
    // user session is authed, and session and auth header match, so forward request on.
    chain.doFilter();
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) BasicAuthInfo(password.pwm.util.BasicAuthInfo) UserInfo(password.pwm.ldap.UserInfo) OAuthMachine(password.pwm.http.servlet.oauth.OAuthMachine) OAuthSettings(password.pwm.http.servlet.oauth.OAuthSettings) PwmSession(password.pwm.http.PwmSession)

Example 5 with PwmSession

use of password.pwm.http.PwmSession 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)

Aggregations

PwmSession (password.pwm.http.PwmSession)74 PwmApplication (password.pwm.PwmApplication)55 ErrorInformation (password.pwm.error.ErrorInformation)38 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)30 PwmOperationalException (password.pwm.error.PwmOperationalException)29 Configuration (password.pwm.config.Configuration)21 UserIdentity (password.pwm.bean.UserIdentity)20 FormConfiguration (password.pwm.config.value.data.FormConfiguration)19 PwmException (password.pwm.error.PwmException)14 ChaiUser (com.novell.ldapchai.ChaiUser)12 ActionConfiguration (password.pwm.config.value.data.ActionConfiguration)12 UserInfo (password.pwm.ldap.UserInfo)12 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)11 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)9 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)9 IOException (java.io.IOException)9 Instant (java.time.Instant)9 RestResultBean (password.pwm.ws.server.RestResultBean)9 ServletException (javax.servlet.ServletException)8 MacroMachine (password.pwm.util.macro.MacroMachine)8