Search in sources :

Example 1 with IPMatcher

use of password.pwm.util.IPMatcher in project pwm by pwm-project.

the class RequestInitializationFilter method handleRequestSecurityChecks.

@SuppressWarnings("checkstyle:MethodLength")
public static void handleRequestSecurityChecks(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
    final LocalSessionStateBean ssBean = pwmRequest.getPwmSession().getSessionStateBean();
    // check the user's IP address
    if (!pwmRequest.getConfig().readSettingAsBoolean(PwmSetting.MULTI_IP_SESSION_ALLOWED)) {
        final String remoteAddress = readUserIPAddress(pwmRequest.getHttpServletRequest(), pwmRequest.getConfig());
        if (!ssBean.getSrcAddress().equals(remoteAddress)) {
            final String errorMsg = "current network address '" + remoteAddress + "' has changed from original network address '" + ssBean.getSrcAddress() + "'";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
            throw new PwmUnrecoverableException(errorInformation);
        }
    }
    // check total time.
    {
        if (ssBean.getSessionCreationTime() != null) {
            final Long maxSessionSeconds = pwmRequest.getConfig().readSettingAsLong(PwmSetting.SESSION_MAX_SECONDS);
            final TimeDuration sessionAge = TimeDuration.fromCurrent(ssBean.getSessionCreationTime());
            if (sessionAge.getTotalSeconds() > maxSessionSeconds) {
                final String errorMsg = "session age (" + sessionAge.asCompactString() + ") is longer than maximum permitted age";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
                throw new PwmUnrecoverableException(errorInformation);
            }
        }
    }
    // check headers
    {
        final List<String> requiredHeaders = pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.REQUIRED_HEADERS);
        if (requiredHeaders != null && !requiredHeaders.isEmpty()) {
            final Map<String, String> configuredValues = StringUtil.convertStringListToNameValuePair(requiredHeaders, "=");
            for (final Map.Entry<String, String> entry : configuredValues.entrySet()) {
                final String key = entry.getKey();
                if (key != null && key.length() > 0) {
                    final String requiredValue = entry.getValue();
                    if (requiredValue != null && requiredValue.length() > 0) {
                        final String value = pwmRequest.readHeaderValueAsString(key);
                        if (value == null || value.length() < 1) {
                            final String errorMsg = "request is missing required value for header '" + key + "'";
                            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
                            throw new PwmUnrecoverableException(errorInformation);
                        } else {
                            if (!requiredValue.equals(value)) {
                                final String errorMsg = "request has incorrect required value for header '" + key + "'";
                                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
                                throw new PwmUnrecoverableException(errorInformation);
                            }
                        }
                    }
                }
            }
        }
    }
    // check permitted source IP address
    {
        final List<String> requiredHeaders = pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.IP_PERMITTED_RANGE);
        if (requiredHeaders != null && !requiredHeaders.isEmpty()) {
            boolean match = false;
            final String requestAddress = pwmRequest.getHttpServletRequest().getRemoteAddr();
            for (int i = 0; i < requiredHeaders.size() && !match; i++) {
                final String ipMatchString = requiredHeaders.get(i);
                try {
                    final IPMatcher ipMatcher = new IPMatcher(ipMatchString);
                    try {
                        if (ipMatcher.match(requestAddress)) {
                            match = true;
                        }
                    } catch (IPMatcher.IPMatcherException e) {
                        LOGGER.error("error while attempting to match permitted address range '" + ipMatchString + "', error: " + e);
                    }
                } catch (IPMatcher.IPMatcherException e) {
                    LOGGER.error("error parsing permitted address range '" + ipMatchString + "', error: " + e);
                }
            }
            if (!match) {
                final String errorMsg = "request network address '" + requestAddress + "' does not match any configured permitted source address";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, errorMsg);
                throw new PwmUnrecoverableException(errorInformation);
            }
        }
    }
    // csrf cross-site request forgery checks
    final boolean performCsrfHeaderChecks = Boolean.parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.SECURITY_HTTP_PERFORM_CSRF_HEADER_CHECKS));
    if (performCsrfHeaderChecks && !pwmRequest.getMethod().isIdempotent() && !pwmRequest.getURL().isRestService()) {
        final String originValue = pwmRequest.readHeaderValueAsString(HttpHeader.Origin);
        final String referrerValue = pwmRequest.readHeaderValueAsString(HttpHeader.Referer);
        final String siteUrl = pwmRequest.getPwmApplication().getConfig().readSettingAsString(PwmSetting.PWM_SITE_URL);
        final String targetValue = pwmRequest.getHttpServletRequest().getRequestURL().toString();
        if (StringUtil.isEmpty(targetValue)) {
            final String msg = "malformed request instance, missing target uri value";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
            LOGGER.debug(pwmRequest, errorInformation.toDebugStr() + " [" + makeHeaderDebugStr(pwmRequest) + "]");
            throw new PwmUnrecoverableException(errorInformation);
        }
        final boolean originHeaderEvaluated;
        if (!StringUtil.isEmpty(originValue)) {
            if (!PwmURL.compareUriBase(originValue, targetValue)) {
                final String msg = "cross-origin request not permitted: origin header does not match incoming target url" + " [" + makeHeaderDebugStr(pwmRequest) + "]";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
                LOGGER.debug(pwmRequest, errorInformation.toDebugStr());
                throw new PwmUnrecoverableException(errorInformation);
            }
            originHeaderEvaluated = true;
        } else {
            originHeaderEvaluated = false;
        }
        final boolean referrerHeaderEvaluated;
        if (!StringUtil.isEmpty(referrerValue)) {
            if (!PwmURL.compareUriBase(referrerValue, targetValue) && !PwmURL.compareUriBase(referrerValue, siteUrl)) {
                final String msg = "cross-origin request not permitted: referrer header does not match incoming target url" + " [" + makeHeaderDebugStr(pwmRequest) + "]";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
                LOGGER.debug(pwmRequest, errorInformation.toDebugStr());
                throw new PwmUnrecoverableException(errorInformation);
            }
            referrerHeaderEvaluated = true;
        } else {
            referrerHeaderEvaluated = false;
        }
        if (!referrerHeaderEvaluated && !originHeaderEvaluated && !PwmURL.compareUriBase(originValue, siteUrl)) {
            final String msg = "neither referer nor origin header request are present on non-idempotent request";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_SECURITY_VIOLATION, msg);
            LOGGER.debug(pwmRequest, errorInformation.toDebugStr() + " [" + makeHeaderDebugStr(pwmRequest) + "]");
            throw new PwmUnrecoverableException(errorInformation);
        }
    }
    // check trial
    if (PwmConstants.TRIAL_MODE) {
        final StatisticsManager statisticsManager = pwmRequest.getPwmApplication().getStatisticsManager();
        final String currentAuthString = statisticsManager.getStatBundleForKey(StatisticsManager.KEY_CURRENT).getStatistic(Statistic.AUTHENTICATIONS);
        if (new BigInteger(currentAuthString).compareTo(BigInteger.valueOf(PwmConstants.TRIAL_MAX_AUTHENTICATIONS)) > 0) {
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TRIAL_VIOLATION, "maximum usage per server startup exceeded"));
        }
        final String totalAuthString = statisticsManager.getStatBundleForKey(StatisticsManager.KEY_CUMULATIVE).getStatistic(Statistic.AUTHENTICATIONS);
        if (new BigInteger(totalAuthString).compareTo(BigInteger.valueOf(PwmConstants.TRIAL_MAX_TOTAL_AUTH)) > 0) {
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TRIAL_VIOLATION, "maximum usage for this server has been exceeded"));
        }
    }
    // check intruder
    pwmRequest.getPwmApplication().getIntruderManager().convenience().checkAddressAndSession(pwmRequest.getPwmSession());
}
Also used : PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ErrorInformation(password.pwm.error.ErrorInformation) IPMatcher(password.pwm.util.IPMatcher) StatisticsManager(password.pwm.svc.stats.StatisticsManager) BigInteger(java.math.BigInteger) LocalSessionStateBean(password.pwm.bean.LocalSessionStateBean) TimeDuration(password.pwm.util.java.TimeDuration) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

BigInteger (java.math.BigInteger)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 LocalSessionStateBean (password.pwm.bean.LocalSessionStateBean)1 ErrorInformation (password.pwm.error.ErrorInformation)1 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)1 StatisticsManager (password.pwm.svc.stats.StatisticsManager)1 IPMatcher (password.pwm.util.IPMatcher)1 TimeDuration (password.pwm.util.java.TimeDuration)1