Search in sources :

Example 36 with PasswordData

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

the class RestSetPasswordServer method doSetPassword.

private static RestResultBean doSetPassword(final RestRequest restRequest, final JsonInputData jsonInputData) {
    final String password = jsonInputData.getPassword();
    final boolean random = jsonInputData.isRandom();
    if ((password == null || password.length() < 1) && !random) {
        final String errorMessage = "field '" + FIELD_PASSWORD + "' must have a value or field '" + FIELD_RANDOM + "' must be set to true";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, errorMessage, new String[] { FIELD_PASSWORD });
        return RestResultBean.fromError(restRequest, errorInformation);
    }
    if ((password != null && password.length() > 0) && random) {
        final String errorMessage = "field '" + FIELD_PASSWORD + "' cannot have a value or field '" + FIELD_RANDOM + "' must be set to true";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, errorMessage, new String[] { FIELD_PASSWORD });
        return RestResultBean.fromError(restRequest, errorInformation);
    }
    try {
        final TargetUserIdentity targetUserIdentity = RestUtility.resolveRequestedUsername(restRequest, jsonInputData.username);
        final PasswordData newPassword;
        if (random) {
            final PwmPasswordPolicy passwordPolicy = PasswordUtility.readPasswordPolicyForUser(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getUserIdentity(), targetUserIdentity.getChaiUser(), restRequest.getLocale());
            newPassword = RandomPasswordGenerator.createRandomPassword(restRequest.getSessionLabel(), passwordPolicy, restRequest.getPwmApplication());
        } else {
            newPassword = new PasswordData(password);
        }
        final PasswordData oldPassword;
        if (targetUserIdentity.isSelf()) {
            final BasicAuthInfo basicAuthInfo = BasicAuthInfo.parseAuthHeader(restRequest.getPwmApplication(), restRequest.getHttpServletRequest());
            oldPassword = basicAuthInfo == null ? null : basicAuthInfo.getPassword();
        } else {
            oldPassword = null;
        }
        final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getUserIdentity(), restRequest.getLocale());
        PasswordUtility.setPassword(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getChaiProvider(), userInfo, oldPassword, newPassword);
        StatisticsManager.incrementStat(restRequest.getPwmApplication(), Statistic.REST_SETPASSWORD);
        final JsonInputData jsonResultData = new JsonInputData(targetUserIdentity.getUserIdentity().toDelimitedKey(), null, random);
        return RestResultBean.forSuccessMessage(jsonResultData, restRequest, Message.Success_PasswordChange);
    } catch (PwmException e) {
        LOGGER.error("error during set password REST operation: " + e.getMessage());
        return RestResultBean.fromError(restRequest, e.getErrorInformation());
    } catch (Exception e) {
        final String errorMessage = "unexpected error executing web service: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMessage);
        LOGGER.error("error during set password REST operation: " + e.getMessage(), e);
        return RestResultBean.fromError(restRequest, errorInformation);
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PasswordData(password.pwm.util.PasswordData) PwmPasswordPolicy(password.pwm.config.profile.PwmPasswordPolicy) BasicAuthInfo(password.pwm.util.BasicAuthInfo) UserInfo(password.pwm.ldap.UserInfo) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException)

Example 37 with PasswordData

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

the class LDAPStatusChecker method checkBasicLdapConnectivity.

