Search in sources :

Example 1 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class IdleTimeoutCalculator method figureMaxSessionTimeout.

public static MaxIdleTimeoutResult figureMaxSessionTimeout(final PwmApplication pwmApplication, final PwmSession pwmSession) throws PwmUnrecoverableException {
    final Configuration configuration = pwmApplication.getConfig();
    final SortedSet<MaxIdleTimeoutResult> results = new TreeSet<>();
    {
        final long idleSetting = configuration.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
        results.add(new MaxIdleTimeoutResult(MaxIdleTimeoutResult.reasonFor(PwmSetting.IDLE_TIMEOUT_SECONDS, null), new TimeDuration(idleSetting, TimeUnit.SECONDS)));
    }
    if (!pwmSession.isAuthenticated()) {
        if (pwmApplication.getApplicationMode() == PwmApplicationMode.NEW) {
            final long configGuideIdleTimeout = Long.parseLong(configuration.readAppProperty(AppProperty.CONFIG_GUIDE_IDLE_TIMEOUT));
            results.add(new MaxIdleTimeoutResult("Configuration Guide Idle Timeout", new TimeDuration(configGuideIdleTimeout, TimeUnit.SECONDS)));
        }
        if (configuration.readSettingAsBoolean(PwmSetting.PEOPLE_SEARCH_ENABLE_PUBLIC)) {
            final long peopleSearchIdleTimeout = configuration.readSettingAsLong(PwmSetting.PEOPLE_SEARCH_IDLE_TIMEOUT_SECONDS);
            if (peopleSearchIdleTimeout > 0) {
                results.add(new MaxIdleTimeoutResult(MaxIdleTimeoutResult.reasonFor(PwmSetting.PEOPLE_SEARCH_IDLE_TIMEOUT_SECONDS, null), new TimeDuration(peopleSearchIdleTimeout, TimeUnit.SECONDS)));
            }
        }
    } else {
        final UserInfo userInfo = pwmSession.getUserInfo();
        final boolean userIsAdmin = pwmSession.getSessionManager().checkPermission(pwmApplication, Permission.PWMADMIN);
        final Set<MaxIdleTimeoutResult> loggedInResults = figureMaxAuthUserTimeout(configuration, userInfo, userIsAdmin);
        results.addAll(loggedInResults);
    }
    return results.last();
}
Also used : Configuration(password.pwm.config.Configuration) TreeSet(java.util.TreeSet) TimeDuration(password.pwm.util.java.TimeDuration) UserInfo(password.pwm.ldap.UserInfo)

Example 2 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class IdleTimeoutCalculator method idleTimeoutForRequest.

public static TimeDuration idleTimeoutForRequest(final PwmURL pwmURL, final PwmApplication pwmApplication, final PwmSession pwmSession) throws PwmUnrecoverableException {
    if (pwmURL.isResourceURL()) {
        return figureMaxSessionTimeout(pwmApplication, pwmSession).getIdleTimeout();
    }
    final Configuration config = pwmApplication.getConfig();
    if (pwmURL.isPwmServletURL(PwmServletDefinition.Helpdesk)) {
        if (config.readSettingAsBoolean(PwmSetting.HELPDESK_ENABLE)) {
            final HelpdeskProfile helpdeskProfile = pwmSession.getSessionManager().getHelpdeskProfile(pwmApplication);
            if (helpdeskProfile != null) {
                final long helpdeskIdleTimeout = helpdeskProfile.readSettingAsLong(PwmSetting.HELPDESK_IDLE_TIMEOUT_SECONDS);
                if (helpdeskIdleTimeout > 0) {
                    return new TimeDuration(helpdeskIdleTimeout, TimeUnit.SECONDS);
                }
            }
        }
    }
    if ((pwmURL.isPwmServletURL(PwmServletDefinition.PrivatePeopleSearch) || pwmURL.isPwmServletURL(PwmServletDefinition.PublicPeopleSearch)) && pwmURL.isPrivateUrl()) {
        if (config.readSettingAsBoolean(PwmSetting.PEOPLE_SEARCH_ENABLE)) {
            final long peopleSearchIdleTimeout = config.readSettingAsLong(PwmSetting.PEOPLE_SEARCH_IDLE_TIMEOUT_SECONDS);
            if (peopleSearchIdleTimeout > 0) {
                return new TimeDuration(peopleSearchIdleTimeout, TimeUnit.SECONDS);
            }
        }
    }
    if (pwmURL.isPwmServletURL(PwmServletDefinition.ConfigEditor)) {
        try {
            if (pwmSession.getSessionManager().checkPermission(pwmApplication, Permission.PWMADMIN)) {
                final long configEditorIdleTimeout = Long.parseLong(config.readAppProperty(AppProperty.CONFIG_EDITOR_IDLE_TIMEOUT));
                if (configEditorIdleTimeout > 0) {
                    return new TimeDuration(configEditorIdleTimeout, TimeUnit.SECONDS);
                }
            }
        } catch (PwmUnrecoverableException e) {
            LOGGER.error(pwmSession, "error while figuring max idle timeout for session: " + e.getMessage());
        }
    }
    if (pwmURL.isPwmServletURL(PwmServletDefinition.ConfigGuide)) {
        if (pwmApplication.getApplicationMode() == PwmApplicationMode.NEW) {
            final long configGuideIdleTimeout = Long.parseLong(config.readAppProperty(AppProperty.CONFIG_GUIDE_IDLE_TIMEOUT));
            if (configGuideIdleTimeout > 0) {
                return new TimeDuration(configGuideIdleTimeout, TimeUnit.SECONDS);
            }
        }
    }
    final long idleTimeout = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS);
    return new TimeDuration(idleTimeout, TimeUnit.SECONDS);
}
Also used : Configuration(password.pwm.config.Configuration) HelpdeskProfile(password.pwm.config.profile.HelpdeskProfile) TimeDuration(password.pwm.util.java.TimeDuration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException)

