Search in sources :

Example 81 with Configuration

use of password.pwm.config.Configuration in project pwm by pwm-project.

the class ConfigurationReader method saveConfiguration.

public void saveConfiguration(final StoredConfigurationImpl storedConfiguration, final PwmApplication pwmApplication, final SessionLabel sessionLabel) throws IOException, PwmUnrecoverableException, PwmOperationalException {
    File backupDirectory = null;
    int backupRotations = 0;
    if (pwmApplication != null) {
        final Configuration configuration = new Configuration(storedConfiguration);
        final String backupDirSetting = configuration.readAppProperty(AppProperty.BACKUP_LOCATION);
        if (backupDirSetting != null && backupDirSetting.length() > 0) {
            final File pwmPath = pwmApplication.getPwmEnvironment().getApplicationPath();
            backupDirectory = FileSystemUtility.figureFilepath(backupDirSetting, pwmPath);
        }
        backupRotations = Integer.parseInt(configuration.readAppProperty(AppProperty.BACKUP_CONFIG_COUNT));
    }
    {
        // increment the config epoch
        String epochStrValue = storedConfiguration.readConfigProperty(ConfigurationProperty.CONFIG_EPOCH);
        try {
            final BigInteger epochValue = epochStrValue == null || epochStrValue.length() < 0 ? BigInteger.ZERO : new BigInteger(epochStrValue);
            epochStrValue = epochValue.add(BigInteger.ONE).toString();
        } catch (Exception e) {
            LOGGER.error(sessionLabel, "error trying to parse previous config epoch property: " + e.getMessage());
            epochStrValue = "0";
        }
        storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_EPOCH, epochStrValue);
    }
    if (backupDirectory != null && !backupDirectory.exists()) {
        if (!backupDirectory.mkdirs()) {
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unable to create backup directory structure '" + backupDirectory.toString() + "'"));
        }
    }
    try {
        final File tempWriteFile = new File(configFile.getAbsoluteFile() + ".new");
        LOGGER.info(sessionLabel, "beginning write to configuration file " + tempWriteFile);
        saveInProgress = true;
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempWriteFile, false)) {
            storedConfiguration.toXml(fileOutputStream);
        }
        LOGGER.info("saved configuration " + JsonUtil.serialize(storedConfiguration.toJsonDebugObject()));
        if (pwmApplication != null) {
            final String actualChecksum = storedConfiguration.settingChecksum();
            pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.CONFIG_HASH, actualChecksum);
        }
        LOGGER.trace("renaming file " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath());
        try {
            Files.move(tempWriteFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception e) {
            final String errorMsg = "unable to rename temporary save file from " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath() + "; error: " + e.getMessage();
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
        }
        if (backupDirectory != null) {
            final String configFileName = configFile.getName();
            final String backupFilePath = backupDirectory.getAbsolutePath() + File.separatorChar + configFileName + "-backup";
            final File backupFile = new File(backupFilePath);
            FileSystemUtility.rotateBackups(backupFile, backupRotations);
            try (FileOutputStream fileOutputStream = new FileOutputStream(backupFile, false)) {
                storedConfiguration.toXml(fileOutputStream);
            }
        }
    } finally {
        saveInProgress = false;
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) Configuration(password.pwm.config.Configuration) FileOutputStream(java.io.FileOutputStream) BigInteger(java.math.BigInteger) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) File(java.io.File) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) IOException(java.io.IOException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 82 with Configuration

use of password.pwm.config.Configuration in project pwm by pwm-project.

the class UserMatchViewerFunction method discoverMatchingUsers.

public Collection<UserIdentity> discoverMatchingUsers(final PwmApplication pwmApplication, final int maxResultSize, final StoredConfigurationImpl storedConfiguration, final PwmSetting setting, final String profile) throws Exception {
    final Configuration config = new Configuration(storedConfiguration);
    final PwmApplication tempApplication = new PwmApplication(pwmApplication.getPwmEnvironment().makeRuntimeInstance(config));
    final List<UserPermission> permissions = (List<UserPermission>) storedConfiguration.readSetting(setting, profile).toNativeObject();
    for (final UserPermission userPermission : permissions) {
        if (userPermission.getType() == UserPermission.Type.ldapQuery) {
            if (userPermission.getLdapBase() != null && !userPermission.getLdapBase().isEmpty()) {
                testIfLdapDNIsValid(tempApplication, userPermission.getLdapBase(), userPermission.getLdapProfileID());
            }
        } else if (userPermission.getType() == UserPermission.Type.ldapGroup) {
            testIfLdapDNIsValid(tempApplication, userPermission.getLdapBase(), userPermission.getLdapProfileID());
        }
    }
    return LdapPermissionTester.discoverMatchingUsers(tempApplication, maxResultSize, permissions, SessionLabel.SYSTEM_LABEL).keySet();
}
Also used : PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) List(java.util.List) UserPermission(password.pwm.config.value.data.UserPermission)