public List<HealthRecord> checkBasicLdapConnectivity(final PwmApplication pwmApplication, final Configuration config, final LdapProfile ldapProfile, final boolean testContextlessRoot) {
    final List<HealthRecord> returnRecords = new ArrayList<>();
    ChaiProvider chaiProvider = null;
    try {
        final DirectoryVendor directoryVendor;
        try {
            final String proxyDN = ldapProfile.readSettingAsString(PwmSetting.LDAP_PROXY_USER_DN);
            final PasswordData proxyPW = ldapProfile.readSettingAsPassword(PwmSetting.LDAP_PROXY_USER_PASSWORD);
            if (proxyDN == null || proxyDN.length() < 1) {
                return Collections.singletonList(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "Missing Proxy User DN"));
            }
            if (proxyPW == null) {
                return Collections.singletonList(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "Missing Proxy User Password"));
            }
            chaiProvider = LdapOperationsHelper.createChaiProvider(pwmApplication, SessionLabel.HEALTH_SESSION_LABEL, ldapProfile, config, proxyDN, proxyPW);
            final ChaiEntry adminEntry = chaiProvider.getEntryFactory().newChaiEntry(proxyDN);
            adminEntry.exists();
            directoryVendor = chaiProvider.getDirectoryVendor();
        } catch (ChaiException e) {
            final ChaiError chaiError = ChaiErrors.getErrorForMessage(e.getMessage());
            final PwmError pwmError = PwmError.forChaiError(chaiError);
            final StringBuilder errorString = new StringBuilder();
            final String profileName = ldapProfile.getIdentifier();
            errorString.append("error connecting to ldap directory (").append(profileName).append("), error: ").append(e.getMessage());
            if (chaiError != null && chaiError != ChaiError.UNKNOWN) {
                errorString.append(" (");
                errorString.append(chaiError.toString());
                if (pwmError != null && pwmError != PwmError.ERROR_UNKNOWN) {
                    errorString.append(" - ");
                    errorString.append(pwmError.getLocalizedMessage(PwmConstants.DEFAULT_LOCALE, pwmApplication.getConfig()));
                }
                errorString.append(")");
            }
            returnRecords.add(new HealthRecord(HealthStatus.WARN, makeLdapTopic(ldapProfile, config), errorString.toString()));
            pwmApplication.getLdapConnectionService().setLastLdapFailure(ldapProfile, new ErrorInformation(PwmError.ERROR_DIRECTORY_UNAVAILABLE, errorString.toString()));
            return returnRecords;
        } catch (Exception e) {
            final HealthRecord record = HealthRecord.forMessage(HealthMessage.LDAP_No_Connection, e.getMessage());
            returnRecords.add(record);
            pwmApplication.getLdapConnectionService().setLastLdapFailure(ldapProfile, new ErrorInformation(PwmError.ERROR_DIRECTORY_UNAVAILABLE, record.getDetail(PwmConstants.DEFAULT_LOCALE, pwmApplication.getConfig())));
            return returnRecords;
        }
        if (directoryVendor != null && directoryVendor == DirectoryVendor.ACTIVE_DIRECTORY) {
            returnRecords.addAll(checkAd(pwmApplication, config, ldapProfile));
        }
        if (testContextlessRoot) {
            for (final String loopContext : ldapProfile.readSettingAsStringArray(PwmSetting.LDAP_CONTEXTLESS_ROOT)) {
                try {
                    final ChaiEntry contextEntry = chaiProvider.getEntryFactory().newChaiEntry(loopContext);
                    final Set<String> objectClasses = contextEntry.readObjectClass();
                    if (objectClasses == null || objectClasses.isEmpty()) {
                        final String errorString = "ldap context setting '" + loopContext + "' is not valid";
                        returnRecords.add(new HealthRecord(HealthStatus.WARN, makeLdapTopic(ldapProfile, config), errorString));
                    }
                } catch (Exception e) {
                    final String errorString = "ldap root context '" + loopContext + "' is not valid: " + e.getMessage();
                    returnRecords.add(new HealthRecord(HealthStatus.WARN, makeLdapTopic(ldapProfile, config), errorString));
                }
            }
        }
    } finally {
        if (chaiProvider != null) {
            try {
                chaiProvider.close();
            } catch (Exception e) {
            /* ignore */
            }
        }
    }
    return returnRecords;
}
Also used : PwmError(password.pwm.error.PwmError) ArrayList(java.util.ArrayList) ChaiEntry(com.novell.ldapchai.ChaiEntry) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ChaiException(com.novell.ldapchai.exception.ChaiException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ErrorInformation(password.pwm.error.ErrorInformation) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) PasswordData(password.pwm.util.PasswordData) ChaiError(com.novell.ldapchai.exception.ChaiError) DirectoryVendor(com.novell.ldapchai.provider.DirectoryVendor) ChaiException(com.novell.ldapchai.exception.ChaiException)

Example 38 with PasswordData

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

the class PasswordValue method factory.

public static StoredValueFactory factory() {
    return new StoredValueFactory() {

        public PasswordValue fromJson(final String value) {
            final String strValue = JsonUtil.deserialize(value, String.class);
            if (strValue != null && !strValue.isEmpty()) {
                try {
                    return new PasswordValue(new PasswordData(strValue));
                } catch (PwmUnrecoverableException e) {
                    throw new IllegalStateException("PasswordValue can not be json de-serialized: " + e.getMessage());
                }
            }
            return new PasswordValue();
        }

        public PasswordValue fromXmlElement(final Element settingElement, final PwmSecurityKey key) throws PwmOperationalException, PwmUnrecoverableException {
            final Element valueElement = settingElement.getChild("value");
            final String rawValue = valueElement.getText();
            final PasswordValue newPasswordValue = new PasswordValue();
            if (rawValue == null || rawValue.isEmpty()) {
                return newPasswordValue;
            }
            final boolean plainTextSetting;
            {
                final String plainTextAttributeStr = valueElement.getAttributeValue("plaintext");
                plainTextSetting = plainTextAttributeStr != null && Boolean.parseBoolean(plainTextAttributeStr);
            }
            if (plainTextSetting) {
                newPasswordValue.value = new PasswordData(rawValue);
                newPasswordValue.requiresStoredUpdate = true;
            } else {
                try {
                    newPasswordValue.value = new PasswordData(SecureEngine.decryptStringValue(rawValue, key, PwmBlockAlgorithm.CONFIG));
                    return newPasswordValue;
                } catch (Exception e) {
                    final String errorMsg = "unable to decode encrypted password value for setting: " + e.getMessage();
                    final ErrorInformation errorInfo = new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg);
                    throw new PwmOperationalException(errorInfo);
                }
            }
            return newPasswordValue;
        }
    };
}
Also used : PwmSecurityKey(password.pwm.util.secure.PwmSecurityKey) ErrorInformation(password.pwm.error.ErrorInformation) PasswordData(password.pwm.util.PasswordData) Element(org.jdom2.Element) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 39 with PasswordData

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