Example 3 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class LdapProfile method readCanonicalDN.

public String readCanonicalDN(final PwmApplication pwmApplication, final String dnValue) throws PwmUnrecoverableException {
    {
        final boolean doCanonicalDnResolve = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_RESOLVE_CANONICAL_DN));
        if (!doCanonicalDnResolve) {
            return dnValue;
        }
    }
    final boolean enableCanonicalCache = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_CANONICAL_ENABLE));
    String canonicalValue = null;
    final CacheKey cacheKey = CacheKey.makeCacheKey(LdapPermissionTester.class, null, "canonicalDN-" + this.getIdentifier() + "-" + dnValue);
    if (enableCanonicalCache) {
        final String cachedDN = pwmApplication.getCacheService().get(cacheKey);
        if (cachedDN != null) {
            canonicalValue = cachedDN;
        }
    }
    if (canonicalValue == null) {
        try {
            final ChaiProvider chaiProvider = this.getProxyChaiProvider(pwmApplication);
            final ChaiEntry chaiEntry = chaiProvider.getEntryFactory().newChaiEntry(dnValue);
            canonicalValue = chaiEntry.readCanonicalDN();
            if (enableCanonicalCache) {
                final long cacheSeconds = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_CANONICAL_SECONDS));
                final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpiration(new TimeDuration(cacheSeconds, TimeUnit.SECONDS));
                pwmApplication.getCacheService().put(cacheKey, cachePolicy, canonicalValue);
            }
            LOGGER.trace("read and cached canonical ldap DN value for input '" + dnValue + "' as '" + canonicalValue + "'");
        } catch (ChaiUnavailableException | ChaiOperationException e) {
            LOGGER.error("error while reading canonicalDN for dn value '" + dnValue + "', error: " + e.getMessage());
            return dnValue;
        }
    }
    return canonicalValue;
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) CachePolicy(password.pwm.svc.cache.CachePolicy) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiEntry(com.novell.ldapchai.ChaiEntry) TimeDuration(password.pwm.util.java.TimeDuration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) CacheKey(password.pwm.svc.cache.CacheKey)

Example 4 with TimeDuration

use of password.pwm.util.java.TimeDuration 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)

Example 5 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class HealthMonitorSettings method fromConfiguration.

public static HealthMonitorSettings fromConfiguration(final Configuration config) {
    final HealthMonitorSettings settings = new HealthMonitorSettings();
    settings.nominalCheckInterval = new TimeDuration(Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_NOMINAL_CHECK_INTERVAL)), TimeUnit.SECONDS);
    settings.minimumCheckInterval = new TimeDuration(Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MIN_CHECK_INTERVAL)), TimeUnit.SECONDS);
    settings.maximumRecordAge = new TimeDuration(Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MAX_RECORD_AGE)), TimeUnit.SECONDS);
    settings.maximumForceCheckWait = new TimeDuration(Long.parseLong(config.readAppProperty(AppProperty.HEALTHCHECK_MAX_FORCE_WAIT)), TimeUnit.SECONDS);
    return settings;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration)

Aggregations

TimeDuration (password.pwm.util.java.TimeDuration)75 Instant (java.time.Instant)28 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)19 PwmException (password.pwm.error.PwmException)14 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 IOException (java.io.IOException)9 Configuration (password.pwm.config.Configuration)8 PwmOperationalException (password.pwm.error.PwmOperationalException)8 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)7 Map (java.util.Map)7 UserIdentity (password.pwm.bean.UserIdentity)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)6 MacroMachine (password.pwm.util.macro.MacroMachine)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Locale (java.util.Locale)5