Example 83 with Configuration

use of password.pwm.config.Configuration in project pwm by pwm-project.

the class SessionFilter method handleStandardRequestOperations.

private ProcessStatus handleStandardRequestOperations(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmRequest.getConfig();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    final PwmResponse resp = pwmRequest.getPwmResponse();
    // debug the http session headers
    if (!pwmSession.getSessionStateBean().isDebugInitialized()) {
        LOGGER.trace(pwmSession, pwmRequest.debugHttpHeaders());
        pwmSession.getSessionStateBean().setDebugInitialized(true);
    }
    try {
        pwmApplication.getSessionStateService().readLoginSessionState(pwmRequest);
    } catch (PwmUnrecoverableException e) {
        LOGGER.warn(pwmRequest, "error while reading login session state: " + e.getMessage());
    }
    // mark last url
    if (!new PwmURL(pwmRequest.getHttpServletRequest()).isCommandServletURL()) {
        ssBean.setLastRequestURL(pwmRequest.getHttpServletRequest().getRequestURI());
    }
    // mark last request time.
    ssBean.setSessionLastAccessedTime(Instant.now());
    // check the page leave notice
    if (checkPageLeaveNotice(pwmSession, config)) {
        LOGGER.warn("invalidating session due to dirty page leave time greater then configured timeout");
        pwmRequest.invalidateSession();
        resp.sendRedirect(pwmRequest.getHttpServletRequest().getRequestURI());
        return ProcessStatus.Halt;
    }
    // override session locale due to parameter
    handleLocaleParam(pwmRequest);
    // set the session's theme
    handleThemeParam(pwmRequest);
    // check the sso override flag
    handleSsoOverrideParam(pwmRequest);
    // check for session verification failure
    if (!ssBean.isSessionVerified()) {
        // ignore resource requests
        final SessionVerificationMode mode = config.readSettingAsEnum(PwmSetting.ENABLE_SESSION_VERIFICATION, SessionVerificationMode.class);
        if (mode == SessionVerificationMode.OFF) {
            ssBean.setSessionVerified(true);
        } else {
            if (verifySession(pwmRequest, mode) == ProcessStatus.Halt) {
                return ProcessStatus.Halt;
            }
        }
    }
    {
        final String forwardURLParamName = config.readAppProperty(AppProperty.HTTP_PARAM_NAME_FORWARD_URL);
        final String forwardURL = pwmRequest.readParameterAsString(forwardURLParamName);
        if (forwardURL != null && forwardURL.length() > 0) {
            try {
                checkUrlAgainstWhitelist(pwmApplication, pwmRequest.getSessionLabel(), forwardURL);
            } catch (PwmOperationalException e) {
                LOGGER.error(pwmRequest, e.getErrorInformation());
                pwmRequest.respondWithError(e.getErrorInformation());
                return ProcessStatus.Halt;
            }
            ssBean.setForwardURL(forwardURL);
            LOGGER.debug(pwmRequest, "forwardURL parameter detected in request, setting session forward url to " + forwardURL);
        }
    }
    {
        final String logoutURLParamName = config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOGOUT_URL);
        final String logoutURL = pwmRequest.readParameterAsString(logoutURLParamName);
        if (logoutURL != null && logoutURL.length() > 0) {
            try {
                checkUrlAgainstWhitelist(pwmApplication, pwmRequest.getSessionLabel(), logoutURL);
            } catch (PwmOperationalException e) {
                LOGGER.error(pwmRequest, e.getErrorInformation());
                pwmRequest.respondWithError(e.getErrorInformation());
                return ProcessStatus.Halt;
            }
            ssBean.setLogoutURL(logoutURL);
            LOGGER.debug(pwmRequest, "logoutURL parameter detected in request, setting session logout url to " + logoutURL);
        }
    }
    {
        final String expireParamName = pwmRequest.getConfig().readAppProperty(AppProperty.HTTP_PARAM_NAME_PASSWORD_EXPIRED);
        if ("true".equalsIgnoreCase(pwmRequest.readParameterAsString(expireParamName))) {
            LOGGER.debug(pwmSession, "detected param '" + expireParamName + "'=true in request, will force pw change");
            pwmSession.getLoginInfoBean().getLoginFlags().add(LoginInfoBean.LoginFlag.forcePwChange);
        }
    }
    // update last request time.
    ssBean.setSessionLastAccessedTime(Instant.now());
    if (pwmApplication.getStatisticsManager() != null) {
        pwmApplication.getStatisticsManager().incrementValue(Statistic.HTTP_REQUESTS);
    }
    return ProcessStatus.Continue;
}
Also used : PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) SessionVerificationMode(password.pwm.config.option.SessionVerificationMode) PwmResponse(password.pwm.http.PwmResponse) LocalSessionStateBean(password.pwm.bean.LocalSessionStateBean) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmURL(password.pwm.http.PwmURL) PwmSession(password.pwm.http.PwmSession) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 84 with Configuration

