diff --git a/docs/en/security/tribe-clients-integrations/java.asciidoc b/docs/en/security/tribe-clients-integrations/java.asciidoc index 3ceebef6657..ad36a569019 100644 --- a/docs/en/security/tribe-clients-integrations/java.asciidoc +++ b/docs/en/security/tribe-clients-integrations/java.asciidoc @@ -125,9 +125,9 @@ request: + [source,java] -------------------------------------------------------------------------------------------------- +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; @@ -142,7 +142,7 @@ TransportClient client = new PreBuiltXPackTransportClient(Settings.builder() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9301)) -String token = basicAuthHeaderValue("test_user", new SecuredString("changeme".toCharArray())); +String token = basicAuthHeaderValue("test_user", new SecureString("changeme".toCharArray())); client.filterWithHeader(Collections.singletonMap("Authorization", token)) .prepareSearch().get(); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/XPackClient.java b/plugin/src/main/java/org/elasticsearch/xpack/XPackClient.java index 95d22b0f35d..6f3681e94ae 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/XPackClient.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/XPackClient.java @@ -7,6 +7,7 @@ package org.elasticsearch.xpack; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.license.LicensingClient; import org.elasticsearch.license.XPackInfoResponse; import org.elasticsearch.xpack.action.XPackInfoAction; @@ -14,7 +15,6 @@ import org.elasticsearch.xpack.action.XPackInfoRequest; import org.elasticsearch.xpack.action.XPackInfoRequestBuilder; import org.elasticsearch.xpack.ml.client.MachineLearningClient; import org.elasticsearch.xpack.monitoring.client.MonitoringClient; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.watcher.client.WatcherClient; @@ -78,7 +78,7 @@ public class XPackClient { * @param passwd The password of the user. This char array can be cleared after calling this method. */ public XPackClient withAuth(String username, char[] passwd) { - return withHeaders(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(username, new SecuredString(passwd)))); + return withHeaders(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(username, new SecureString(passwd)))); } public XPackInfoRequestBuilder prepareInfo() { diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/Security.java b/plugin/src/main/java/org/elasticsearch/xpack/security/Security.java index e80688bc713..b20a78b807e 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/Security.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/Security.java @@ -29,6 +29,7 @@ import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.IndexScopedSettings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; @@ -100,7 +101,6 @@ import org.elasticsearch.xpack.security.authc.esnative.NativeRealm; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.authz.AuthorizationService; import org.elasticsearch.xpack.security.authz.RoleDescriptor; @@ -571,7 +571,7 @@ public class Security implements ActionPlugin, IngestPlugin, NetworkPlugin { if (settings.get(authHeaderSettingName) != null) { return; } - Optional userOptional = USER_SETTING.get(settings); + Optional userOptional = USER_SETTING.get(settings); // TODO migrate to securesetting! userOptional.ifPresent(userSetting -> { final int i = userSetting.indexOf(":"); if (i < 0 || i == userSetting.length() - 1) { @@ -580,8 +580,7 @@ public class Security implements ActionPlugin, IngestPlugin, NetworkPlugin { } String username = userSetting.substring(0, i); String password = userSetting.substring(i + 1); - settingsBuilder.put(authHeaderSettingName, UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString(password - .toCharArray()))); + settingsBuilder.put(authHeaderSettingName, UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString(password))); }); } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/ChangePasswordAction.java b/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/ChangePasswordAction.java index f1c04b97095..4bd43b1e4b7 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/ChangePasswordAction.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/ChangePasswordAction.java @@ -19,7 +19,7 @@ public class ChangePasswordAction extends Action { public ChangePasswordRequestBuilder(ElasticsearchClient client) { - this(client, ChangePasswordAction.INSTANCE); - } - - public ChangePasswordRequestBuilder(ElasticsearchClient client, ChangePasswordAction action) { - super(client, action, new ChangePasswordRequest()); + super(client, ChangePasswordAction.INSTANCE, new ChangePasswordRequest()); } public ChangePasswordRequestBuilder username(String username) { @@ -47,14 +43,14 @@ public class ChangePasswordRequestBuilder * Sets the password. Note: the char[] passed to this method will be cleared. */ public ChangePasswordRequestBuilder password(char[] password) { - try (SecuredString securedString = new SecuredString(password)) { + try (SecureString secureString = new SecureString(password)) { Validation.Error error = Validation.Users.validatePassword(password); if (error != null) { ValidationException validationException = new ValidationException(); validationException.addValidationError(error.toString()); throw validationException; } - request.passwordHash(Hasher.BCRYPT.hash(securedString)); + request.passwordHash(Hasher.BCRYPT.hash(secureString)); } return this; } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/PutUserRequestBuilder.java b/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/PutUserRequestBuilder.java index 33ae6e01857..a8f91df37f0 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/PutUserRequestBuilder.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/action/user/PutUserRequestBuilder.java @@ -13,12 +13,12 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.ValidationException; import org.elasticsearch.common.bytes.BytesReference; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.support.Validation; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.xpack.common.xcontent.XContentUtils; @@ -59,7 +59,7 @@ public class PutUserRequestBuilder extends ActionRequestBuilder userSource) { + // TODO we should store the hash as something other than a string... bytes? final String passwordHash = (String) userSource.get(User.Fields.PASSWORD.getPreferredName()); if (passwordHash == null) { throw new IllegalStateException("passwordHash should never be null"); @@ -201,8 +202,8 @@ public class NativeRealmMigrator implements IndexLifecycleManager.IndexDataMigra return false; } - try (SecuredString securedString = new SecuredString(passwordHash.toCharArray())) { - return Hasher.BCRYPT.verify(ReservedRealm.DEFAULT_PASSWORD_TEXT, securedString.internalChars()); + try (SecureString secureString = new SecureString(passwordHash.toCharArray())) { + return Hasher.BCRYPT.verify(ReservedRealm.DEFAULT_PASSWORD_TEXT, secureString.getChars()); } } } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java index 997b71c4994..03654930289 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java @@ -25,6 +25,7 @@ import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.ValidationException; import org.elasticsearch.common.component.AbstractComponent; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; @@ -41,7 +42,6 @@ import org.elasticsearch.xpack.security.action.user.ChangePasswordRequest; import org.elasticsearch.xpack.security.action.user.DeleteUserRequest; import org.elasticsearch.xpack.security.action.user.PutUserRequest; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.security.user.SystemUser; import org.elasticsearch.xpack.security.user.User; @@ -457,7 +457,7 @@ public class NativeUsersStore extends AbstractComponent { * @param username username to lookup the user by * @param password the plaintext password to verify */ - void verifyPassword(String username, final SecuredString password, ActionListener listener) { + void verifyPassword(String username, final SecureString password, ActionListener listener) { getUserAndPassword(username, ActionListener.wrap((userAndPassword) -> { if (userAndPassword == null || userAndPassword.passwordHash() == null) { listener.onResponse(null); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealm.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealm.java index 5c5f6fa32db..54ee9d93c57 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealm.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealm.java @@ -9,6 +9,7 @@ import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -20,7 +21,6 @@ import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore.ReservedUserInfo; import org.elasticsearch.xpack.security.authc.support.CachingUsernamePasswordRealm; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.support.Exceptions; import org.elasticsearch.xpack.security.user.AnonymousUser; @@ -44,7 +44,7 @@ public class ReservedRealm extends CachingUsernamePasswordRealm { public static final String TYPE = "reserved"; - public static final SecuredString DEFAULT_PASSWORD_TEXT = new SecuredString("changeme".toCharArray()); + public static final SecureString DEFAULT_PASSWORD_TEXT = new SecureString("changeme".toCharArray()); static final char[] DEFAULT_PASSWORD_HASH = Hasher.BCRYPT.hash(DEFAULT_PASSWORD_TEXT); private static final ReservedUserInfo DEFAULT_USER_INFO = new ReservedUserInfo(DEFAULT_PASSWORD_HASH, true, true); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStore.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStore.java index 27aa06c9e73..1691836463f 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStore.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStore.java @@ -10,6 +10,7 @@ import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.inject.internal.Nullable; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.watcher.FileChangesListener; @@ -19,7 +20,6 @@ import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.support.NoOpLogger; import org.elasticsearch.xpack.security.support.Validation; import org.elasticsearch.xpack.security.support.Validation.Users; @@ -78,7 +78,7 @@ public class FileUserPasswdStore { return users.size(); } - public boolean verifyPassword(String username, SecuredString password) { + public boolean verifyPassword(String username, SecureString password) { char[] hash = users.get(username); if (hash == null) { return false; diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/tool/UsersTool.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/tool/UsersTool.java index 32ed0a8a0bc..1b1882d6c04 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/tool/UsersTool.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/file/tool/UsersTool.java @@ -13,6 +13,7 @@ import org.elasticsearch.cli.EnvironmentAwareCommand; import org.elasticsearch.cli.Terminal; import org.elasticsearch.cli.UserException; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.env.Environment; @@ -20,7 +21,6 @@ import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.file.FileUserPasswdStore; import org.elasticsearch.xpack.security.authc.file.FileUserRolesStore; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authz.store.FileRolesStore; import org.elasticsearch.xpack.security.authz.store.ReservedRolesStore; import org.elasticsearch.xpack.security.support.FileAttributesChecker; @@ -104,7 +104,7 @@ public class UsersTool extends MultiCommand { throw new UserException(ExitCodes.CODE_ERROR, "User [" + username + "] already exists"); } Hasher hasher = Hasher.BCRYPT; - users.put(username, hasher.hash(new SecuredString(password))); + users.put(username, hasher.hash(new SecureString(password))); FileUserPasswdStore.writeFile(users, passwordFile); if (roles.length > 0) { @@ -202,7 +202,7 @@ public class UsersTool extends MultiCommand { if (users.containsKey(username) == false) { throw new UserException(ExitCodes.NO_USER, "User [" + username + "] doesn't exist"); } - users.put(username, Hasher.BCRYPT.hash(new SecuredString(password))); + users.put(username, Hasher.BCRYPT.hash(new SecureString(password))); FileUserPasswdStore.writeFile(users, file); attributesChecker.check(terminal); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactory.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactory.java index e5ffd56238a..132c0124aee 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactory.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactory.java @@ -16,6 +16,7 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; @@ -25,7 +26,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession.GroupsResolver; import org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.SSLService; import java.util.HashSet; @@ -90,7 +90,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { * @param username name of the windows user without the domain */ @Override - public void session(String username, SecuredString password, ActionListener listener) { + public void session(String username, SecureString password, ActionListener listener) { // the runnable action here allows us make the control/flow logic simpler to understand. If we got a connection then lets // authenticate. If there was a failure pass it back using the listener Runnable runnable; @@ -156,11 +156,11 @@ class ActiveDirectorySessionFactory extends SessionFactory { userSearchScope = LdapSearchScope.resolve(settings.get(AD_USER_SEARCH_SCOPE_SETTING), LdapSearchScope.SUB_TREE); } - final void authenticate(LDAPConnection connection, String username, SecuredString password, + final void authenticate(LDAPConnection connection, String username, SecureString password, ActionListener listener) { boolean success = false; try { - connection.bind(bindUsername(username), new String(password.internalChars())); + connection.bind(bindUsername(username), new String(password.getChars())); searchForDN(connection, username, password, Math.toIntExact(timeout.seconds()), ActionListener.wrap((entry) -> { if (entry == null) { IOUtils.close(connection); @@ -189,7 +189,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { return username; } - abstract void searchForDN(LDAPConnection connection, String username, SecuredString password, int timeLimitSeconds, + abstract void searchForDN(LDAPConnection connection, String username, SecureString password, int timeLimitSeconds, ActionListener listener); } @@ -212,7 +212,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { } @Override - void searchForDN(LDAPConnection connection, String username, SecuredString password, + void searchForDN(LDAPConnection connection, String username, SecureString password, int timeLimitSeconds, ActionListener listener) { try { searchForEntry(connection, userSearchDN, userSearchScope.scope(), @@ -255,7 +255,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { } @Override - void searchForDN(LDAPConnection connection, String username, SecuredString password, int timeLimitSeconds, + void searchForDN(LDAPConnection connection, String username, SecureString password, int timeLimitSeconds, ActionListener listener) { String[] parts = username.split("\\\\"); assert parts.length == 2; @@ -283,7 +283,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { })); } - void netBiosDomainNameToDn(LDAPConnection connection, String netBiosDomainName, String username, SecuredString password, + void netBiosDomainNameToDn(LDAPConnection connection, String netBiosDomainName, String username, SecureString password, int timeLimitSeconds, ActionListener listener) { final String cachedName = domainNameCache.get(netBiosDomainName); if (cachedName != null) { @@ -306,7 +306,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { searchConnection = LdapUtils.privilegedConnect(() -> new LDAPConnection(options, connection.getConnectedAddress(), 389)); } - searchConnection.bind(username, new String(password.internalChars())); + searchConnection.bind(username, new String(password.getChars())); final LDAPConnection finalConnection = searchConnection; search(finalConnection, domainDN, LdapSearchScope.SUB_TREE.scope(), filter, timeLimitSeconds, ignoreReferralErrors, ActionListener.wrap( @@ -382,7 +382,7 @@ class ActiveDirectorySessionFactory extends SessionFactory { super(settings, timeout, ignoreReferralErrors, logger, groupsResolver, domainDN); } - void searchForDN(LDAPConnection connection, String username, SecuredString password, int timeLimitSeconds, + void searchForDN(LDAPConnection connection, String username, SecureString password, int timeLimitSeconds, ActionListener listener) { String[] parts = username.split("@"); assert parts.length == 2; diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactory.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactory.java index 4b831333999..9e313f8e5b5 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactory.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactory.java @@ -13,6 +13,7 @@ import org.apache.logging.log4j.util.Supplier; import org.apache.lucene.util.IOUtils; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xpack.security.authc.RealmConfig; @@ -22,7 +23,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession.GroupsRes import org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; import org.elasticsearch.xpack.security.authc.support.CharArrays; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.SSLService; import java.text.MessageFormat; @@ -69,11 +69,11 @@ public class LdapSessionFactory extends SessionFactory { * @param username a relative name, Not a distinguished name, that will be inserted into the template. */ @Override - public void session(String username, SecuredString password, ActionListener listener) { + public void session(String username, SecureString password, ActionListener listener) { LDAPException lastException = null; LDAPConnection connection = null; LdapSession ldapSession = null; - final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.internalChars()); + final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.getChars()); boolean success = false; try { connection = LdapUtils.privilegedConnect(serverSet::getConnection); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactory.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactory.java index 4c9cd693ee0..e4e4a3a4cef 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactory.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactory.java @@ -17,6 +17,7 @@ import com.unboundid.ldap.sdk.SimpleBindRequest; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.IOUtils; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; @@ -28,7 +29,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession.GroupsRes import org.elasticsearch.xpack.security.authc.ldap.support.LdapUtils; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; import org.elasticsearch.xpack.security.authc.support.CharArrays; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.SSLService; import java.util.Arrays; @@ -155,7 +155,7 @@ class LdapUserSearchSessionFactory extends SessionFactory { } @Override - public void session(String user, SecuredString password, ActionListener listener) { + public void session(String user, SecureString password, ActionListener listener) { if (useConnectionPool) { getSessionWithPool(user, password, listener); } else { @@ -166,13 +166,13 @@ class LdapUserSearchSessionFactory extends SessionFactory { /** * Sets up a LDAPSession using the connection pool that potentially holds existing connections to the server */ - private void getSessionWithPool(String user, SecuredString password, ActionListener listener) { + private void getSessionWithPool(String user, SecureString password, ActionListener listener) { findUser(user, connectionPool, ActionListener.wrap((entry) -> { if (entry == null) { listener.onResponse(null); } else { final String dn = entry.getDN(); - final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.internalChars()); + final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.getChars()); try { LdapUtils.privilegedConnect(() -> connectionPool.bindAndRevertAuthentication(new SimpleBindRequest(dn, passwordBytes))); listener.onResponse(new LdapSession(logger, connectionPool, dn, groupResolver, timeout, entry.getAttributes())); @@ -197,7 +197,7 @@ class LdapUserSearchSessionFactory extends SessionFactory { *
  • Creates a new LDAPSession with the bound connection
  • * */ - private void getSessionWithoutPool(String user, SecuredString password, ActionListener listener) { + private void getSessionWithoutPool(String user, SecureString password, ActionListener listener) { boolean success = false; LDAPConnection connection = null; try { @@ -214,7 +214,7 @@ class LdapUserSearchSessionFactory extends SessionFactory { final String dn = entry.getDN(); boolean sessionCreated = false; LDAPConnection userConnection = null; - final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.internalChars()); + final byte[] passwordBytes = CharArrays.toUtf8Bytes(password.getChars()); try { userConnection = LdapUtils.privilegedConnect(serverSet::getConnection); userConnection.bind(new SimpleBindRequest(dn, passwordBytes)); diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java index 54c35d2863d..997acc93d9c 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java @@ -14,12 +14,12 @@ import org.apache.logging.log4j.Logger; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.DeprecationLogger; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.RealmSettings; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.SSLConfigurationSettings; import org.elasticsearch.xpack.ssl.SSLService; import org.elasticsearch.xpack.ssl.VerificationMode; @@ -99,7 +99,7 @@ public abstract class SessionFactory { * @param password The password of the user * @param listener the listener to call on a failure or result */ - public abstract void session(String user, SecuredString password, + public abstract void session(String user, SecureString password, ActionListener listener); /** diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/BCrypt.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/BCrypt.java index 10579cc5474..7871d2b2e04 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/BCrypt.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/BCrypt.java @@ -14,6 +14,8 @@ package org.elasticsearch.xpack.security.authc.support; // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +import org.elasticsearch.common.settings.SecureString; + import java.security.SecureRandom; /** @@ -642,14 +644,14 @@ public class BCrypt { /** * Hash a password using the OpenBSD bcrypt scheme. * - * Modified from the original to take a SecuredString instead of the original + * Modified from the original to take a SecureString instead of the original * * @param password the password to hash * @param salt the salt to hash with (perhaps generated * using BCrypt.gensalt) * @return the hashed password */ - public static String hashpw(SecuredString password, String salt) { + public static String hashpw(SecureString password, String salt) { BCrypt B; String real_salt; byte passwordb[], saltb[], hashed[]; @@ -676,7 +678,7 @@ public class BCrypt { real_salt = salt.substring(off + 3, off + 25); /*************************** ES CHANGE START *************************/ - /* original code before introducing SecuredString + /* original code before introducing SecureString try { passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); } catch (UnsupportedEncodingException uee) { @@ -685,14 +687,13 @@ public class BCrypt { */ - // the next lines are the SecuredString replacement for the above commented-out section + // the next lines are the SecureString replacement for the above commented-out section if (minor >= 'a') { - SecuredString securedString = password.concat("\000"); - passwordb = securedString.utf8Bytes(); - // clear here since this is a new object and we don't need to reuse it - securedString.clear(); + try (SecureString secureString = new SecureString(CharArrays.concat(password.getChars(), "\000".toCharArray()))) { + passwordb = CharArrays.toUtf8Bytes(secureString.getChars()); + } } else { - passwordb = password.utf8Bytes(); + passwordb = CharArrays.toUtf8Bytes(password.getChars()); } /*************************** ES CHANGE END *************************/ @@ -772,15 +773,15 @@ public class BCrypt { * Check that a plaintext password matches a previously hashed * one. * - * Modified from the original to take a SecuredString plaintext and use a constant time comparison + * Modified from the original to take a SecureString plaintext and use a constant time comparison * @param plaintext the plaintext password to verify * @param hashed the previously-hashed password * @return true if the passwords match, false otherwise */ - public static boolean checkpw(SecuredString plaintext, String hashed) { + public static boolean checkpw(SecureString plaintext, String hashed) { /*************************** ES CHANGE START *************************/ // this method previously took a string and did its own constant time comparison - return SecuredString.constantTimeEquals(hashed, hashpw(plaintext, hashed)); + return CharArrays.constantTimeEquals(hashed, hashpw(plaintext, hashed)); /*************************** ES CHANGE END *************************/ } } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealm.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealm.java index 330ee0679a0..78647f7e20e 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealm.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealm.java @@ -8,6 +8,7 @@ package org.elasticsearch.xpack.security.authc.support; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.security.authc.AuthenticationToken; @@ -15,7 +16,6 @@ import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.user.User; import java.util.Arrays; -import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -193,13 +193,13 @@ public abstract class CachingUsernamePasswordRealm extends UsernamePasswordRealm char[] hash; Hasher hasher; - UserWithHash(User user, SecuredString password, Hasher hasher) { + UserWithHash(User user, SecureString password, Hasher hasher) { this.user = user; this.hash = password == null ? null : hasher.hash(password); this.hasher = hasher; } - boolean verify(SecuredString password) { + boolean verify(SecureString password) { return hash != null && hasher.verify(password, hash); } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CharArrays.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CharArrays.java index 65c2acec9ed..e537c6675b7 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CharArrays.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/CharArrays.java @@ -36,6 +36,10 @@ public class CharArrays { return -1; } + /** + * Converts the provided char[] to a UTF-8 byte[]. The provided char[] is not modified by this + * method, so the caller needs to take care of clearing the value if it is sensitive. + */ public static byte[] toUtf8Bytes(char[] chars) { CharBuffer charBuffer = CharBuffer.wrap(chars); ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer); @@ -61,4 +65,37 @@ public class CharArrays { return true; } + + public static boolean constantTimeEquals(char[] a, char[] b) { + if (a.length != b.length) { + return false; + } + + int equals = 0; + for (int i = 0; i < a.length; i++) { + equals |= a[i] ^ b[i]; + } + + return equals == 0; + } + + public static boolean constantTimeEquals(String a, String b) { + if (a.length() != b.length()) { + return false; + } + + int equals = 0; + for (int i = 0; i < a.length(); i++) { + equals |= a.charAt(i) ^ b.charAt(i); + } + + return equals == 0; + } + + public static char[] concat(char[] a, char[] b) { + final char[] result = new char[a.length + b.length]; + System.arraycopy(a, 0, result, 0, a.length); + System.arraycopy(b, 0, result, a.length, b.length); + return result; + } } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/Hasher.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/Hasher.java index 3f74064f24f..d9f1e07dcf5 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/Hasher.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/Hasher.java @@ -7,6 +7,7 @@ package org.elasticsearch.xpack.security.authc.support; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.hash.MessageDigests; +import org.elasticsearch.common.settings.SecureString; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -18,13 +19,13 @@ public enum Hasher { BCRYPT() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -35,13 +36,13 @@ public enum Hasher { BCRYPT4() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(4); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -52,13 +53,13 @@ public enum Hasher { BCRYPT5() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(5); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -69,13 +70,13 @@ public enum Hasher { BCRYPT6() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(6); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -86,13 +87,13 @@ public enum Hasher { BCRYPT7() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(7); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -103,13 +104,13 @@ public enum Hasher { BCRYPT8() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(8); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -120,13 +121,13 @@ public enum Hasher { BCRYPT9() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { String salt = org.elasticsearch.xpack.security.authc.support.BCrypt.gensalt(9); return BCrypt.hashpw(text, salt).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(BCRYPT_PREFIX)) { return false; @@ -137,8 +138,8 @@ public enum Hasher { SHA1() { @Override - public char[] hash(SecuredString text) { - byte[] textBytes = CharArrays.toUtf8Bytes(text.internalChars()); + public char[] hash(SecureString text) { + byte[] textBytes = CharArrays.toUtf8Bytes(text.getChars()); MessageDigest md = MessageDigests.sha1(); md.update(textBytes); String hash = Base64.getEncoder().encodeToString(md.digest()); @@ -146,48 +147,48 @@ public enum Hasher { } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(SHA1_PREFIX)) { return false; } - byte[] textBytes = CharArrays.toUtf8Bytes(text.internalChars()); + byte[] textBytes = CharArrays.toUtf8Bytes(text.getChars()); MessageDigest md = MessageDigests.sha1(); md.update(textBytes); String passwd64 = Base64.getEncoder().encodeToString(md.digest()); String hashNoPrefix = hashStr.substring(SHA1_PREFIX.length()); - return SecuredString.constantTimeEquals(hashNoPrefix, passwd64); + return CharArrays.constantTimeEquals(hashNoPrefix, passwd64); } }, MD5() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { MessageDigest md = MessageDigests.md5(); - md.update(CharArrays.toUtf8Bytes(text.internalChars())); + md.update(CharArrays.toUtf8Bytes(text.getChars())); String hash = Base64.getEncoder().encodeToString(md.digest()); return (MD5_PREFIX + hash).toCharArray(); } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(MD5_PREFIX)) { return false; } hashStr = hashStr.substring(MD5_PREFIX.length()); MessageDigest md = MessageDigests.md5(); - md.update(CharArrays.toUtf8Bytes(text.internalChars())); + md.update(CharArrays.toUtf8Bytes(text.getChars())); String computedHashStr = Base64.getEncoder().encodeToString(md.digest()); - return SecuredString.constantTimeEquals(hashStr, computedHashStr); + return CharArrays.constantTimeEquals(hashStr, computedHashStr); } }, SSHA256() { @Override - public char[] hash(SecuredString text) { + public char[] hash(SecureString text) { MessageDigest md = MessageDigests.sha256(); - md.update(CharArrays.toUtf8Bytes(text.internalChars())); + md.update(CharArrays.toUtf8Bytes(text.getChars())); char[] salt = SaltProvider.salt(8); md.update(CharArrays.toUtf8Bytes(salt)); String hash = Base64.getEncoder().encodeToString(md.digest()); @@ -199,7 +200,7 @@ public enum Hasher { } @Override - public boolean verify(SecuredString text, char[] hash) { + public boolean verify(SecureString text, char[] hash) { String hashStr = new String(hash); if (!hashStr.startsWith(SSHA256_PREFIX)) { return false; @@ -207,22 +208,22 @@ public enum Hasher { hashStr = hashStr.substring(SSHA256_PREFIX.length()); char[] saltAndHash = hashStr.toCharArray(); MessageDigest md = MessageDigests.sha256(); - md.update(CharArrays.toUtf8Bytes(text.internalChars())); + md.update(CharArrays.toUtf8Bytes(text.getChars())); md.update(new String(saltAndHash, 0, 8).getBytes(StandardCharsets.UTF_8)); String computedHash = Base64.getEncoder().encodeToString(md.digest()); - return SecuredString.constantTimeEquals(computedHash, new String(saltAndHash, 8, saltAndHash.length - 8)); + return CharArrays.constantTimeEquals(computedHash, new String(saltAndHash, 8, saltAndHash.length - 8)); } }, NOOP() { @Override - public char[] hash(SecuredString text) { - return text.copyChars(); + public char[] hash(SecureString text) { + return text.clone().getChars(); } @Override - public boolean verify(SecuredString text, char[] hash) { - return SecuredString.constantTimeEquals(text.internalChars(), hash); + public boolean verify(SecureString text, char[] hash) { + return CharArrays.constantTimeEquals(text.getChars(), hash); } }; @@ -272,9 +273,9 @@ public enum Hasher { return hasher; } - public abstract char[] hash(SecuredString data); + public abstract char[] hash(SecureString data); - public abstract boolean verify(SecuredString data, char[] hash); + public abstract boolean verify(SecureString data, char[] hash); static final class SaltProvider { diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/SecuredString.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/SecuredString.java deleted file mode 100644 index 4f6220c56b5..00000000000 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/SecuredString.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.security.authc.support; - -import org.elasticsearch.ElasticsearchException; - -import java.nio.CharBuffer; -import java.util.Arrays; -import java.util.Objects; - -/** - * This is not a string but a CharSequence that can be cleared of its memory. Important for handling passwords. - * - * Not thread safe There is a chance that the chars could be cleared while doing operations on the chars. - *

    - * TODO: dot net's SecureString implementation does some obfuscation of the password to prevent gleaming passwords - * from memory dumps. (this is hard as dot net uses windows system crypto. Thats probably the reason java still doesn't have it) - */ -public class SecuredString implements CharSequence, AutoCloseable { - - public static final SecuredString EMPTY = new SecuredString(new char[0]); - - private final char[] chars; - private boolean cleared = false; - - /** - * Creates a new SecuredString from the chars. These chars will be cleared when the SecuredString is closed so they should not be - * used directly outside of using the SecuredString - */ - public SecuredString(char[] chars) { - this.chars = Objects.requireNonNull(chars, "chars must not be null!"); - } - - /** - * This constructor is used internally for the concatenate method. - */ - private SecuredString(char[] chars, int start, int end) { - this.chars = new char[end - start]; - System.arraycopy(chars, start, this.chars, 0, this.chars.length); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - // Require password to calculate equals - if (this == EMPTY || o == EMPTY) return false; - - if (o instanceof SecuredString) { - SecuredString that = (SecuredString) o; - - if (cleared != that.cleared) return false; - if (!Arrays.equals(chars, that.chars)) return false; - - return true; - } else if (o instanceof CharSequence) { - CharSequence that = (CharSequence) o; - if (cleared) return false; - if (chars.length != that.length()) return false; - - for (int i = 0; i < chars.length; i++) { - if (chars[i] != that.charAt(i)) { - return false; - } - } - return true; - } - return false; - } - - @Override - public int hashCode() { - int result = Arrays.hashCode(chars); - result = 31 * result + (cleared ? 1 : 0); - return result; - } - - /** - * Note: This is a dangerous call that exists for performance/optimization - * DO NOT modify the array returned by this method and DO NOT cache it (as it will be cleared). - * - * To clear the array call SecureString.clear(). - * - * @return the internal characters that MUST NOT be cleared manually - */ - public char[] internalChars() { - throwIfCleared(); - return chars; - } - - /** - * @return A copy of the internal characters. May be used for caching. - */ - public char[] copyChars() { - throwIfCleared(); - return Arrays.copyOf(chars, chars.length); - } - - /** - * @return utf8 encoded bytes - */ - public byte[] utf8Bytes() { - throwIfCleared(); - return CharArrays.toUtf8Bytes(chars); - } - - @Override - public int length() { - throwIfCleared(); - return chars.length; - } - - @Override - public char charAt(int index) { - throwIfCleared(); - return chars[index]; - } - - @Override - public SecuredString subSequence(int start, int end) { - throwIfCleared(); - return new SecuredString(this.chars, start, end); - } - - /** - * Manually clear the underlying array holding the characters - */ - public void clear() { - cleared = true; - Arrays.fill(chars, (char) 0); - } - - /** - * @param toAppend String to combine with this SecureString - * @return a new SecureString with toAppend concatenated - */ - public SecuredString concat(CharSequence toAppend) { - throwIfCleared(); - - CharBuffer buffer = CharBuffer.allocate(chars.length + toAppend.length()); - buffer.put(chars); - for (int i = 0; i < toAppend.length(); i++) { - buffer.put(i + chars.length, toAppend.charAt(i)); - } - return new SecuredString(buffer.array()); - } - - private void throwIfCleared() { - if (cleared) { - throw new ElasticsearchException("attempt to use cleared password"); - } - } - - /** - * This does a char by char comparison of the two Strings to provide protection against timing attacks. In other - * words it does not exit at the first character that does not match and only exits at the end of the comparison. - * - * NOTE: length will cause this function to exit early, which is OK as it is not considered feasible to prevent - * length attacks - * - * @param a the first string to be compared - * @param b the second string to be compared - * @return true if both strings match completely - */ - public static boolean constantTimeEquals(String a, String b) { - char[] aChars = a.toCharArray(); - char[] bChars = b.toCharArray(); - - return constantTimeEquals(aChars, bChars); - } - - /** - * This does a char by char comparison of the two Strings to provide protection against timing attacks. In other - * words it does not exit at the first character that does not match and only exits at the end of the comparison. - * - * NOTE: length will cause this function to exit early, which is OK as it is not considered feasible to prevent - * length attacks - * - * @param securedString the securedstring to compare to string char by char - * @param string the string to compare - * @return true if both match char for char - */ - public static boolean constantTimeEquals(SecuredString securedString, String string) { - return constantTimeEquals(securedString.internalChars(), string.toCharArray()); - } - - /** - * This does a char by char comparison of the two Strings to provide protection against timing attacks. In other - * words it does not exit at the first character that does not match and only exits at the end of the comparison. - * - * NOTE: length will cause this function to exit early, which is OK as it is not considered feasible to prevent - * length attacks - * - * @param securedString the securedstring to compare to string char by char - * @param otherString the other securedstring to compare - * @return true if both match char for char - */ - public static boolean constantTimeEquals(SecuredString securedString, SecuredString otherString) { - return constantTimeEquals(securedString.internalChars(), otherString.internalChars()); - } - - /** - * This does a char by char comparison of the two arrays to provide protection against timing attacks. In other - * words it does not exit at the first character that does not match and only exits at the end of the comparison. - * - * NOTE: length will cause this function to exit early, which is OK as it is not considered feasible to prevent - * length attacks - * - * @param a the first char array - * @param b the second char array - * @return true if both match char for char - */ - public static boolean constantTimeEquals(char[] a, char[] b) { - if (a.length != b.length) { - return false; - } - - int equals = 0; - for (int i = 0; i < a.length; i++) { - equals |= a[i] ^ b[i]; - } - - return equals == 0; - } - - @Override - public void close() { - clear(); - } -} diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordToken.java b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordToken.java index 411fe185164..fddfec9758f 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordToken.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordToken.java @@ -5,6 +5,7 @@ */ package org.elasticsearch.xpack.security.authc.support; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.xpack.security.authc.AuthenticationToken; @@ -21,9 +22,9 @@ public class UsernamePasswordToken implements AuthenticationToken { private static final String BASIC_AUTH_PREFIX = "Basic "; private final String username; - private final SecuredString password; + private final SecureString password; - public UsernamePasswordToken(String username, SecuredString password) { + public UsernamePasswordToken(String username, SecureString password) { this.username = username; this.password = password; } @@ -34,13 +35,13 @@ public class UsernamePasswordToken implements AuthenticationToken { } @Override - public SecuredString credentials() { + public SecureString credentials() { return password; } @Override public void clearCredentials() { - password.clear(); + password.close(); } @Override @@ -93,19 +94,28 @@ public class UsernamePasswordToken implements AuthenticationToken { return new UsernamePasswordToken( new String(Arrays.copyOfRange(userpasswd, 0, i)), - new SecuredString(Arrays.copyOfRange(userpasswd, i + 1, userpasswd.length))); + new SecureString(Arrays.copyOfRange(userpasswd, i + 1, userpasswd.length))); } public static void putTokenHeader(ThreadContext context, UsernamePasswordToken token) { context.putHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue(token.username, token.password)); } - public static String basicAuthHeaderValue(String username, SecuredString passwd) { + public static String basicAuthHeaderValue(String username, SecureString passwd) { CharBuffer chars = CharBuffer.allocate(username.length() + passwd.length() + 1); - chars.put(username).put(':').put(passwd.internalChars()); + byte[] charBytes = null; + try { + chars.put(username).put(':').put(passwd.getChars()); + charBytes = CharArrays.toUtf8Bytes(chars.array()); - //TODO we still have passwords in Strings in headers - String basicToken = Base64.getEncoder().encodeToString(CharArrays.toUtf8Bytes(chars.array())); - return "Basic " + basicToken; + //TODO we still have passwords in Strings in headers. Maybe we can look into using a CharSequence? + String basicToken = Base64.getEncoder().encodeToString(charBytes); + return "Basic " + basicToken; + } finally { + Arrays.fill(chars.array(), (char) 0); + if (charBytes != null) { + Arrays.fill(charBytes, (byte) 0); + } + } } } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/security/crypto/CryptoService.java b/plugin/src/main/java/org/elasticsearch/xpack/security/crypto/CryptoService.java index 1b516a23f79..17e05e6f29b 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/security/crypto/CryptoService.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/security/crypto/CryptoService.java @@ -36,7 +36,7 @@ import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.security.authc.support.CharArrays; import static org.elasticsearch.xpack.security.Security.setting; -import static org.elasticsearch.xpack.security.authc.support.SecuredString.constantTimeEquals; +import static org.elasticsearch.xpack.security.authc.support.CharArrays.constantTimeEquals; /** * Service that provides cryptographic methods based on a shared system key diff --git a/plugin/src/main/java/org/elasticsearch/xpack/ssl/PEMKeyConfig.java b/plugin/src/main/java/org/elasticsearch/xpack/ssl/PEMKeyConfig.java index ce78cfae1c9..2bad70508d6 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/ssl/PEMKeyConfig.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/ssl/PEMKeyConfig.java @@ -7,8 +7,8 @@ package org.elasticsearch.xpack.ssl; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.env.Environment; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509ExtendedTrustManager; @@ -25,7 +25,6 @@ import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -60,8 +59,8 @@ class PEMKeyConfig extends KeyConfig { } Certificate[] certificateChain = CertUtils.readCertificates(Collections.singletonList(certPath), environment); // password must be non-null for keystore... - try (SecuredString securedKeyPasswordChars = new SecuredString(keyPassword == null ? new char[0] : keyPassword.toCharArray())) { - return CertUtils.keyManager(certificateChain, privateKey, securedKeyPasswordChars.internalChars()); + try (SecureString securedKeyPasswordChars = new SecureString(keyPassword == null ? new char[0] : keyPassword.toCharArray())) { + return CertUtils.keyManager(certificateChain, privateKey, securedKeyPasswordChars.getChars()); } } catch (IOException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException | KeyStoreException e) { throw new ElasticsearchException("failed to initialize a KeyManagerFactory", e); @@ -79,12 +78,12 @@ class PEMKeyConfig extends KeyConfig { private PrivateKey readPrivateKey(Path keyPath) throws IOException { try (Reader reader = Files.newBufferedReader(keyPath, StandardCharsets.UTF_8); - SecuredString securedString = new SecuredString(keyPassword == null ? new char[0] : keyPassword.toCharArray())) { + SecureString secureString = new SecureString(keyPassword == null ? new char[0] : keyPassword.toCharArray())) { return CertUtils.readPrivateKey(reader, () -> { if (keyPassword == null) { return null; } else { - return securedString.internalChars(); + return secureString.getChars(); } }); } diff --git a/plugin/src/main/java/org/elasticsearch/xpack/ssl/StoreKeyConfig.java b/plugin/src/main/java/org/elasticsearch/xpack/ssl/StoreKeyConfig.java index 4a805867b96..b3b92adcb55 100644 --- a/plugin/src/main/java/org/elasticsearch/xpack/ssl/StoreKeyConfig.java +++ b/plugin/src/main/java/org/elasticsearch/xpack/ssl/StoreKeyConfig.java @@ -7,8 +7,8 @@ package org.elasticsearch.xpack.ssl; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.env.Environment; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509ExtendedTrustManager; @@ -62,8 +62,8 @@ class StoreKeyConfig extends KeyConfig { try { KeyStore ks = getKeyStore(environment); checkKeyStore(ks); - try (SecuredString keyPasswordSecuredString = new SecuredString(keyPassword.toCharArray())) { - return CertUtils.keyManager(ks, keyPasswordSecuredString.internalChars(), keyStoreAlgorithm); + try (SecureString keyPasswordSecureString = new SecureString(keyPassword.toCharArray())) { + return CertUtils.keyManager(ks, keyPasswordSecureString.getChars(), keyStoreAlgorithm); } } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e) { throw new ElasticsearchException("failed to initialize a KeyManagerFactory", e); @@ -88,12 +88,12 @@ class StoreKeyConfig extends KeyConfig { List privateKeys(@Nullable Environment environment) { try { KeyStore keyStore = getKeyStore(environment); - try (SecuredString keyPasswordSecuredString = new SecuredString(keyPassword.toCharArray())) { + try (SecureString keyPasswordSecureString = new SecureString(keyPassword.toCharArray())) { List privateKeys = new ArrayList<>(); for (Enumeration e = keyStore.aliases(); e.hasMoreElements(); ) { final String alias = e.nextElement(); if (keyStore.isKeyEntry(alias)) { - Key key = keyStore.getKey(alias, keyPasswordSecuredString.internalChars()); + Key key = keyStore.getKey(alias, keyPasswordSecureString.getChars()); if (key instanceof PrivateKey) { privateKeys.add((PrivateKey) key); } @@ -114,8 +114,8 @@ class StoreKeyConfig extends KeyConfig { if (keyStorePassword == null) { throw new IllegalArgumentException("keystore password may not be null"); } - try (SecuredString keyStorePasswordSecuredString = new SecuredString(keyStorePassword.toCharArray())) { - ks.load(in, keyStorePasswordSecuredString.internalChars()); + try (SecureString keyStorePasswordSecureString = new SecureString(keyStorePassword.toCharArray())) { + ks.load(in, keyStorePasswordSecureString.getChars()); } return ks; } diff --git a/plugin/src/test/java/org/elasticsearch/bench/HasherBenchmark.java b/plugin/src/test/java/org/elasticsearch/bench/HasherBenchmark.java index 7fa8723c7f6..400ba3102c8 100644 --- a/plugin/src/test/java/org/elasticsearch/bench/HasherBenchmark.java +++ b/plugin/src/test/java/org/elasticsearch/bench/HasherBenchmark.java @@ -10,9 +10,9 @@ import org.elasticsearch.common.Randomness; import com.carrotsearch.randomizedtesting.generators.RandomStrings; import org.elasticsearch.common.SuppressForbidden; import org.elasticsearch.common.metrics.MeanMetric; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; @SuppressForbidden(reason = "benchmark") public class HasherBenchmark { @@ -35,7 +35,7 @@ public class HasherBenchmark { System.out.print("warming up [" + hasher.name() + "]..."); for (int i = 0; i < WARMING_ITERS; i++) { - SecuredString str = new SecuredString(RandomStrings.randomAsciiOfLength(Randomness.get(), 8).toCharArray()); + SecureString str = new SecureString(RandomStrings.randomAsciiOfLength(Randomness.get(), 8).toCharArray()); char[] hash = hasher.hash(str); hasher.verify(str, hash); } @@ -46,7 +46,7 @@ public class HasherBenchmark { long start; for (int i = 0; i < BENCH_ITERS; i++) { - SecuredString str = new SecuredString(RandomStrings.randomAsciiOfLength(Randomness.get(), 8).toCharArray()); + SecureString str = new SecureString(RandomStrings.randomAsciiOfLength(Randomness.get(), 8).toCharArray()); start = System.nanoTime(); char[] hash = hasher.hash(str); diff --git a/plugin/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java b/plugin/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java index e172678437e..ca1e17d0d81 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java @@ -13,9 +13,9 @@ import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import java.io.IOException; @@ -33,13 +33,13 @@ import static org.hamcrest.Matchers.not; */ public abstract class AbstractPrivilegeTestCase extends SecurityIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("passwd".toCharArray()))); protected void assertAccessIsAllowed(String user, String method, String uri, String body, Map params) throws IOException { Response response = getRestClient().performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); + UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray())))); StatusLine statusLine = response.getStatusLine(); String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); @@ -67,7 +67,7 @@ public abstract class AbstractPrivilegeTestCase extends SecurityIntegTestCase { ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))); + UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray()))))); StatusLine statusLine = responseException.getResponse().getStatusLine(); String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method, uri, body, statusLine.getStatusCode(), statusLine.getReasonPhrase(), @@ -88,7 +88,7 @@ public abstract class AbstractPrivilegeTestCase extends SecurityIntegTestCase { Map params) throws IOException { Response resp = getRestClient().performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); + UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray())))); StatusLine statusLine = resp.getStatusLine(); assertThat(statusLine.getStatusCode(), is(200)); HttpEntity bodyEntity = resp.getEntity(); diff --git a/plugin/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java b/plugin/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java index 05480628505..0ed05fb486b 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java @@ -15,12 +15,12 @@ import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; import org.elasticsearch.xpack.XPackSettings; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import java.io.IOException; @@ -75,7 +75,7 @@ public class BulkUpdateTests extends SecurityIntegTestCase { final String path = "/index1/type/1"; final Header basicAuthHeader = new BasicHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); StringEntity body = new StringEntity("{\"test\":\"test\"}", ContentType.APPLICATION_JSON); Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader); diff --git a/plugin/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/plugin/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index 25990fbb210..deeccdcd497 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -12,6 +12,7 @@ import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.client.Response; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; @@ -20,8 +21,6 @@ import org.elasticsearch.xpack.security.action.realm.ClearRealmCacheResponse; import org.elasticsearch.xpack.security.authc.Realm; import org.elasticsearch.xpack.security.authc.Realms; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.security.user.User; @@ -43,7 +42,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.sameInstance; public class ClearRealmsCacheTests extends SecurityIntegTestCase { - private static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); + private static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("passwd".toCharArray()))); private static String[] usernames; @@ -166,7 +165,7 @@ public class ClearRealmsCacheTests extends SecurityIntegTestCase { Response response = getRestClient().performRequest("POST", path, params, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); assertNotNull(response.getEntity()); assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); } @@ -221,7 +220,7 @@ public class ClearRealmsCacheTests extends SecurityIntegTestCase { private void testScenario(Scenario scenario) throws Exception { Map tokens = new HashMap<>(); for (String user : usernames) { - tokens.put(user, new UsernamePasswordToken(user, SecuredStringTests.build("passwd"))); + tokens.put(user, new UsernamePasswordToken(user, new SecureString("passwd"))); } List realms = new ArrayList<>(); diff --git a/plugin/src/test/java/org/elasticsearch/integration/DateMathExpressionIntegTests.java b/plugin/src/test/java/org/elasticsearch/integration/DateMathExpressionIntegTests.java index d774268da2d..5232cf8e848 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/DateMathExpressionIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/DateMathExpressionIntegTests.java @@ -17,11 +17,11 @@ import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.util.Collections; @@ -33,7 +33,7 @@ import static org.hamcrest.Matchers.is; public class DateMathExpressionIntegTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(USERS_PASSWD)); @Override diff --git a/plugin/src/test/java/org/elasticsearch/integration/DocumentAndFieldLevelSecurityTests.java b/plugin/src/test/java/org/elasticsearch/integration/DocumentAndFieldLevelSecurityTests.java index 73ed5e8e696..0ed0745bdb9 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/DocumentAndFieldLevelSecurityTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/DocumentAndFieldLevelSecurityTests.java @@ -6,13 +6,13 @@ package org.elasticsearch.integration; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.IndexModule; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import java.util.Collections; @@ -27,7 +27,7 @@ import static org.hamcrest.Matchers.equalTo; public class DocumentAndFieldLevelSecurityTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(USERS_PASSWD)); @Override diff --git a/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityRandomTests.java b/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityRandomTests.java index c8b7014d485..cd6087e03a2 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityRandomTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityRandomTests.java @@ -8,11 +8,11 @@ package org.elasticsearch.integration; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import java.util.ArrayList; @@ -26,8 +26,8 @@ import static org.hamcrest.Matchers.equalTo; public class DocumentLevelSecurityRandomTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); // can't add a second test method, because each test run creates a new instance of this class and that will will result // in a new random value: diff --git a/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityTests.java b/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityTests.java index 3e09296fbb3..2035d77c012 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/DocumentLevelSecurityTests.java @@ -18,6 +18,7 @@ import org.elasticsearch.action.termvectors.TermVectorsRequest; import org.elasticsearch.action.termvectors.TermVectorsResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.Requests; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilder; @@ -34,7 +35,6 @@ import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.util.Collections; @@ -55,7 +55,7 @@ import static org.hamcrest.Matchers.is; public class DocumentLevelSecurityTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(USERS_PASSWD)); @Override diff --git a/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityRandomTests.java b/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityRandomTests.java index d93729f4044..4612696416f 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityRandomTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityRandomTests.java @@ -7,12 +7,12 @@ package org.elasticsearch.integration; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import java.util.ArrayList; @@ -33,8 +33,8 @@ import static org.hamcrest.Matchers.equalTo; public class FieldLevelSecurityRandomTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); private static Set allowedFields; private static Set disAllowedFields; diff --git a/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityTests.java b/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityTests.java index b3ec66dc8b2..a2d052b8da6 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/FieldLevelSecurityTests.java @@ -19,6 +19,7 @@ import org.elasticsearch.action.termvectors.TermVectorsRequest; import org.elasticsearch.action.termvectors.TermVectorsResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.Requests; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; @@ -31,7 +32,6 @@ import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.SecurityIntegTestCase; @@ -57,8 +57,8 @@ import static org.hamcrest.Matchers.nullValue; @ESIntegTestCase.ClusterScope(randomDynamicTemplates = false) public class FieldLevelSecurityTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); @Override protected String configUsers() { diff --git a/plugin/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java b/plugin/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java index c9e975413af..cf5e4087ffc 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java @@ -8,11 +8,11 @@ package org.elasticsearch.integration; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.transport.Netty4Plugin; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.junit.Before; @@ -418,7 +418,7 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { try { getRestClient().performRequest("GET", "/", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecuredString("passwd".toCharArray())))); + UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecureString("passwd".toCharArray())))); fail("request should have failed"); } catch(ResponseException e) { assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); diff --git a/plugin/src/test/java/org/elasticsearch/integration/IndicesPermissionsWithAliasesWildcardsAndRegexsTests.java b/plugin/src/test/java/org/elasticsearch/integration/IndicesPermissionsWithAliasesWildcardsAndRegexsTests.java index edd72021444..9216ae5e20d 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/IndicesPermissionsWithAliasesWildcardsAndRegexsTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/IndicesPermissionsWithAliasesWildcardsAndRegexsTests.java @@ -7,10 +7,10 @@ package org.elasticsearch.integration; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import java.util.Collections; @@ -23,8 +23,8 @@ import static org.hamcrest.Matchers.equalTo; public class IndicesPermissionsWithAliasesWildcardsAndRegexsTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); @Override protected String configUsers() { diff --git a/plugin/src/test/java/org/elasticsearch/integration/KibanaUserRoleIntegTests.java b/plugin/src/test/java/org/elasticsearch/integration/KibanaUserRoleIntegTests.java index 54af84c507b..8d5bca8807d 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/KibanaUserRoleIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/KibanaUserRoleIntegTests.java @@ -20,9 +20,9 @@ import org.elasticsearch.action.search.MultiSearchResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.test.SecurityIntegTestCase; @@ -41,8 +41,8 @@ import static org.hamcrest.Matchers.notNullValue; public class KibanaUserRoleIntegTests extends SecurityIntegTestCase { - protected static final SecuredString USERS_PASSWD = new SecuredString("change_me".toCharArray()); - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final SecureString USERS_PASSWD = new SecureString("change_me".toCharArray()); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); @Override public String configRoles() { diff --git a/plugin/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java b/plugin/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java index 9867f9a00c8..5d4ffc856f0 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/MultipleIndicesPermissionsTests.java @@ -11,9 +11,9 @@ import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.MultiSearchResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; @@ -28,7 +28,7 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFa import static org.hamcrest.Matchers.is; public class MultipleIndicesPermissionsTests extends SecurityIntegTestCase { - protected static final SecuredString PASSWD = new SecuredString("passwd".toCharArray()); + protected static final SecureString PASSWD = new SecureString("passwd".toCharArray()); protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(PASSWD)); @Override diff --git a/plugin/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java b/plugin/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java index c06ad09727a..1ecb1c89c41 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/PermissionPrecedenceTests.java @@ -11,10 +11,9 @@ import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateActio import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import java.util.Collections; @@ -34,7 +33,7 @@ import static org.hamcrest.Matchers.hasSize; * index template actions. */ public class PermissionPrecedenceTests extends SecurityIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("test123".toCharArray()))); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("test123".toCharArray()))); @Override protected String configRoles() { @@ -70,8 +69,8 @@ public class PermissionPrecedenceTests extends SecurityIntegTestCase { } @Override - protected SecuredString nodeClientPassword() { - return new SecuredString("test123".toCharArray()); + protected SecureString nodeClientPassword() { + return new SecureString("test123".toCharArray()); } @Override @@ -80,8 +79,8 @@ public class PermissionPrecedenceTests extends SecurityIntegTestCase { } @Override - protected SecuredString transportClientPassword() { - return new SecuredString("test123".toCharArray()); + protected SecureString transportClientPassword() { + return new SecureString("test123".toCharArray()); } public void testDifferentCombinationsOfIndices() throws Exception { @@ -110,7 +109,7 @@ public class PermissionPrecedenceTests extends SecurityIntegTestCase { .setTemplate("test_*")::get, PutIndexTemplateAction.NAME, "user"); Map headers = Collections.singletonMap(UsernamePasswordToken.BASIC_AUTH_HEADER, basicAuthHeaderValue("user", - SecuredStringTests.build("test123"))); + new SecureString("test123"))); assertThrowsAuthorizationException(client.filterWithHeader(headers).admin().indices().prepareGetTemplates("template1")::get, GetIndexTemplatesAction.NAME, "user"); } diff --git a/plugin/src/test/java/org/elasticsearch/integration/SecurityCachePermissionTests.java b/plugin/src/test/java/org/elasticsearch/integration/SecurityCachePermissionTests.java index c25da1b5274..e1f5e23a8fa 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/SecurityCachePermissionTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/SecurityCachePermissionTests.java @@ -7,11 +7,11 @@ package org.elasticsearch.integration; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.TermsLookup; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.Before; import static java.util.Collections.singletonMap; @@ -61,7 +61,7 @@ public class SecurityCachePermissionTests extends SecurityIntegTestCase { // Repeat with unauthorized user!!!! try { response = client().filterWithHeader(singletonMap("Authorization", basicAuthHeaderValue(READ_ONE_IDX_USER, - new SecuredString("changeme".toCharArray())))) + new SecureString("changeme".toCharArray())))) .prepareSearch("data").setTypes("a").setQuery(QueryBuilders.constantScoreQuery( QueryBuilders.termsLookupQuery("token", new TermsLookup("tokens", "tokens", "1", "tokens")))) .execute().actionGet(); diff --git a/plugin/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java b/plugin/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java index 840ac979a22..0d6691e1e55 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java +++ b/plugin/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java @@ -12,10 +12,10 @@ import org.elasticsearch.action.search.ClearScrollResponse; import org.elasticsearch.action.search.MultiSearchRequestBuilder; import org.elasticsearch.action.search.MultiSearchResponse; import org.elasticsearch.action.search.SearchPhaseExecutionException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.SecurityIntegTestCase; import org.junit.After; import org.junit.Before; @@ -33,7 +33,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class SecurityClearScrollTests extends SecurityIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("change_me".toCharArray()))); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("change_me".toCharArray()))); private List scrollIds; @@ -90,7 +90,7 @@ public class SecurityClearScrollTests extends SecurityIntegTestCase { public void testThatClearingAllScrollIdsWorks() throws Exception { String user = "allowed_user:change_me"; - String basicAuth = basicAuthHeaderValue("allowed_user", new SecuredString("change_me".toCharArray())); + String basicAuth = basicAuthHeaderValue("allowed_user", new SecureString("change_me".toCharArray())); Map headers = new HashMap<>(); headers.put(Security.USER_SETTING.getKey(), user); headers.put(BASIC_AUTH_HEADER, basicAuth); @@ -104,7 +104,7 @@ public class SecurityClearScrollTests extends SecurityIntegTestCase { public void testThatClearingAllScrollIdsRequirePermissions() throws Exception { String user = "denied_user:change_me"; - String basicAuth = basicAuthHeaderValue("denied_user", new SecuredString("change_me".toCharArray())); + String basicAuth = basicAuthHeaderValue("denied_user", new SecureString("change_me".toCharArray())); Map headers = new HashMap<>(); headers.put(Security.USER_SETTING.getKey(), user); headers.put(BASIC_AUTH_HEADER, basicAuth); diff --git a/plugin/src/test/java/org/elasticsearch/integration/ldap/AbstractAdLdapRealmTestCase.java b/plugin/src/test/java/org/elasticsearch/integration/ldap/AbstractAdLdapRealmTestCase.java index 0735f69840b..38f06c73ba5 100644 --- a/plugin/src/test/java/org/elasticsearch/integration/ldap/AbstractAdLdapRealmTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/integration/ldap/AbstractAdLdapRealmTestCase.java @@ -11,10 +11,10 @@ import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.logging.ESLoggerFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.ldap.LdapRealm; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -177,7 +177,7 @@ public abstract class AbstractAdLdapRealmTestCase extends SecurityIntegTestCase } protected static String userHeader(String username, String password) { - return UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString(password.toCharArray())); + return UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString(password.toCharArray())); } private Settings sslSettingsForStore(Path store, String password) { diff --git a/plugin/src/test/java/org/elasticsearch/license/LicensingTests.java b/plugin/src/test/java/org/elasticsearch/license/LicensingTests.java index d51b79f2c65..8a62208e18e 100644 --- a/plugin/src/test/java/org/elasticsearch/license/LicensingTests.java +++ b/plugin/src/test/java/org/elasticsearch/license/LicensingTests.java @@ -33,6 +33,7 @@ import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContentHelper; @@ -49,7 +50,6 @@ import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.action.user.GetUsersResponse; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.template.TemplateUtils; @@ -202,7 +202,7 @@ public class LicensingTests extends SecurityIntegTestCase { assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); final String basicAuthValue = UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())); response = getRestClient().performRequest("GET", "/", new BasicHeader("Authorization", basicAuthValue)); assertThat(response.getStatusLine().getStatusCode(), is(200)); response = getRestClient() diff --git a/plugin/src/test/java/org/elasticsearch/test/SecurityIntegTestCase.java b/plugin/src/test/java/org/elasticsearch/test/SecurityIntegTestCase.java index fdfea3742ed..3e34807c35c 100644 --- a/plugin/src/test/java/org/elasticsearch/test/SecurityIntegTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/test/SecurityIntegTestCase.java @@ -17,6 +17,7 @@ import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.network.NetworkAddress; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.gateway.GatewayService; @@ -28,7 +29,6 @@ import org.elasticsearch.xpack.ml.MachineLearning; import org.elasticsearch.xpack.security.InternalClient; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.SecurityLifecycleService; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.client.SecurityClient; import org.junit.AfterClass; import org.junit.Before; @@ -278,7 +278,7 @@ public abstract class SecurityIntegTestCase extends ESIntegTestCase { * {@link org.elasticsearch.test.ESIntegTestCase.ClusterScope} is set to * {@link org.elasticsearch.test.ESIntegTestCase.Scope#SUITE} or {@link org.elasticsearch.test.ESIntegTestCase.Scope#TEST} */ - protected SecuredString nodeClientPassword() { + protected SecureString nodeClientPassword() { return SECURITY_DEFAULT_SETTINGS.nodeClientPassword(); } @@ -296,7 +296,7 @@ public abstract class SecurityIntegTestCase extends ESIntegTestCase { * {@link org.elasticsearch.test.ESIntegTestCase.ClusterScope} is set to * {@link org.elasticsearch.test.ESIntegTestCase.Scope#SUITE} or {@link org.elasticsearch.test.ESIntegTestCase.Scope#TEST} */ - protected SecuredString transportClientPassword() { + protected SecureString transportClientPassword() { return SECURITY_DEFAULT_SETTINGS.transportClientPassword(); } @@ -342,7 +342,7 @@ public abstract class SecurityIntegTestCase extends ESIntegTestCase { } @Override - protected SecuredString nodeClientPassword() { + protected SecureString nodeClientPassword() { return SecurityIntegTestCase.this.nodeClientPassword(); } @@ -352,7 +352,7 @@ public abstract class SecurityIntegTestCase extends ESIntegTestCase { } @Override - protected SecuredString transportClientPassword() { + protected SecureString transportClientPassword() { return SecurityIntegTestCase.this.transportClientPassword(); } diff --git a/plugin/src/test/java/org/elasticsearch/test/SecuritySettingsSource.java b/plugin/src/test/java/org/elasticsearch/test/SecuritySettingsSource.java index 9596a741fad..02ebdbe6cb0 100644 --- a/plugin/src/test/java/org/elasticsearch/test/SecuritySettingsSource.java +++ b/plugin/src/test/java/org/elasticsearch/test/SecuritySettingsSource.java @@ -8,6 +8,7 @@ package org.elasticsearch.test; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.PathUtils; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -23,7 +24,6 @@ import org.elasticsearch.xpack.security.audit.logfile.LoggingAuditTrail; import org.elasticsearch.xpack.security.authc.esnative.NativeRealm; import org.elasticsearch.xpack.security.authc.file.FileRealm; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.crypto.CryptoService; import org.elasticsearch.xpack.security.test.SecurityTestUtils; @@ -51,7 +51,8 @@ public class SecuritySettingsSource extends ClusterDiscoveryConfiguration.Unicas public static final String DEFAULT_USER_NAME = "test_user"; public static final String DEFAULT_PASSWORD = "changeme"; - public static final String DEFAULT_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString(DEFAULT_PASSWORD.toCharArray()))); + public static final SecureString DEFAULT_PASSWORD_SECURE_STRING = new SecureString("changeme".toCharArray()); + public static final String DEFAULT_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString(DEFAULT_PASSWORD.toCharArray()))); public static final String DEFAULT_ROLE = "user"; public static final String DEFAULT_TRANSPORT_CLIENT_ROLE = "transport_client"; @@ -142,7 +143,7 @@ public class SecuritySettingsSource extends ClusterDiscoveryConfiguration.Unicas .put(getClientSSLSettings()); if (randomBoolean()) { builder.put(Security.USER_SETTING.getKey(), - transportClientUsername() + ":" + new String(transportClientPassword().internalChars())); + transportClientUsername() + ":" + new String(transportClientPassword().getChars())); } else { builder.put(ThreadContext.PREFIX + ".Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())); @@ -177,16 +178,16 @@ public class SecuritySettingsSource extends ClusterDiscoveryConfiguration.Unicas return DEFAULT_USER_NAME; } - protected SecuredString nodeClientPassword() { - return new SecuredString(DEFAULT_PASSWORD.toCharArray()); + protected SecureString nodeClientPassword() { + return new SecureString(DEFAULT_PASSWORD.toCharArray()); } protected String transportClientUsername() { return DEFAULT_TRANSPORT_CLIENT_USER_NAME; } - protected SecuredString transportClientPassword() { - return new SecuredString(DEFAULT_PASSWORD.toCharArray()); + protected SecureString transportClientPassword() { + return new SecureString(DEFAULT_PASSWORD.toCharArray()); } protected byte[] systemKey() { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/DatafeedJobIT.java b/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/DatafeedJobIT.java index b45a2a9fb10..0ee8788b8ff 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/DatafeedJobIT.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/DatafeedJobIT.java @@ -11,11 +11,11 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xpack.ml.MachineLearning; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.After; import org.junit.Before; @@ -33,9 +33,9 @@ import static org.hamcrest.Matchers.equalTo; public class DatafeedJobIT extends ESRestTestCase { private static final String BASIC_AUTH_VALUE_ELASTIC = - basicAuthHeaderValue("elastic", new SecuredString("changeme".toCharArray())); + basicAuthHeaderValue("elastic", new SecureString("changeme".toCharArray())); private static final String BASIC_AUTH_VALUE_ML_ADMIN = - basicAuthHeaderValue("ml_admin", new SecuredString("changeme".toCharArray())); + basicAuthHeaderValue("ml_admin", new SecureString("changeme".toCharArray())); @Override protected Settings restClientSettings() { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/MlJobIT.java b/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/MlJobIT.java index 1d084e85304..f2917da1987 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/MlJobIT.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/ml/integration/MlJobIT.java @@ -9,12 +9,12 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xpack.ml.MachineLearning; import org.elasticsearch.xpack.ml.job.persistence.AnomalyDetectorsIndex; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.After; import java.io.BufferedReader; @@ -35,7 +35,7 @@ import static org.hamcrest.Matchers.not; public class MlJobIT extends ESRestTestCase { - private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("elastic", new SecuredString("changeme".toCharArray())); + private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("elastic", new SecureString("changeme".toCharArray())); @Override protected Settings restClientSettings() { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkTests.java b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkTests.java index 0968c728f35..8ec3954b35a 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/action/MonitoringBulkTests.java @@ -17,6 +17,7 @@ import org.elasticsearch.client.RestClient; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.xcontent.XContentType; @@ -26,7 +27,6 @@ import org.elasticsearch.xpack.monitoring.MonitoredSystem; import org.elasticsearch.xpack.monitoring.exporter.MonitoringTemplateUtils; import org.elasticsearch.xpack.monitoring.resolver.bulk.MonitoringBulkTimestampedResolver; import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import java.util.List; @@ -186,7 +186,7 @@ public class MonitoringBulkTests extends MonitoringIntegTestCase { RestClient restClient = getRestClient(); final Header authorization = new BasicHeader(HttpHeaders.AUTHORIZATION, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, - new SecuredString(SecuritySettings.TEST_PASSWORD.toCharArray()))); + new SecureString(SecuritySettings.TEST_PASSWORD.toCharArray()))); Response response = restClient.performRequest("POST", "/_xpack/monitoring/_bulk", MapBuilder.newMapBuilder().put("system_id", MonitoredSystem.KIBANA.getSystem()) .put("system_api_version", MonitoringTemplateUtils.TEMPLATE_VERSION) diff --git a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/security/MonitoringSettingsFilterTests.java b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/security/MonitoringSettingsFilterTests.java index 2f823750943..b9d2d836e34 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/security/MonitoringSettingsFilterTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/security/MonitoringSettingsFilterTests.java @@ -9,13 +9,13 @@ import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.transport.Netty4Plugin; import org.elasticsearch.xpack.monitoring.MonitoringSettings; import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.util.ArrayList; import java.util.Collection; @@ -60,7 +60,7 @@ public class MonitoringSettingsFilterTests extends MonitoringIntegTestCase { headers = new Header[] { new BasicHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, - new SecuredString(SecuritySettings.TEST_PASSWORD.toCharArray())))}; + new SecureString(SecuritySettings.TEST_PASSWORD.toCharArray())))}; } else { headers = new Header[0]; } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/test/MonitoringIntegTestCase.java b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/test/MonitoringIntegTestCase.java index f8de2fc454e..92ee8e257a5 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/monitoring/test/MonitoringIntegTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/monitoring/test/MonitoringIntegTestCase.java @@ -15,6 +15,7 @@ import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.regex.Regex; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.CountDown; @@ -42,7 +43,6 @@ import org.elasticsearch.xpack.monitoring.resolver.ResolversRegistry; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.authc.file.FileRealm; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.crypto.CryptoService; import org.elasticsearch.xpack.watcher.WatcherLifeCycleService; import org.hamcrest.Matcher; @@ -164,7 +164,7 @@ public abstract class MonitoringIntegTestCase extends ESIntegTestCase { return Function.identity(); } Map headers = Collections.singletonMap("Authorization", - basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, new SecuredString(SecuritySettings.TEST_PASSWORD.toCharArray()))); + basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, new SecureString(SecuritySettings.TEST_PASSWORD.toCharArray()))); return client -> (client instanceof NodeClient) ? client.filterWithHeader(headers) : client; } @@ -417,7 +417,7 @@ public abstract class MonitoringIntegTestCase extends ESIntegTestCase { public static final String TEST_USERNAME = "test"; public static final String TEST_PASSWORD = "changeme"; - private static final String TEST_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString(TEST_PASSWORD.toCharArray()))); + private static final String TEST_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString(TEST_PASSWORD.toCharArray()))); static boolean auditLogsEnabled = SystemPropertyUtil.getBoolean("tests.audit_logs", true); static byte[] systemKey = generateKey(); // must be the same for all nodes diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityPluginTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityPluginTests.java index cdbfc30f236..ba4b931e12b 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityPluginTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityPluginTests.java @@ -8,10 +8,10 @@ package org.elasticsearch.xpack.security; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import java.io.IOException; @@ -44,7 +44,7 @@ public class SecurityPluginTests extends SecurityIntegTestCase { Response response = getRestClient().performRequest("GET", "/_xpack", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); } } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityTribeIT.java b/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityTribeIT.java index e8c1a3a00a9..26ea6c6cd55 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityTribeIT.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/SecurityTribeIT.java @@ -12,6 +12,7 @@ import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateObserver; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.UUIDs; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -28,7 +29,6 @@ import org.elasticsearch.test.SecuritySettingsSource; import org.elasticsearch.xpack.security.action.role.GetRolesResponse; import org.elasticsearch.xpack.security.action.role.PutRoleResponse; import org.elasticsearch.xpack.security.action.user.PutUserResponse; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.client.SecurityClient; import org.junit.After; @@ -202,7 +202,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { public void testThatTribeCanAuthenticateElasticUser() throws Exception { setupTribeNode(Settings.EMPTY); ClusterHealthResponse response = tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("changeme".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("changeme".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -214,7 +214,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { assertTribeNodeHasAllIndices(); ClusterHealthResponse response = tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -226,7 +226,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { assertTribeNodeHasAllIndices(); ClusterHealthResponse response = tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -263,7 +263,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { assertTribeNodeHasAllIndices(); for (String username : shouldBeSuccessfulUsers) { ClusterHealthResponse response = tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -271,7 +271,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { for (String username : shouldFailUsers) { ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get()); assertThat(e.getMessage(), containsString("authenticate")); } @@ -298,7 +298,7 @@ public class SecurityTribeIT extends NativeRealmIntegTestCase { assertTribeNodeHasAllIndices(); for (String username : shouldBeSuccessfulUsers) { ClusterHealthResponse response = tribeClient.filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java index 6447e5214cf..75369a2c400 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java @@ -9,10 +9,10 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.elasticsearch.xpack.security.user.ElasticUser; import org.elasticsearch.xpack.security.user.KibanaUser; @@ -54,7 +54,7 @@ public class TransportChangePasswordActionTests extends ESTestCase { ChangePasswordRequest request = new ChangePasswordRequest(); request.username(anonymousUser.principal()); - request.passwordHash(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))); + request.passwordHash(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -85,7 +85,7 @@ public class TransportChangePasswordActionTests extends ESTestCase { ChangePasswordRequest request = new ChangePasswordRequest(); request.username(randomFrom(SystemUser.INSTANCE.principal(), XPackUser.INSTANCE.principal())); - request.passwordHash(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))); + request.passwordHash(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -112,7 +112,7 @@ public class TransportChangePasswordActionTests extends ESTestCase { NativeUsersStore usersStore = mock(NativeUsersStore.class); ChangePasswordRequest request = new ChangePasswordRequest(); request.username(user.principal()); - request.passwordHash(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))); + request.passwordHash(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); @@ -152,7 +152,7 @@ public class TransportChangePasswordActionTests extends ESTestCase { NativeUsersStore usersStore = mock(NativeUsersStore.class); ChangePasswordRequest request = new ChangePasswordRequest(); request.username(user.principal()); - request.passwordHash(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))); + request.passwordHash(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))); final Exception e = randomFrom(new ElasticsearchSecurityException(""), new IllegalStateException(), new RuntimeException()); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java index a7bf1b8c78f..2eb2259782a 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java @@ -11,6 +11,7 @@ import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.ValidationException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -19,7 +20,6 @@ import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.elasticsearch.xpack.security.user.SystemUser; import org.elasticsearch.xpack.security.user.User; @@ -163,7 +163,7 @@ public class TransportPutUserActionTests extends ESTestCase { final PutUserRequest request = new PutUserRequest(); request.username(user.principal()); if (isCreate) { - request.passwordHash(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))); + request.passwordHash(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))); } final boolean created = isCreate ? randomBoolean() : false; // updates should always return false for create doAnswer(new Answer() { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java index 447f5f8b430..183e7ac69ff 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java @@ -19,6 +19,7 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -33,7 +34,6 @@ import org.elasticsearch.xpack.security.authc.Authentication.RealmRef; import org.elasticsearch.xpack.security.authc.AuthenticationService.Authenticator; import org.elasticsearch.xpack.security.authc.Realm.Factory; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.elasticsearch.xpack.security.user.SystemUser; @@ -197,7 +197,7 @@ public class AuthenticationServiceTests extends ESTestCase { public void testAuthenticateNonExistentRestRequestUserThrowsAuthenticationException() throws Exception { when(firstRealm.token(threadContext)).thenReturn(new UsernamePasswordToken("idonotexist", - new SecuredString("passwd".toCharArray()))); + new SecureString("passwd".toCharArray()))); try { authenticateBlocking(restRequest); fail("Authentication was successful but should not"); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/RunAsIntegTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/RunAsIntegTests.java index 7a9b03df17c..1918f8413a2 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/RunAsIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/RunAsIntegTests.java @@ -14,11 +14,10 @@ import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.xpack.security.Security; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; @@ -29,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.elasticsearch.test.SecuritySettingsSource.DEFAULT_PASSWORD_SECURE_STRING; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; @@ -100,7 +100,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { Map headers = new HashMap<>(); headers.put("Authorization", UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); headers.put(AuthenticationService.RUN_AS_USER_HEADER, SecuritySettingsSource.DEFAULT_USER_NAME); // lets set the user ClusterHealthResponse response = client.filterWithHeader(headers).admin().cluster().prepareHealth().get(); @@ -114,7 +114,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { getRestClient().performRequest("GET", "/_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, - SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))), + DEFAULT_PASSWORD_SECURE_STRING)), new BasicHeader(AuthenticationService.RUN_AS_USER_HEADER, SecuritySettingsSource.DEFAULT_USER_NAME)); fail("request should have failed"); } catch(ResponseException e) { @@ -126,7 +126,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { getRestClient().performRequest("GET", "/_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD)))); + DEFAULT_PASSWORD_SECURE_STRING))); fail("request should have failed"); } catch(ResponseException e) { assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403)); @@ -136,7 +136,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { Response response = getRestClient().performRequest("GET", "/_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))), + DEFAULT_PASSWORD_SECURE_STRING)), new BasicHeader(AuthenticationService.RUN_AS_USER_HEADER, SecuritySettingsSource.DEFAULT_USER_NAME)); assertThat(response.getStatusLine().getStatusCode(), is(200)); } @@ -152,7 +152,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { try { Map headers = new HashMap<>(); headers.put("Authorization", UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); headers.put(AuthenticationService.RUN_AS_USER_HEADER, ""); client.filterWithHeader(headers).admin().cluster().prepareHealth().get(); @@ -168,7 +168,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { getRestClient().performRequest("GET", "/_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))), + DEFAULT_PASSWORD_SECURE_STRING)), new BasicHeader(AuthenticationService.RUN_AS_USER_HEADER, "")); fail("request should have failed"); } catch(ResponseException e) { @@ -187,7 +187,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { try { Map headers = new HashMap<>(); headers.put("Authorization", UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); headers.put(AuthenticationService.RUN_AS_USER_HEADER, "idontexist"); client.filterWithHeader(headers).admin().cluster().prepareHealth().get(); @@ -203,7 +203,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase { getRestClient().performRequest("GET", "/_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))), + DEFAULT_PASSWORD_SECURE_STRING)), new BasicHeader(AuthenticationService.RUN_AS_USER_HEADER, "idontexist")); fail("request should have failed"); } catch (ResponseException e) { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ESNativeMigrateToolTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ESNativeMigrateToolTests.java index 6eeac983fe0..3878afd82ac 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ESNativeMigrateToolTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ESNativeMigrateToolTests.java @@ -15,6 +15,7 @@ import org.elasticsearch.env.Environment; import org.elasticsearch.test.NativeRealmIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; import org.elasticsearch.xpack.security.SecurityLifecycleService; +import org.elasticsearch.xpack.security.authc.support.CharArrays; import org.elasticsearch.xpack.security.client.SecurityClient; import org.junit.BeforeClass; @@ -76,7 +77,7 @@ public class ESNativeMigrateToolTests extends NativeRealmIntegTestCase { MockTerminal t = new MockTerminal(); String username = nodeClientUsername(); - String password = new String(nodeClientPassword().utf8Bytes(), StandardCharsets.UTF_8); + String password = new String(CharArrays.toUtf8Bytes(nodeClientPassword().getChars()), StandardCharsets.UTF_8); String url = getHttpURL(); ESNativeRealmMigrateTool.MigrateUserOrRoles muor = new ESNativeRealmMigrateTool.MigrateUserOrRoles(); Settings sslSettings = @@ -121,7 +122,7 @@ public class ESNativeMigrateToolTests extends NativeRealmIntegTestCase { MockTerminal t = new MockTerminal(); String username = nodeClientUsername(); - String password = new String(nodeClientPassword().utf8Bytes(), StandardCharsets.UTF_8); + String password = new String(CharArrays.toUtf8Bytes(nodeClientPassword().getChars()), StandardCharsets.UTF_8); String url = getHttpURL(); ESNativeRealmMigrateTool.MigrateUserOrRoles muor = new ESNativeRealmMigrateTool.MigrateUserOrRoles(); Settings sslSettings = diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java index edcbc74c257..1ed60c53256 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java @@ -16,6 +16,7 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.ValidationException; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.collect.MapBuilder; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.xpack.security.SecurityLifecycleService; @@ -28,7 +29,6 @@ import org.elasticsearch.xpack.security.action.user.AuthenticateResponse; import org.elasticsearch.xpack.security.action.user.ChangePasswordResponse; import org.elasticsearch.xpack.security.action.user.DeleteUserResponse; import org.elasticsearch.xpack.security.action.user.GetUsersResponse; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authz.RoleDescriptor; import org.elasticsearch.xpack.security.authz.permission.Role; import org.elasticsearch.xpack.security.authz.store.NativeRolesStore; @@ -240,7 +240,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { // Index a document with the default test user client().prepareIndex("idx", "doc", "1").setSource("body", "foo").setRefreshPolicy(IMMEDIATE).get(); - String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); SearchResponse searchResp = client().filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("idx").get(); assertEquals(searchResp.getHits().getTotalHits(), 1L); @@ -261,7 +261,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { ensureGreen("idx"); // Index a document with the default test user client().prepareIndex("idx", "doc", "1").setSource("body", "foo").setRefreshPolicy(IMMEDIATE).get(); - String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); SearchResponse searchResp = client().filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("idx").get(); assertEquals(searchResp.getHits().getTotalHits(), 1L); @@ -276,7 +276,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { assertThat(e.status(), is(RestStatus.UNAUTHORIZED)); } - token = basicAuthHeaderValue("joe", new SecuredString("s3krit2".toCharArray())); + token = basicAuthHeaderValue("joe", new SecureString("s3krit2".toCharArray())); searchResp = client().filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("idx").get(); assertEquals(searchResp.getHits().getTotalHits(), 1L); } @@ -296,7 +296,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { ensureGreen("idx"); // Index a document with the default test user client().prepareIndex("idx", "doc", "1").setSource("body", "foo").setRefreshPolicy(IMMEDIATE).get(); - String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); SearchResponse searchResp = client().filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("idx").get(); assertEquals(searchResp.getHits().getTotalHits(), 1L); @@ -327,7 +327,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { ensureGreen(SecurityLifecycleService.SECURITY_INDEX_NAME); if (authenticate) { - final String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + final String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); ClusterHealthResponse response = client().filterWithHeader(Collections.singletonMap("Authorization", token)).admin().cluster() .prepareHealth().get(); assertFalse(response.isTimedOut()); @@ -375,7 +375,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { logger.error("--> waiting for .security index"); ensureGreen(SecurityLifecycleService.SECURITY_INDEX_NAME); - final String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + final String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); ClusterHealthResponse response = client().filterWithHeader(Collections.singletonMap("Authorization", token)).admin().cluster() .prepareHealth().get(); assertFalse(response.isTimedOut()); @@ -416,7 +416,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { // create joe with a password and verify the user works client.preparePutUser("joe", "changeme".toCharArray(), "admin_role").get(); assertThat(client.prepareGetUsers("joe").get().hasUsers(), is(true)); - final String token = basicAuthHeaderValue("joe", new SecuredString("changeme".toCharArray())); + final String token = basicAuthHeaderValue("joe", new SecureString("changeme".toCharArray())); ClusterHealthResponse response = client().filterWithHeader(Collections.singletonMap("Authorization", token)).admin().cluster() .prepareHealth().get(); assertFalse(response.isTimedOut()); @@ -462,7 +462,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { response = client() .filterWithHeader( Collections.singletonMap("Authorization", - basicAuthHeaderValue("joe", new SecuredString("changeme2".toCharArray())))) + basicAuthHeaderValue("joe", new SecureString("changeme2".toCharArray())))) .admin().cluster().prepareHealth().get(); assertFalse(response.isTimedOut()); } @@ -549,7 +549,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { // authenticate should work AuthenticateResponse authenticateResponse = client() .filterWithHeader(Collections.singletonMap("Authorization", - basicAuthHeaderValue(username, new SecuredString("changeme".toCharArray())))) + basicAuthHeaderValue(username, new SecureString("changeme".toCharArray())))) .execute(AuthenticateAction.INSTANCE, new AuthenticateRequest(username)) .get(); assertThat(authenticateResponse.user().principal(), is(username)); @@ -573,7 +573,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { public void testCreateAndChangePassword() throws Exception { securityClient().preparePutUser("joe", "s3krit".toCharArray(), SecuritySettingsSource.DEFAULT_ROLE).get(); - final String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + final String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); ClusterHealthResponse response = client().filterWithHeader(Collections.singletonMap("Authorization", token)) .admin().cluster().prepareHealth().get(); assertThat(response.isTimedOut(), is(false)); @@ -592,7 +592,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { response = client() .filterWithHeader( Collections.singletonMap("Authorization", - basicAuthHeaderValue("joe", new SecuredString("changeme".toCharArray())))) + basicAuthHeaderValue("joe", new SecureString("changeme".toCharArray())))) .admin().cluster().prepareHealth().get(); assertThat(response.isTimedOut(), is(false)); } @@ -657,7 +657,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { public void testSetEnabled() throws Exception { securityClient().preparePutUser("joe", "s3krit".toCharArray(), SecuritySettingsSource.DEFAULT_ROLE).get(); - final String token = basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())); + final String token = basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())); ClusterHealthResponse response = client().filterWithHeader(Collections.singletonMap("Authorization", token)) .admin().cluster().prepareHealth().get(); assertThat(response.isTimedOut(), is(false)); @@ -687,13 +687,13 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { if (anonymousEnabled && roleExists) { ClusterHealthResponse response = client() .filterWithHeader(Collections.singletonMap("Authorization", - basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())))) + basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } else { ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> client() .filterWithHeader(Collections.singletonMap("Authorization", - basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())))) + basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())))) .admin().cluster().prepareHealth().get()); assertThat(e.status(), is(RestStatus.FORBIDDEN)); } @@ -702,7 +702,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { securityClient.preparePutRole("unknown_role").cluster("all").get(); ClusterHealthResponse response = client() .filterWithHeader(Collections.singletonMap("Authorization", - basicAuthHeaderValue("joe", new SecuredString("s3krit".toCharArray())))) + basicAuthHeaderValue("joe", new SecureString("s3krit".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -718,7 +718,7 @@ public class NativeRealmIntegTests extends NativeRealmIntegTestCase { public void testConcurrentRunAs() throws Exception { securityClient().preparePutUser("joe", "s3krit".toCharArray(), SecuritySettingsSource.DEFAULT_ROLE).get(); securityClient().preparePutUser("executor", "s3krit".toCharArray(), "superuser").get(); - final String token = basicAuthHeaderValue("executor", new SecuredString("s3krit".toCharArray())); + final String token = basicAuthHeaderValue("executor", new SecureString("s3krit".toCharArray())); final Client client = client().filterWithHeader(MapBuilder.newMapBuilder() .put("Authorization", token) .put("es-security-runas-user", "joe") diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmIntegTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmIntegTests.java index c3fd7fde812..36bd0e5a533 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmIntegTests.java @@ -7,11 +7,11 @@ package org.elasticsearch.xpack.security.authc.esnative; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.security.user.ElasticUser; import org.elasticsearch.xpack.security.user.KibanaUser; import org.elasticsearch.xpack.security.action.user.ChangePasswordResponse; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.NativeRealmIntegTestCase; import java.util.Arrays; @@ -27,7 +27,7 @@ import static org.hamcrest.Matchers.notNullValue; */ public class ReservedRealmIntegTests extends NativeRealmIntegTestCase { - private static final SecuredString DEFAULT_PASSWORD = new SecuredString("changeme".toCharArray()); + private static final SecureString DEFAULT_PASSWORD = new SecureString("changeme".toCharArray()); public void testAuthenticate() { for (String username : Arrays.asList(ElasticUser.NAME, KibanaUser.NAME)) { @@ -89,7 +89,7 @@ public class ReservedRealmIntegTests extends NativeRealmIntegTestCase { assertThat(elasticsearchSecurityException.getMessage(), containsString("authenticate")); ClusterHealthResponse healthResponse = client() - .filterWithHeader(singletonMap("Authorization", basicAuthHeaderValue(username, new SecuredString(newPassword)))) + .filterWithHeader(singletonMap("Authorization", basicAuthHeaderValue(username, new SecureString(newPassword)))) .admin() .cluster() .prepareHealth() diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmNoDefaultPasswordIntegTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmNoDefaultPasswordIntegTests.java index 6d91181805a..142c1c121ec 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmNoDefaultPasswordIntegTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmNoDefaultPasswordIntegTests.java @@ -7,9 +7,9 @@ package org.elasticsearch.xpack.security.authc.esnative; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.NativeRealmIntegTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.client.SecurityClient; import org.elasticsearch.xpack.security.user.KibanaUser; @@ -23,7 +23,7 @@ import static org.hamcrest.Matchers.is; */ public class ReservedRealmNoDefaultPasswordIntegTests extends NativeRealmIntegTestCase { - private static final SecuredString DEFAULT_PASSWORD = new SecuredString("changeme".toCharArray()); + private static final SecureString DEFAULT_PASSWORD = new SecureString("changeme".toCharArray()); @Override protected Settings nodeSettings(int nodeOrdinal) { @@ -49,8 +49,8 @@ public class ReservedRealmNoDefaultPasswordIntegTests extends NativeRealmIntegTe .get()); assertThat(elasticsearchSecurityException.getMessage(), containsString("authenticate")); - final SecuredString newPassword = new SecuredString("not-the-default-password".toCharArray()); - c.prepareChangePassword(KibanaUser.NAME, newPassword.copyChars()).get(); + final SecureString newPassword = new SecureString("not-the-default-password".toCharArray()); + c.prepareChangePassword(KibanaUser.NAME, newPassword.clone().getChars()).get(); ClusterHealthResponse response = client() .filterWithHeader(singletonMap("Authorization", basicAuthHeaderValue(KibanaUser.NAME, newPassword))) diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java index e4df6e1e91d..b0b4fcde688 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java @@ -9,6 +9,7 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -17,7 +18,6 @@ import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.SecurityLifecycleService; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore.ReservedUserInfo; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.elasticsearch.xpack.security.user.BeatsSystemUser; @@ -58,7 +58,7 @@ import static org.mockito.Mockito.when; */ public class ReservedRealmTests extends ESTestCase { - private static final SecuredString DEFAULT_PASSWORD = new SecuredString("changeme".toCharArray()); + private static final SecureString DEFAULT_PASSWORD = new SecureString("changeme".toCharArray()); public static final String ACCEPT_DEFAULT_PASSWORDS = ReservedRealm.ACCEPT_DEFAULT_PASSWORD_SETTING.getKey(); private NativeUsersStore usersStore; private SecurityLifecycleService securityLifecycleService; @@ -171,7 +171,7 @@ public class ReservedRealmTests extends ESTestCase { new AnonymousUser(settings), securityLifecycleService, new ThreadContext(Settings.EMPTY)); final User expectedUser = randomFrom(new ElasticUser(enabled), new KibanaUser(enabled), new LogstashSystemUser(enabled)); final String principal = expectedUser.principal(); - final SecuredString newPassword = new SecuredString("foobar".toCharArray()); + final SecureString newPassword = new SecureString("foobar".toCharArray()); when(securityLifecycleService.securityIndexExists()).thenReturn(true); doAnswer((i) -> { ActionListener callback = (ActionListener) i.getArguments()[1]; @@ -327,13 +327,13 @@ public class ReservedRealmTests extends ESTestCase { // maybe cache a successful auth if (randomBoolean()) { PlainActionFuture future = new PlainActionFuture<>(); - reservedRealm.authenticate(new UsernamePasswordToken(ElasticUser.NAME, new SecuredString("changeme".toCharArray())), future); + reservedRealm.authenticate(new UsernamePasswordToken(ElasticUser.NAME, new SecureString("changeme".toCharArray())), future); User user = future.actionGet(); assertEquals(new ElasticUser(true), user); } PlainActionFuture future = new PlainActionFuture<>(); - reservedRealm.authenticate(new UsernamePasswordToken(ElasticUser.NAME, new SecuredString("foobar".toCharArray())), future); + reservedRealm.authenticate(new UsernamePasswordToken(ElasticUser.NAME, new SecureString("foobar".toCharArray())), future); ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, future::actionGet); assertThat(e.getMessage(), containsString("failed to authenticate")); } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java index a7c35f6d590..34bef017c03 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java @@ -6,12 +6,12 @@ package org.elasticsearch.xpack.security.authc.file; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.test.ESTestCase; @@ -48,12 +48,12 @@ public class FileRealmTests extends ESTestCase { } public void testAuthenticate() throws Exception { - when(userPasswdStore.verifyPassword("user1", SecuredStringTests.build("test123"))).thenReturn(true); + when(userPasswdStore.verifyPassword("user1", new SecureString("test123"))).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[] { "role1", "role2" }); RealmConfig config = new RealmConfig("file-test", Settings.EMPTY, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user = future.actionGet(); assertThat(user, notNullValue()); assertThat(user.principal(), equalTo("user1")); @@ -67,14 +67,14 @@ public class FileRealmTests extends ESTestCase { .put("cache.hash_algo", Hasher.values()[randomIntBetween(0, Hasher.values().length - 1)].name().toLowerCase(Locale.ROOT)) .build(); RealmConfig config = new RealmConfig("file-test", settings, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); - when(userPasswdStore.verifyPassword("user1", SecuredStringTests.build("test123"))).thenReturn(true); + when(userPasswdStore.verifyPassword("user1", new SecureString("test123"))).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[]{"role1", "role2"}); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user1 = future.actionGet(); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user2 = future.actionGet(); assertThat(user1, sameInstance(user2)); } @@ -83,54 +83,54 @@ public class FileRealmTests extends ESTestCase { RealmConfig config = new RealmConfig("file-test", Settings.EMPTY, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); userPasswdStore = spy(new UserPasswdStore(config)); userRolesStore = spy(new UserRolesStore(config)); - doReturn(true).when(userPasswdStore).verifyPassword("user1", SecuredStringTests.build("test123")); + doReturn(true).when(userPasswdStore).verifyPassword("user1", new SecureString("test123")); doReturn(new String[] { "role1", "role2" }).when(userRolesStore).roles("user1"); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user1 = future.actionGet(); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user2 = future.actionGet(); assertThat(user1, sameInstance(user2)); userPasswdStore.notifyRefresh(); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user3 = future.actionGet(); assertThat(user2, not(sameInstance(user3))); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user4 = future.actionGet(); assertThat(user3, sameInstance(user4)); userRolesStore.notifyRefresh(); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user5 = future.actionGet(); assertThat(user4, not(sameInstance(user5))); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user1", SecuredStringTests.build("test123")), future); + realm.authenticate(new UsernamePasswordToken("user1", new SecureString("test123")), future); User user6 = future.actionGet(); assertThat(user5, sameInstance(user6)); } public void testToken() throws Exception { RealmConfig config = new RealmConfig("file-test", Settings.EMPTY, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); - when(userPasswdStore.verifyPassword("user1", SecuredStringTests.build("test123"))).thenReturn(true); + when(userPasswdStore.verifyPassword("user1", new SecureString("test123"))).thenReturn(true); when(userRolesStore.roles("user1")).thenReturn(new String[]{"role1", "role2"}); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore); ThreadContext threadContext = new ThreadContext(Settings.EMPTY); - UsernamePasswordToken.putTokenHeader(threadContext, new UsernamePasswordToken("user1", SecuredStringTests.build("test123"))); + UsernamePasswordToken.putTokenHeader(threadContext, new UsernamePasswordToken("user1", new SecureString("test123"))); UsernamePasswordToken token = realm.token(threadContext); assertThat(token, notNullValue()); assertThat(token.principal(), equalTo("user1")); assertThat(token.credentials(), notNullValue()); - assertThat(new String(token.credentials().internalChars()), equalTo("test123")); + assertThat(new String(token.credentials().getChars()), equalTo("test123")); } public void testLookup() throws Exception { diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStoreTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStoreTests.java index f5fe01c2710..424661ef513 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStoreTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserPasswdStoreTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.xpack.security.authc.file; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; @@ -16,7 +17,6 @@ import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xpack.security.audit.logfile.CapturingLogger; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.XPackPlugin; import org.junit.After; import org.junit.Before; @@ -92,13 +92,13 @@ public class FileUserPasswdStoreTests extends ESTestCase { FileUserPasswdStore store = new FileUserPasswdStore(config, watcherService, latch::countDown); assertThat(store.userExists("bcrypt"), is(true)); - assertThat(store.verifyPassword("bcrypt", SecuredStringTests.build("test123")), is(true)); + assertThat(store.verifyPassword("bcrypt", new SecureString("test123")), is(true)); watcherService.start(); try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { writer.newLine(); - writer.append("foobar:").append(new String(Hasher.BCRYPT.hash(SecuredStringTests.build("barfoo")))); + writer.append("foobar:").append(new String(Hasher.BCRYPT.hash(new SecureString("barfoo")))); } if (!latch.await(5, TimeUnit.SECONDS)) { @@ -106,7 +106,7 @@ public class FileUserPasswdStoreTests extends ESTestCase { } assertThat(store.userExists("foobar"), is(true)); - assertThat(store.verifyPassword("foobar", SecuredStringTests.build("barfoo")), is(true)); + assertThat(store.verifyPassword("foobar", new SecureString("barfoo")), is(true)); } public void testStore_AutoReload_WithParseFailures() throws Exception { @@ -126,7 +126,7 @@ public class FileUserPasswdStoreTests extends ESTestCase { FileUserPasswdStore store = new FileUserPasswdStore(config, watcherService, latch::countDown); - assertTrue(store.verifyPassword("bcrypt", SecuredStringTests.build("test123"))); + assertTrue(store.verifyPassword("bcrypt", new SecureString("test123"))); watcherService.start(); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/tool/UsersToolTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/tool/UsersToolTests.java index d0659a63852..ce0502ff013 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/tool/UsersToolTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/file/tool/UsersToolTests.java @@ -14,12 +14,11 @@ import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.UserException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.PathUtilsForTesting; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.XPackSettings; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authz.store.ReservedRolesStore; import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.security.user.ElasticUser; @@ -66,9 +65,9 @@ public class UsersToolTests extends CommandTestCase { confDir = homeDir.resolve("config").resolve(XPackPlugin.NAME); Files.createDirectories(confDir); Files.write(confDir.resolve("users"), Arrays.asList( - "existing_user:" + new String(Hasher.BCRYPT.hash(new SecuredString("changeme".toCharArray()))), - "existing_user2:" + new String(Hasher.BCRYPT.hash(new SecuredString("changeme2".toCharArray()))), - "existing_user3:" + new String(Hasher.BCRYPT.hash(new SecuredString("changeme3".toCharArray()))) + "existing_user:" + new String(Hasher.BCRYPT.hash(new SecureString("changeme".toCharArray()))), + "existing_user2:" + new String(Hasher.BCRYPT.hash(new SecureString("changeme2".toCharArray()))), + "existing_user3:" + new String(Hasher.BCRYPT.hash(new SecureString("changeme3".toCharArray()))) ), StandardCharsets.UTF_8); Files.write(confDir.resolve("users_roles"), Arrays.asList( "test_admin:existing_user,existing_user2", @@ -116,7 +115,7 @@ public class UsersToolTests extends CommandTestCase { continue; } String gotHash = usernameHash[1]; - SecuredString expectedHash = SecuredStringTests.build(password); + SecureString expectedHash = new SecureString(password); assertTrue("Expected hash " + expectedHash + " for password " + password + " but got " + gotHash, Hasher.BCRYPT.verify(expectedHash, gotHash.toCharArray())); return; diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java index a5803bf2b6c..f6e3c67e966 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java @@ -15,6 +15,7 @@ import com.unboundid.ldap.sdk.schema.Schema; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -22,8 +23,6 @@ import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.support.CachingUsernamePasswordRealm; import org.elasticsearch.xpack.security.authc.support.DnRoleMapper; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; @@ -137,7 +136,7 @@ public class ActiveDirectoryRealmTests extends ESTestCase { LdapRealm realm = new LdapRealm(LdapRealm.AD_TYPE, config, sessionFactory, roleMapper, threadPool); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, is(notNullValue())); assertThat(user.roles(), arrayContaining(containsString("Avengers"))); @@ -152,7 +151,7 @@ public class ActiveDirectoryRealmTests extends ESTestCase { // Thor does not have a UPN of form CN=Thor@ad.test.elasticsearch.com PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=Thor", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=Thor", new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, is(notNullValue())); assertThat(user.roles(), arrayContaining(containsString("Avengers"))); @@ -177,12 +176,12 @@ public class ActiveDirectoryRealmTests extends ESTestCase { int count = randomIntBetween(2, 10); for (int i = 0; i < count; i++) { PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); future.actionGet(); } // verify one and only one session as further attempts should be returned from cache - verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecuredString.class), any(ActionListener.class)); + verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); } public void testAuthenticateCachingCanBeDisabled() throws Exception { @@ -195,12 +194,12 @@ public class ActiveDirectoryRealmTests extends ESTestCase { int count = randomIntBetween(2, 10); for (int i = 0; i < count; i++) { PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); future.actionGet(); } // verify one and only one session as second attempt should be returned from cache - verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecuredString.class), any(ActionListener.class)); + verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); } public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Exception { @@ -213,23 +212,23 @@ public class ActiveDirectoryRealmTests extends ESTestCase { int count = randomIntBetween(2, 10); for (int i = 0; i < count; i++) { PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); future.actionGet(); } // verify one and only one session as further attempts should be returned from cache - verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecuredString.class), any(ActionListener.class)); + verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); // Refresh the role mappings roleMapper.notifyRefresh(); for (int i = 0; i < count; i++) { PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); future.actionGet(); } - verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecuredString.class), any(ActionListener.class)); + verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); } public void testRealmMapsGroupsToRoles() throws Exception { @@ -242,7 +241,7 @@ public class ActiveDirectoryRealmTests extends ESTestCase { LdapRealm realm = new LdapRealm(LdapRealm.AD_TYPE, config, sessionFactory, roleMapper, threadPool); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=ironman", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, is(notNullValue())); assertThat(user.roles(), arrayContaining(equalTo("group_role"))); @@ -258,7 +257,7 @@ public class ActiveDirectoryRealmTests extends ESTestCase { LdapRealm realm = new LdapRealm(LdapRealm.AD_TYPE, config, sessionFactory, roleMapper, threadPool); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("CN=Thor", SecuredStringTests.build(PASSWORD)), future); + realm.authenticate(new UsernamePasswordToken("CN=Thor", new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, is(notNullValue())); assertThat(user.roles(), arrayContainingInAnyOrder(equalTo("group_role"), equalTo("user_role"))); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java index cb0a82bcce5..694beccd985 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.xpack.security.authc.ldap; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.ResultCode; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.concurrent.UncategorizedExecutionException; @@ -17,8 +18,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSearchScope; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.test.junit.annotations.Network; import org.elasticsearch.xpack.ssl.VerificationMode; @@ -35,7 +34,7 @@ import static org.hamcrest.Matchers.is; @Network public class ActiveDirectorySessionFactoryTests extends AbstractActiveDirectoryIntegTests { - private final SecuredString SECURED_PASSWORD = SecuredStringTests.build(PASSWORD); + private final SecureString SECURED_PASSWORD = new SecureString(PASSWORD); @Override public boolean enableWarningsCheck() { @@ -382,7 +381,7 @@ public class ActiveDirectorySessionFactoryTests extends AbstractActiveDirectoryI return builder.build(); } - private LdapSession session(SessionFactory factory, String username, SecuredString password) { + private LdapSession session(SessionFactory factory, String username, SecureString password) { PlainActionFuture future = new PlainActionFuture<>(); factory.session(username, password, future); return future.actionGet(); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java index cef8f281428..cc71b3bb556 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.xpack.security.authc.ldap; import com.unboundid.ldap.sdk.LDAPURL; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -17,8 +18,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; import org.elasticsearch.xpack.security.authc.support.CachingUsernamePasswordRealm; import org.elasticsearch.xpack.security.authc.support.DnRoleMapper; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.threadpool.TestThreadPool; @@ -86,7 +85,7 @@ public class LdapRealmTests extends LdapTestCase { threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, notNullValue()); assertThat(user.roles(), arrayContaining("HMS Victory")); @@ -109,7 +108,7 @@ public class LdapRealmTests extends LdapTestCase { new LdapRealm(LdapRealm.LDAP_TYPE, config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, notNullValue()); assertThat("For roles " + Arrays.toString(user.roles()), user.roles(), arrayContaining("HMS Victory")); @@ -132,14 +131,14 @@ public class LdapRealmTests extends LdapTestCase { LdapRealm ldap = new LdapRealm(LdapRealm.LDAP_TYPE, config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); //verify one and only one session -> caching is working - verify(ldapFactory, times(1)).session(anyString(), any(SecuredString.class), any(ActionListener.class)); + verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), any(ActionListener.class)); } public void testAuthenticateCachingRefresh() throws Exception { @@ -155,23 +154,23 @@ public class LdapRealmTests extends LdapTestCase { ldapFactory = spy(ldapFactory); LdapRealm ldap = new LdapRealm(LdapRealm.LDAP_TYPE, config, ldapFactory, roleMapper, threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); //verify one and only one session -> caching is working - verify(ldapFactory, times(1)).session(anyString(), any(SecuredString.class), any(ActionListener.class)); + verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), any(ActionListener.class)); roleMapper.notifyRefresh(); future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); //we need to session again - verify(ldapFactory, times(2)).session(anyString(), any(SecuredString.class), any(ActionListener.class)); + verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), any(ActionListener.class)); } public void testAuthenticateNoncaching() throws Exception { @@ -188,14 +187,14 @@ public class LdapRealmTests extends LdapTestCase { LdapRealm ldap = new LdapRealm(LdapRealm.LDAP_TYPE, config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); future.actionGet(); //verify two and only two binds -> caching is disabled - verify(ldapFactory, times(2)).session(anyString(), any(SecuredString.class), any(ActionListener.class)); + verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), any(ActionListener.class)); } public void testLdapRealmSelectsLdapSessionFactory() throws Exception { @@ -282,7 +281,7 @@ public class LdapRealmTests extends LdapTestCase { new DnRoleMapper(LdapRealm.LDAP_TYPE, config, resourceWatcherService), threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken("Horatio Hornblower", SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken("Horatio Hornblower", new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, notNullValue()); assertThat(user.roles(), arrayContaining("avenger")); @@ -306,7 +305,7 @@ public class LdapRealmTests extends LdapTestCase { threadPool); PlainActionFuture future = new PlainActionFuture<>(); - ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, SecuredStringTests.build(PASSWORD)), future); + ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future); User user = future.actionGet(); assertThat(user, nullValue()); } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java index 6c4f9518942..5d73761b0f0 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java @@ -8,6 +8,7 @@ package org.elasticsearch.xpack.security.authc.ldap; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPURL; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.concurrent.UncategorizedExecutionException; @@ -17,8 +18,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSearchScope; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.test.junit.annotations.Network; import org.elasticsearch.xpack.ssl.SSLService; import org.junit.Before; @@ -58,7 +57,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { RealmConfig config = new RealmConfig("ldap_realm", settings, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); LdapSessionFactory sessionFactory = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); ldapServer.setProcessingDelayMillis(500L); try { @@ -88,7 +87,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { RealmConfig config = new RealmConfig("ldap_realm", settings, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings)); LdapSessionFactory sessionFactory = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); long start = System.currentTimeMillis(); LDAPException expected = expectThrows(LDAPException.class, () -> session(sessionFactory, user, userPass)); @@ -112,7 +111,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { LdapSessionFactory sessionFactory = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try (LdapSession ldap = session(sessionFactory, user, userPass)) { String dn = ldap.userDn(); @@ -133,7 +132,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { LdapSessionFactory ldapFac = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); UncategorizedExecutionException e = expectThrows(UncategorizedExecutionException.class, () -> session(ldapFac, user, userPass)); assertThat(e.getCause(), instanceOf(ExecutionException.class)); assertThat(e.getCause().getCause(), instanceOf(LDAPException.class)); @@ -151,7 +150,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { LdapSessionFactory ldapFac = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try (LdapSession ldap = session(ldapFac, user, userPass)) { List groups = groups(ldap); @@ -168,7 +167,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { LdapSessionFactory ldapFac = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - try (LdapSession ldap = session(ldapFac, user, SecuredStringTests.build("pass"))) { + try (LdapSession ldap = session(ldapFac, user, new SecureString("pass"))) { List groups = groups(ldap); assertThat(groups, contains("cn=HMS Lydia,ou=crews,ou=groups,o=sevenSeas")); } @@ -183,7 +182,7 @@ public class LdapSessionFactoryTests extends LdapTestCase { LdapSessionFactory ldapFac = new LdapSessionFactory(config, sslService); String user = "Horatio Hornblower"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try (LdapSession ldap = session(ldapFac, user, userPass)) { List groups = groups(ldap); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java index 2aa57896cbf..d37ba555d3f 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java @@ -14,6 +14,7 @@ import com.unboundid.ldap.sdk.LDAPURL; import com.unboundid.ldap.sdk.SimpleBindRequest; import com.unboundid.ldap.sdk.SingleServerSet; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -22,8 +23,6 @@ import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSearchScope; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.xpack.ssl.SSLService; import org.elasticsearch.xpack.security.support.NoOpLogger; import org.elasticsearch.test.junit.annotations.Network; @@ -98,7 +97,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { // auth @@ -134,7 +133,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { assertNull(session(sessionFactory, user, userPass)); @@ -161,7 +160,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { // auth @@ -197,7 +196,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { assertNull(session(sessionFactory, user, userPass)); @@ -224,7 +223,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { //auth @@ -259,7 +258,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "William Bush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { assertNull(session(sessionFactory, user, userPass)); @@ -284,7 +283,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService); String user = "wbush"; - SecuredString userPass = SecuredStringTests.build("pass"); + SecureString userPass = new SecureString("pass"); try { //auth @@ -331,7 +330,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { String user = "Bruce Banner"; try { //auth - try (LdapSession ldap = session(sessionFactory, user, SecuredStringTests.build(ActiveDirectorySessionFactoryTests.PASSWORD))) { + try (LdapSession ldap = session(sessionFactory, user, new SecureString(ActiveDirectorySessionFactoryTests.PASSWORD))) { List groups = groups(ldap); assertThat(groups, containsInAnyOrder( @@ -381,7 +380,7 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { try { for (String user : users) { //auth - try (LdapSession ldap = session(sessionFactory, user, SecuredStringTests.build(OpenLdapTests.PASSWORD))) { + try (LdapSession ldap = session(sessionFactory, user, new SecureString(OpenLdapTests.PASSWORD))) { assertThat(ldap.userDn(), is(equalTo(new MessageFormat("uid={0},ou=people,dc=oldap,dc=test,dc=elasticsearch,dc=com", Locale.ROOT).format(new Object[]{user}, new StringBuffer(), null).toString()))); assertThat(groups(ldap), hasItem(containsString("Avengers"))); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapTests.java index 9973e25d541..81f43867788 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.xpack.security.authc.ldap; import com.unboundid.ldap.sdk.LDAPException; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.concurrent.UncategorizedExecutionException; @@ -16,8 +17,6 @@ import org.elasticsearch.xpack.security.authc.ldap.support.LdapSearchScope; import org.elasticsearch.xpack.security.authc.ldap.support.LdapSession; import org.elasticsearch.xpack.security.authc.ldap.support.LdapTestCase; import org.elasticsearch.xpack.security.authc.ldap.support.SessionFactory; -import org.elasticsearch.xpack.security.authc.support.SecuredString; -import org.elasticsearch.xpack.security.authc.support.SecuredStringTests; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.junit.annotations.Network; import org.elasticsearch.xpack.ssl.SSLService; @@ -38,6 +37,7 @@ public class OpenLdapTests extends ESTestCase { public static final String OPEN_LDAP_URL = "ldaps://54.200.235.244:636"; public static final String PASSWORD = "NickFuryHeartsES"; + public static final SecureString PASSWORD_SECURE_STRING = new SecureString(PASSWORD.toCharArray()); private boolean useGlobalSSL; private SSLService sslService; @@ -85,7 +85,7 @@ public class OpenLdapTests extends ESTestCase { String[] users = new String[] { "blackwidow", "cap", "hawkeye", "hulk", "ironman", "thor" }; for (String user : users) { - try (LdapSession ldap = session(sessionFactory, user, SecuredStringTests.build(PASSWORD))) { + try (LdapSession ldap = session(sessionFactory, user, PASSWORD_SECURE_STRING)) { assertThat(groups(ldap), hasItem(containsString("Avengers"))); } } @@ -102,7 +102,7 @@ public class OpenLdapTests extends ESTestCase { String[] users = new String[] { "blackwidow", "cap", "hawkeye", "hulk", "ironman", "thor" }; for (String user : users) { - LdapSession ldap = session(sessionFactory, user, SecuredStringTests.build(PASSWORD)); + LdapSession ldap = session(sessionFactory, user, PASSWORD_SECURE_STRING); assertThat(groups(ldap), hasItem(containsString("Avengers"))); ldap.close(); } @@ -119,7 +119,7 @@ public class OpenLdapTests extends ESTestCase { RealmConfig config = new RealmConfig("oldap-test", settings, globalSettings, new ThreadContext(Settings.EMPTY)); LdapSessionFactory sessionFactory = new LdapSessionFactory(config, sslService); - try (LdapSession ldap = session(sessionFactory, "selvig", SecuredStringTests.build(PASSWORD))){ + try (LdapSession ldap = session(sessionFactory, "selvig", PASSWORD_SECURE_STRING)){ assertThat(groups(ldap), hasItem(containsString("Geniuses"))); } } @@ -138,7 +138,7 @@ public class OpenLdapTests extends ESTestCase { LdapSessionFactory sessionFactory = new LdapSessionFactory(config, sslService); LDAPException expected = expectThrows(LDAPException.class, - () -> session(sessionFactory, "thor", SecuredStringTests.build(PASSWORD)).groups(new PlainActionFuture<>())); + () -> session(sessionFactory, "thor", PASSWORD_SECURE_STRING).groups(new PlainActionFuture<>())); assertThat(expected.getMessage(), containsString("A client-side timeout was encountered while waiting")); } @@ -156,7 +156,7 @@ public class OpenLdapTests extends ESTestCase { String user = "blackwidow"; UncategorizedExecutionException e = expectThrows(UncategorizedExecutionException.class, - () -> session(sessionFactory, user, SecuredStringTests.build(PASSWORD))); + () -> session(sessionFactory, user, PASSWORD_SECURE_STRING)); assertThat(e.getCause(), instanceOf(ExecutionException.class)); assertThat(e.getCause().getCause(), instanceOf(LDAPException.class)); assertThat(e.getCause().getCause().getMessage(), @@ -175,7 +175,7 @@ public class OpenLdapTests extends ESTestCase { .build(); } - protected LdapSession session(SessionFactory factory, String username, SecuredString password) { + protected LdapSession session(SessionFactory factory, String username, SecureString password) { PlainActionFuture future = new PlainActionFuture<>(); factory.session(username, password, future); return future.actionGet(); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapTestCase.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapTestCase.java index 36491928194..7135d0e2851 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/LdapTestCase.java @@ -11,6 +11,7 @@ import com.unboundid.ldap.sdk.LDAPException; import com.unboundid.ldap.sdk.LDAPURL; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.xpack.security.authc.RealmConfig; @@ -19,7 +20,6 @@ import org.elasticsearch.xpack.security.authc.ldap.LdapSessionFactory; import org.elasticsearch.xpack.security.authc.support.DnRoleMapper; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.watcher.ResourceWatcherService; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.VerificationMode; import org.junit.After; import org.junit.Before; @@ -139,7 +139,7 @@ public abstract class LdapTestCase extends ESTestCase { return new DnRoleMapper(LdapRealm.LDAP_TYPE, config, resourceWatcherService); } - protected LdapSession session(SessionFactory factory, String username, SecuredString password) { + protected LdapSession session(SessionFactory factory, String username, SecureString password) { PlainActionFuture future = new PlainActionFuture<>(); factory.session(username, password, future); return future.actionGet(); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java index 646d656ada6..bf1d53f3357 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java @@ -8,11 +8,11 @@ package org.elasticsearch.xpack.security.authc.ldap.support; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.sdk.LDAPConnection; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.security.authc.RealmConfig; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.ssl.SSLService; import java.util.ArrayList; @@ -179,7 +179,7 @@ public class SessionFactoryLoadBalancingTests extends LdapTestCase { } @Override - public void session(String user, SecuredString password, ActionListener listener) { + public void session(String user, SecureString password, ActionListener listener) { listener.onResponse(null); } } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java index e7124de8e66..b803d590fc7 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java @@ -10,11 +10,11 @@ import com.unboundid.util.ssl.HostNameSSLSocketVerifier; import com.unboundid.util.ssl.TrustAllSSLSocketVerifier; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.security.authc.RealmConfig; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.ssl.SSLService; import org.elasticsearch.xpack.ssl.VerificationMode; @@ -95,7 +95,7 @@ public class SessionFactoryTests extends ESTestCase { return new SessionFactory(realmConfig, null) { @Override - public void session(String user, SecuredString password, ActionListener listener) { + public void session(String user, SecureString password, ActionListener listener) { listener.onResponse(null); } }; diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiOptionalClientAuthTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiOptionalClientAuthTests.java index aacbf056706..7922bc09348 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiOptionalClientAuthTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiOptionalClientAuthTests.java @@ -11,10 +11,10 @@ import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.ssl.SSLClientAuth; import org.junit.BeforeClass; @@ -79,7 +79,7 @@ public class PkiOptionalClientAuthTests extends SecurityIntegTestCase { Response response = restClient.performRequest("GET", "_nodes", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); assertThat(response.getStatusLine().getStatusCode(), is(200)); } } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java index 8760195b76c..9a8559f538d 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java @@ -6,6 +6,7 @@ package org.elasticsearch.xpack.security.authc.pki; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; @@ -14,7 +15,6 @@ import org.elasticsearch.xpack.ssl.SSLService; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.xpack.security.authc.RealmConfig; import org.elasticsearch.xpack.security.authc.support.DnRoleMapper; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.support.NoOpLogger; import org.elasticsearch.test.ESTestCase; @@ -59,7 +59,7 @@ public class PkiRealmTests extends ESTestCase { PkiRealm realm = new PkiRealm(config, mock(DnRoleMapper.class), sslService); assertThat(realm.supports(null), is(false)); - assertThat(realm.supports(new UsernamePasswordToken("", new SecuredString(new char[0]))), is(false)); + assertThat(realm.supports(new UsernamePasswordToken("", new SecureString(new char[0]))), is(false)); assertThat(realm.supports(new X509AuthenticationToken(new X509Certificate[0], "", "")), is(true)); } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/BCryptTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/BCryptTests.java index dc93330edb6..ce53c472745 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/BCryptTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/BCryptTests.java @@ -5,6 +5,7 @@ */ package org.elasticsearch.xpack.security.authc.support; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.test.ESTestCase; import java.util.ArrayList; @@ -32,7 +33,7 @@ public class BCryptTests extends ESTestCase { @AwaitsFix(bugUrl = "need a better way to test this") public void testUnderLoad() throws Exception { final String password = randomAlphaOfLengthBetween(10, 32); - final String bcrypt = BCrypt.hashpw(SecuredStringTests.build(password), BCrypt.gensalt()); + final String bcrypt = BCrypt.hashpw(new SecureString(password), BCrypt.gensalt()); ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(100); try { @@ -44,7 +45,7 @@ public class BCryptTests extends ESTestCase { @Override public Boolean call() throws Exception { for (int i = 0; i < 10000 && !failed.get(); i++) { - if (BCrypt.checkpw(SecuredStringTests.build(password), bcrypt) == false) { + if (BCrypt.checkpw(new SecureString(password), bcrypt) == false) { failed.set(true); return false; } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealmTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealmTests.java index 94e0a66596f..d3e14e1dec6 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealmTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/CachingUsernamePasswordRealmTests.java @@ -7,6 +7,7 @@ package org.elasticsearch.xpack.security.authc.support; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -66,7 +67,7 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { public void testAuthCache() { AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); - SecuredString pass = SecuredStringTests.build("pass"); + SecureString pass = new SecureString("pass"); PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(new UsernamePasswordToken("a", pass), future); future.actionGet(); @@ -132,7 +133,7 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { // now authenticate future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("a", SecuredStringTests.build("pass")), future); + realm.authenticate(new UsernamePasswordToken("a", new SecureString("pass")), future); User user = future.actionGet(); assertThat(realm.lookupInvocationCounter.intValue(), is(1)); assertThat(realm.authInvocationCounter.intValue(), is(1)); @@ -141,7 +142,7 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { // authenticate a different user first future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("b", SecuredStringTests.build("pass")), future); + realm.authenticate(new UsernamePasswordToken("b", new SecureString("pass")), future); user = future.actionGet(); assertThat(realm.lookupInvocationCounter.intValue(), is(1)); assertThat(realm.authInvocationCounter.intValue(), is(2)); @@ -159,8 +160,8 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { AlwaysAuthenticateCachingRealm realm = new AlwaysAuthenticateCachingRealm(globalSettings); String user = "testUser"; - SecuredString pass1 = SecuredStringTests.build("pass"); - SecuredString pass2 = SecuredStringTests.build("password"); + SecureString pass1 = new SecureString("pass"); + SecureString pass2 = new SecureString("password"); PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(new UsernamePasswordToken(user, pass1), future); @@ -184,13 +185,13 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { public void testAuthenticateContract() throws Exception { Realm realm = new FailingAuthenticationRealm(Settings.EMPTY, globalSettings); PlainActionFuture future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user", SecuredStringTests.build("pass")), future); + realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future); User user = future.actionGet(); assertThat(user , nullValue()); realm = new ThrowingAuthenticationRealm(Settings.EMPTY, globalSettings); future = new PlainActionFuture<>(); - realm.authenticate(new UsernamePasswordToken("user", SecuredStringTests.build("pass")), future); + realm.authenticate(new UsernamePasswordToken("user", new SecureString("pass")), future); RuntimeException e = expectThrows(RuntimeException.class, future::actionGet); assertThat(e.getMessage() , containsString("whatever exception")); } @@ -211,8 +212,8 @@ public class CachingUsernamePasswordRealmTests extends ESTestCase { public void testCacheConcurrency() throws Exception { final String username = "username"; - final SecuredString password = new SecuredString("changeme".toCharArray()); - final SecuredString randomPassword = new SecuredString(randomAlphaOfLength(password.length()).toCharArray()); + final SecureString password = new SecureString("changeme".toCharArray()); + final SecureString randomPassword = new SecureString(randomAlphaOfLength(password.length()).toCharArray()); final String passwordHash = new String(Hasher.BCRYPT.hash(password)); RealmConfig config = new RealmConfig("test_realm", Settings.EMPTY, globalSettings, new ThreadContext(Settings.EMPTY)); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/HasherTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/HasherTests.java index f8773241c35..793b4b7cbe5 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/HasherTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/HasherTests.java @@ -5,6 +5,7 @@ */ package org.elasticsearch.xpack.security.authc.support; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.test.ESTestCase; import static org.hamcrest.Matchers.sameInstance; @@ -60,7 +61,7 @@ public class HasherTests extends ESTestCase { } private static void testHasherSelfGenerated(Hasher hasher) throws Exception { - SecuredString passwd = SecuredStringTests.build(randomAlphaOfLength(10)); + SecureString passwd = new SecureString(randomAlphaOfLength(10)); char[] hash = hasher.hash(passwd); assertTrue(hasher.verify(passwd, hash)); } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/SecuredStringTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/SecuredStringTests.java deleted file mode 100644 index e0e643ffdc2..00000000000 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/SecuredStringTests.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -package org.elasticsearch.xpack.security.authc.support; - -import org.elasticsearch.test.ESTestCase; - -import java.nio.charset.StandardCharsets; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; - -public class SecuredStringTests extends ESTestCase { - public static SecuredString build(String password){ - return new SecuredString(password.toCharArray()); - } - - public void testAccessAfterClear(){ - SecuredString password = new SecuredString("password".toCharArray()); - SecuredString password2 = new SecuredString("password".toCharArray()); - - password.clear(); - - try { - password.internalChars(); - fail(); - } catch(Exception e){} - - try { - password.length(); - fail(); - } catch(Exception e){} - - try { - password.charAt(0); - fail(); - } catch(Exception e){} - - try { - password.concat("_suffix"); - fail(); - } catch(Exception e){} - - assertNotEquals(password, password2); - } - - public void testEqualsHashCode(){ - SecuredString password = new SecuredString("password".toCharArray()); - SecuredString password2 = new SecuredString("password".toCharArray()); - - assertEquals(password, password2); - assertEquals(password.hashCode(), password2.hashCode()); - } - - public void testsEqualsCharSequence(){ - SecuredString password = new SecuredString("password".toCharArray()); - StringBuffer password2 = new StringBuffer("password"); - String password3 = "password"; - - assertEquals(password, password2); - assertEquals(password, password3); - } - - public void testConcat() { - SecuredString password = new SecuredString("password".toCharArray()); - SecuredString password2 = new SecuredString("password".toCharArray()); - - SecuredString password3 = password.concat(password2); - assertThat(password3.length(), equalTo(password.length() + password2.length())); - assertThat(password3.internalChars(), equalTo("passwordpassword".toCharArray())); - } - - public void testSubsequence(){ - SecuredString password = new SecuredString("password".toCharArray()); - SecuredString password2 = password.subSequence(4, 8); - SecuredString password3 = password.subSequence(0, 4); - - assertThat(password2.internalChars(), equalTo("word".toCharArray())); - assertThat(password3.internalChars(), equalTo("pass".toCharArray())); - assertThat("ensure original is unmodified", password.internalChars(), equalTo("password".toCharArray())); - } - - public void testUFT8(){ - String password = "эластичный поиск-弾性検索"; - SecuredString securePass = new SecuredString(password.toCharArray()); - byte[] utf8 = securePass.utf8Bytes(); - String password2 = new String(utf8, StandardCharsets.UTF_8); - assertThat(password2, equalTo(password)); - } - - public void testCopyChars() throws Exception { - String password = "эластичный поиск-弾性検索"; - SecuredString securePass = new SecuredString(password.toCharArray()); - char[] copy = securePass.copyChars(); - assertThat(copy, not(sameInstance(securePass.internalChars()))); - assertThat(copy, equalTo(securePass.internalChars())); - - // just a sanity check to make sure that clearing the secured string - // doesn't modify the returned copied chars - securePass.clear(); - assertThat(new String(copy), equalTo("эластичный поиск-弾性検索")); - } -} diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordTokenTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordTokenTests.java index 34dcdeb24fb..446bc6ea1bc 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordTokenTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authc/support/UsernamePasswordTokenTests.java @@ -6,6 +6,7 @@ package org.elasticsearch.xpack.security.authc.support; import org.elasticsearch.ElasticsearchSecurityException; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.ESTestCase; @@ -27,7 +28,7 @@ public class UsernamePasswordTokenTests extends ESTestCase { public void testPutToken() throws Exception { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); - UsernamePasswordToken.putTokenHeader(threadContext, new UsernamePasswordToken("user1", SecuredStringTests.build("test123"))); + UsernamePasswordToken.putTokenHeader(threadContext, new UsernamePasswordToken("user1", new SecureString("test123"))); String header = threadContext.getHeader(UsernamePasswordToken.BASIC_AUTH_HEADER); assertThat(header, notNullValue()); assertTrue(header.startsWith("Basic ")); @@ -48,7 +49,7 @@ public class UsernamePasswordTokenTests extends ESTestCase { UsernamePasswordToken token = UsernamePasswordToken.extractToken(threadContext); assertThat(token, notNullValue()); assertThat(token.principal(), equalTo("user1")); - assertThat(new String(token.credentials().internalChars()), equalTo("test123")); + assertThat(new String(token.credentials().getChars()), equalTo("test123")); } public void testExtractTokenInvalid() throws Exception { @@ -80,24 +81,24 @@ public class UsernamePasswordTokenTests extends ESTestCase { } public void testEqualsWithDifferentPasswords() { - UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); - UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecuredString("new password".toCharArray())); + UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecureString("password".toCharArray())); + UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecureString("new password".toCharArray())); assertThat(token1, not(equalTo(token2))); } public void testEqualsWithDifferentUsernames() { - UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); - UsernamePasswordToken token2 = new UsernamePasswordToken("username1", new SecuredString("password".toCharArray())); + UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecureString("password".toCharArray())); + UsernamePasswordToken token2 = new UsernamePasswordToken("username1", new SecureString("password".toCharArray())); assertThat(token1, not(equalTo(token2))); } public void testEquals() { - UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); - UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecuredString("password".toCharArray())); + UsernamePasswordToken token1 = new UsernamePasswordToken("username", new SecureString("password".toCharArray())); + UsernamePasswordToken token2 = new UsernamePasswordToken("username", new SecureString("password".toCharArray())); assertThat(token1, equalTo(token2)); } public static String basicAuthHeaderValue(String username, String passwd) { - return UsernamePasswordToken.basicAuthHeaderValue(username, new SecuredString(passwd.toCharArray())); + return UsernamePasswordToken.basicAuthHeaderValue(username, new SecureString(passwd.toCharArray())); } } diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authz/AnalyzeTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authz/AnalyzeTests.java index 0770500d5c1..12b1237e2e0 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authz/AnalyzeTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authz/AnalyzeTests.java @@ -6,9 +6,9 @@ package org.elasticsearch.xpack.security.authz; import org.elasticsearch.action.admin.indices.analyze.AnalyzeAction; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.util.Collections; @@ -17,7 +17,7 @@ import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordTok import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; public class AnalyzeTests extends SecurityIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("test123".toCharArray()))); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("test123".toCharArray()))); @Override protected String configUsers() { @@ -54,7 +54,7 @@ public class AnalyzeTests extends SecurityIntegTestCase { ensureGreen(); //ok: user has permissions for analyze on test_* - SecuredString passwd = new SecuredString("test123".toCharArray()); + SecureString passwd = new SecureString("test123".toCharArray()); client().filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("analyze_indices", passwd))) .admin().indices().prepareAnalyze("this is my text").setIndex("test_1").setAnalyzer("standard").get(); @@ -74,7 +74,7 @@ public class AnalyzeTests extends SecurityIntegTestCase { public void testAnalyzeWithoutIndices() { //this test tries to execute different analyze api variants from a user that has analyze privileges only at cluster level - SecuredString passwd = new SecuredString("test123".toCharArray()); + SecureString passwd = new SecureString("test123".toCharArray()); //fails: user doesn't have permissions for analyze on index test_1 assertThrowsAuthorizationException(client().filterWithHeader( Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("analyze_cluster", passwd))) diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java index 3b3060815b4..83b283539cf 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.security.authz; -import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesAction; import org.elasticsearch.action.admin.indices.alias.get.GetAliasesAction; @@ -14,10 +13,10 @@ import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexAction; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.Client; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.Before; import java.util.Collections; @@ -32,7 +31,7 @@ import static org.hamcrest.CoreMatchers.equalTo; public class IndexAliasesTests extends SecurityIntegTestCase { - protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("test123".toCharArray()))); + protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString("test123".toCharArray()))); @Override protected String configUsers() { @@ -99,7 +98,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexThenAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to add/remove aliases Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_only", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertAcked(client().filterWithHeader(headers).admin().indices().prepareCreate("test_1").get()); assertThrowsAuthorizationException( @@ -114,7 +113,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { //user has create permission only: allows to create indices, manage_aliases is required to add aliases although they are part of // the same create index request Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_only", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertThrowsAuthorizationException( client().filterWithHeader(headers).admin().indices().prepareCreate("test_1").addAlias(new Alias("test_2"))::get, @@ -124,7 +123,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testDeleteAliasesCreateOnlyPermission() { //user has create permission only: allows to create indices, manage_aliases is required to add/remove aliases Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_only", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertThrowsAuthorizationException( client().filterWithHeader(headers).admin().indices().prepareAliases().removeAlias("test_1", "alias_1")::get, @@ -140,7 +139,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testGetAliasesCreateOnlyPermissionStrict() { //user has create permission only: allows to create indices, manage_aliases is required to retrieve aliases though Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_only", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertThrowsAuthorizationException(client().filterWithHeader(headers).admin().indices().prepareGetAliases("test_1") .setIndices("test_1").setIndicesOptions(IndicesOptions.strictExpand())::get, GetAliasesAction.NAME, "create_only"); @@ -165,7 +164,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testGetAliasesCreateOnlyPermissionIgnoreUnavailable() { //user has create permission only: allows to create indices, manage_aliases is required to retrieve aliases though Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_only", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertThrowsAuthorizationException(client().filterWithHeader(headers).admin().indices().prepareGetAliases("test_1") .setIndices("test_1").setIndicesOptions(IndicesOptions.lenientExpandOpen())::get, GetAliasesAction.NAME, "create_only"); @@ -190,7 +189,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { //user has create and manage_aliases permission on test_*. manage_aliases is required to add/remove aliases on both aliases and // indices Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test", new SecureString("test123".toCharArray()))); assertAcked(client().filterWithHeader(headers).admin().indices().prepareCreate("test_1").get()); @@ -211,7 +210,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { // indices //ok: user has manage_aliases on test_* Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_test_aliases_test", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertAcked(client().filterWithHeader(headers).admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias")).get()); //fails: user doesn't have manage_aliases on alias_1 @@ -225,7 +224,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { // indices //ok: user has manage_aliases on test_* Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_test_aliases_test", - new SecuredString("test123".toCharArray()))); + new SecureString("test123".toCharArray()))); assertAcked(client().filterWithHeader(headers).admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias_1")) .addAlias(new Alias("test_alias_2")) @@ -260,7 +259,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { //user has create and manage_aliases permission on test_*. manage_aliases is required to retrieve aliases on both aliases and // indices Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); assertAcked(client.admin().indices().prepareCreate("test_1").addAlias(new Alias("test_alias")).get()); @@ -311,7 +310,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexThenAliasesCreateAndAliasesPermission2() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases @@ -335,7 +334,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexAndAliasesCreateAndAliasesPermission2() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("create_test_aliases_alias", new - SecuredString("test123".toCharArray()))); + SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases @@ -348,7 +347,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testDeleteAliasesCreateAndAliasesPermission2() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to add/remove aliases @@ -365,7 +364,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testGetAliasesCreateAndAliasesPermission2() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on alias_*. manage_aliases is required to retrieve aliases @@ -407,7 +406,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexThenAliasesCreateAndAliasesPermission3() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. @@ -422,7 +421,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexAndAliasesCreateAndAliasesPermission3() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. @@ -433,7 +432,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testDeleteAliasesCreateAndAliasesPermission3() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. @@ -456,7 +455,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testGetAliasesCreateAndAliasesPermission3() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("create_test_aliases_test_alias", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("create_test_aliases_test_alias", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has create permission on test_* and manage_aliases permission on test_*,alias_*. All good. @@ -491,13 +490,13 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testCreateIndexAliasesOnlyPermission() { assertThrowsAuthorizationException(client().filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("aliases_only", new SecuredString("test123".toCharArray())))) + basicAuthHeaderValue("aliases_only", new SecureString("test123".toCharArray())))) .admin().indices().prepareCreate("test_1")::get, CreateIndexAction.NAME, "aliases_only"); } public void testGetAliasesAliasesOnlyPermissionStrict() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("aliases_only", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("aliases_only", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has manage_aliases only permissions on both alias_* and test_* @@ -517,7 +516,7 @@ public class IndexAliasesTests extends SecurityIntegTestCase { public void testGetAliasesAliasesOnlyPermissionIgnoreUnavailable() { Map headers = Collections.singletonMap(BASIC_AUTH_HEADER, - basicAuthHeaderValue("aliases_only", new SecuredString("test123".toCharArray()))); + basicAuthHeaderValue("aliases_only", new SecureString("test123".toCharArray()))); final Client client = client().filterWithHeader(headers); //user has manage_aliases only permissions on both alias_* and test_* diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/rest/action/RestAuthenticateActionTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/rest/action/RestAuthenticateActionTests.java index a2388780b48..3217e2e4a45 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/rest/action/RestAuthenticateActionTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/rest/action/RestAuthenticateActionTests.java @@ -9,11 +9,11 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecuritySettingsSource; import org.elasticsearch.test.rest.yaml.ObjectPath; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authz.AuthorizationService; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.junit.BeforeClass; @@ -51,7 +51,7 @@ public class RestAuthenticateActionTests extends SecurityIntegTestCase { public void testAuthenticateApi() throws Exception { Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", new BasicHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, - new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); + new SecureString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())))); assertThat(response.getStatusLine().getStatusCode(), is(200)); ObjectPath objectPath = ObjectPath.createFromResponse(response); assertThat(objectPath.evaluate("username").toString(), equalTo(SecuritySettingsSource.DEFAULT_USER_NAME)); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java b/plugin/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java index 33599c36f28..6ff3038a28f 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java @@ -102,7 +102,7 @@ public class SslIntegrationTests extends SecurityIntegTestCase { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(nodeClientUsername(), - new String(nodeClientPassword().internalChars()))); + new String(nodeClientPassword().getChars()))); try (CloseableHttpClient client = HttpClients.custom() .setSSLSocketFactory(new SSLConnectionSocketFactory(service.sslSocketFactory(Settings.EMPTY), SSLConnectionSocketFactory.getDefaultHostnameVerifier())) diff --git a/plugin/src/test/java/org/elasticsearch/xpack/ssl/SSLClientAuthTests.java b/plugin/src/test/java/org/elasticsearch/xpack/ssl/SSLClientAuthTests.java index f6582095273..595a3d079d2 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/ssl/SSLClientAuthTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/ssl/SSLClientAuthTests.java @@ -95,7 +95,7 @@ public class SSLClientAuthTests extends SecurityIntegTestCase { .put("xpack.ssl.keystore.password", "testclient-client-profile") .put("cluster.name", internalCluster().getClusterName()) .put(Security.USER_SETTING.getKey(), - transportClientUsername() + ":" + new String(transportClientPassword().internalChars())) + transportClientUsername() + ":" + new String(transportClientPassword().getChars())) .build(); try (TransportClient client = new TestXPackTransportClient(settings)) { Transport transport = internalCluster().getDataNodeInstance(Transport.class); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java b/plugin/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java index 813fd7aa52d..c5609f4a49a 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java @@ -9,11 +9,11 @@ package org.elasticsearch.xpack.test.rest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -22,7 +22,7 @@ import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordTok public abstract class XPackRestTestCase extends ESClientYamlSuiteTestCase { private static final String BASIC_AUTH_VALUE = - basicAuthHeaderValue("elastic", new SecuredString("changeme".toCharArray())); + basicAuthHeaderValue("elastic", new SecureString("changeme".toCharArray())); public XPackRestTestCase(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/watcher/security/BasicSecurityTests.java b/plugin/src/test/java/org/elasticsearch/xpack/watcher/security/BasicSecurityTests.java index b42e5b96314..c96d0b01815 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/watcher/security/BasicSecurityTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/watcher/security/BasicSecurityTests.java @@ -5,9 +5,9 @@ */ package org.elasticsearch.xpack.watcher.security; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xpack.security.Security; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.watcher.WatcherState; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.elasticsearch.xpack.watcher.transport.actions.delete.DeleteWatchResponse; @@ -63,7 +63,7 @@ public class BasicSecurityTests extends AbstractWatcherIntegrationTestCase { } // stats and get watch apis require at least monitor role: - String token = basicAuthHeaderValue("test", new SecuredString("changeme".toCharArray())); + String token = basicAuthHeaderValue("test", new SecureString("changeme".toCharArray())); try { watcherClient().filterWithHeader(Collections.singletonMap("Authorization", token)).prepareWatcherStats() .get(); @@ -81,7 +81,7 @@ public class BasicSecurityTests extends AbstractWatcherIntegrationTestCase { } // stats and get watch are allowed by role monitor: - token = basicAuthHeaderValue("monitor", new SecuredString("changeme".toCharArray())); + token = basicAuthHeaderValue("monitor", new SecureString("changeme".toCharArray())); WatcherStatsResponse statsResponse = watcherClient().filterWithHeader(Collections.singletonMap("Authorization", token)) .prepareWatcherStats().get(); assertThat(statsResponse.getWatcherState(), equalTo(WatcherState.STARTED)); @@ -102,7 +102,7 @@ public class BasicSecurityTests extends AbstractWatcherIntegrationTestCase { public void testWatcherAdminRole() throws Exception { // put, execute and delete watch apis requires watcher admin role: - String token = basicAuthHeaderValue("test", new SecuredString("changeme".toCharArray())); + String token = basicAuthHeaderValue("test", new SecureString("changeme".toCharArray())); try { watcherClient().filterWithHeader(Collections.singletonMap("Authorization", token)).preparePutWatch("_id") .setSource(watchBuilder().trigger(schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)))) @@ -131,7 +131,7 @@ public class BasicSecurityTests extends AbstractWatcherIntegrationTestCase { } // put, execute and delete watch apis are allowed by role admin: - token = basicAuthHeaderValue("admin", new SecuredString("changeme".toCharArray())); + token = basicAuthHeaderValue("admin", new SecureString("changeme".toCharArray())); PutWatchResponse putWatchResponse = watcherClient().filterWithHeader(Collections.singletonMap("Authorization", token)) .preparePutWatch("_id") .setSource(watchBuilder().trigger(schedule(interval(5, IntervalSchedule.Interval.Unit.SECONDS)))) @@ -148,7 +148,7 @@ public class BasicSecurityTests extends AbstractWatcherIntegrationTestCase { assertThat(deleteWatchResponse.isFound(), is(true)); // stats and get watch are also allowed by role monitor: - token = basicAuthHeaderValue("admin", new SecuredString("changeme".toCharArray())); + token = basicAuthHeaderValue("admin", new SecureString("changeme".toCharArray())); WatcherStatsResponse statsResponse = watcherClient().filterWithHeader(Collections.singletonMap("Authorization", token)) .prepareWatcherStats() .get(); diff --git a/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java b/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java index 8c411962cbd..1329ec8cfd3 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java @@ -23,6 +23,7 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.ClusterSettings; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.Callback; @@ -58,7 +59,6 @@ import org.elasticsearch.xpack.notification.email.Profile; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.authc.file.FileRealm; import org.elasticsearch.xpack.security.authc.support.Hasher; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.crypto.CryptoService; import org.elasticsearch.xpack.support.clock.ClockMock; import org.elasticsearch.xpack.template.TemplateUtils; @@ -183,7 +183,7 @@ public abstract class AbstractWatcherIntegrationTestCase extends ESIntegTestCase return Function.identity(); } Map headers = Collections.singletonMap("Authorization", - basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, new SecuredString(SecuritySettings.TEST_PASSWORD.toCharArray()))); + basicAuthHeaderValue(SecuritySettings.TEST_USERNAME, new SecureString(SecuritySettings.TEST_PASSWORD.toCharArray()))); // we need to wrap node clients because we do not specify a user for nodes and all requests will use the system // user. This is ok for internal n2n stuff but the test framework does other things like wiping indices, repositories, etc // that the system user cannot do. so we wrap the node client with a user that can do these things since the client() calls @@ -687,7 +687,7 @@ public abstract class AbstractWatcherIntegrationTestCase extends ESIntegTestCase public static final String TEST_USERNAME = "test"; public static final String TEST_PASSWORD = "changeme"; - private static final String TEST_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString(TEST_PASSWORD.toCharArray()))); + private static final String TEST_PASSWORD_HASHED = new String(Hasher.BCRYPT.hash(new SecureString(TEST_PASSWORD.toCharArray()))); static boolean auditLogsEnabled = SystemPropertyUtil.getBoolean("tests.audit_logs", true); static byte[] systemKey = generateKey(); // must be the same for all nodes diff --git a/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java b/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java index 1241433f850..d8f437e8446 100644 --- a/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/plugin/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java @@ -11,13 +11,13 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.transport.Netty4Plugin; import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.junit.After; @@ -64,7 +64,7 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa headers = new Header[] { new BasicHeader(BASIC_AUTH_HEADER, basicAuthHeaderValue(MonitoringIntegTestCase.SecuritySettings.TEST_USERNAME, - new SecuredString(MonitoringIntegTestCase.SecuritySettings.TEST_PASSWORD.toCharArray())))}; + new SecureString(MonitoringIntegTestCase.SecuritySettings.TEST_PASSWORD.toCharArray())))}; } else { headers = new Header[0]; } diff --git a/qa/audit-tests/src/test/java/org/elasticsearch/xpack/security/audit/IndexAuditIT.java b/qa/audit-tests/src/test/java/org/elasticsearch/xpack/security/audit/IndexAuditIT.java index a1143b14d9d..d3862138ae7 100644 --- a/qa/audit-tests/src/test/java/org/elasticsearch/xpack/security/audit/IndexAuditIT.java +++ b/qa/audit-tests/src/test/java/org/elasticsearch/xpack/security/audit/IndexAuditIT.java @@ -14,12 +14,12 @@ import org.elasticsearch.client.Response; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.audit.index.IndexAuditTrail; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.xpack.XPackPlugin; @@ -41,7 +41,7 @@ public class IndexAuditIT extends ESIntegTestCase { public void testShieldIndexAuditTrailWorking() throws Exception { Response response = getRestClient().performRequest("GET", "/", new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())))); + UsernamePasswordToken.basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())))); assertThat(response.getStatusLine().getStatusCode(), is(200)); final AtomicReference lastClusterState = new AtomicReference<>(); final AtomicBoolean indexExists = new AtomicBoolean(false); diff --git a/qa/core-rest-tests-with-security/src/test/java/org/elasticsearch/xpack/security/CoreWithSecurityClientYamlTestSuiteIT.java b/qa/core-rest-tests-with-security/src/test/java/org/elasticsearch/xpack/security/CoreWithSecurityClientYamlTestSuiteIT.java index bebd2d11bea..0d7c4737bc2 100644 --- a/qa/core-rest-tests-with-security/src/test/java/org/elasticsearch/xpack/security/CoreWithSecurityClientYamlTestSuiteIT.java +++ b/qa/core-rest-tests-with-security/src/test/java/org/elasticsearch/xpack/security/CoreWithSecurityClientYamlTestSuiteIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.xpack.security; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -34,7 +34,7 @@ public class CoreWithSecurityClientYamlTestSuiteIT extends ESClientYamlSuiteTest @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); + String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/multi-cluster-search-security/src/test/java/org/elasticsearch/xpack/security/MultiClusterSearchWithSecurityYamlTestSuiteIT.java b/qa/multi-cluster-search-security/src/test/java/org/elasticsearch/xpack/security/MultiClusterSearchWithSecurityYamlTestSuiteIT.java index 41f1f4d0163..8e309571064 100644 --- a/qa/multi-cluster-search-security/src/test/java/org/elasticsearch/xpack/security/MultiClusterSearchWithSecurityYamlTestSuiteIT.java +++ b/qa/multi-cluster-search-security/src/test/java/org/elasticsearch/xpack/security/MultiClusterSearchWithSecurityYamlTestSuiteIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.xpack.security; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -40,7 +40,7 @@ public class MultiClusterSearchWithSecurityYamlTestSuiteIT extends SecurityClust @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); + String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityClientYamlTestSuiteIT.java b/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityClientYamlTestSuiteIT.java index 2cad5ac0de1..fd97ec6bec8 100644 --- a/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityClientYamlTestSuiteIT.java +++ b/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityClientYamlTestSuiteIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.xpack.security; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -36,7 +36,7 @@ public class ReindexWithSecurityClientYamlTestSuiteIT extends ESClientYamlSuiteT */ @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); + String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/security-client-tests/src/test/java/org/elasticsearch/xpack/security/qa/SecurityTransportClientIT.java b/qa/security-client-tests/src/test/java/org/elasticsearch/xpack/security/qa/SecurityTransportClientIT.java index 329deddf6a7..1b0e6b5748f 100644 --- a/qa/security-client-tests/src/test/java/org/elasticsearch/xpack/security/qa/SecurityTransportClientIT.java +++ b/qa/security-client-tests/src/test/java/org/elasticsearch/xpack/security/qa/SecurityTransportClientIT.java @@ -11,12 +11,12 @@ import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient; import org.elasticsearch.xpack.security.Security; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.xpack.XPackPlugin; @@ -96,7 +96,7 @@ public class SecurityTransportClientIT extends ESIntegTestCase { ClusterHealthResponse response; if (useTransportUser) { response = client.filterWithHeader(Collections.singletonMap("Authorization", - basicAuthHeaderValue("test_user", new SecuredString("changeme".toCharArray())))) + basicAuthHeaderValue("test_user", new SecureString("changeme".toCharArray())))) .admin().cluster().prepareHealth().get(); } else { response = client.admin().cluster().prepareHealth().get(); diff --git a/qa/security-example-extension/src/main/java/org/elasticsearch/example/realm/CustomRealm.java b/qa/security-example-extension/src/main/java/org/elasticsearch/example/realm/CustomRealm.java index bbd37aa7e11..e25242f9b0a 100644 --- a/qa/security-example-extension/src/main/java/org/elasticsearch/example/realm/CustomRealm.java +++ b/qa/security-example-extension/src/main/java/org/elasticsearch/example/realm/CustomRealm.java @@ -6,12 +6,13 @@ package org.elasticsearch.example.realm; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.xpack.security.authc.support.CharArrays; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.xpack.security.authc.AuthenticationToken; import org.elasticsearch.xpack.security.authc.Realm; import org.elasticsearch.xpack.security.authc.RealmConfig; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; public class CustomRealm extends Realm { @@ -22,7 +23,7 @@ public class CustomRealm extends Realm { public static final String PW_HEADER = "Password"; public static final String KNOWN_USER = "custom_user"; - public static final String KNOWN_PW = "changeme"; + public static final SecureString KNOWN_PW = new SecureString("changeme".toCharArray()); static final String[] ROLES = new String[] { "superuser" }; public CustomRealm(RealmConfig config) { @@ -40,7 +41,7 @@ public class CustomRealm extends Realm { if (user != null) { String password = threadContext.getHeader(PW_HEADER); if (password != null) { - return new UsernamePasswordToken(user, new SecuredString(password.toCharArray())); + return new UsernamePasswordToken(user, new SecureString(password.toCharArray())); } } return null; @@ -50,7 +51,7 @@ public class CustomRealm extends Realm { public void authenticate(AuthenticationToken authToken, ActionListener listener) { UsernamePasswordToken token = (UsernamePasswordToken)authToken; final String actualUser = token.principal(); - if (KNOWN_USER.equals(actualUser) && SecuredString.constantTimeEquals(token.credentials(), KNOWN_PW)) { + if (KNOWN_USER.equals(actualUser) && CharArrays.constantTimeEquals(token.credentials().getChars(), KNOWN_PW.getChars())) { listener.onResponse(new User(actualUser, ROLES)); } else { listener.onResponse(null); diff --git a/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index 2e81cc479c5..04360ec535d 100644 --- a/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -63,7 +63,7 @@ public class CustomRealmIT extends ESIntegTestCase { public void testHttpAuthentication() throws Exception { Response response = getRestClient().performRequest("GET", "/", new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), - new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW)); + new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW.toString())); assertThat(response.getStatusLine().getStatusCode(), is(200)); } diff --git a/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java b/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java index 407c5ad80ca..f5857f2abb4 100644 --- a/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java +++ b/qa/security-example-extension/src/test/java/org/elasticsearch/example/realm/CustomRealmTests.java @@ -6,12 +6,12 @@ package org.elasticsearch.example.realm; import org.elasticsearch.action.support.PlainActionFuture; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.xpack.security.authc.RealmConfig; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESTestCase; @@ -23,7 +23,7 @@ public class CustomRealmTests extends ESTestCase { public void testAuthenticate() { Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); CustomRealm realm = new CustomRealm(new RealmConfig("test", Settings.EMPTY, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings))); - SecuredString password = new SecuredString(CustomRealm.KNOWN_PW.toCharArray()); + SecureString password = CustomRealm.KNOWN_PW.clone(); UsernamePasswordToken token = new UsernamePasswordToken(CustomRealm.KNOWN_USER, password); PlainActionFuture plainActionFuture = new PlainActionFuture<>(); realm.authenticate(token, plainActionFuture); @@ -36,7 +36,7 @@ public class CustomRealmTests extends ESTestCase { public void testAuthenticateBadUser() { Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); CustomRealm realm = new CustomRealm(new RealmConfig("test", Settings.EMPTY, globalSettings, new Environment(globalSettings), new ThreadContext(globalSettings))); - SecuredString password = new SecuredString(CustomRealm.KNOWN_PW.toCharArray()); + SecureString password = CustomRealm.KNOWN_PW.clone(); UsernamePasswordToken token = new UsernamePasswordToken(CustomRealm.KNOWN_USER + "1", password); PlainActionFuture plainActionFuture = new PlainActionFuture<>(); realm.authenticate(token, plainActionFuture); diff --git a/qa/security-example-extension/src/test/java/org/elasticsearch/example/role/CustomRolesProviderIT.java b/qa/security-example-extension/src/test/java/org/elasticsearch/example/role/CustomRolesProviderIT.java index 1291404a0a2..eef08e140a3 100644 --- a/qa/security-example-extension/src/test/java/org/elasticsearch/example/role/CustomRolesProviderIT.java +++ b/qa/security-example-extension/src/test/java/org/elasticsearch/example/role/CustomRolesProviderIT.java @@ -9,13 +9,13 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.example.realm.CustomRealm; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.xpack.XPackPlugin; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.client.SecurityClient; @@ -90,6 +90,6 @@ public class CustomRolesProviderIT extends ESIntegTestCase { private BasicHeader authHeader() { return new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - basicAuthHeaderValue(TEST_USER, new SecuredString(TEST_PWD.toCharArray()))); + basicAuthHeaderValue(TEST_USER, new SecureString(TEST_PWD.toCharArray()))); } } diff --git a/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java b/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java index af54b38b4f5..248460f9ba4 100644 --- a/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java +++ b/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java @@ -13,6 +13,7 @@ import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.common.Priority; import org.elasticsearch.common.io.PathUtils; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.env.Environment; @@ -20,7 +21,6 @@ import org.elasticsearch.xpack.security.action.role.GetRolesResponse; import org.elasticsearch.xpack.security.action.user.GetUsersResponse; import org.elasticsearch.xpack.security.action.user.PutUserResponse; import org.elasticsearch.xpack.security.authc.esnative.ESNativeRealmMigrateTool; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authz.RoleDescriptor; import org.elasticsearch.xpack.security.authz.permission.FieldPermissions; import org.elasticsearch.xpack.security.authz.permission.FieldPermissionsDefinition; @@ -113,7 +113,7 @@ public class MigrateToolIT extends MigrateToolTestCase { } // Check that bob can access the things the "actual_role" says he can - String token = basicAuthHeaderValue("bob", new SecuredString("changeme".toCharArray())); + String token = basicAuthHeaderValue("bob", new SecureString("changeme".toCharArray())); // Create "index1" index and try to search from it as "bob" client.filterWithHeader(Collections.singletonMap("Authorization", token)).admin().indices().prepareCreate("index1").get(); // Wait for the index to be ready so it doesn't fail if no shards are initialized diff --git a/qa/smoke-test-graph-with-security/src/test/java/org/elasticsearch/smoketest/GraphWithSecurityIT.java b/qa/smoke-test-graph-with-security/src/test/java/org/elasticsearch/smoketest/GraphWithSecurityIT.java index 082ba9b9b86..1212066094d 100644 --- a/qa/smoke-test-graph-with-security/src/test/java/org/elasticsearch/smoketest/GraphWithSecurityIT.java +++ b/qa/smoke-test-graph-with-security/src/test/java/org/elasticsearch/smoketest/GraphWithSecurityIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -41,7 +41,7 @@ public class GraphWithSecurityIT extends ESClientYamlSuiteTestCase { @Override protected Settings restClientSettings() { String[] creds = getCredentials(); - String token = basicAuthHeaderValue(creds[0], new SecuredString(creds[1].toCharArray())); + String token = basicAuthHeaderValue(creds[0], new SecureString(creds[1].toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); @@ -49,7 +49,7 @@ public class GraphWithSecurityIT extends ESClientYamlSuiteTestCase { @Override protected Settings restAdminSettings() { - String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray())); + String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecureString(TEST_ADMIN_PASSWORD.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/smoke-test-ml-with-security/src/test/java/org/elasticsearch/smoketest/MlWithSecurityIT.java b/qa/smoke-test-ml-with-security/src/test/java/org/elasticsearch/smoketest/MlWithSecurityIT.java index 416e1561098..75aba8af941 100644 --- a/qa/smoke-test-ml-with-security/src/test/java/org/elasticsearch/smoketest/MlWithSecurityIT.java +++ b/qa/smoke-test-ml-with-security/src/test/java/org/elasticsearch/smoketest/MlWithSecurityIT.java @@ -9,6 +9,7 @@ import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.apache.http.HttpStatus; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; @@ -18,7 +19,6 @@ import org.elasticsearch.xpack.ml.MachineLearningTemplateRegistry; import org.elasticsearch.xpack.ml.integration.MlRestTestStateCleaner; import org.elasticsearch.xpack.ml.job.persistence.AnomalyDetectorsIndex; import org.elasticsearch.xpack.security.SecurityLifecycleService; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.After; import org.junit.Before; @@ -55,7 +55,7 @@ public class MlWithSecurityIT extends ESClientYamlSuiteTestCase { Map securityParams = Collections.singletonMap("name", SecurityLifecycleService.SECURITY_TEMPLATE_NAME); Map anomaliesParams = Collections.singletonMap("name", AnomalyDetectorsIndex.jobResultsIndexPrefix()); Map headers = Collections.singletonMap("Authorization", - basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray()))); + basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecureString(TEST_ADMIN_PASSWORD.toCharArray()))); for (Map params : Arrays.asList(securityParams, anomaliesParams)) { AtomicReference exceptionHolder = new AtomicReference<>(); @@ -92,7 +92,7 @@ public class MlWithSecurityIT extends ESClientYamlSuiteTestCase { @Override protected Settings restClientSettings() { String[] creds = getCredentials(); - String token = basicAuthHeaderValue(creds[0], new SecuredString(creds[1].toCharArray())); + String token = basicAuthHeaderValue(creds[0], new SecureString(creds[1].toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); @@ -100,7 +100,7 @@ public class MlWithSecurityIT extends ESClientYamlSuiteTestCase { @Override protected Settings restAdminSettings() { - String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray())); + String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecureString(TEST_ADMIN_PASSWORD.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslClientYamlTestSuiteIT.java b/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslClientYamlTestSuiteIT.java index 2928478db57..e8e617e42ab 100644 --- a/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslClientYamlTestSuiteIT.java +++ b/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslClientYamlTestSuiteIT.java @@ -10,12 +10,12 @@ import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.io.PathUtils; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -62,7 +62,7 @@ public class SmokeTestPluginsSslClientYamlTestSuiteIT extends ESClientYamlSuiteT @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); + String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .put(ESRestTestCase.TRUSTSTORE_PATH, keyStore) diff --git a/qa/smoke-test-plugins/src/test/java/org/elasticsearch/smoketest/XSmokeTestPluginsClientYamlTestSuiteIT.java b/qa/smoke-test-plugins/src/test/java/org/elasticsearch/smoketest/XSmokeTestPluginsClientYamlTestSuiteIT.java index 7e71130eda9..18d4a0d6238 100644 --- a/qa/smoke-test-plugins/src/test/java/org/elasticsearch/smoketest/XSmokeTestPluginsClientYamlTestSuiteIT.java +++ b/qa/smoke-test-plugins/src/test/java/org/elasticsearch/smoketest/XSmokeTestPluginsClientYamlTestSuiteIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -34,7 +34,7 @@ public class XSmokeTestPluginsClientYamlTestSuiteIT extends ESClientYamlSuiteTes @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); + String token = basicAuthHeaderValue(USER, new SecureString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/smoke-test-security-with-mustache/src/test/java/org/elasticsearch/smoketest/SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java b/qa/smoke-test-security-with-mustache/src/test/java/org/elasticsearch/smoketest/SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java index 91400eeb926..8c61cc9dd13 100644 --- a/qa/smoke-test-security-with-mustache/src/test/java/org/elasticsearch/smoketest/SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java +++ b/qa/smoke-test-security-with-mustache/src/test/java/org/elasticsearch/smoketest/SmokeTestSecurityWithMustacheClientYamlTestSuiteIT.java @@ -8,12 +8,12 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; import org.elasticsearch.xpack.security.SecurityClusterClientYamlTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import java.io.IOException; @@ -21,7 +21,7 @@ import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordTok public class SmokeTestSecurityWithMustacheClientYamlTestSuiteIT extends SecurityClusterClientYamlTestCase { - private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("test_admin", new SecuredString("changeme".toCharArray())); + private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("test_admin", new SecureString("changeme".toCharArray())); public SmokeTestSecurityWithMustacheClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); diff --git a/qa/smoke-test-watcher-with-security/src/test/java/org/elasticsearch/smoketest/SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java b/qa/smoke-test-watcher-with-security/src/test/java/org/elasticsearch/smoketest/SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java index 4990d57dd7d..bbad010ed81 100644 --- a/qa/smoke-test-watcher-with-security/src/test/java/org/elasticsearch/smoketest/SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java +++ b/qa/smoke-test-watcher-with-security/src/test/java/org/elasticsearch/smoketest/SmokeTestWatcherWithSecurityClientYamlTestSuiteIT.java @@ -8,11 +8,11 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.test.rest.yaml.ClientYamlTestCandidate; import org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.junit.After; import org.junit.Before; @@ -49,7 +49,7 @@ public class SmokeTestWatcherWithSecurityClientYamlTestSuiteIT extends ESClientY @Override protected Settings restClientSettings() { - String token = basicAuthHeaderValue("watcher_manager", new SecuredString("changeme".toCharArray())); + String token = basicAuthHeaderValue("watcher_manager", new SecureString("changeme".toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); @@ -57,7 +57,7 @@ public class SmokeTestWatcherWithSecurityClientYamlTestSuiteIT extends ESClientY @Override protected Settings restAdminSettings() { - String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray())); + String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecureString(TEST_ADMIN_PASSWORD.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) .build(); diff --git a/qa/tribe-tests-with-security/src/test/java/org/elasticsearch/test/TribeWithSecurityIT.java b/qa/tribe-tests-with-security/src/test/java/org/elasticsearch/test/TribeWithSecurityIT.java index a685e7f74ea..e8ddcf3a6c0 100644 --- a/qa/tribe-tests-with-security/src/test/java/org/elasticsearch/test/TribeWithSecurityIT.java +++ b/qa/tribe-tests-with-security/src/test/java/org/elasticsearch/test/TribeWithSecurityIT.java @@ -12,12 +12,12 @@ import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper; import org.elasticsearch.common.network.NetworkModule; +import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.xpack.security.Security; import org.elasticsearch.xpack.security.action.role.GetRolesResponse; import org.elasticsearch.xpack.security.action.role.PutRoleResponse; -import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.client.SecurityClient; import org.junit.After; @@ -110,7 +110,7 @@ public class TribeWithSecurityIT extends SecurityIntegTestCase { public void testThatTribeCanAuthenticateElasticUser() throws Exception { ClusterHealthResponse response = tribeNode.client().filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("changeme".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("changeme".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -120,7 +120,7 @@ public class TribeWithSecurityIT extends SecurityIntegTestCase { assertTribeNodeHasAllIndices(); ClusterHealthResponse response = tribeNode.client().filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); } @@ -131,7 +131,7 @@ public class TribeWithSecurityIT extends SecurityIntegTestCase { assertTribeNodeHasAllIndices(); ClusterHealthResponse response = tribeNode.client().filterWithHeader(Collections.singletonMap("Authorization", - UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecuredString("password".toCharArray())))) + UsernamePasswordToken.basicAuthHeaderValue("elastic", new SecureString("password".toCharArray())))) .admin().cluster().prepareHealth().get(); assertNoTimeout(response); }