the class PwmApplication method outputKeystore.

private static void outputKeystore(final PwmApplication pwmApplication) throws Exception {
    final Map<PwmEnvironment.ApplicationParameter, String> applicationParams = pwmApplication.getPwmEnvironment().getParameters();
    final String keystoreFileString = applicationParams.get(PwmEnvironment.ApplicationParameter.AutoExportHttpsKeyStoreFile);
    if (keystoreFileString != null && !keystoreFileString.isEmpty()) {
        LOGGER.trace("attempting to output keystore as configured by environment parameters to " + keystoreFileString);
        final File keyStoreFile = new File(keystoreFileString);
        final String password = applicationParams.get(PwmEnvironment.ApplicationParameter.AutoExportHttpsKeyStorePassword);
        final String alias = applicationParams.get(PwmEnvironment.ApplicationParameter.AutoExportHttpsKeyStoreAlias);
        final KeyStore keyStore = HttpsServerCertificateManager.keyStoreForApplication(pwmApplication, new PasswordData(password), alias);
        final ByteArrayOutputStream outputContents = new ByteArrayOutputStream();
        keyStore.store(outputContents, password.toCharArray());
        if (keyStoreFile.exists()) {
            LOGGER.trace("deleting existing keystore file " + keyStoreFile.getAbsolutePath());
            if (keyStoreFile.delete()) {
                LOGGER.trace("deleted existing keystore file: " + keyStoreFile.getAbsolutePath());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFile)) {
            fileOutputStream.write(outputContents.toByteArray());
        }
        LOGGER.info("successfully exported application https key to keystore file " + keyStoreFile.getAbsolutePath());
    }
}
Also used : PasswordData(password.pwm.util.PasswordData) FileOutputStream(java.io.FileOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) KeyStore(java.security.KeyStore)

Example 40 with PasswordData

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

the class Configuration method getSecurityKey.

public PwmSecurityKey getSecurityKey() throws PwmUnrecoverableException {
    final PasswordData configValue = readSettingAsPassword(PwmSetting.PWM_SECURITY_KEY);
    if (configValue == null || configValue.getStringValue().isEmpty()) {
        final String errorMsg = "Security Key value is not configured,will generate temp value for use by runtime instance";
        final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_INVALID_SECURITY_KEY, errorMsg);
        LOGGER.warn(errorInfo.toDebugStr());
        if (tempInstanceKey == null) {
            tempInstanceKey = new PwmSecurityKey(PwmRandom.getInstance().alphaNumericString(256));
        }
        return tempInstanceKey;
    }
    final int minSecurityKeyLength = Integer.parseInt(readAppProperty(AppProperty.SECURITY_CONFIG_MIN_SECURITY_KEY_LENGTH));
    if (configValue.getStringValue().length() < minSecurityKeyLength) {
        final String errorMsg = "Security Key must be greater than 32 characters in length";
        final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_INVALID_SECURITY_KEY, errorMsg);
        throw new PwmUnrecoverableException(errorInfo);
    }
    try {
        return new PwmSecurityKey(configValue.getStringValue());
    } catch (Exception e) {
        final String errorMsg = "unexpected error generating Security Key crypto: " + e.getMessage();
        final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_INVALID_SECURITY_KEY, errorMsg);
        LOGGER.error(errorInfo.toDebugStr(), e);
        throw new PwmUnrecoverableException(errorInfo);
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmSecurityKey(password.pwm.util.secure.PwmSecurityKey) PasswordData(password.pwm.util.PasswordData) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

PasswordData (password.pwm.util.PasswordData)44 ErrorInformation (password.pwm.error.ErrorInformation)20 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)17 PwmOperationalException (password.pwm.error.PwmOperationalException)12 ChaiUser (com.novell.ldapchai.ChaiUser)10 UserInfo (password.pwm.ldap.UserInfo)10 ChaiProvider (com.novell.ldapchai.provider.ChaiProvider)8 ArrayList (java.util.ArrayList)8 UserIdentity (password.pwm.bean.UserIdentity)7 PwmException (password.pwm.error.PwmException)7 PwmPasswordPolicy (password.pwm.config.profile.PwmPasswordPolicy)6 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)5 LinkedHashMap (java.util.LinkedHashMap)5 ChaiException (com.novell.ldapchai.exception.ChaiException)4 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)4 Locale (java.util.Locale)4 Map (java.util.Map)4 FormConfiguration (password.pwm.config.value.data.FormConfiguration)4 RandomPasswordGenerator (password.pwm.util.RandomPasswordGenerator)4 PwmSecurityKey (password.pwm.util.secure.PwmSecurityKey)4