use of password.pwm.config.Configuration in project pwm by pwm-project.

the class SessionFilter method handleLocaleParam.

private static void handleLocaleParam(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
    final Configuration config = pwmRequest.getConfig();
    final String localeParamName = config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE);
    final String localeCookieName = config.readAppProperty(AppProperty.HTTP_COOKIE_LOCALE_NAME);
    final String requestedLocale = pwmRequest.readParameterAsString(localeParamName);
    final int cookieAgeSeconds = (int) pwmRequest.getConfig().readSettingAsLong(PwmSetting.LOCALE_COOKIE_MAX_AGE);
    if (requestedLocale != null && requestedLocale.length() > 0) {
        LOGGER.debug(pwmRequest, "detected locale request parameter " + localeParamName + " with value " + requestedLocale);
        if (pwmRequest.getPwmSession().setLocale(pwmRequest.getPwmApplication(), requestedLocale)) {
            if (cookieAgeSeconds > 0) {
                pwmRequest.getPwmResponse().writeCookie(localeCookieName, requestedLocale, cookieAgeSeconds, PwmHttpResponseWrapper.CookiePath.Application);
            }
        }
    }
}
Also used : Configuration(password.pwm.config.Configuration)

Example 85 with Configuration

use of password.pwm.config.Configuration 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

Configuration (password.pwm.config.Configuration)111 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)45 FormConfiguration (password.pwm.config.value.data.FormConfiguration)37 PwmApplication (password.pwm.PwmApplication)33 ErrorInformation (password.pwm.error.ErrorInformation)33 PwmOperationalException (password.pwm.error.PwmOperationalException)25 ActionConfiguration (password.pwm.config.value.data.ActionConfiguration)23 Locale (java.util.Locale)22 PwmSession (password.pwm.http.PwmSession)21 PwmException (password.pwm.error.PwmException)17 EmailItemBean (password.pwm.bean.EmailItemBean)16 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)16 UserInfo (password.pwm.ldap.UserInfo)15 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)14 IOException (java.io.IOException)14 ArrayList (java.util.ArrayList)13 MacroMachine (password.pwm.util.macro.MacroMachine)13 LinkedHashMap (java.util.LinkedHashMap)12 Instant (java.time.Instant)11 UserIdentity (password.pwm.bean.UserIdentity)10